Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependents: TEST_USB_Nucleo_F429ZI Essais_USB_Nucleo_F429ZI SID_V3_Nucleo_F429ZI SID_V4_Nucleo_F429ZI_copy
Revision 0:77ca32e8e04e, committed 2020-09-25
- Comitter:
- pierreprovent
- Date:
- Fri Sep 25 10:17:49 2020 +0000
- Commit message:
- Programme acquisition en enregistrement sur clef USB carte Nucleo F429ZI cours ELE118 Cnam
Changed in this revision
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/ChaN/ccsbcs.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,348 @@ +/*------------------------------------------------------------------------*/ +/* Unicode - Local code bidirectional converter (C)ChaN, 2015 */ +/* (SBCS code pages) */ +/*------------------------------------------------------------------------*/ +/* 437 U.S. +/ 720 Arabic +/ 737 Greek +/ 771 KBL +/ 775 Baltic +/ 850 Latin 1 +/ 852 Latin 2 +/ 855 Cyrillic +/ 857 Turkish +/ 860 Portuguese +/ 861 Icelandic +/ 862 Hebrew +/ 863 Canadian French +/ 864 Arabic +/ 865 Nordic +/ 866 Russian +/ 869 Greek 2 +*/ + +#include "ff.h" + + +#if _CODE_PAGE == 437 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP437(0x80-0xFF) to Unicode conversion table */ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, + 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 720 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP720(0x80-0xFF) to Unicode conversion table */ + 0x0000, 0x0000, 0x00E9, 0x00E2, 0x0000, 0x00E0, 0x0000, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0000, 0x0000, 0x0000, + 0x0000, 0x0651, 0x0652, 0x00F4, 0x00A4, 0x0640, 0x00FB, 0x00F9, 0x0621, 0x0622, 0x0623, 0x0624, 0x00A3, 0x0625, 0x0626, 0x0627, + 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x0636, 0x0637, 0x0638, 0x0639, 0x063A, 0x0641, 0x00B5, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, + 0x2261, 0x064B, 0x064C, 0x064D, 0x064E, 0x064F, 0x0650, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 737 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP737(0x80-0xFF) to Unicode conversion table */ + 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0, + 0x03A1, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, + 0x03B9, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C3, 0x03C2, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x03C9, 0x03AC, 0x03AD, 0x03AE, 0x03CA, 0x03AF, 0x03CC, 0x03CD, 0x03CB, 0x03CE, 0x0386, 0x0388, 0x0389, 0x038A, 0x038C, 0x038E, + 0x038F, 0x00B1, 0x2265, 0x2264, 0x03AA, 0x03AB, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 771 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP771(0x80-0xFF) to Unicode conversion table */ + 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, + 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, + 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x2558, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x0104, 0x0105, 0x010C, 0x010D, + 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F, + 0x0118, 0x0119, 0x0116, 0x0117, 0x012E, 0x012F, 0x0160, 0x0161, 0x0172, 0x0173, 0x016A, 0x016B, 0x017D, 0x017E, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 775 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP775(0x80-0xFF) to Unicode conversion table */ + 0x0106, 0x00FC, 0x00E9, 0x0101, 0x00E4, 0x0123, 0x00E5, 0x0107, 0x0142, 0x0113, 0x0156, 0x0157, 0x012B, 0x0179, 0x00C4, 0x00C5, + 0x00C9, 0x00E6, 0x00C6, 0x014D, 0x00F6, 0x0122, 0x00A2, 0x015A, 0x015B, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x00A4, + 0x0100, 0x012A, 0x00F3, 0x017B, 0x017C, 0x017A, 0x201D, 0x00A6, 0x00A9, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x0141, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x0104, 0x010C, 0x0118, 0x0116, 0x2563, 0x2551, 0x2557, 0x255D, 0x012E, 0x0160, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0172, 0x016A, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x017D, + 0x0105, 0x010D, 0x0119, 0x0117, 0x012F, 0x0161, 0x0173, 0x016B, 0x017E, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x00D3, 0x00DF, 0x014C, 0x0143, 0x00F5, 0x00D5, 0x00B5, 0x0144, 0x0136, 0x0137, 0x013B, 0x013C, 0x0146, 0x0112, 0x0145, 0x2019, + 0x00AD, 0x00B1, 0x201C, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x201E, 0x00B0, 0x2219, 0x00B7, 0x00B9, 0x00B3, 0x00B2, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 850 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP850(0x80-0xFF) to Unicode conversion table */ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, + 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, 0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, + 0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x0131, 0x00CD, 0x00CE, 0x00CF, 0x2518, 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, + 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE, 0x00DE, 0x00DA, 0x00DB, 0x00D9, 0x00FD, 0x00DD, 0x00AF, 0x00B4, + 0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 852 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP852(0x80-0xFF) to Unicode conversion table */ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x016F, 0x0107, 0x00E7, 0x0142, 0x00EB, 0x0150, 0x0151, 0x00EE, 0x0179, 0x00C4, 0x0106, + 0x00C9, 0x0139, 0x013A, 0x00F4, 0x00F6, 0x013D, 0x013E, 0x015A, 0x015B, 0x00D6, 0x00DC, 0x0164, 0x0165, 0x0141, 0x00D7, 0x010D, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x0104, 0x0105, 0x017D, 0x017E, 0x0118, 0x0119, 0x00AC, 0x017A, 0x010C, 0x015F, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, 0x00C2, 0x011A, 0x015E, 0x2563, 0x2551, 0x2557, 0x255D, 0x017B, 0x017C, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0102, 0x0103, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, + 0x0111, 0x0110, 0x010E, 0x00CB, 0x010F, 0x0147, 0x00CD, 0x00CE, 0x011B, 0x2518, 0x250C, 0x2588, 0x2584, 0x0162, 0x016E, 0x2580, + 0x00D3, 0x00DF, 0x00D4, 0x0143, 0x0144, 0x0148, 0x0160, 0x0161, 0x0154, 0x00DA, 0x0155, 0x0170, 0x00FD, 0x00DD, 0x0163, 0x00B4, + 0x00AD, 0x02DD, 0x02DB, 0x02C7, 0x02D8, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x02D9, 0x0171, 0x0158, 0x0159, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 855 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP855(0x80-0xFF) to Unicode conversion table */ + 0x0452, 0x0402, 0x0453, 0x0403, 0x0451, 0x0401, 0x0454, 0x0404, 0x0455, 0x0405, 0x0456, 0x0406, 0x0457, 0x0407, 0x0458, 0x0408, + 0x0459, 0x0409, 0x045A, 0x040A, 0x045B, 0x040B, 0x045C, 0x040C, 0x045E, 0x040E, 0x045F, 0x040F, 0x044E, 0x042E, 0x044A, 0x042A, + 0x0430, 0x0410, 0x0431, 0x0411, 0x0446, 0x0426, 0x0434, 0x0414, 0x0435, 0x0415, 0x0444, 0x0424, 0x0433, 0x0413, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x0445, 0x0425, 0x0438, 0x0418, 0x2563, 0x2551, 0x2557, 0x255D, 0x0439, 0x0419, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x043A, 0x041A, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, + 0x043B, 0x041B, 0x043C, 0x041C, 0x043D, 0x041D, 0x043E, 0x041E, 0x043F, 0x2518, 0x250C, 0x2588, 0x2584, 0x041F, 0x044F, 0x2580, + 0x042F, 0x0440, 0x0420, 0x0441, 0x0421, 0x0442, 0x0422, 0x0443, 0x0423, 0x0436, 0x0416, 0x0432, 0x0412, 0x044C, 0x042C, 0x2116, + 0x00AD, 0x044B, 0x042B, 0x0437, 0x0417, 0x0448, 0x0428, 0x044D, 0x042D, 0x0449, 0x0429, 0x0447, 0x0427, 0x00A7, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 857 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP857(0x80-0xFF) to Unicode conversion table */ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0131, 0x00C4, 0x00C5, + 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x0130, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x015E, 0x015F, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x011E, 0x011F, 0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, 0x00C2, 0x00C0, 0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4, + 0x00BA, 0x00AA, 0x00CA, 0x00CB, 0x00C8, 0x0000, 0x00CD, 0x00CE, 0x00CF, 0x2518, 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580, + 0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x0000, 0x00D7, 0x00DA, 0x00DB, 0x00D9, 0x00EC, 0x00FF, 0x00AF, 0x00B4, + 0x00AD, 0x00B1, 0x0000, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8, 0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 860 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP860(0x80-0xFF) to Unicode conversion table */ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E3, 0x00E0, 0x00C1, 0x00E7, 0x00EA, 0x00CA, 0x00E8, 0x00CD, 0x00D4, 0x00EC, 0x00C3, 0x00C2, + 0x00C9, 0x00C0, 0x00C8, 0x00F4, 0x00F5, 0x00F2, 0x00DA, 0x00F9, 0x00CC, 0x00D5, 0x00DC, 0x00A2, 0x00A3, 0x00D9, 0x20A7, 0x00D3, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x00D2, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x2558, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 861 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP861(0x80-0xFF) to Unicode conversion table */ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E6, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00D0, 0x00F0, 0x00DE, 0x00C4, 0x00C5, + 0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00FE, 0x00FB, 0x00DD, 0x00FD, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x20A7, 0x0192, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00C1, 0x00CD, 0x00D3, 0x00DA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 862 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP862(0x80-0xFF) to Unicode conversion table */ + 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, + 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 863 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP863(0x80-0xFF) to Unicode conversion table */ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00C2, 0x00E0, 0x00B6, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x2017, 0x00C0, + 0x00C9, 0x00C8, 0x00CA, 0x00F4, 0x00CB, 0x00CF, 0x00FB, 0x00F9, 0x00A4, 0x00D4, 0x00DC, 0x00A2, 0x00A3, 0x00D9, 0x00DB, 0x0192, + 0x00A6, 0x00B4, 0x00F3, 0x00FA, 0x00A8, 0x00BB, 0x00B3, 0x00AF, 0x00CE, 0x3210, 0x00AC, 0x00BD, 0x00BC, 0x00BE, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2219, + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 864 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP864(0x80-0xFF) to Unicode conversion table */ + 0x00B0, 0x00B7, 0x2219, 0x221A, 0x2592, 0x2500, 0x2502, 0x253C, 0x2524, 0x252C, 0x251C, 0x2534, 0x2510, 0x250C, 0x2514, 0x2518, + 0x03B2, 0x221E, 0x03C6, 0x00B1, 0x00BD, 0x00BC, 0x2248, 0x00AB, 0x00BB, 0xFEF7, 0xFEF8, 0x0000, 0x0000, 0xFEFB, 0xFEFC, 0x0000, + 0x00A0, 0x00AD, 0xFE82, 0x00A3, 0x00A4, 0xFE84, 0x0000, 0x20AC, 0xFE8E, 0xFE8F, 0xFE95, 0xFE99, 0x060C, 0xFE9D, 0xFEA1, 0xFEA5, + 0x0660, 0x0661, 0x0662, 0x0663, 0x0664, 0x0665, 0x0666, 0x0667, 0x0668, 0x0669, 0xFED1, 0x061B, 0xFEB1, 0xFEB5, 0xFEB9, 0x061F, + 0x00A2, 0xFE80, 0xFE81, 0xFE83, 0xFE85, 0xFECA, 0xFE8B, 0xFE8D, 0xFE91, 0xFE93, 0xFE97, 0xFE9B, 0xFE9F, 0xFEA3, 0xFEA7, 0xFEA9, + 0xFEAB, 0xFEAD, 0xFEAF, 0xFEB3, 0xFEB7, 0xFEBB, 0xFEBF, 0xFEC1, 0xFEC5, 0xFECB, 0xFECF, 0x00A6, 0x00AC, 0x00F7, 0x00D7, 0xFEC9, + 0x0640, 0xFED3, 0xFED7, 0xFEDB, 0xFEDF, 0xFEE3, 0xFEE7, 0xFEEB, 0xFEED, 0xFEEF, 0xFEF3, 0xFEBD, 0xFECC, 0xFECE, 0xFECD, 0xFEE1, + 0xFE7D, 0x0651, 0xFEE5, 0xFEE9, 0xFEEC, 0xFEF0, 0xFEF2, 0xFED0, 0xFED5, 0xFEF5, 0xFEF6, 0xFEDD, 0xFED9, 0xFEF1, 0x25A0, 0x0000 +}; + +#elif _CODE_PAGE == 865 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP865(0x80-0xFF) to Unicode conversion table */ + 0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7, 0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5, + 0x00C5, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9, 0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x20A7, 0x0192, + 0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA, 0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00A4, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x2558, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4, 0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229, + 0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 866 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP866(0x80-0xFF) to Unicode conversion table */ + 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, + 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, + 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567, + 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B, 0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580, + 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F, + 0x0401, 0x0451, 0x0404, 0x0454, 0x0407, 0x0457, 0x040E, 0x045E, 0x00B0, 0x2219, 0x00B7, 0x221A, 0x2116, 0x00A4, 0x25A0, 0x00A0 +}; + +#elif _CODE_PAGE == 869 +#define _TBLDEF 1 +static +const WCHAR Tbl[] = { /* CP869(0x80-0xFF) to Unicode conversion table */ + 0x00B7, 0x00B7, 0x00B7, 0x00B7, 0x00B7, 0x00B7, 0x0386, 0x00B7, 0x00B7, 0x00AC, 0x00A6, 0x2018, 0x2019, 0x0388, 0x2015, 0x0389, + 0x038A, 0x03AA, 0x038C, 0x00B7, 0x00B7, 0x038E, 0x03AB, 0x00A9, 0x038F, 0x00B2, 0x00B3, 0x03AC, 0x00A3, 0x03AD, 0x03AE, 0x03AF, + 0x03CA, 0x0390, 0x03CC, 0x03CD, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x00BD, 0x0398, 0x0399, 0x00AB, 0x00BB, + 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x039A, 0x039B, 0x039C, 0x039D, 0x2563, 0x2551, 0x2557, 0x255D, 0x039E, 0x039F, 0x2510, + 0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0A30, 0x03A1, 0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x03A3, + 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9, 0x03B1, 0x03B2, 0x03B3, 0x2518, 0x250C, 0x2588, 0x2584, 0x03B4, 0x03B5, 0x2580, + 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BE, 0x03BF, 0x03C0, 0x03C1, 0x03C3, 0x03C2, 0x03C4, 0x0384, + 0x00AD, 0x00B1, 0x03C5, 0x03C6, 0x03C7, 0x00A7, 0x03C8, 0x0385, 0x00B0, 0x00A8, 0x03C9, 0x03CB, 0x03B0, 0x03CE, 0x25A0, 0x00A0 +}; + +#endif + + +#if !_TBLDEF || !_USE_LFN +#error This file is not needed at current configuration. Remove from the project. +#endif + + + + +WCHAR ff_convert ( /* Converted character, Returns zero on error */ + WCHAR chr, /* Character code to be converted */ + UINT dir /* 0: Unicode to OEM code, 1: OEM code to Unicode */ +) +{ + WCHAR c; + + + if (chr < 0x80) { /* ASCII */ + c = chr; + + } else { + if (dir) { /* OEM code to Unicode */ + c = (chr >= 0x100) ? 0 : Tbl[chr - 0x80]; + + } else { /* Unicode to OEM code */ + for (c = 0; c < 0x80; c++) { + if (chr == Tbl[c]) break; + } + c = (c + 0x80) & 0xFF; + } + } + + return c; +} + + + + +WCHAR ff_wtoupper ( /* Returns upper converted character */ + WCHAR chr /* Unicode character to be upper converted */ +) +{ + static const WCHAR lower[] = { /* Lower case characters to be converted */ + /* Latin Supplement */ 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF, + /* Latin Extended-A */ 0x101,0x103,0x105,0x107,0x109,0x10B,0x10D,0x10F,0x111,0x113,0x115,0x117,0x119,0x11B,0x11D,0x11F,0x121,0x123,0x125,0x127,0x129,0x12B,0x12D,0x12F,0x131,0x133,0x135,0x137,0x13A,0x13C,0x13E,0x140,0x142,0x144,0x146,0x148,0x14B,0x14D,0x14F,0x151,0x153,0x155,0x157,0x159,0x15B,0x15D,0x15F,0x161,0x163,0x165,0x167,0x169,0x16B,0x16D,0x16F,0x171,0x173,0x175,0x177,0x17A,0x17C,0x17E, + /* Latin Extended-B */ 0x183,0x185,0x188,0x18C,0x192,0x199,0x1A1,0x1A3,0x1A8,0x1AD,0x1B0,0x1B4,0x1B6,0x1B9,0x1BD,0x1C6,0x1C9,0x1CC,0x1CE,0x1D0,0x1D2,0x1D4,0x1D6,0x1D8,0x1DA,0x1DC,0x1DD,0x1DF,0x1E1,0x1E3,0x1E5,0x1E7,0x1E9,0x1EB,0x1ED,0x1EF,0x1F3,0x1F5,0x1FB,0x1FD,0x1FF,0x201,0x203,0x205,0x207,0x209,0x20B,0x20D,0x20F,0x211,0x213,0x215,0x217, + /* Greek, Coptic */ 0x3B1,0x3B2,0x3B3,0x3B4,0x3B5,0x3B6,0x3B7,0x3B8,0x3B9,0x3BA,0x3BB,0x3BC,0x3BD,0x3BE,0x3BF,0x3C0,0x3C1,0x3C3,0x3C4,0x3C5,0x3C6,0x3C7,0x3C8,0x3C9,0x3CA,0x3CB,0x3CC,0x3CD,0x3CE,0x3E3,0x3E5,0x3E7,0x3E9,0x3EB, + /* Cyrillic */ 0x430,0x431,0x432,0x433,0x434,0x435,0x436,0x437,0x438,0x439,0x43A,0x43B,0x43C,0x43D,0x43E,0x43F,0x440,0x441,0x442,0x443,0x444,0x445,0x446,0x447,0x448,0x449,0x44A,0x44B,0x44C,0x44D,0x44E,0x44F,0x452,0x453,0x454,0x455,0x456,0x457,0x458,0x459,0x45A,0x45B,0x45C,0x45E,0x45F,0x461,0x463,0x465,0x467,0x469,0x46B,0x46D,0x46F,0x471,0x473,0x475,0x477,0x479,0x47B,0x47D,0x47F,0x481,0x491,0x493,0x495,0x497,0x499,0x49B,0x49D,0x49F,0x4A1,0x4A3,0x4A5,0x4A7,0x4A9,0x4AB,0x4AD,0x4AF,0x4B1,0x4B3,0x4B5,0x4B7,0x4B9,0x4BB,0x4BD,0x4BF,0x4C2,0x4C4,0x4C8,0x4D1,0x4D3,0x4D5,0x4D7,0x4D9,0x4DB,0x4DD,0x4DF,0x4E1,0x4E3,0x4E5,0x4E7,0x4E9,0x4EB,0x4ED,0x4EF,0x4F1,0x4F3,0x4F5,0x4F9, + /* Armenian */ 0x561,0x562,0x563,0x564,0x565,0x566,0x567,0x568,0x569,0x56A,0x56B,0x56C,0x56D,0x56E,0x56F,0x570,0x571,0x572,0x573,0x574,0x575,0x576,0x577,0x578,0x579,0x57A,0x57B,0x57C,0x57D,0x57E,0x57F,0x580,0x581,0x582,0x583,0x584,0x585,0x586, + /* Latin Extended Additional */ 0x1E01,0x1E03,0x1E05,0x1E07,0x1E09,0x1E0B,0x1E0D,0x1E0F,0x1E11,0x1E13,0x1E15,0x1E17,0x1E19,0x1E1B,0x1E1D,0x1E1F,0x1E21,0x1E23,0x1E25,0x1E27,0x1E29,0x1E2B,0x1E2D,0x1E2F,0x1E31,0x1E33,0x1E35,0x1E37,0x1E39,0x1E3B,0x1E3D,0x1E3F,0x1E41,0x1E43,0x1E45,0x1E47,0x1E49,0x1E4B,0x1E4D,0x1E4F,0x1E51,0x1E53,0x1E55,0x1E57,0x1E59,0x1E5B,0x1E5D,0x1E5F,0x1E61,0x1E63,0x1E65,0x1E67,0x1E69,0x1E6B,0x1E6D,0x1E6F,0x1E71,0x1E73,0x1E75,0x1E77,0x1E79,0x1E7B,0x1E7D,0x1E7F,0x1E81,0x1E83,0x1E85,0x1E87,0x1E89,0x1E8B,0x1E8D,0x1E8F,0x1E91,0x1E93,0x1E95,0x1E97,0x1E99,0x1E9B,0x1E9D,0x1E9F,0x1EA1,0x1EA3,0x1EA5,0x1EA7,0x1EA9,0x1EAB,0x1EAD,0x1EAF,0x1EB1,0x1EB3,0x1EB5,0x1EB7,0x1EB9,0x1EBB,0x1EBD,0x1EBF,0x1EC1,0x1EC3,0x1EC5,0x1EC7,0x1EC9,0x1ECB,0x1ECD,0x1ECF,0x1ED1,0x1ED3,0x1ED5,0x1ED7,0x1ED9,0x1EDB,0x1EDD,0x1EDF,0x1EE1,0x1EE3,0x1EE5,0x1EE7,0x1EE9,0x1EEB,0x1EED,0x1EEF,0x1EF1,0x1EF3,0x1EF5,0x1EF7,0x1EF9, + /* Number forms */ 0x2170,0x2171,0x2172,0x2173,0x2174,0x2175,0x2176,0x2177,0x2178,0x2179,0x217A,0x217B,0x217C,0x217D,0x217E,0x217F, + /* Full-width */ 0xFF41,0xFF42,0xFF43,0xFF44,0xFF45,0xFF46,0xFF47,0xFF48,0xFF49,0xFF4A,0xFF4B,0xFF4C,0xFF4D,0xFF4E,0xFF4F,0xFF50,0xFF51,0xFF52,0xFF53,0xFF54,0xFF55,0xFF56,0xFF57,0xFF58,0xFF59,0xFF5A + }; + static const WCHAR upper[] = { /* Upper case characters correspond to lower[] */ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x178, + 0x100,0x102,0x104,0x106,0x108,0x10A,0x10C,0x10E,0x110,0x112,0x114,0x116,0x118,0x11A,0x11C,0x11E,0x120,0x122,0x124,0x126,0x128,0x12A,0x12C,0x12E,0x130,0x132,0x134,0x136,0x139,0x13B,0x13D,0x13F,0x141,0x143,0x145,0x147,0x14A,0x14C,0x14E,0x150,0x152,0x154,0x156,0x158,0x15A,0x15C,0x15E,0x160,0x162,0x164,0x166,0x168,0x16A,0x16C,0x16E,0x170,0x172,0x174,0x176,0x179,0x17B,0x17D, + 0x182,0x184,0x187,0x18B,0x191,0x198,0x1A0,0x1A2,0x1A7,0x1AC,0x1AF,0x1B3,0x1B5,0x1B8,0x1BC,0x1C4,0x1C7,0x1CA,0x1CD,0x1CF,0x1D1,0x1D3,0x1D5,0x1D7,0x1D9,0x1DB,0x18E,0x1DE,0x1E0,0x1E2,0x1E4,0x1E6,0x1E8,0x1EA,0x1EC,0x1EE,0x1F1,0x1F4,0x1FA,0x1FC,0x1FE,0x200,0x202,0x204,0x206,0x208,0x20A,0x20C,0x20E,0x210,0x212,0x214,0x216, + 0x391,0x392,0x393,0x394,0x395,0x396,0x397,0x398,0x399,0x39A,0x39B,0x39C,0x39D,0x39E,0x39F,0x3A0,0x3A1,0x3A3,0x3A4,0x3A5,0x3A6,0x3A7,0x3A8,0x3A9,0x3AA,0x3AB,0x38C,0x38E,0x38F,0x3E2,0x3E4,0x3E6,0x3E8,0x3EA, + 0x410,0x411,0x412,0x413,0x414,0x415,0x416,0x417,0x418,0x419,0x41A,0x41B,0x41C,0x41D,0x41E,0x41F,0x420,0x421,0x422,0x423,0x424,0x425,0x426,0x427,0x428,0x429,0x42A,0x42B,0x42C,0x42D,0x42E,0x42F,0x402,0x403,0x404,0x405,0x406,0x407,0x408,0x409,0x40A,0x40B,0x40C,0x40E,0x40F,0x460,0x462,0x464,0x466,0x468,0x46A,0x46C,0x46E,0x470,0x472,0x474,0x476,0x478,0x47A,0x47C,0x47E,0x480,0x490,0x492,0x494,0x496,0x498,0x49A,0x49C,0x49E,0x4A0,0x4A2,0x4A4,0x4A6,0x4A8,0x4AA,0x4AC,0x4AE,0x4B0,0x4B2,0x4B4,0x4B6,0x4B8,0x4BA,0x4BC,0x4BE,0x4C1,0x4C3,0x5C7,0x4D0,0x4D2,0x4D4,0x4D6,0x4D8,0x4DA,0x4DC,0x4DE,0x4E0,0x4E2,0x4E4,0x4E6,0x4E8,0x4EA,0x4EC,0x4EE,0x4F0,0x4F2,0x4F4,0x4F8, + 0x531,0x532,0x533,0x534,0x535,0x536,0x537,0x538,0x539,0x53A,0x53B,0x53C,0x53D,0x53E,0x53F,0x540,0x541,0x542,0x543,0x544,0x545,0x546,0x547,0x548,0x549,0x54A,0x54B,0x54C,0x54D,0x54E,0x54F,0x550,0x551,0x552,0x553,0x554,0x555,0x556, + 0x1E00,0x1E02,0x1E04,0x1E06,0x1E08,0x1E0A,0x1E0C,0x1E0E,0x1E10,0x1E12,0x1E14,0x1E16,0x1E18,0x1E1A,0x1E1C,0x1E1E,0x1E20,0x1E22,0x1E24,0x1E26,0x1E28,0x1E2A,0x1E2C,0x1E2E,0x1E30,0x1E32,0x1E34,0x1E36,0x1E38,0x1E3A,0x1E3C,0x1E3E,0x1E40,0x1E42,0x1E44,0x1E46,0x1E48,0x1E4A,0x1E4C,0x1E4E,0x1E50,0x1E52,0x1E54,0x1E56,0x1E58,0x1E5A,0x1E5C,0x1E5E,0x1E60,0x1E62,0x1E64,0x1E66,0x1E68,0x1E6A,0x1E6C,0x1E6E,0x1E70,0x1E72,0x1E74,0x1E76,0x1E78,0x1E7A,0x1E7C,0x1E7E,0x1E80,0x1E82,0x1E84,0x1E86,0x1E88,0x1E8A,0x1E8C,0x1E8E,0x1E90,0x1E92,0x1E94,0x1E96,0x1E98,0x1E9A,0x1E9C,0x1E9E,0x1EA0,0x1EA2,0x1EA4,0x1EA6,0x1EA8,0x1EAA,0x1EAC,0x1EAE,0x1EB0,0x1EB2,0x1EB4,0x1EB6,0x1EB8,0x1EBA,0x1EBC,0x1EBE,0x1EC0,0x1EC2,0x1EC4,0x1EC6,0x1EC8,0x1ECA,0x1ECC,0x1ECE,0x1ED0,0x1ED2,0x1ED4,0x1ED6,0x1ED8,0x1EDA,0x1EDC,0x1EDE,0x1EE0,0x1EE2,0x1EE4,0x1EE6,0x1EE8,0x1EEA,0x1EEC,0x1EEE,0x1EF0,0x1EF2,0x1EF4,0x1EF6,0x1EF8, + 0x2160,0x2161,0x2162,0x2163,0x2164,0x2165,0x2166,0x2167,0x2168,0x2169,0x216A,0x216B,0x216C,0x216D,0x216E,0x216F, + 0xFF21,0xFF22,0xFF23,0xFF24,0xFF25,0xFF26,0xFF27,0xFF28,0xFF29,0xFF2A,0xFF2B,0xFF2C,0xFF2D,0xFF2E,0xFF2F,0xFF30,0xFF31,0xFF32,0xFF33,0xFF34,0xFF35,0xFF36,0xFF37,0xFF38,0xFF39,0xFF3A + }; + UINT i, n, hi, li; + + + if (chr < 0x80) { /* ASCII characters (acceleration) */ + if (chr >= 0x61 && chr <= 0x7A) chr -= 0x20; + + } else { /* Non ASCII characters (table search) */ + n = 12; li = 0; hi = sizeof lower / sizeof lower[0]; + do { + i = li + (hi - li) / 2; + if (chr == lower[i]) break; + if (chr > lower[i]) li = i; else hi = i; + } while (--n); + if (n) chr = upper[i]; + } + + return chr; +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/ChaN/diskio.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,117 @@ +/*-----------------------------------------------------------------------*/ +/* Low level disk I/O module skeleton for FatFs (C)ChaN, 2014 */ +/*-----------------------------------------------------------------------*/ +/* If a working storage control module is available, it should be */ +/* attached to the FatFs via a glue function rather than modifying it. */ +/* This is an example of glue functions to attach various exsisting */ +/* storage control modules to the FatFs module with a defined API. */ +/*-----------------------------------------------------------------------*/ + +#include "diskio.h" +#include "mbed_debug.h" +#include "FATFileSystem.h" + +using namespace mbed; + +/*-----------------------------------------------------------------------*/ +/* Get Drive Status */ +/*-----------------------------------------------------------------------*/ + +DSTATUS disk_status ( + BYTE pdrv /* Physical drive nmuber to identify the drive */ +) +{ + debug_if(FFS_DBG, "disk_status on pdrv [%d]\n", pdrv); + return (DSTATUS)FATFileSystem::_ffs[pdrv]->disk_status(); +} + +/*-----------------------------------------------------------------------*/ +/* Inidialize a Drive */ +/*-----------------------------------------------------------------------*/ + +DSTATUS disk_initialize ( + BYTE pdrv /* Physical drive nmuber to identify the drive */ +) +{ + debug_if(FFS_DBG, "disk_initialize on pdrv [%d]\n", pdrv); + return (DSTATUS)FATFileSystem::_ffs[pdrv]->disk_initialize(); +} + +/*-----------------------------------------------------------------------*/ +/* Read Sector(s) */ +/*-----------------------------------------------------------------------*/ + +DRESULT disk_read ( + BYTE pdrv, /* Physical drive nmuber to identify the drive */ + BYTE* buff, /* Data buffer to store read data */ + DWORD sector, /* Sector address in LBA */ + UINT count /* Number of sectors to read */ +) +{ + debug_if(FFS_DBG, "disk_read(sector %d, count %d) on pdrv [%d]\n", sector, count, pdrv); + if (FATFileSystem::_ffs[pdrv]->disk_read((uint8_t*)buff, sector, count)) + return RES_PARERR; + else + return RES_OK; +} + +/*-----------------------------------------------------------------------*/ +/* Write Sector(s) */ +/*-----------------------------------------------------------------------*/ + +#if _USE_WRITE +DRESULT disk_write ( + BYTE pdrv, /* Physical drive nmuber to identify the drive */ + const BYTE* buff, /* Data to be written */ + DWORD sector, /* Sector address in LBA */ + UINT count /* Number of sectors to write */ +) +{ + debug_if(FFS_DBG, "disk_write(sector %d, count %d) on pdrv [%d]\n", sector, count, pdrv); + if (FATFileSystem::_ffs[pdrv]->disk_write((uint8_t*)buff, sector, count)) + return RES_PARERR; + else + return RES_OK; +} +#endif + +/*-----------------------------------------------------------------------*/ +/* Miscellaneous Functions */ +/*-----------------------------------------------------------------------*/ + +#if _USE_IOCTL +DRESULT disk_ioctl ( + BYTE pdrv, /* Physical drive nmuber (0..) */ + BYTE cmd, /* Control code */ + void* buff /* Buffer to send/receive control data */ +) +{ + debug_if(FFS_DBG, "disk_ioctl(%d)\n", cmd); + switch(cmd) { + case CTRL_SYNC: + if(FATFileSystem::_ffs[pdrv] == NULL) { + return RES_NOTRDY; + } else if(FATFileSystem::_ffs[pdrv]->disk_sync()) { + return RES_ERROR; + } + return RES_OK; + case GET_SECTOR_COUNT: + if(FATFileSystem::_ffs[pdrv] == NULL) { + return RES_NOTRDY; + } else { + DWORD res = FATFileSystem::_ffs[pdrv]->disk_sectors(); + if(res > 0) { + *((DWORD*)buff) = res; // minimum allowed + return RES_OK; + } else { + return RES_ERROR; + } + } + case GET_BLOCK_SIZE: + *((DWORD*)buff) = 1; // default when not known + return RES_OK; + + } + return RES_PARERR; +} +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/ChaN/diskio.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,80 @@ +/*-----------------------------------------------------------------------/ +/ Low level disk interface modlue include file (C)ChaN, 2014 / +/-----------------------------------------------------------------------*/ + +#ifndef _DISKIO_DEFINED +#define _DISKIO_DEFINED + +#ifdef __cplusplus +extern "C" { +#endif + +#define _USE_WRITE 1 /* 1: Enable disk_write function */ +#define _USE_IOCTL 1 /* 1: Enable disk_ioctl fucntion */ + +#include "integer.h" + + +/* Status of Disk Functions */ +typedef BYTE DSTATUS; + +/* Results of Disk Functions */ +typedef enum { + RES_OK = 0, /* 0: Successful */ + RES_ERROR, /* 1: R/W Error */ + RES_WRPRT, /* 2: Write Protected */ + RES_NOTRDY, /* 3: Not Ready */ + RES_PARERR /* 4: Invalid Parameter */ +} DRESULT; + + +/*---------------------------------------*/ +/* Prototypes for disk control functions */ + + +DSTATUS disk_initialize (BYTE pdrv); +DSTATUS disk_status (BYTE pdrv); +DRESULT disk_read (BYTE pdrv, BYTE* buff, DWORD sector, UINT count); +DRESULT disk_write (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count); +DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff); + + +/* Disk Status Bits (DSTATUS) */ + +#define STA_NOINIT 0x01 /* Drive not initialized */ +#define STA_NODISK 0x02 /* No medium in the drive */ +#define STA_PROTECT 0x04 /* Write protected */ + + +/* Command code for disk_ioctrl fucntion */ + +/* Generic command (Used by FatFs) */ +#define CTRL_SYNC 0 /* Complete pending write process (needed at _FS_READONLY == 0) */ +#define GET_SECTOR_COUNT 1 /* Get media size (needed at _USE_MKFS == 1) */ +#define GET_SECTOR_SIZE 2 /* Get sector size (needed at _MAX_SS != _MIN_SS) */ +#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at _USE_MKFS == 1) */ +#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at _USE_TRIM == 1) */ + +/* Generic command (Not used by FatFs) */ +#define CTRL_POWER 5 /* Get/Set power status */ +#define CTRL_LOCK 6 /* Lock/Unlock media removal */ +#define CTRL_EJECT 7 /* Eject media */ +#define CTRL_FORMAT 8 /* Create physical format on the media */ + +/* MMC/SDC specific ioctl command */ +#define MMC_GET_TYPE 10 /* Get card type */ +#define MMC_GET_CSD 11 /* Get CSD */ +#define MMC_GET_CID 12 /* Get CID */ +#define MMC_GET_OCR 13 /* Get OCR */ +#define MMC_GET_SDSTAT 14 /* Get SD status */ + +/* ATA/CF specific ioctl command */ +#define ATA_GET_REV 20 /* Get F/W revision */ +#define ATA_GET_MODEL 21 /* Get model name */ +#define ATA_GET_SN 22 /* Get serial number */ + +#ifdef __cplusplus +} +#endif + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/ChaN/ff.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,4691 @@ +/*----------------------------------------------------------------------------/ +/ FatFs - FAT file system module R0.11a (C)ChaN, 2015 / +/-----------------------------------------------------------------------------/ +/ FatFs module is a free software that opened under license policy of +/ following conditions. +/ +/ Copyright (C) 2015, ChaN, all right reserved. +/ +/ 1. Redistributions of source code must retain the above copyright notice, +/ this condition and the following disclaimer. +/ +/ This software is provided by the copyright holder and contributors "AS IS" +/ and any warranties related to this software are DISCLAIMED. +/ The copyright owner or contributors be NOT LIABLE for any damages caused +/ by use of this software. +/----------------------------------------------------------------------------*/ + + +#include "ff.h" /* Declarations of FatFs API */ +#include "diskio.h" /* Declarations of disk I/O functions */ + + +/*-------------------------------------------------------------------------- + + Module Private Definitions + +---------------------------------------------------------------------------*/ + +#if _FATFS != 64180 /* Revision ID */ +#error Wrong include file (ff.h). +#endif + + +/* Reentrancy related */ +#if _FS_REENTRANT +#if _USE_LFN == 1 +#error Static LFN work area cannot be used at thread-safe configuration +#endif +#define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; } +#define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; } +#else +#define ENTER_FF(fs) +#define LEAVE_FF(fs, res) return res +#endif + +#define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); } + + +/* Definitions of sector size */ +#if (_MAX_SS < _MIN_SS) || (_MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096) || (_MIN_SS != 512 && _MIN_SS != 1024 && _MIN_SS != 2048 && _MIN_SS != 4096) +#error Wrong sector size configuration +#endif +#if _MAX_SS == _MIN_SS +#define SS(fs) ((UINT)_MAX_SS) /* Fixed sector size */ +#else +#define SS(fs) ((fs)->ssize) /* Variable sector size */ +#endif + + +/* Timestamp feature */ +#if _FS_NORTC == 1 +#if _NORTC_YEAR < 1980 || _NORTC_YEAR > 2107 || _NORTC_MON < 1 || _NORTC_MON > 12 || _NORTC_MDAY < 1 || _NORTC_MDAY > 31 +#error Invalid _FS_NORTC settings +#endif +#define GET_FATTIME() ((DWORD)(_NORTC_YEAR - 1980) << 25 | (DWORD)_NORTC_MON << 21 | (DWORD)_NORTC_MDAY << 16) +#else +#define GET_FATTIME() get_fattime() +#endif + + +/* File access control feature */ +#if _FS_LOCK +#if _FS_READONLY +#error _FS_LOCK must be 0 at read-only configuration +#endif +typedef struct { + FATFS *fs; /* Object ID 1, volume (NULL:blank entry) */ + DWORD clu; /* Object ID 2, directory (0:root) */ + WORD idx; /* Object ID 3, directory index */ + WORD ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */ +} FILESEM; +#endif + + + +/* DBCS code ranges and SBCS upper conversion tables */ + +#if _CODE_PAGE == 932 /* Japanese Shift-JIS */ +#define _DF1S 0x81 /* DBC 1st byte range 1 start */ +#define _DF1E 0x9F /* DBC 1st byte range 1 end */ +#define _DF2S 0xE0 /* DBC 1st byte range 2 start */ +#define _DF2E 0xFC /* DBC 1st byte range 2 end */ +#define _DS1S 0x40 /* DBC 2nd byte range 1 start */ +#define _DS1E 0x7E /* DBC 2nd byte range 1 end */ +#define _DS2S 0x80 /* DBC 2nd byte range 2 start */ +#define _DS2E 0xFC /* DBC 2nd byte range 2 end */ + +#elif _CODE_PAGE == 936 /* Simplified Chinese GBK */ +#define _DF1S 0x81 +#define _DF1E 0xFE +#define _DS1S 0x40 +#define _DS1E 0x7E +#define _DS2S 0x80 +#define _DS2E 0xFE + +#elif _CODE_PAGE == 949 /* Korean */ +#define _DF1S 0x81 +#define _DF1E 0xFE +#define _DS1S 0x41 +#define _DS1E 0x5A +#define _DS2S 0x61 +#define _DS2E 0x7A +#define _DS3S 0x81 +#define _DS3E 0xFE + +#elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */ +#define _DF1S 0x81 +#define _DF1E 0xFE +#define _DS1S 0x40 +#define _DS1E 0x7E +#define _DS2S 0xA1 +#define _DS2E 0xFE + +#elif _CODE_PAGE == 437 /* U.S. */ +#define _DF1S 0 +#define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \ + 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ + 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 720 /* Arabic */ +#define _DF1S 0 +#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \ + 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ + 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 737 /* Greek */ +#define _DF1S 0 +#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \ + 0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \ + 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xEF,0xF5,0xF0,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 771 /* KBL */ +#define _DF1S 0 +#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \ + 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ + 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDC,0xDE,0xDE, \ + 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ + 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFE,0xFF} + +#elif _CODE_PAGE == 775 /* Baltic */ +#define _DF1S 0 +#define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F, \ + 0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \ + 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 850 /* Latin 1 */ +#define _DF1S 0 +#define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x41,0x43,0x45,0x45,0x45,0x49,0x49,0x49,0x41,0x41, \ + 0x45,0x92,0x92,0x4F,0x4F,0x4F,0x55,0x55,0x59,0x4F,0x55,0x4F,0x9C,0x4F,0x9E,0x9F, \ + 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0x41,0x41,0x41,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0x41,0x41,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD1,0xD1,0x45,0x45,0x45,0x49,0x49,0x49,0x49,0xD9,0xDA,0xDB,0xDC,0xDD,0x49,0xDF, \ + 0x4F,0xE1,0x4F,0x4F,0x4F,0x4F,0xE6,0xE8,0xE8,0x55,0x55,0x55,0x59,0x59,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 852 /* Latin 2 */ +#define _DF1S 0 +#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F, \ + 0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0xAC, \ + 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF} + +#elif _CODE_PAGE == 855 /* Cyrillic */ +#define _DF1S 0 +#define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F, \ + 0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \ + 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \ + 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF, \ + 0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 857 /* Turkish */ +#define _DF1S 0 +#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x49,0x8E,0x8F, \ + 0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \ + 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0x49,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0xED,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 860 /* Portuguese */ +#define _DF1S 0 +#define _EXCVT {0x80,0x9A,0x90,0x8F,0x8E,0x91,0x86,0x80,0x89,0x89,0x92,0x8B,0x8C,0x98,0x8E,0x8F, \ + 0x90,0x91,0x92,0x8C,0x99,0xA9,0x96,0x9D,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ + 0x86,0x8B,0x9F,0x96,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 861 /* Icelandic */ +#define _DF1S 0 +#define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x8B,0x8B,0x8D,0x8E,0x8F, \ + 0x90,0x92,0x92,0x4F,0x99,0x8D,0x55,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \ + 0xA4,0xA5,0xA6,0xA7,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 862 /* Hebrew */ +#define _DF1S 0 +#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \ + 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ + 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 863 /* Canadian-French */ +#define _DF1S 0 +#define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x41,0x8F, \ + 0x45,0x45,0x45,0x4F,0x45,0x49,0x55,0x55,0x98,0x4F,0x55,0x9B,0x9C,0x55,0x55,0x9F, \ + 0xA0,0xA1,0x4F,0x55,0xA4,0xA5,0xA6,0xA7,0x49,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 864 /* Arabic */ +#define _DF1S 0 +#define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \ + 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ + 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 865 /* Nordic */ +#define _DF1S 0 +#define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \ + 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ + 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \ + 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 866 /* Russian */ +#define _DF1S 0 +#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \ + 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ + 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ + 0x90,0x91,0x92,0x93,0x9d,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ + 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} + +#elif _CODE_PAGE == 869 /* Greek 2 */ +#define _DF1S 0 +#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \ + 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x86,0x9C,0x8D,0x8F,0x90, \ + 0x91,0x90,0x92,0x95,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \ + 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ + 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \ + 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xA4,0xA5,0xA6,0xD9,0xDA,0xDB,0xDC,0xA7,0xA8,0xDF, \ + 0xA9,0xAA,0xAC,0xAD,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xCF,0xCF,0xD0,0xEF, \ + 0xF0,0xF1,0xD1,0xD2,0xD3,0xF5,0xD4,0xF7,0xF8,0xF9,0xD5,0x96,0x95,0x98,0xFE,0xFF} + +#elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */ +#if _USE_LFN +#error Cannot use LFN feature without valid code page. +#endif +#define _DF1S 0 + +#else +#error Unknown code page + +#endif + + +/* Character code support macros */ +#define IsUpper(c) (((c)>='A')&&((c)<='Z')) +#define IsLower(c) (((c)>='a')&&((c)<='z')) +#define IsDigit(c) (((c)>='0')&&((c)<='9')) + +#if _DF1S /* Code page is DBCS */ + +#ifdef _DF2S /* Two 1st byte areas */ +#define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E)) +#else /* One 1st byte area */ +#define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) +#endif + +#ifdef _DS3S /* Three 2nd byte areas */ +#define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E)) +#else /* Two 2nd byte areas */ +#define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E)) +#endif + +#else /* Code page is SBCS */ + +#define IsDBCS1(c) 0 +#define IsDBCS2(c) 0 + +#endif /* _DF1S */ + + +/* Name status flags */ +#define NSFLAG 11 /* Index of name status byte in fn[] */ +#define NS_LOSS 0x01 /* Out of 8.3 format */ +#define NS_LFN 0x02 /* Force to create LFN entry */ +#define NS_LAST 0x04 /* Last segment */ +#define NS_BODY 0x08 /* Lower case flag (body) */ +#define NS_EXT 0x10 /* Lower case flag (ext) */ +#define NS_DOT 0x20 /* Dot entry */ + + +/* FAT sub-type boundaries (Differ from specs but correct for real DOS/Windows) */ +#define MIN_FAT16 4086U /* Minimum number of clusters of FAT16 */ +#define MIN_FAT32 65526U /* Minimum number of clusters of FAT32 */ + + +/* FatFs refers the members in the FAT structures as byte array instead of +/ structure members because the structure is not binary compatible between +/ different platforms */ + +#define BS_jmpBoot 0 /* x86 jump instruction (3) */ +#define BS_OEMName 3 /* OEM name (8) */ +#define BPB_BytsPerSec 11 /* Sector size [byte] (2) */ +#define BPB_SecPerClus 13 /* Cluster size [sector] (1) */ +#define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (2) */ +#define BPB_NumFATs 16 /* Number of FAT copies (1) */ +#define BPB_RootEntCnt 17 /* Number of root directory entries for FAT12/16 (2) */ +#define BPB_TotSec16 19 /* Volume size [sector] (2) */ +#define BPB_Media 21 /* Media descriptor (1) */ +#define BPB_FATSz16 22 /* FAT size [sector] (2) */ +#define BPB_SecPerTrk 24 /* Track size [sector] (2) */ +#define BPB_NumHeads 26 /* Number of heads (2) */ +#define BPB_HiddSec 28 /* Number of special hidden sectors (4) */ +#define BPB_TotSec32 32 /* Volume size [sector] (4) */ +#define BS_DrvNum 36 /* Physical drive number (1) */ +#define BS_NTres 37 /* Error flag (1) */ +#define BS_BootSig 38 /* Extended boot signature (1) */ +#define BS_VolID 39 /* Volume serial number (4) */ +#define BS_VolLab 43 /* Volume label (8) */ +#define BS_FilSysType 54 /* File system type (1) */ +#define BPB_FATSz32 36 /* FAT size [sector] (4) */ +#define BPB_ExtFlags 40 /* Extended flags (2) */ +#define BPB_FSVer 42 /* File system version (2) */ +#define BPB_RootClus 44 /* Root directory first cluster (4) */ +#define BPB_FSInfo 48 /* Offset of FSINFO sector (2) */ +#define BPB_BkBootSec 50 /* Offset of backup boot sector (2) */ +#define BS_DrvNum32 64 /* Physical drive number (1) */ +#define BS_NTres32 65 /* Error flag (1) */ +#define BS_BootSig32 66 /* Extended boot signature (1) */ +#define BS_VolID32 67 /* Volume serial number (4) */ +#define BS_VolLab32 71 /* Volume label (8) */ +#define BS_FilSysType32 82 /* File system type (1) */ +#define FSI_LeadSig 0 /* FSI: Leading signature (4) */ +#define FSI_StrucSig 484 /* FSI: Structure signature (4) */ +#define FSI_Free_Count 488 /* FSI: Number of free clusters (4) */ +#define FSI_Nxt_Free 492 /* FSI: Last allocated cluster (4) */ +#define MBR_Table 446 /* MBR: Partition table offset (2) */ +#define SZ_PTE 16 /* MBR: Size of a partition table entry */ +#define BS_55AA 510 /* Signature word (2) */ + +#define DIR_Name 0 /* Short file name (11) */ +#define DIR_Attr 11 /* Attribute (1) */ +#define DIR_NTres 12 /* Lower case flag (1) */ +#define DIR_CrtTimeTenth 13 /* Created time sub-second (1) */ +#define DIR_CrtTime 14 /* Created time (2) */ +#define DIR_CrtDate 16 /* Created date (2) */ +#define DIR_LstAccDate 18 /* Last accessed date (2) */ +#define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (2) */ +#define DIR_WrtTime 22 /* Modified time (2) */ +#define DIR_WrtDate 24 /* Modified date (2) */ +#define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (2) */ +#define DIR_FileSize 28 /* File size (4) */ +#define LDIR_Ord 0 /* LFN entry order and LLE flag (1) */ +#define LDIR_Attr 11 /* LFN attribute (1) */ +#define LDIR_Type 12 /* LFN type (1) */ +#define LDIR_Chksum 13 /* Checksum of corresponding SFN entry */ +#define LDIR_FstClusLO 26 /* Must be zero (0) */ +#define SZ_DIRE 32 /* Size of a directory entry */ +#define LLEF 0x40 /* Last long entry flag in LDIR_Ord */ +#define DDEM 0xE5 /* Deleted directory entry mark at DIR_Name[0] */ +#define RDDEM 0x05 /* Replacement of the character collides with DDEM */ + + + + +/*-------------------------------------------------------------------------- + + Module Private Work Area + +---------------------------------------------------------------------------*/ + +/* Remark: Uninitialized variables with static duration are guaranteed +/ zero/null at start-up. If not, either the linker or start-up routine +/ being used is not compliance with ANSI-C standard. +*/ + +#if _VOLUMES < 1 || _VOLUMES > 9 +#error Wrong _VOLUMES setting +#endif +static FATFS *FatFs[_VOLUMES]; /* Pointer to the file system objects (logical drives) */ +static WORD Fsid; /* File system mount ID */ + +#if _FS_RPATH && _VOLUMES >= 2 +static BYTE CurrVol; /* Current drive */ +#endif + +#if _FS_LOCK +static FILESEM Files[_FS_LOCK]; /* Open object lock semaphores */ +#endif + +#if _USE_LFN == 0 /* Non LFN feature */ +#define DEFINE_NAMEBUF BYTE sfn[12] +#define INIT_BUF(dobj) (dobj).fn = sfn +#define FREE_BUF() +#else +#if _MAX_LFN < 12 || _MAX_LFN > 255 +#error Wrong _MAX_LFN setting +#endif +#if _USE_LFN == 1 /* LFN feature with static working buffer */ +static WCHAR LfnBuf[_MAX_LFN + 1]; +#define DEFINE_NAMEBUF BYTE sfn[12] +#define INIT_BUF(dobj) { (dobj).fn = sfn; (dobj).lfn = LfnBuf; } +#define FREE_BUF() +#elif _USE_LFN == 2 /* LFN feature with dynamic working buffer on the stack */ +#define DEFINE_NAMEBUF BYTE sfn[12]; WCHAR lbuf[_MAX_LFN + 1] +#define INIT_BUF(dobj) { (dobj).fn = sfn; (dobj).lfn = lbuf; } +#define FREE_BUF() +#elif _USE_LFN == 3 /* LFN feature with dynamic working buffer on the heap */ +#define DEFINE_NAMEBUF BYTE sfn[12]; WCHAR *lfn +#define INIT_BUF(dobj) { lfn = ff_memalloc((_MAX_LFN + 1) * 2); if (!lfn) LEAVE_FF((dobj).fs, FR_NOT_ENOUGH_CORE); (dobj).lfn = lfn; (dobj).fn = sfn; } +#define FREE_BUF() ff_memfree(lfn) +#else +#error Wrong _USE_LFN setting +#endif +#endif + +#ifdef _EXCVT +static const BYTE ExCvt[] = _EXCVT; /* Upper conversion table for SBCS extended characters */ +#endif + + + + + + +/*-------------------------------------------------------------------------- + + Module Private Functions + +---------------------------------------------------------------------------*/ + + +/*-----------------------------------------------------------------------*/ +/* String functions */ +/*-----------------------------------------------------------------------*/ + +/* Copy memory to memory */ +static +void mem_cpy (void* dst, const void* src, UINT cnt) { + BYTE *d = (BYTE*)dst; + const BYTE *s = (const BYTE*)src; + +#if _WORD_ACCESS == 1 + while (cnt >= sizeof (int)) { + *(int*)d = *(int*)s; + d += sizeof (int); s += sizeof (int); + cnt -= sizeof (int); + } +#endif + while (cnt--) + *d++ = *s++; +} + +/* Fill memory */ +static +void mem_set (void* dst, int val, UINT cnt) { + BYTE *d = (BYTE*)dst; + + while (cnt--) + *d++ = (BYTE)val; +} + +/* Compare memory to memory */ +static +int mem_cmp (const void* dst, const void* src, UINT cnt) { + const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src; + int r = 0; + + while (cnt-- && (r = *d++ - *s++) == 0) ; + return r; +} + +/* Check if chr is contained in the string */ +static +int chk_chr (const char* str, int chr) { + while (*str && *str != chr) str++; + return *str; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Request/Release grant to access the volume */ +/*-----------------------------------------------------------------------*/ +#if _FS_REENTRANT +static +int lock_fs ( + FATFS* fs /* File system object */ +) +{ + return ff_req_grant(fs->sobj); +} + + +static +void unlock_fs ( + FATFS* fs, /* File system object */ + FRESULT res /* Result code to be returned */ +) +{ + if (fs && + res != FR_NOT_ENABLED && + res != FR_INVALID_DRIVE && + res != FR_INVALID_OBJECT && + res != FR_TIMEOUT) { + ff_rel_grant(fs->sobj); + } +} +#endif + + + + +/*-----------------------------------------------------------------------*/ +/* File lock control functions */ +/*-----------------------------------------------------------------------*/ +#if _FS_LOCK + +static +FRESULT chk_lock ( /* Check if the file can be accessed */ + FATFS_DIR* dp, /* Directory object pointing the file to be checked */ + int acc /* Desired access type (0:Read, 1:Write, 2:Delete/Rename) */ +) +{ + UINT i, be; + + /* Search file semaphore table */ + for (i = be = 0; i < _FS_LOCK; i++) { + if (Files[i].fs) { /* Existing entry */ + if (Files[i].fs == dp->fs && /* Check if the object matched with an open object */ + Files[i].clu == dp->sclust && + Files[i].idx == dp->index) break; + } else { /* Blank entry */ + be = 1; + } + } + if (i == _FS_LOCK) /* The object is not opened */ + return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES; /* Is there a blank entry for new object? */ + + /* The object has been opened. Reject any open against writing file and all write mode open */ + return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK; +} + + +static +int enq_lock (void) /* Check if an entry is available for a new object */ +{ + UINT i; + + for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ; + return (i == _FS_LOCK) ? 0 : 1; +} + + +static +UINT inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */ + FATFS_DIR* dp, /* Directory object pointing the file to register or increment */ + int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */ +) +{ + UINT i; + + + for (i = 0; i < _FS_LOCK; i++) { /* Find the object */ + if (Files[i].fs == dp->fs && + Files[i].clu == dp->sclust && + Files[i].idx == dp->index) break; + } + + if (i == _FS_LOCK) { /* Not opened. Register it as new. */ + for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ; + if (i == _FS_LOCK) return 0; /* No free entry to register (int err) */ + Files[i].fs = dp->fs; + Files[i].clu = dp->sclust; + Files[i].idx = dp->index; + Files[i].ctr = 0; + } + + if (acc && Files[i].ctr) return 0; /* Access violation (int err) */ + + Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */ + + return i + 1; +} + + +static +FRESULT dec_lock ( /* Decrement object open counter */ + UINT i /* Semaphore index (1..) */ +) +{ + WORD n; + FRESULT res; + + + if (--i < _FS_LOCK) { /* Shift index number origin from 0 */ + n = Files[i].ctr; + if (n == 0x100) n = 0; /* If write mode open, delete the entry */ + if (n) n--; /* Decrement read mode open count */ + Files[i].ctr = n; + if (!n) Files[i].fs = 0; /* Delete the entry if open count gets zero */ + res = FR_OK; + } else { + res = FR_INT_ERR; /* Invalid index nunber */ + } + return res; +} + + +static +void clear_lock ( /* Clear lock entries of the volume */ + FATFS *fs +) +{ + UINT i; + + for (i = 0; i < _FS_LOCK; i++) { + if (Files[i].fs == fs) Files[i].fs = 0; + } +} +#endif + + + + +/*-----------------------------------------------------------------------*/ +/* Move/Flush disk access window in the file system object */ +/*-----------------------------------------------------------------------*/ +#if !_FS_READONLY +static +FRESULT sync_window ( /* FR_OK:succeeded, !=0:error */ + FATFS* fs /* File system object */ +) +{ + DWORD wsect; + UINT nf; + FRESULT res = FR_OK; + + + if (fs->wflag) { /* Write back the sector if it is dirty */ + wsect = fs->winsect; /* Current sector number */ + if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK) { + res = FR_DISK_ERR; + } else { + fs->wflag = 0; + if (wsect - fs->fatbase < fs->fsize) { /* Is it in the FAT area? */ + for (nf = fs->n_fats; nf >= 2; nf--) { /* Reflect the change to all FAT copies */ + wsect += fs->fsize; + disk_write(fs->drv, fs->win, wsect, 1); + } + } + } + } + return res; +} +#endif + + +static +FRESULT move_window ( /* FR_OK(0):succeeded, !=0:error */ + FATFS* fs, /* File system object */ + DWORD sector /* Sector number to make appearance in the fs->win[] */ +) +{ + FRESULT res = FR_OK; + + + if (sector != fs->winsect) { /* Window offset changed? */ +#if !_FS_READONLY + res = sync_window(fs); /* Write-back changes */ +#endif + if (res == FR_OK) { /* Fill sector window with new data */ + if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK) { + sector = 0xFFFFFFFF; /* Invalidate window if data is not reliable */ + res = FR_DISK_ERR; + } + fs->winsect = sector; + } + } + return res; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Synchronize file system and strage device */ +/*-----------------------------------------------------------------------*/ +#if !_FS_READONLY +static +FRESULT sync_fs ( /* FR_OK:succeeded, !=0:error */ + FATFS* fs /* File system object */ +) +{ + FRESULT res; + + + res = sync_window(fs); + if (res == FR_OK) { + /* Update FSInfo sector if needed */ + if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) { + /* Create FSInfo structure */ + mem_set(fs->win, 0, SS(fs)); + ST_WORD(fs->win + BS_55AA, 0xAA55); + ST_DWORD(fs->win + FSI_LeadSig, 0x41615252); + ST_DWORD(fs->win + FSI_StrucSig, 0x61417272); + ST_DWORD(fs->win + FSI_Free_Count, fs->free_clust); + ST_DWORD(fs->win + FSI_Nxt_Free, fs->last_clust); + /* Write it into the FSInfo sector */ + fs->winsect = fs->volbase + 1; + disk_write(fs->drv, fs->win, fs->winsect, 1); + fs->fsi_flag = 0; + } + /* Make sure that no pending write process in the physical drive */ + if (disk_ioctl(fs->drv, CTRL_SYNC, 0) != RES_OK) + res = FR_DISK_ERR; + } + + return res; +} +#endif + + + + +/*-----------------------------------------------------------------------*/ +/* Get sector# from cluster# */ +/*-----------------------------------------------------------------------*/ +/* Hidden API for hacks and disk tools */ + +DWORD clust2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */ + FATFS* fs, /* File system object */ + DWORD clst /* Cluster# to be converted */ +) +{ + clst -= 2; + if (clst >= fs->n_fatent - 2) return 0; /* Invalid cluster# */ + return clst * fs->csize + fs->database; +} + + + + +/*-----------------------------------------------------------------------*/ +/* FAT access - Read value of a FAT entry */ +/*-----------------------------------------------------------------------*/ +/* Hidden API for hacks and disk tools */ + +DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x0FFFFFFF:Cluster status */ + FATFS* fs, /* File system object */ + DWORD clst /* FAT index number (cluster number) to get the value */ +) +{ + UINT wc, bc; + BYTE *p; + DWORD val; + + + if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */ + val = 1; /* Internal error */ + + } else { + val = 0xFFFFFFFF; /* Default value falls on disk error */ + + switch (fs->fs_type) { + case FS_FAT12 : + bc = (UINT)clst; bc += bc / 2; + if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break; + wc = fs->win[bc++ % SS(fs)]; + if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break; + wc |= fs->win[bc % SS(fs)] << 8; + val = clst & 1 ? wc >> 4 : (wc & 0xFFF); + break; + + case FS_FAT16 : + if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))) != FR_OK) break; + p = &fs->win[clst * 2 % SS(fs)]; + val = LD_WORD(p); + break; + + case FS_FAT32 : + if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break; + p = &fs->win[clst * 4 % SS(fs)]; + val = LD_DWORD(p) & 0x0FFFFFFF; + break; + + default: + val = 1; /* Internal error */ + } + } + + return val; +} + + + + +/*-----------------------------------------------------------------------*/ +/* FAT access - Change value of a FAT entry */ +/*-----------------------------------------------------------------------*/ +/* Hidden API for hacks and disk tools */ + +#if !_FS_READONLY +FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */ + FATFS* fs, /* File system object */ + DWORD clst, /* FAT index number (cluster number) to be changed */ + DWORD val /* New value to be set to the entry */ +) +{ + UINT bc; + BYTE *p; + FRESULT res; + + + if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */ + res = FR_INT_ERR; + + } else { + switch (fs->fs_type) { + case FS_FAT12 : + bc = (UINT)clst; bc += bc / 2; + res = move_window(fs, fs->fatbase + (bc / SS(fs))); + if (res != FR_OK) break; + p = &fs->win[bc++ % SS(fs)]; + *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val; + fs->wflag = 1; + res = move_window(fs, fs->fatbase + (bc / SS(fs))); + if (res != FR_OK) break; + p = &fs->win[bc % SS(fs)]; + *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F)); + fs->wflag = 1; + break; + + case FS_FAT16 : + res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))); + if (res != FR_OK) break; + p = &fs->win[clst * 2 % SS(fs)]; + ST_WORD(p, (WORD)val); + fs->wflag = 1; + break; + + case FS_FAT32 : + res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))); + if (res != FR_OK) break; + p = &fs->win[clst * 4 % SS(fs)]; + val |= LD_DWORD(p) & 0xF0000000; + ST_DWORD(p, val); + fs->wflag = 1; + break; + + default : + res = FR_INT_ERR; + } + } + + return res; +} +#endif /* !_FS_READONLY */ + + + + +/*-----------------------------------------------------------------------*/ +/* FAT handling - Remove a cluster chain */ +/*-----------------------------------------------------------------------*/ +#if !_FS_READONLY +static +FRESULT remove_chain ( /* FR_OK(0):succeeded, !=0:error */ + FATFS* fs, /* File system object */ + DWORD clst /* Cluster# to remove a chain from */ +) +{ + FRESULT res; + DWORD nxt; +#if _USE_TRIM + DWORD scl = clst, ecl = clst, rt[2]; +#endif + + if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */ + res = FR_INT_ERR; + + } else { + res = FR_OK; + while (clst < fs->n_fatent) { /* Not a last link? */ + nxt = get_fat(fs, clst); /* Get cluster status */ + if (nxt == 0) break; /* Empty cluster? */ + if (nxt == 1) { res = FR_INT_ERR; break; } /* Internal error? */ + if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; } /* Disk error? */ + res = put_fat(fs, clst, 0); /* Mark the cluster "empty" */ + if (res != FR_OK) break; + if (fs->free_clust != 0xFFFFFFFF) { /* Update FSINFO */ + fs->free_clust++; + fs->fsi_flag |= 1; + } +#if _USE_TRIM + if (ecl + 1 == nxt) { /* Is next cluster contiguous? */ + ecl = nxt; + } else { /* End of contiguous clusters */ + rt[0] = clust2sect(fs, scl); /* Start sector */ + rt[1] = clust2sect(fs, ecl) + fs->csize - 1; /* End sector */ + disk_ioctl(fs->drv, CTRL_TRIM, rt); /* Erase the block */ + scl = ecl = nxt; + } +#endif + clst = nxt; /* Next cluster */ + } + } + + return res; +} +#endif + + + + +/*-----------------------------------------------------------------------*/ +/* FAT handling - Stretch or Create a cluster chain */ +/*-----------------------------------------------------------------------*/ +#if !_FS_READONLY +static +DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */ + FATFS* fs, /* File system object */ + DWORD clst /* Cluster# to stretch, 0:Create a new chain */ +) +{ + DWORD cs, ncl, scl; + FRESULT res; + + + if (clst == 0) { /* Create a new chain */ + scl = fs->last_clust; /* Get suggested start point */ + if (!scl || scl >= fs->n_fatent) scl = 1; + } + else { /* Stretch the current chain */ + cs = get_fat(fs, clst); /* Check the cluster status */ + if (cs < 2) return 1; /* Invalid value */ + if (cs == 0xFFFFFFFF) return cs; /* A disk error occurred */ + if (cs < fs->n_fatent) return cs; /* It is already followed by next cluster */ + scl = clst; + } + + ncl = scl; /* Start cluster */ + for (;;) { + ncl++; /* Next cluster */ + if (ncl >= fs->n_fatent) { /* Check wrap around */ + ncl = 2; + if (ncl > scl) return 0; /* No free cluster */ + } + cs = get_fat(fs, ncl); /* Get the cluster status */ + if (cs == 0) break; /* Found a free cluster */ + if (cs == 0xFFFFFFFF || cs == 1)/* An error occurred */ + return cs; + if (ncl == scl) return 0; /* No free cluster */ + } + + res = put_fat(fs, ncl, 0x0FFFFFFF); /* Mark the new cluster "last link" */ + if (res == FR_OK && clst != 0) { + res = put_fat(fs, clst, ncl); /* Link it to the previous one if needed */ + } + if (res == FR_OK) { + fs->last_clust = ncl; /* Update FSINFO */ + if (fs->free_clust != 0xFFFFFFFF) { + fs->free_clust--; + fs->fsi_flag |= 1; + } + } else { + ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1; + } + + return ncl; /* Return new cluster number or error code */ +} +#endif /* !_FS_READONLY */ + + + + +/*-----------------------------------------------------------------------*/ +/* FAT handling - Convert offset into cluster with link map table */ +/*-----------------------------------------------------------------------*/ + +#if _USE_FASTSEEK +static +DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */ + FIL* fp, /* Pointer to the file object */ + DWORD ofs /* File offset to be converted to cluster# */ +) +{ + DWORD cl, ncl, *tbl; + + + tbl = fp->cltbl + 1; /* Top of CLMT */ + cl = ofs / SS(fp->fs) / fp->fs->csize; /* Cluster order from top of the file */ + for (;;) { + ncl = *tbl++; /* Number of cluters in the fragment */ + if (!ncl) return 0; /* End of table? (error) */ + if (cl < ncl) break; /* In this fragment? */ + cl -= ncl; tbl++; /* Next fragment */ + } + return cl + *tbl; /* Return the cluster number */ +} +#endif /* _USE_FASTSEEK */ + + + + +/*-----------------------------------------------------------------------*/ +/* Directory handling - Set directory index */ +/*-----------------------------------------------------------------------*/ + +static +FRESULT dir_sdi ( /* FR_OK(0):succeeded, !=0:error */ + FATFS_DIR* dp, /* Pointer to directory object */ + UINT idx /* Index of directory table */ +) +{ + DWORD clst, sect; + UINT ic; + + + dp->index = (WORD)idx; /* Current index */ + clst = dp->sclust; /* Table start cluster (0:root) */ + if (clst == 1 || clst >= dp->fs->n_fatent) /* Check start cluster range */ + return FR_INT_ERR; + if (!clst && dp->fs->fs_type == FS_FAT32) /* Replace cluster# 0 with root cluster# if in FAT32 */ + clst = dp->fs->dirbase; + + if (clst == 0) { /* Static table (root-directory in FAT12/16) */ + if (idx >= dp->fs->n_rootdir) /* Is index out of range? */ + return FR_INT_ERR; + sect = dp->fs->dirbase; + } + else { /* Dynamic table (root-directory in FAT32 or sub-directory) */ + ic = SS(dp->fs) / SZ_DIRE * dp->fs->csize; /* Entries per cluster */ + while (idx >= ic) { /* Follow cluster chain */ + clst = get_fat(dp->fs, clst); /* Get next cluster */ + if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */ + if (clst < 2 || clst >= dp->fs->n_fatent) /* Reached to end of table or internal error */ + return FR_INT_ERR; + idx -= ic; + } + sect = clust2sect(dp->fs, clst); + } + dp->clust = clst; /* Current cluster# */ + if (!sect) return FR_INT_ERR; + dp->sect = sect + idx / (SS(dp->fs) / SZ_DIRE); /* Sector# of the directory entry */ + dp->dir = dp->fs->win + (idx % (SS(dp->fs) / SZ_DIRE)) * SZ_DIRE; /* Ptr to the entry in the sector */ + + return FR_OK; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Directory handling - Move directory table index next */ +/*-----------------------------------------------------------------------*/ + +static +FRESULT dir_next ( /* FR_OK(0):succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */ + FATFS_DIR* dp, /* Pointer to the directory object */ + int stretch /* 0: Do not stretch table, 1: Stretch table if needed */ +) +{ + DWORD clst; + UINT i; +#if !_FS_READONLY + UINT c; +#endif + + + i = dp->index + 1; + if (!(i & 0xFFFF) || !dp->sect) /* Report EOT when index has reached 65535 */ + return FR_NO_FILE; + + if (!(i % (SS(dp->fs) / SZ_DIRE))) { /* Sector changed? */ + dp->sect++; /* Next sector */ + + if (!dp->clust) { /* Static table */ + if (i >= dp->fs->n_rootdir) /* Report EOT if it reached end of static table */ + return FR_NO_FILE; + } + else { /* Dynamic table */ + if (((i / (SS(dp->fs) / SZ_DIRE)) & (dp->fs->csize - 1)) == 0) { /* Cluster changed? */ + clst = get_fat(dp->fs, dp->clust); /* Get next cluster */ + if (clst <= 1) return FR_INT_ERR; + if (clst == 0xFFFFFFFF) return FR_DISK_ERR; + if (clst >= dp->fs->n_fatent) { /* If it reached end of dynamic table, */ +#if !_FS_READONLY + if (!stretch) return FR_NO_FILE; /* If do not stretch, report EOT */ + clst = create_chain(dp->fs, dp->clust); /* Stretch cluster chain */ + if (clst == 0) return FR_DENIED; /* No free cluster */ + if (clst == 1) return FR_INT_ERR; + if (clst == 0xFFFFFFFF) return FR_DISK_ERR; + /* Clean-up stretched table */ + if (sync_window(dp->fs)) return FR_DISK_ERR;/* Flush disk access window */ + mem_set(dp->fs->win, 0, SS(dp->fs)); /* Clear window buffer */ + dp->fs->winsect = clust2sect(dp->fs, clst); /* Cluster start sector */ + for (c = 0; c < dp->fs->csize; c++) { /* Fill the new cluster with 0 */ + dp->fs->wflag = 1; + if (sync_window(dp->fs)) return FR_DISK_ERR; + dp->fs->winsect++; + } + dp->fs->winsect -= c; /* Rewind window offset */ +#else + if (!stretch) return FR_NO_FILE; /* If do not stretch, report EOT (this is to suppress warning) */ + return FR_NO_FILE; /* Report EOT */ +#endif + } + dp->clust = clst; /* Initialize data for new cluster */ + dp->sect = clust2sect(dp->fs, clst); + } + } + } + + dp->index = (WORD)i; /* Current index */ + dp->dir = dp->fs->win + (i % (SS(dp->fs) / SZ_DIRE)) * SZ_DIRE; /* Current entry in the window */ + + return FR_OK; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Directory handling - Reserve directory entry */ +/*-----------------------------------------------------------------------*/ + +#if !_FS_READONLY +static +FRESULT dir_alloc ( /* FR_OK(0):succeeded, !=0:error */ + FATFS_DIR* dp, /* Pointer to the directory object */ + UINT nent /* Number of contiguous entries to allocate (1-21) */ +) +{ + FRESULT res; + UINT n; + + + res = dir_sdi(dp, 0); + if (res == FR_OK) { + n = 0; + do { + res = move_window(dp->fs, dp->sect); + if (res != FR_OK) break; + if (dp->dir[0] == DDEM || dp->dir[0] == 0) { /* Is it a free entry? */ + if (++n == nent) break; /* A block of contiguous free entries is found */ + } else { + n = 0; /* Not a blank entry. Restart to search */ + } + res = dir_next(dp, 1); /* Next entry with table stretch enabled */ + } while (res == FR_OK); + } + if (res == FR_NO_FILE) res = FR_DENIED; /* No directory entry to allocate */ + return res; +} +#endif + + + + +/*-----------------------------------------------------------------------*/ +/* Directory handling - Load/Store start cluster number */ +/*-----------------------------------------------------------------------*/ + +static +DWORD ld_clust ( /* Returns the top cluster value of the SFN entry */ + FATFS* fs, /* Pointer to the fs object */ + const BYTE* dir /* Pointer to the SFN entry */ +) +{ + DWORD cl; + + cl = LD_WORD(dir + DIR_FstClusLO); + if (fs->fs_type == FS_FAT32) + cl |= (DWORD)LD_WORD(dir + DIR_FstClusHI) << 16; + + return cl; +} + + +#if !_FS_READONLY +static +void st_clust ( + BYTE* dir, /* Pointer to the SFN entry */ + DWORD cl /* Value to be set */ +) +{ + ST_WORD(dir + DIR_FstClusLO, cl); + ST_WORD(dir + DIR_FstClusHI, cl >> 16); +} +#endif + + + + +/*-----------------------------------------------------------------------*/ +/* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry */ +/*-----------------------------------------------------------------------*/ +#if _USE_LFN +static +const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN characters in the directory entry */ + + +static +int cmp_lfn ( /* 1:matched, 0:not matched */ + WCHAR* lfnbuf, /* Pointer to the LFN working buffer to be compared */ + BYTE* dir /* Pointer to the directory entry containing the part of LFN */ +) +{ + UINT i, s; + WCHAR wc, uc; + + + if (LD_WORD(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */ + + i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */ + + for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */ + uc = LD_WORD(dir + LfnOfs[s]); /* Pick an LFN character */ + if (wc) { + if (i >= _MAX_LFN || ff_wtoupper(uc) != ff_wtoupper(lfnbuf[i++])) /* Compare it */ + return 0; /* Not matched */ + wc = uc; + } else { + if (uc != 0xFFFF) return 0; /* Check filler */ + } + } + + if ((dir[LDIR_Ord] & LLEF) && wc && lfnbuf[i]) /* Last segment matched but different length */ + return 0; + + return 1; /* The part of LFN matched */ +} + + + +static +int pick_lfn ( /* 1:succeeded, 0:buffer overflow or invalid LFN entry */ + WCHAR* lfnbuf, /* Pointer to the LFN working buffer */ + BYTE* dir /* Pointer to the LFN entry */ +) +{ + UINT i, s; + WCHAR wc, uc; + + + if (LD_WORD(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */ + + i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */ + + for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */ + uc = LD_WORD(dir + LfnOfs[s]); /* Pick an LFN character */ + if (wc) { + if (i >= _MAX_LFN) return 0; /* Buffer overflow? */ + lfnbuf[i++] = wc = uc; /* Store it */ + } else { + if (uc != 0xFFFF) return 0; /* Check filler */ + } + } + + if (dir[LDIR_Ord] & LLEF) { /* Put terminator if it is the last LFN part */ + if (i >= _MAX_LFN) return 0; /* Buffer overflow? */ + lfnbuf[i] = 0; + } + + return 1; /* The part of LFN is valid */ +} + + +#if !_FS_READONLY +static +void fit_lfn ( + const WCHAR* lfnbuf, /* Pointer to the LFN working buffer */ + BYTE* dir, /* Pointer to the LFN entry to be processed */ + BYTE ord, /* LFN order (1-20) */ + BYTE sum /* Checksum of the corresponding SFN */ +) +{ + UINT i, s; + WCHAR wc; + + + dir[LDIR_Chksum] = sum; /* Set checksum */ + dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */ + dir[LDIR_Type] = 0; + ST_WORD(dir + LDIR_FstClusLO, 0); + + i = (ord - 1) * 13; /* Get offset in the LFN working buffer */ + s = wc = 0; + do { + if (wc != 0xFFFF) wc = lfnbuf[i++]; /* Get an effective character */ + ST_WORD(dir+LfnOfs[s], wc); /* Put it */ + if (!wc) wc = 0xFFFF; /* Padding characters following last character */ + } while (++s < 13); + if (wc == 0xFFFF || !lfnbuf[i]) ord |= LLEF; /* Bottom LFN part is the start of LFN sequence */ + dir[LDIR_Ord] = ord; /* Set the LFN order */ +} + +#endif +#endif + + + + +/*-----------------------------------------------------------------------*/ +/* Create numbered name */ +/*-----------------------------------------------------------------------*/ +#if _USE_LFN +static +void gen_numname ( + BYTE* dst, /* Pointer to the buffer to store numbered SFN */ + const BYTE* src, /* Pointer to SFN */ + const WCHAR* lfn, /* Pointer to LFN */ + UINT seq /* Sequence number */ +) +{ + BYTE ns[8], c; + UINT i, j; + WCHAR wc; + DWORD sr; + + + mem_cpy(dst, src, 11); + + if (seq > 5) { /* On many collisions, generate a hash number instead of sequential number */ + sr = seq; + while (*lfn) { /* Create a CRC */ + wc = *lfn++; + for (i = 0; i < 16; i++) { + sr = (sr << 1) + (wc & 1); + wc >>= 1; + if (sr & 0x10000) sr ^= 0x11021; + } + } + seq = (UINT)sr; + } + + /* itoa (hexdecimal) */ + i = 7; + do { + c = (seq % 16) + '0'; + if (c > '9') c += 7; + ns[i--] = c; + seq /= 16; + } while (seq); + ns[i] = '~'; + + /* Append the number */ + for (j = 0; j < i && dst[j] != ' '; j++) { + if (IsDBCS1(dst[j])) { + if (j == i - 1) break; + j++; + } + } + do { + dst[j++] = (i < 8) ? ns[i++] : ' '; + } while (j < 8); +} +#endif + + + + +/*-----------------------------------------------------------------------*/ +/* Calculate checksum of an SFN entry */ +/*-----------------------------------------------------------------------*/ +#if _USE_LFN +static +BYTE sum_sfn ( + const BYTE* dir /* Pointer to the SFN entry */ +) +{ + BYTE sum = 0; + UINT n = 11; + + do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n); + return sum; +} +#endif + + + + +/*-----------------------------------------------------------------------*/ +/* Directory handling - Find an object in the directory */ +/*-----------------------------------------------------------------------*/ + +static +FRESULT dir_find ( /* FR_OK(0):succeeded, !=0:error */ + FATFS_DIR* dp /* Pointer to the directory object linked to the file name */ +) +{ + FRESULT res; + BYTE c, *dir; +#if _USE_LFN + BYTE a, ord, sum; +#endif + + res = dir_sdi(dp, 0); /* Rewind directory object */ + if (res != FR_OK) return res; + +#if _USE_LFN + ord = sum = 0xFF; dp->lfn_idx = 0xFFFF; /* Reset LFN sequence */ +#endif + do { + res = move_window(dp->fs, dp->sect); + if (res != FR_OK) break; + dir = dp->dir; /* Ptr to the directory entry of current index */ + c = dir[DIR_Name]; + if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */ +#if _USE_LFN /* LFN configuration */ + a = dir[DIR_Attr] & AM_MASK; + if (c == DDEM || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */ + ord = 0xFF; dp->lfn_idx = 0xFFFF; /* Reset LFN sequence */ + } else { + if (a == AM_LFN) { /* An LFN entry is found */ + if (dp->lfn) { + if (c & LLEF) { /* Is it start of LFN sequence? */ + sum = dir[LDIR_Chksum]; + c &= ~LLEF; ord = c; /* LFN start order */ + dp->lfn_idx = dp->index; /* Start index of LFN */ + } + /* Check validity of the LFN entry and compare it with given name */ + ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dp->lfn, dir)) ? ord - 1 : 0xFF; + } + } else { /* An SFN entry is found */ + if (!ord && sum == sum_sfn(dir)) break; /* LFN matched? */ + if (!(dp->fn[NSFLAG] & NS_LOSS) && !mem_cmp(dir, dp->fn, 11)) break; /* SFN matched? */ + ord = 0xFF; dp->lfn_idx = 0xFFFF; /* Reset LFN sequence */ + } + } +#else /* Non LFN configuration */ + if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dp->fn, 11)) /* Is it a valid entry? */ + break; +#endif + res = dir_next(dp, 0); /* Next entry */ + } while (res == FR_OK); + + return res; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Read an object from the directory */ +/*-----------------------------------------------------------------------*/ +#if _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 +static +FRESULT dir_read ( + FATFS_DIR* dp, /* Pointer to the directory object */ + int vol /* Filtered by 0:file/directory or 1:volume label */ +) +{ + FRESULT res; + BYTE a, c, *dir; +#if _USE_LFN + BYTE ord = 0xFF, sum = 0xFF; +#endif + + res = FR_NO_FILE; + while (dp->sect) { + res = move_window(dp->fs, dp->sect); + if (res != FR_OK) break; + dir = dp->dir; /* Ptr to the directory entry of current index */ + c = dir[DIR_Name]; + if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */ + a = dir[DIR_Attr] & AM_MASK; +#if _USE_LFN /* LFN configuration */ + if (c == DDEM || (!_FS_RPATH && c == '.') || (int)((a & ~AM_ARC) == AM_VOL) != vol) { /* An entry without valid data */ + ord = 0xFF; + } else { + if (a == AM_LFN) { /* An LFN entry is found */ + if (c & LLEF) { /* Is it start of LFN sequence? */ + sum = dir[LDIR_Chksum]; + c &= ~LLEF; ord = c; + dp->lfn_idx = dp->index; + } + /* Check LFN validity and capture it */ + ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dp->lfn, dir)) ? ord - 1 : 0xFF; + } else { /* An SFN entry is found */ + if (ord || sum != sum_sfn(dir)) /* Is there a valid LFN? */ + dp->lfn_idx = 0xFFFF; /* It has no LFN. */ + break; + } + } +#else /* Non LFN configuration */ + if (c != DDEM && (_FS_RPATH || c != '.') && a != AM_LFN && (int)((a & ~AM_ARC) == AM_VOL) == vol) /* Is it a valid entry? */ + break; +#endif + res = dir_next(dp, 0); /* Next entry */ + if (res != FR_OK) break; + } + + if (res != FR_OK) dp->sect = 0; + + return res; +} +#endif /* _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 */ + + + + +/*-----------------------------------------------------------------------*/ +/* Register an object to the directory */ +/*-----------------------------------------------------------------------*/ +#if !_FS_READONLY +static +FRESULT dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too many SFN collision, FR_DISK_ERR:disk error */ + FATFS_DIR* dp /* Target directory with object name to be created */ +) +{ + FRESULT res; +#if _USE_LFN /* LFN configuration */ + UINT n, nent; + BYTE sn[12], *fn, sum; + WCHAR *lfn; + + + fn = dp->fn; lfn = dp->lfn; + mem_cpy(sn, fn, 12); + + if (_FS_RPATH && (sn[NSFLAG] & NS_DOT)) /* Cannot create dot entry */ + return FR_INVALID_NAME; + + if (sn[NSFLAG] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */ + fn[NSFLAG] = 0; dp->lfn = 0; /* Find only SFN */ + for (n = 1; n < 100; n++) { + gen_numname(fn, sn, lfn, n); /* Generate a numbered name */ + res = dir_find(dp); /* Check if the name collides with existing SFN */ + if (res != FR_OK) break; + } + if (n == 100) return FR_DENIED; /* Abort if too many collisions */ + if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */ + fn[NSFLAG] = sn[NSFLAG]; dp->lfn = lfn; + } + + if (sn[NSFLAG] & NS_LFN) { /* When LFN is to be created, allocate entries for an SFN + LFNs. */ + for (n = 0; lfn[n]; n++) ; + nent = (n + 25) / 13; + } else { /* Otherwise allocate an entry for an SFN */ + nent = 1; + } + res = dir_alloc(dp, nent); /* Allocate entries */ + + if (res == FR_OK && --nent) { /* Set LFN entry if needed */ + res = dir_sdi(dp, dp->index - nent); + if (res == FR_OK) { + sum = sum_sfn(dp->fn); /* Checksum value of the SFN tied to the LFN */ + do { /* Store LFN entries in bottom first */ + res = move_window(dp->fs, dp->sect); + if (res != FR_OK) break; + fit_lfn(dp->lfn, dp->dir, (BYTE)nent, sum); + dp->fs->wflag = 1; + res = dir_next(dp, 0); /* Next entry */ + } while (res == FR_OK && --nent); + } + } +#else /* Non LFN configuration */ + res = dir_alloc(dp, 1); /* Allocate an entry for SFN */ +#endif + + if (res == FR_OK) { /* Set SFN entry */ + res = move_window(dp->fs, dp->sect); + if (res == FR_OK) { + mem_set(dp->dir, 0, SZ_DIRE); /* Clean the entry */ + mem_cpy(dp->dir, dp->fn, 11); /* Put SFN */ +#if _USE_LFN + dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put NT flag */ +#endif + dp->fs->wflag = 1; + } + } + + return res; +} +#endif /* !_FS_READONLY */ + + + + +/*-----------------------------------------------------------------------*/ +/* Remove an object from the directory */ +/*-----------------------------------------------------------------------*/ +#if !_FS_READONLY && !_FS_MINIMIZE +static +FRESULT dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */ + FATFS_DIR* dp /* Directory object pointing the entry to be removed */ +) +{ + FRESULT res; +#if _USE_LFN /* LFN configuration */ + UINT i; + + i = dp->index; /* SFN index */ + res = dir_sdi(dp, (dp->lfn_idx == 0xFFFF) ? i : dp->lfn_idx); /* Goto the SFN or top of the LFN entries */ + if (res == FR_OK) { + do { + res = move_window(dp->fs, dp->sect); + if (res != FR_OK) break; + mem_set(dp->dir, 0, SZ_DIRE); /* Clear and mark the entry "deleted" */ + *dp->dir = DDEM; + dp->fs->wflag = 1; + if (dp->index >= i) break; /* When reached SFN, all entries of the object has been deleted. */ + res = dir_next(dp, 0); /* Next entry */ + } while (res == FR_OK); + if (res == FR_NO_FILE) res = FR_INT_ERR; + } + +#else /* Non LFN configuration */ + res = dir_sdi(dp, dp->index); + if (res == FR_OK) { + res = move_window(dp->fs, dp->sect); + if (res == FR_OK) { + mem_set(dp->dir, 0, SZ_DIRE); /* Clear and mark the entry "deleted" */ + *dp->dir = DDEM; + dp->fs->wflag = 1; + } + } +#endif + + return res; +} +#endif /* !_FS_READONLY */ + + + + +/*-----------------------------------------------------------------------*/ +/* Get file information from directory entry */ +/*-----------------------------------------------------------------------*/ +#if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 +static +void get_fileinfo ( /* No return code */ + FATFS_DIR* dp, /* Pointer to the directory object */ + FILINFO* fno /* Pointer to the file information to be filled */ +) +{ + UINT i; + TCHAR *p, c; + BYTE *dir; +#if _USE_LFN + WCHAR w, *lfn; +#endif + + p = fno->fname; + if (dp->sect) { /* Get SFN */ + dir = dp->dir; + i = 0; + while (i < 11) { /* Copy name body and extension */ + c = (TCHAR)dir[i++]; + if (c == ' ') continue; /* Skip padding spaces */ + if (c == RDDEM) c = (TCHAR)DDEM; /* Restore replaced DDEM character */ + if (i == 9) *p++ = '.'; /* Insert a . if extension is exist */ +#if _USE_LFN + if (IsUpper(c) && (dir[DIR_NTres] & (i >= 9 ? NS_EXT : NS_BODY))) + c += 0x20; /* To lower */ +#if _LFN_UNICODE + if (IsDBCS1(c) && i != 8 && i != 11 && IsDBCS2(dir[i])) + c = c << 8 | dir[i++]; + c = ff_convert(c, 1); /* OEM -> Unicode */ + if (!c) c = '?'; +#endif +#endif + *p++ = c; + } + fno->fattrib = dir[DIR_Attr]; /* Attribute */ + fno->fsize = LD_DWORD(dir + DIR_FileSize); /* Size */ + fno->fdate = LD_WORD(dir + DIR_WrtDate); /* Date */ + fno->ftime = LD_WORD(dir + DIR_WrtTime); /* Time */ + } + *p = 0; /* Terminate SFN string by a \0 */ + +#if _USE_LFN + if (fno->lfname) { + i = 0; p = fno->lfname; + if (dp->sect && fno->lfsize && dp->lfn_idx != 0xFFFF) { /* Get LFN if available */ + lfn = dp->lfn; + while ((w = *lfn++) != 0) { /* Get an LFN character */ +#if !_LFN_UNICODE + w = ff_convert(w, 0); /* Unicode -> OEM */ + if (!w) { i = 0; break; } /* No LFN if it could not be converted */ + if (_DF1S && w >= 0x100) /* Put 1st byte if it is a DBC (always false on SBCS cfg) */ + p[i++] = (TCHAR)(w >> 8); +#endif + if (i >= fno->lfsize - 1) { i = 0; break; } /* No LFN if buffer overflow */ + p[i++] = (TCHAR)w; + } + } + p[i] = 0; /* Terminate LFN string by a \0 */ + } +#endif +} +#endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */ + + + + +/*-----------------------------------------------------------------------*/ +/* Pattern matching */ +/*-----------------------------------------------------------------------*/ +#if _USE_FIND && _FS_MINIMIZE <= 1 +static +WCHAR get_achar ( /* Get a character and advances ptr 1 or 2 */ + const TCHAR** ptr /* Pointer to pointer to the SBCS/DBCS/Unicode string */ +) +{ + WCHAR chr; + +#if !_LFN_UNICODE + chr = (BYTE)*(*ptr)++; /* Get a byte */ + if (IsLower(chr)) chr -= 0x20; /* To upper ASCII char */ + if (IsDBCS1(chr) && IsDBCS2(**ptr)) /* Get DBC 2nd byte if needed */ + chr = chr << 8 | (BYTE)*(*ptr)++; +#ifdef _EXCVT + if (chr >= 0x80) chr = ExCvt[chr - 0x80]; /* To upper SBCS extended char */ +#endif +#else + chr = ff_wtoupper(*(*ptr)++); /* Get a word and to upper */ +#endif + return chr; +} + + +static +int pattern_matching ( /* 0:mismatched, 1:matched */ + const TCHAR* pat, /* Matching pattern */ + const TCHAR* nam, /* String to be tested */ + int skip, /* Number of pre-skip chars (number of ?s) */ + int inf /* Infinite search (* specified) */ +) +{ + const TCHAR *pp, *np; + WCHAR pc, nc; + int nm, nx; + + + while (skip--) { /* Pre-skip name chars */ + if (!get_achar(&nam)) return 0; /* Branch mismatched if less name chars */ + } + if (!*pat && inf) return 1; /* (short circuit) */ + + do { + pp = pat; np = nam; /* Top of pattern and name to match */ + for (;;) { + if (*pp == '?' || *pp == '*') { /* Wildcard? */ + nm = nx = 0; + do { /* Analyze the wildcard chars */ + if (*pp++ == '?') nm++; else nx = 1; + } while (*pp == '?' || *pp == '*'); + if (pattern_matching(pp, np, nm, nx)) return 1; /* Test new branch (recurs upto number of wildcard blocks in the pattern) */ + nc = *np; break; /* Branch mismatched */ + } + pc = get_achar(&pp); /* Get a pattern char */ + nc = get_achar(&np); /* Get a name char */ + if (pc != nc) break; /* Branch mismatched? */ + if (!pc) return 1; /* Branch matched? (matched at end of both strings) */ + } + get_achar(&nam); /* nam++ */ + } while (inf && nc); /* Retry until end of name if infinite search is specified */ + + return 0; +} +#endif /* _USE_FIND && _FS_MINIMIZE <= 1 */ + + + + +/*-----------------------------------------------------------------------*/ +/* Pick a top segment and create the object name in directory form */ +/*-----------------------------------------------------------------------*/ + +static +FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not create */ + FATFS_DIR* dp, /* Pointer to the directory object */ + const TCHAR** path /* Pointer to pointer to the segment in the path string */ +) +{ +#if _USE_LFN /* LFN configuration */ + BYTE b, cf; + WCHAR w, *lfn; + UINT i, ni, si, di; + const TCHAR *p; + + /* Create LFN in Unicode */ + for (p = *path; *p == '/' || *p == '\\'; p++) ; /* Strip duplicated separator */ + lfn = dp->lfn; + si = di = 0; + for (;;) { + w = p[si++]; /* Get a character */ + if (w < ' ' || w == '/' || w == '\\') break; /* Break on end of segment */ + if (di >= _MAX_LFN) /* Reject too long name */ + return FR_INVALID_NAME; +#if !_LFN_UNICODE + w &= 0xFF; + if (IsDBCS1(w)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */ + b = (BYTE)p[si++]; /* Get 2nd byte */ + w = (w << 8) + b; /* Create a DBC */ + if (!IsDBCS2(b)) + return FR_INVALID_NAME; /* Reject invalid sequence */ + } + w = ff_convert(w, 1); /* Convert ANSI/OEM to Unicode */ + if (!w) return FR_INVALID_NAME; /* Reject invalid code */ +#endif + if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) /* Reject illegal characters for LFN */ + return FR_INVALID_NAME; + lfn[di++] = w; /* Store the Unicode character */ + } + *path = &p[si]; /* Return pointer to the next segment */ + cf = (w < ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */ +#if _FS_RPATH + if ((di == 1 && lfn[di - 1] == '.') || + (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) { /* Is this segment a dot entry? */ + lfn[di] = 0; + for (i = 0; i < 11; i++) /* Create dot name for SFN entry */ + dp->fn[i] = (i < di) ? '.' : ' '; + dp->fn[i] = cf | NS_DOT; /* This is a dot entry */ + return FR_OK; + } +#endif + while (di) { /* Snip off trailing spaces and dots if exist */ + w = lfn[di - 1]; + if (w != ' ' && w != '.') break; + di--; + } + if (!di) return FR_INVALID_NAME; /* Reject nul string */ + lfn[di] = 0; /* LFN is created */ + + /* Create SFN in directory form */ + mem_set(dp->fn, ' ', 11); + for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ; /* Strip leading spaces and dots */ + if (si) cf |= NS_LOSS | NS_LFN; + while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */ + + b = i = 0; ni = 8; + for (;;) { + w = lfn[si++]; /* Get an LFN character */ + if (!w) break; /* Break on end of the LFN */ + if (w == ' ' || (w == '.' && si != di)) { /* Remove spaces and dots */ + cf |= NS_LOSS | NS_LFN; continue; + } + + if (i >= ni || si == di) { /* Extension or end of SFN */ + if (ni == 11) { /* Long extension */ + cf |= NS_LOSS | NS_LFN; break; + } + if (si != di) cf |= NS_LOSS | NS_LFN; /* Out of 8.3 format */ + if (si > di) break; /* No extension */ + si = di; i = 8; ni = 11; /* Enter extension section */ + b <<= 2; continue; + } + + if (w >= 0x80) { /* Non ASCII character */ +#ifdef _EXCVT + w = ff_convert(w, 0); /* Unicode -> OEM code */ + if (w) w = ExCvt[w - 0x80]; /* Convert extended character to upper (SBCS) */ +#else + w = ff_convert(ff_wtoupper(w), 0); /* Upper converted Unicode -> OEM code */ +#endif + cf |= NS_LFN; /* Force create LFN entry */ + } + + if (_DF1S && w >= 0x100) { /* Is this DBC? (always false at SBCS cfg) */ + if (i >= ni - 1) { + cf |= NS_LOSS | NS_LFN; i = ni; continue; + } + dp->fn[i++] = (BYTE)(w >> 8); + } else { /* SBC */ + if (!w || chk_chr("+,;=[]", w)) { /* Replace illegal characters for SFN */ + w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */ + } else { + if (IsUpper(w)) { /* ASCII large capital */ + b |= 2; + } else { + if (IsLower(w)) { /* ASCII small capital */ + b |= 1; w -= 0x20; + } + } + } + } + dp->fn[i++] = (BYTE)w; + } + + if (dp->fn[0] == DDEM) dp->fn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */ + + if (ni == 8) b <<= 2; + if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) /* Create LFN entry when there are composite capitals */ + cf |= NS_LFN; + if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended character, NT flags are created */ + if ((b & 0x03) == 0x01) cf |= NS_EXT; /* NT flag (Extension has only small capital) */ + if ((b & 0x0C) == 0x04) cf |= NS_BODY; /* NT flag (Filename has only small capital) */ + } + + dp->fn[NSFLAG] = cf; /* SFN is created */ + + return FR_OK; + + +#else /* Non-LFN configuration */ + BYTE b, c, d, *sfn; + UINT ni, si, i; + const char *p; + + /* Create file name in directory form */ + for (p = *path; *p == '/' || *p == '\\'; p++) ; /* Skip duplicated separator */ + sfn = dp->fn; + mem_set(sfn, ' ', 11); + si = i = b = 0; ni = 8; +#if _FS_RPATH + if (p[si] == '.') { /* Is this a dot entry? */ + for (;;) { + c = (BYTE)p[si++]; + if (c != '.' || si >= 3) break; + sfn[i++] = c; + } + if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME; + *path = &p[si]; /* Return pointer to the next segment */ + sfn[NSFLAG] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of path */ + return FR_OK; + } +#endif + for (;;) { + c = (BYTE)p[si++]; + if (c <= ' ' || c == '/' || c == '\\') break; /* Break on end of segment */ + if (c == '.' || i >= ni) { + if (ni != 8 || c != '.') return FR_INVALID_NAME; + i = 8; ni = 11; + b <<= 2; continue; + } + if (c >= 0x80) { /* Extended character? */ + b |= 3; /* Eliminate NT flag */ +#ifdef _EXCVT + c = ExCvt[c - 0x80]; /* To upper extended characters (SBCS cfg) */ +#else +#if !_DF1S + return FR_INVALID_NAME; /* Reject extended characters (ASCII cfg) */ +#endif +#endif + } + if (IsDBCS1(c)) { /* Check if it is a DBC 1st byte (always false at SBCS cfg.) */ + d = (BYTE)p[si++]; /* Get 2nd byte */ + if (!IsDBCS2(d) || i >= ni - 1) /* Reject invalid DBC */ + return FR_INVALID_NAME; + sfn[i++] = c; + sfn[i++] = d; + } else { /* SBC */ + if (chk_chr("\"*+,:;<=>\?[]|\x7F", c)) /* Reject illegal chrs for SFN */ + return FR_INVALID_NAME; + if (IsUpper(c)) { /* ASCII large capital? */ + b |= 2; + } else { + if (IsLower(c)) { /* ASCII small capital? */ + b |= 1; c -= 0x20; + } + } + sfn[i++] = c; + } + } + *path = &p[si]; /* Return pointer to the next segment */ + c = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */ + + if (!i) return FR_INVALID_NAME; /* Reject nul string */ + if (sfn[0] == DDEM) sfn[0] = RDDEM; /* When first character collides with DDEM, replace it with RDDEM */ + + if (ni == 8) b <<= 2; + if ((b & 0x03) == 0x01) c |= NS_EXT; /* NT flag (Name extension has only small capital) */ + if ((b & 0x0C) == 0x04) c |= NS_BODY; /* NT flag (Name body has only small capital) */ + + sfn[NSFLAG] = c; /* Store NT flag, File name is created */ + + return FR_OK; +#endif +} + + + + +/*-----------------------------------------------------------------------*/ +/* Follow a file path */ +/*-----------------------------------------------------------------------*/ + +static +FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */ + FATFS_DIR* dp, /* Directory object to return last directory and found object */ + const TCHAR* path /* Full-path string to find a file or directory */ +) +{ + FRESULT res; + BYTE *dir, ns; + + +#if _FS_RPATH + if (*path == '/' || *path == '\\') { /* There is a heading separator */ + path++; dp->sclust = 0; /* Strip it and start from the root directory */ + } else { /* No heading separator */ + dp->sclust = dp->fs->cdir; /* Start from the current directory */ + } +#else + if (*path == '/' || *path == '\\') /* Strip heading separator if exist */ + path++; + dp->sclust = 0; /* Always start from the root directory */ +#endif + + if ((UINT)*path < ' ') { /* Null path name is the origin directory itself */ + res = dir_sdi(dp, 0); + dp->dir = 0; + } else { /* Follow path */ + for (;;) { + res = create_name(dp, &path); /* Get a segment name of the path */ + if (res != FR_OK) break; + res = dir_find(dp); /* Find an object with the sagment name */ + ns = dp->fn[NSFLAG]; + if (res != FR_OK) { /* Failed to find the object */ + if (res == FR_NO_FILE) { /* Object is not found */ + if (_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exist, */ + dp->sclust = 0; dp->dir = 0; /* it is the root directory and stay there */ + if (!(ns & NS_LAST)) continue; /* Continue to follow if not last segment */ + res = FR_OK; /* Ended at the root directroy. Function completed. */ + } else { /* Could not find the object */ + if (!(ns & NS_LAST)) res = FR_NO_PATH; /* Adjust error code if not last segment */ + } + } + break; + } + if (ns & NS_LAST) break; /* Last segment matched. Function completed. */ + dir = dp->dir; /* Follow the sub-directory */ + if (!(dir[DIR_Attr] & AM_DIR)) { /* It is not a sub-directory and cannot follow */ + res = FR_NO_PATH; break; + } + dp->sclust = ld_clust(dp->fs, dir); + } + } + + return res; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Get logical drive number from path name */ +/*-----------------------------------------------------------------------*/ + +static +int get_ldnumber ( /* Returns logical drive number (-1:invalid drive) */ + const TCHAR** path /* Pointer to pointer to the path name */ +) +{ + const TCHAR *tp, *tt; + UINT i; + int vol = -1; +#if _STR_VOLUME_ID /* Find string drive id */ + static const char* const str[] = {_VOLUME_STRS}; + const char *sp; + char c; + TCHAR tc; +#endif + + + if (*path) { /* If the pointer is not a null */ + for (tt = *path; (UINT)*tt >= (_USE_LFN ? ' ' : '!') && *tt != ':'; tt++) ; /* Find ':' in the path */ + if (*tt == ':') { /* If a ':' is exist in the path name */ + tp = *path; + i = *tp++ - '0'; + if (i < 10 && tp == tt) { /* Is there a numeric drive id? */ + if (i < _VOLUMES) { /* If a drive id is found, get the value and strip it */ + vol = (int)i; + *path = ++tt; + } + } +#if _STR_VOLUME_ID + else { /* No numeric drive number, find string drive id */ + i = 0; tt++; + do { + sp = str[i]; tp = *path; + do { /* Compare a string drive id with path name */ + c = *sp++; tc = *tp++; + if (IsLower(tc)) tc -= 0x20; + } while (c && (TCHAR)c == tc); + } while ((c || tp != tt) && ++i < _VOLUMES); /* Repeat for each id until pattern match */ + if (i < _VOLUMES) { /* If a drive id is found, get the value and strip it */ + vol = (int)i; + *path = tt; + } + } +#endif + return vol; + } +#if _FS_RPATH && _VOLUMES >= 2 + vol = CurrVol; /* Current drive */ +#else + vol = 0; /* Drive 0 */ +#endif + } + return vol; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Load a sector and check if it is an FAT boot sector */ +/*-----------------------------------------------------------------------*/ + +static +BYTE check_fs ( /* 0:Valid FAT-BS, 1:Valid BS but not FAT, 2:Not a BS, 3:Disk error */ + FATFS* fs, /* File system object */ + DWORD sect /* Sector# (lba) to check if it is an FAT boot record or not */ +) +{ + fs->wflag = 0; fs->winsect = 0xFFFFFFFF; /* Invaidate window */ + if (move_window(fs, sect) != FR_OK) /* Load boot record */ + return 3; + + if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check boot record signature (always placed at offset 510 even if the sector size is >512) */ + return 2; + + if ((LD_DWORD(&fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */ + return 0; + if ((LD_DWORD(&fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */ + return 0; + + return 1; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Find logical drive and check if the volume is mounted */ +/*-----------------------------------------------------------------------*/ + +static +FRESULT find_volume ( /* FR_OK(0): successful, !=0: any error occurred */ + FATFS** rfs, /* Pointer to pointer to the found file system object */ + const TCHAR** path, /* Pointer to pointer to the path name (drive number) */ + BYTE wmode /* !=0: Check write protection for write access */ +) +{ + BYTE fmt, *pt; + int vol; + DSTATUS stat; + DWORD bsect, fasize, tsect, sysect, nclst, szbfat, br[4]; + WORD nrsv; + FATFS *fs; + UINT i; + + + /* Get logical drive number from the path name */ + *rfs = 0; + vol = get_ldnumber(path); + if (vol < 0) return FR_INVALID_DRIVE; + + /* Check if the file system object is valid or not */ + fs = FatFs[vol]; /* Get pointer to the file system object */ + if (!fs) return FR_NOT_ENABLED; /* Is the file system object available? */ + + ENTER_FF(fs); /* Lock the volume */ + *rfs = fs; /* Return pointer to the file system object */ + + if (fs->fs_type) { /* If the volume has been mounted */ + stat = disk_status(fs->drv); + if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized */ + if (!_FS_READONLY && wmode && (stat & STA_PROTECT)) /* Check write protection if needed */ + return FR_WRITE_PROTECTED; + return FR_OK; /* The file system object is valid */ + } + } + + /* The file system object is not valid. */ + /* Following code attempts to mount the volume. (analyze BPB and initialize the fs object) */ + + fs->fs_type = 0; /* Clear the file system object */ + fs->drv = LD2PD(vol); /* Bind the logical drive and a physical drive */ + stat = disk_initialize(fs->drv); /* Initialize the physical drive */ + if (stat & STA_NOINIT) /* Check if the initialization succeeded */ + return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */ + if (!_FS_READONLY && wmode && (stat & STA_PROTECT)) /* Check disk write protection if needed */ + return FR_WRITE_PROTECTED; +#if _MAX_SS != _MIN_SS /* Get sector size (multiple sector size cfg only) */ + if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK + || SS(fs) < _MIN_SS || SS(fs) > _MAX_SS) return FR_DISK_ERR; +#endif + /* Find an FAT partition on the drive. Supports only generic partitioning, FDISK and SFD. */ + bsect = 0; + fmt = check_fs(fs, bsect); /* Load sector 0 and check if it is an FAT boot sector as SFD */ + if (fmt == 1 || (!fmt && (LD2PT(vol)))) { /* Not an FAT boot sector or forced partition number */ + for (i = 0; i < 4; i++) { /* Get partition offset */ + pt = fs->win + MBR_Table + i * SZ_PTE; + br[i] = pt[4] ? LD_DWORD(&pt[8]) : 0; + } + i = LD2PT(vol); /* Partition number: 0:auto, 1-4:forced */ + if (i) i--; + do { /* Find an FAT volume */ + bsect = br[i]; + fmt = bsect ? check_fs(fs, bsect) : 2; /* Check the partition */ + } while (!LD2PT(vol) && fmt && ++i < 4); + } + if (fmt == 3) return FR_DISK_ERR; /* An error occured in the disk I/O layer */ + if (fmt) return FR_NO_FILESYSTEM; /* No FAT volume is found */ + + /* An FAT volume is found. Following code initializes the file system object */ + + if (LD_WORD(fs->win + BPB_BytsPerSec) != SS(fs)) /* (BPB_BytsPerSec must be equal to the physical sector size) */ + return FR_NO_FILESYSTEM; + + fasize = LD_WORD(fs->win + BPB_FATSz16); /* Number of sectors per FAT */ + if (!fasize) fasize = LD_DWORD(fs->win + BPB_FATSz32); + fs->fsize = fasize; + + fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FAT copies */ + if (fs->n_fats != 1 && fs->n_fats != 2) /* (Must be 1 or 2) */ + return FR_NO_FILESYSTEM; + fasize *= fs->n_fats; /* Number of sectors for FAT area */ + + fs->csize = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */ + if (!fs->csize || (fs->csize & (fs->csize - 1))) /* (Must be power of 2) */ + return FR_NO_FILESYSTEM; + + fs->n_rootdir = LD_WORD(fs->win + BPB_RootEntCnt); /* Number of root directory entries */ + if (fs->n_rootdir % (SS(fs) / SZ_DIRE)) /* (Must be sector aligned) */ + return FR_NO_FILESYSTEM; + + tsect = LD_WORD(fs->win + BPB_TotSec16); /* Number of sectors on the volume */ + if (!tsect) tsect = LD_DWORD(fs->win + BPB_TotSec32); + + nrsv = LD_WORD(fs->win + BPB_RsvdSecCnt); /* Number of reserved sectors */ + if (!nrsv) return FR_NO_FILESYSTEM; /* (Must not be 0) */ + + /* Determine the FAT sub type */ + sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZ_DIRE); /* RSV + FAT + FATFS_DIR */ + if (tsect < sysect) return FR_NO_FILESYSTEM; /* (Invalid volume size) */ + nclst = (tsect - sysect) / fs->csize; /* Number of clusters */ + if (!nclst) return FR_NO_FILESYSTEM; /* (Invalid volume size) */ + fmt = FS_FAT12; + if (nclst >= MIN_FAT16) fmt = FS_FAT16; + if (nclst >= MIN_FAT32) fmt = FS_FAT32; + + /* Boundaries and Limits */ + fs->n_fatent = nclst + 2; /* Number of FAT entries */ + fs->volbase = bsect; /* Volume start sector */ + fs->fatbase = bsect + nrsv; /* FAT start sector */ + fs->database = bsect + sysect; /* Data start sector */ + if (fmt == FS_FAT32) { + if (fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be 0) */ + fs->dirbase = LD_DWORD(fs->win + BPB_RootClus); /* Root directory start cluster */ + szbfat = fs->n_fatent * 4; /* (Needed FAT size) */ + } else { + if (!fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must not be 0) */ + fs->dirbase = fs->fatbase + fasize; /* Root directory start sector */ + szbfat = (fmt == FS_FAT16) ? /* (Needed FAT size) */ + fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1); + } + if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) /* (BPB_FATSz must not be less than the size needed) */ + return FR_NO_FILESYSTEM; + +#if !_FS_READONLY + /* Initialize cluster allocation information */ + fs->last_clust = fs->free_clust = 0xFFFFFFFF; + + /* Get fsinfo if available */ + fs->fsi_flag = 0x80; +#if (_FS_NOFSINFO & 3) != 3 + if (fmt == FS_FAT32 /* Enable FSINFO only if FAT32 and BPB_FSInfo == 1 */ + && LD_WORD(fs->win + BPB_FSInfo) == 1 + && move_window(fs, bsect + 1) == FR_OK) + { + fs->fsi_flag = 0; + if (LD_WORD(fs->win + BS_55AA) == 0xAA55 /* Load FSINFO data if available */ + && LD_DWORD(fs->win + FSI_LeadSig) == 0x41615252 + && LD_DWORD(fs->win + FSI_StrucSig) == 0x61417272) + { +#if (_FS_NOFSINFO & 1) == 0 + fs->free_clust = LD_DWORD(fs->win + FSI_Free_Count); +#endif +#if (_FS_NOFSINFO & 2) == 0 + fs->last_clust = LD_DWORD(fs->win + FSI_Nxt_Free); +#endif + } + } +#endif +#endif + fs->fs_type = fmt; /* FAT sub-type */ + fs->id = ++Fsid; /* File system mount ID */ +#if _FS_RPATH + fs->cdir = 0; /* Set current directory to root */ +#endif +#if _FS_LOCK /* Clear file lock semaphores */ + clear_lock(fs); +#endif + + return FR_OK; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Check if the file/directory object is valid or not */ +/*-----------------------------------------------------------------------*/ + +static +FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */ + void* obj /* Pointer to the object FIL/FATFS_DIR to check validity */ +) +{ + FIL *fil = (FIL*)obj; /* Assuming offset of .fs and .id in the FIL/FATFS_DIR structure is identical */ + + + if (!fil || !fil->fs || !fil->fs->fs_type || fil->fs->id != fil->id || (disk_status(fil->fs->drv) & STA_NOINIT)) + return FR_INVALID_OBJECT; + + ENTER_FF(fil->fs); /* Lock file system */ + + return FR_OK; +} + + + + +/*-------------------------------------------------------------------------- + + Public Functions + +---------------------------------------------------------------------------*/ + + + +/*-----------------------------------------------------------------------*/ +/* Mount/Unmount a Logical Drive */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_mount ( + FATFS* fs, /* Pointer to the file system object (NULL:unmount)*/ + const TCHAR* path, /* Logical drive number to be mounted/unmounted */ + BYTE opt /* 0:Do not mount (delayed mount), 1:Mount immediately */ +) +{ + FATFS *cfs; + int vol; + FRESULT res; + const TCHAR *rp = path; + + + vol = get_ldnumber(&rp); + if (vol < 0) return FR_INVALID_DRIVE; + cfs = FatFs[vol]; /* Pointer to fs object */ + + if (cfs) { +#if _FS_LOCK + clear_lock(cfs); +#endif +#if _FS_REENTRANT /* Discard sync object of the current volume */ + if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR; +#endif + cfs->fs_type = 0; /* Clear old fs object */ + } + + if (fs) { + fs->fs_type = 0; /* Clear new fs object */ +#if _FS_REENTRANT /* Create sync object for the new volume */ + if (!ff_cre_syncobj((BYTE)vol, &fs->sobj)) return FR_INT_ERR; +#endif + } + FatFs[vol] = fs; /* Register new fs object */ + + if (!fs || opt != 1) return FR_OK; /* Do not mount now, it will be mounted later */ + + res = find_volume(&fs, &path, 0); /* Force mounted the volume */ + LEAVE_FF(fs, res); +} + + + + +/*-----------------------------------------------------------------------*/ +/* Open or Create a File */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_open ( + FIL* fp, /* Pointer to the blank file object */ + const TCHAR* path, /* Pointer to the file name */ + BYTE mode /* Access mode and file open mode flags */ +) +{ + FRESULT res; + FATFS_DIR dj; + BYTE *dir; + DEFINE_NAMEBUF; +#if !_FS_READONLY + DWORD dw, cl; +#endif + + + if (!fp) return FR_INVALID_OBJECT; + fp->fs = 0; /* Clear file object */ + + /* Get logical drive number */ +#if !_FS_READONLY + mode &= FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW; + res = find_volume(&dj.fs, &path, (BYTE)(mode & ~FA_READ)); +#else + mode &= FA_READ; + res = find_volume(&dj.fs, &path, 0); +#endif + if (res == FR_OK) { + INIT_BUF(dj); + res = follow_path(&dj, path); /* Follow the file path */ + dir = dj.dir; +#if !_FS_READONLY /* R/W configuration */ + if (res == FR_OK) { + if (!dir) /* Default directory itself */ + res = FR_INVALID_NAME; +#if _FS_LOCK + else + res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0); +#endif + } + /* Create or Open a file */ + if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) { + if (res != FR_OK) { /* No file, create new */ + if (res == FR_NO_FILE) /* There is no file to open, create a new entry */ +#if _FS_LOCK + res = enq_lock() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES; +#else + res = dir_register(&dj); +#endif + mode |= FA_CREATE_ALWAYS; /* File is created */ + dir = dj.dir; /* New entry */ + } + else { /* Any object is already existing */ + if (dir[DIR_Attr] & (AM_RDO | AM_DIR)) { /* Cannot overwrite it (R/O or FATFS_DIR) */ + res = FR_DENIED; + } else { + if (mode & FA_CREATE_NEW) /* Cannot create as new file */ + res = FR_EXIST; + } + } + if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate it if overwrite mode */ + dw = GET_FATTIME(); + ST_DWORD(dir + DIR_CrtTime, dw);/* Set created time */ + ST_DWORD(dir + DIR_WrtTime, dw);/* Set modified time */ + dir[DIR_Attr] = 0; /* Reset attribute */ + ST_DWORD(dir + DIR_FileSize, 0);/* Reset file size */ + cl = ld_clust(dj.fs, dir); /* Get cluster chain */ + st_clust(dir, 0); /* Reset cluster */ + dj.fs->wflag = 1; + if (cl) { /* Remove the cluster chain if exist */ + dw = dj.fs->winsect; + res = remove_chain(dj.fs, cl); + if (res == FR_OK) { + dj.fs->last_clust = cl - 1; /* Reuse the cluster hole */ + res = move_window(dj.fs, dw); + } + } + } + } + else { /* Open an existing file */ + if (res == FR_OK) { /* Following succeeded */ + if (dir[DIR_Attr] & AM_DIR) { /* It is a directory */ + res = FR_NO_FILE; + } else { + if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */ + res = FR_DENIED; + } + } + } + if (res == FR_OK) { + if (mode & FA_CREATE_ALWAYS) /* Set file change flag if created or overwritten */ + mode |= FA__WRITTEN; + fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */ + fp->dir_ptr = dir; +#if _FS_LOCK + fp->lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0); + if (!fp->lockid) res = FR_INT_ERR; +#endif + } + +#else /* R/O configuration */ + if (res == FR_OK) { /* Follow succeeded */ + dir = dj.dir; + if (!dir) { /* Current directory itself */ + res = FR_INVALID_NAME; + } else { + if (dir[DIR_Attr] & AM_DIR) /* It is a directory */ + res = FR_NO_FILE; + } + } +#endif + FREE_BUF(); + + if (res == FR_OK) { + fp->flag = mode; /* File access mode */ + fp->err = 0; /* Clear error flag */ + fp->sclust = ld_clust(dj.fs, dir); /* File start cluster */ + fp->fsize = LD_DWORD(dir + DIR_FileSize); /* File size */ + fp->fptr = 0; /* File pointer */ + fp->dsect = 0; +#if _USE_FASTSEEK + fp->cltbl = 0; /* Normal seek mode */ +#endif + fp->fs = dj.fs; /* Validate file object */ + fp->id = fp->fs->id; + } + } + + LEAVE_FF(dj.fs, res); +} + + + + +/*-----------------------------------------------------------------------*/ +/* Read File */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_read ( + FIL* fp, /* Pointer to the file object */ + void* buff, /* Pointer to data buffer */ + UINT btr, /* Number of bytes to read */ + UINT* br /* Pointer to number of bytes read */ +) +{ + FRESULT res; + DWORD clst, sect, remain; + UINT rcnt, cc; + BYTE csect, *rbuff = (BYTE*)buff; + + + *br = 0; /* Clear read byte counter */ + + res = validate(fp); /* Check validity */ + if (res != FR_OK) LEAVE_FF(fp->fs, res); + if (fp->err) /* Check error */ + LEAVE_FF(fp->fs, (FRESULT)fp->err); + if (!(fp->flag & FA_READ)) /* Check access mode */ + LEAVE_FF(fp->fs, FR_DENIED); + remain = fp->fsize - fp->fptr; + if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */ + + for ( ; btr; /* Repeat until all data read */ + rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) { + if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */ + csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */ + if (!csect) { /* On the cluster boundary? */ + if (fp->fptr == 0) { /* On the top of the file? */ + clst = fp->sclust; /* Follow from the origin */ + } else { /* Middle or end of the file */ +#if _USE_FASTSEEK + if (fp->cltbl) + clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */ + else +#endif + clst = get_fat(fp->fs, fp->clust); /* Follow cluster chain on the FAT */ + } + if (clst < 2) ABORT(fp->fs, FR_INT_ERR); + if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR); + fp->clust = clst; /* Update current cluster */ + } + sect = clust2sect(fp->fs, fp->clust); /* Get current sector */ + if (!sect) ABORT(fp->fs, FR_INT_ERR); + sect += csect; + cc = btr / SS(fp->fs); /* When remaining bytes >= sector size, */ + if (cc) { /* Read maximum contiguous sectors directly */ + if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */ + cc = fp->fs->csize - csect; + if (disk_read(fp->fs->drv, rbuff, sect, cc) != RES_OK) + ABORT(fp->fs, FR_DISK_ERR); +#if !_FS_READONLY && _FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */ +#if _FS_TINY + if (fp->fs->wflag && fp->fs->winsect - sect < cc) + mem_cpy(rbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), fp->fs->win, SS(fp->fs)); +#else + if ((fp->flag & FA__DIRTY) && fp->dsect - sect < cc) + mem_cpy(rbuff + ((fp->dsect - sect) * SS(fp->fs)), fp->buf, SS(fp->fs)); +#endif +#endif + rcnt = SS(fp->fs) * cc; /* Number of bytes transferred */ + continue; + } +#if !_FS_TINY + if (fp->dsect != sect) { /* Load data sector if not in cache */ +#if !_FS_READONLY + if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */ + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) + ABORT(fp->fs, FR_DISK_ERR); + fp->flag &= ~FA__DIRTY; + } +#endif + if (disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK) /* Fill sector cache */ + ABORT(fp->fs, FR_DISK_ERR); + } +#endif + fp->dsect = sect; + } + rcnt = SS(fp->fs) - ((UINT)fp->fptr % SS(fp->fs)); /* Get partial sector data from sector buffer */ + if (rcnt > btr) rcnt = btr; +#if _FS_TINY + if (move_window(fp->fs, fp->dsect) != FR_OK) /* Move sector window */ + ABORT(fp->fs, FR_DISK_ERR); + mem_cpy(rbuff, &fp->fs->win[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */ +#else + mem_cpy(rbuff, &fp->buf[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */ +#endif + } + + LEAVE_FF(fp->fs, FR_OK); +} + + + + +#if !_FS_READONLY +/*-----------------------------------------------------------------------*/ +/* Write File */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_write ( + FIL* fp, /* Pointer to the file object */ + const void *buff, /* Pointer to the data to be written */ + UINT btw, /* Number of bytes to write */ + UINT* bw /* Pointer to number of bytes written */ +) +{ + FRESULT res; + DWORD clst, sect; + UINT wcnt, cc; + const BYTE *wbuff = (const BYTE*)buff; + BYTE csect; + bool need_sync = false; + + *bw = 0; /* Clear write byte counter */ + + res = validate(fp); /* Check validity */ + if (res != FR_OK) LEAVE_FF(fp->fs, res); + if (fp->err) /* Check error */ + LEAVE_FF(fp->fs, (FRESULT)fp->err); + if (!(fp->flag & FA_WRITE)) /* Check access mode */ + LEAVE_FF(fp->fs, FR_DENIED); + if (fp->fptr + btw < fp->fptr) btw = 0; /* File size cannot reach 4GB */ + + for ( ; btw; /* Repeat until all data written */ + wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) { + if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */ + csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */ + if (!csect) { /* On the cluster boundary? */ + if (fp->fptr == 0) { /* On the top of the file? */ + clst = fp->sclust; /* Follow from the origin */ + if (clst == 0) /* When no cluster is allocated, */ + clst = create_chain(fp->fs, 0); /* Create a new cluster chain */ + } else { /* Middle or end of the file */ +#if _USE_FASTSEEK + if (fp->cltbl) + clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */ + else +#endif + clst = create_chain(fp->fs, fp->clust); /* Follow or stretch cluster chain on the FAT */ + } + if (clst == 0) break; /* Could not allocate a new cluster (disk full) */ + if (clst == 1) ABORT(fp->fs, FR_INT_ERR); + if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR); + fp->clust = clst; /* Update current cluster */ + if (fp->sclust == 0) fp->sclust = clst; /* Set start cluster if the first write */ + +#if FLUSH_ON_NEW_CLUSTER + // We do not need to flush for the first cluster + if (fp->fptr != 0) { + need_sync = true; + } +#endif + } +#if _FS_TINY + if (fp->fs->winsect == fp->dsect && sync_window(fp->fs)) /* Write-back sector cache */ + ABORT(fp->fs, FR_DISK_ERR); +#else + if (fp->flag & FA__DIRTY) { /* Write-back sector cache */ + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) + ABORT(fp->fs, FR_DISK_ERR); + fp->flag &= ~FA__DIRTY; + } +#endif + sect = clust2sect(fp->fs, fp->clust); /* Get current sector */ + if (!sect) ABORT(fp->fs, FR_INT_ERR); + sect += csect; + cc = btw / SS(fp->fs); /* When remaining bytes >= sector size, */ + if (cc) { /* Write maximum contiguous sectors directly */ + if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */ + cc = fp->fs->csize - csect; + if (disk_write(fp->fs->drv, wbuff, sect, cc) != RES_OK) + ABORT(fp->fs, FR_DISK_ERR); +#if _FS_MINIMIZE <= 2 +#if _FS_TINY + if (fp->fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */ + mem_cpy(fp->fs->win, wbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), SS(fp->fs)); + fp->fs->wflag = 0; + } +#else + if (fp->dsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */ + mem_cpy(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs)); + fp->flag &= ~FA__DIRTY; + } +#endif +#endif + wcnt = SS(fp->fs) * cc; /* Number of bytes transferred */ +#if FLUSH_ON_NEW_SECTOR + need_sync = true; +#endif + continue; + } +#if _FS_TINY + if (fp->fptr >= fp->fsize) { /* Avoid silly cache filling at growing edge */ + if (sync_window(fp->fs)) ABORT(fp->fs, FR_DISK_ERR); + fp->fs->winsect = sect; + } +#else + if (fp->dsect != sect) { /* Fill sector cache with file data */ + if (fp->fptr < fp->fsize && + disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK) + ABORT(fp->fs, FR_DISK_ERR); + } +#endif + fp->dsect = sect; + } + wcnt = SS(fp->fs) - ((UINT)fp->fptr % SS(fp->fs));/* Put partial sector into file I/O buffer */ + if (wcnt > btw) wcnt = btw; +#if _FS_TINY + if (move_window(fp->fs, fp->dsect) != FR_OK) /* Move sector window */ + ABORT(fp->fs, FR_DISK_ERR); + mem_cpy(&fp->fs->win[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */ + fp->fs->wflag = 1; +#else + mem_cpy(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */ + fp->flag |= FA__DIRTY; +#endif + } + + if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */ + fp->flag |= FA__WRITTEN; /* Set file change flag */ + + if (need_sync) { + f_sync (fp); + } + + LEAVE_FF(fp->fs, FR_OK); +} + + + + +/*-----------------------------------------------------------------------*/ +/* Synchronize the File */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_sync ( + FIL* fp /* Pointer to the file object */ +) +{ + FRESULT res; + DWORD tm; + BYTE *dir; + + + res = validate(fp); /* Check validity of the object */ + if (res == FR_OK) { + if (fp->flag & FA__WRITTEN) { /* Is there any change to the file? */ +#if !_FS_TINY + if (fp->flag & FA__DIRTY) { /* Write-back cached data if needed */ + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) + LEAVE_FF(fp->fs, FR_DISK_ERR); + fp->flag &= ~FA__DIRTY; + } +#endif + /* Update the directory entry */ + res = move_window(fp->fs, fp->dir_sect); + if (res == FR_OK) { + dir = fp->dir_ptr; + dir[DIR_Attr] |= AM_ARC; /* Set archive bit */ + ST_DWORD(dir + DIR_FileSize, fp->fsize); /* Update file size */ + st_clust(dir, fp->sclust); /* Update start cluster */ + tm = GET_FATTIME(); /* Update modified time */ + ST_DWORD(dir + DIR_WrtTime, tm); + ST_WORD(dir + DIR_LstAccDate, 0); + fp->flag &= ~FA__WRITTEN; + fp->fs->wflag = 1; + res = sync_fs(fp->fs); + } + } + } + + LEAVE_FF(fp->fs, res); +} + +#endif /* !_FS_READONLY */ + + + + +/*-----------------------------------------------------------------------*/ +/* Close File */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_close ( + FIL *fp /* Pointer to the file object to be closed */ +) +{ + FRESULT res; + + +#if !_FS_READONLY + res = f_sync(fp); /* Flush cached data */ + if (res == FR_OK) +#endif + { + res = validate(fp); /* Lock volume */ + if (res == FR_OK) { +#if _FS_REENTRANT + FATFS *fs = fp->fs; +#endif +#if _FS_LOCK + res = dec_lock(fp->lockid); /* Decrement file open counter */ + if (res == FR_OK) +#endif + fp->fs = 0; /* Invalidate file object */ +#if _FS_REENTRANT + unlock_fs(fs, FR_OK); /* Unlock volume */ +#endif + } + } + return res; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Change Current Directory or Current Drive, Get Current Directory */ +/*-----------------------------------------------------------------------*/ + +#if _FS_RPATH >= 1 +#if _VOLUMES >= 2 +FRESULT f_chdrive ( + const TCHAR* path /* Drive number */ +) +{ + int vol; + + + vol = get_ldnumber(&path); + if (vol < 0) return FR_INVALID_DRIVE; + + CurrVol = (BYTE)vol; + + return FR_OK; +} +#endif + + +FRESULT f_chdir ( + const TCHAR* path /* Pointer to the directory path */ +) +{ + FRESULT res; + FATFS_DIR dj; + DEFINE_NAMEBUF; + + + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 0); + if (res == FR_OK) { + INIT_BUF(dj); + res = follow_path(&dj, path); /* Follow the path */ + FREE_BUF(); + if (res == FR_OK) { /* Follow completed */ + if (!dj.dir) { + dj.fs->cdir = dj.sclust; /* Start directory itself */ + } else { + if (dj.dir[DIR_Attr] & AM_DIR) /* Reached to the directory */ + dj.fs->cdir = ld_clust(dj.fs, dj.dir); + else + res = FR_NO_PATH; /* Reached but a file */ + } + } + if (res == FR_NO_FILE) res = FR_NO_PATH; + } + + LEAVE_FF(dj.fs, res); +} + + +#if _FS_RPATH >= 2 +FRESULT f_getcwd ( + TCHAR* buff, /* Pointer to the directory path */ + UINT len /* Size of path */ +) +{ + FRESULT res; + FATFS_DIR dj; + UINT i, n; + DWORD ccl; + TCHAR *tp; + FILINFO fno; + DEFINE_NAMEBUF; + + + *buff = 0; + /* Get logical drive number */ + res = find_volume(&dj.fs, (const TCHAR**)&buff, 0); /* Get current volume */ + if (res == FR_OK) { + INIT_BUF(dj); + i = len; /* Bottom of buffer (directory stack base) */ + dj.sclust = dj.fs->cdir; /* Start to follow upper directory from current directory */ + while ((ccl = dj.sclust) != 0) { /* Repeat while current directory is a sub-directory */ + res = dir_sdi(&dj, 1); /* Get parent directory */ + if (res != FR_OK) break; + res = dir_read(&dj, 0); + if (res != FR_OK) break; + dj.sclust = ld_clust(dj.fs, dj.dir); /* Goto parent directory */ + res = dir_sdi(&dj, 0); + if (res != FR_OK) break; + do { /* Find the entry links to the child directory */ + res = dir_read(&dj, 0); + if (res != FR_OK) break; + if (ccl == ld_clust(dj.fs, dj.dir)) break; /* Found the entry */ + res = dir_next(&dj, 0); + } while (res == FR_OK); + if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */ + if (res != FR_OK) break; +#if _USE_LFN + fno.lfname = buff; + fno.lfsize = i; +#endif + get_fileinfo(&dj, &fno); /* Get the directory name and push it to the buffer */ + tp = fno.fname; +#if _USE_LFN + if (*buff) tp = buff; +#endif + for (n = 0; tp[n]; n++) ; + if (i < n + 3) { + res = FR_NOT_ENOUGH_CORE; break; + } + while (n) buff[--i] = tp[--n]; + buff[--i] = '/'; + } + tp = buff; + if (res == FR_OK) { +#if _VOLUMES >= 2 + *tp++ = '0' + CurrVol; /* Put drive number */ + *tp++ = ':'; +#endif + if (i == len) { /* Root-directory */ + *tp++ = '/'; + } else { /* Sub-directroy */ + do /* Add stacked path str */ + *tp++ = buff[i++]; + while (i < len); + } + } + *tp = 0; + FREE_BUF(); + } + + LEAVE_FF(dj.fs, res); +} +#endif /* _FS_RPATH >= 2 */ +#endif /* _FS_RPATH >= 1 */ + + + +#if _FS_MINIMIZE <= 2 +/*-----------------------------------------------------------------------*/ +/* Seek File R/W Pointer */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_lseek ( + FIL* fp, /* Pointer to the file object */ + DWORD ofs /* File pointer from top of file */ +) +{ + FRESULT res; + DWORD clst, bcs, nsect, ifptr; +#if _USE_FASTSEEK + DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl; +#endif + + + res = validate(fp); /* Check validity of the object */ + if (res != FR_OK) LEAVE_FF(fp->fs, res); + if (fp->err) /* Check error */ + LEAVE_FF(fp->fs, (FRESULT)fp->err); + +#if _USE_FASTSEEK + if (fp->cltbl) { /* Fast seek */ + if (ofs == CREATE_LINKMAP) { /* Create CLMT */ + tbl = fp->cltbl; + tlen = *tbl++; ulen = 2; /* Given table size and required table size */ + cl = fp->sclust; /* Top of the chain */ + if (cl) { + do { + /* Get a fragment */ + tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */ + do { + pcl = cl; ncl++; + cl = get_fat(fp->fs, cl); + if (cl <= 1) ABORT(fp->fs, FR_INT_ERR); + if (cl == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR); + } while (cl == pcl + 1); + if (ulen <= tlen) { /* Store the length and top of the fragment */ + *tbl++ = ncl; *tbl++ = tcl; + } + } while (cl < fp->fs->n_fatent); /* Repeat until end of chain */ + } + *fp->cltbl = ulen; /* Number of items used */ + if (ulen <= tlen) + *tbl = 0; /* Terminate table */ + else + res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */ + + } else { /* Fast seek */ + if (ofs > fp->fsize) /* Clip offset at the file size */ + ofs = fp->fsize; + fp->fptr = ofs; /* Set file pointer */ + if (ofs) { + fp->clust = clmt_clust(fp, ofs - 1); + dsc = clust2sect(fp->fs, fp->clust); + if (!dsc) ABORT(fp->fs, FR_INT_ERR); + dsc += (ofs - 1) / SS(fp->fs) & (fp->fs->csize - 1); + if (fp->fptr % SS(fp->fs) && dsc != fp->dsect) { /* Refill sector cache if needed */ +#if !_FS_TINY +#if !_FS_READONLY + if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */ + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) + ABORT(fp->fs, FR_DISK_ERR); + fp->flag &= ~FA__DIRTY; + } +#endif + if (disk_read(fp->fs->drv, fp->buf, dsc, 1) != RES_OK) /* Load current sector */ + ABORT(fp->fs, FR_DISK_ERR); +#endif + fp->dsect = dsc; + } + } + } + } else +#endif + + /* Normal Seek */ + { + if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */ +#if !_FS_READONLY + && !(fp->flag & FA_WRITE) +#endif + ) ofs = fp->fsize; + + ifptr = fp->fptr; + fp->fptr = nsect = 0; + if (ofs) { + bcs = (DWORD)fp->fs->csize * SS(fp->fs); /* Cluster size (byte) */ + if (ifptr > 0 && + (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */ + fp->fptr = (ifptr - 1) & ~(bcs - 1); /* start from the current cluster */ + ofs -= fp->fptr; + clst = fp->clust; + } else { /* When seek to back cluster, */ + clst = fp->sclust; /* start from the first cluster */ +#if !_FS_READONLY + if (clst == 0) { /* If no cluster chain, create a new chain */ + clst = create_chain(fp->fs, 0); + if (clst == 1) ABORT(fp->fs, FR_INT_ERR); + if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR); + fp->sclust = clst; + } +#endif + fp->clust = clst; + } + if (clst != 0) { + while (ofs > bcs) { /* Cluster following loop */ +#if !_FS_READONLY + if (fp->flag & FA_WRITE) { /* Check if in write mode or not */ + clst = create_chain(fp->fs, clst); /* Force stretch if in write mode */ + if (clst == 0) { /* When disk gets full, clip file size */ + ofs = bcs; break; + } + } else +#endif + clst = get_fat(fp->fs, clst); /* Follow cluster chain if not in write mode */ + if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR); + if (clst <= 1 || clst >= fp->fs->n_fatent) ABORT(fp->fs, FR_INT_ERR); + fp->clust = clst; + fp->fptr += bcs; + ofs -= bcs; + } + fp->fptr += ofs; + if (ofs % SS(fp->fs)) { + nsect = clust2sect(fp->fs, clst); /* Current sector */ + if (!nsect) ABORT(fp->fs, FR_INT_ERR); + nsect += ofs / SS(fp->fs); + } + } + } + if (fp->fptr % SS(fp->fs) && nsect != fp->dsect) { /* Fill sector cache if needed */ +#if !_FS_TINY +#if !_FS_READONLY + if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */ + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) + ABORT(fp->fs, FR_DISK_ERR); + fp->flag &= ~FA__DIRTY; + } +#endif + if (disk_read(fp->fs->drv, fp->buf, nsect, 1) != RES_OK) /* Fill sector cache */ + ABORT(fp->fs, FR_DISK_ERR); +#endif + fp->dsect = nsect; + } +#if !_FS_READONLY + if (fp->fptr > fp->fsize) { /* Set file change flag if the file size is extended */ + fp->fsize = fp->fptr; + fp->flag |= FA__WRITTEN; + } +#endif + } + + LEAVE_FF(fp->fs, res); +} + + + +#if _FS_MINIMIZE <= 1 +/*-----------------------------------------------------------------------*/ +/* Create a Directory Object */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_opendir ( + FATFS_DIR* dp, /* Pointer to directory object to create */ + const TCHAR* path /* Pointer to the directory path */ +) +{ + FRESULT res; + FATFS* fs; + DEFINE_NAMEBUF; + + + if (!dp) return FR_INVALID_OBJECT; + + /* Get logical drive number */ + res = find_volume(&fs, &path, 0); + if (res == FR_OK) { + dp->fs = fs; + INIT_BUF(*dp); + res = follow_path(dp, path); /* Follow the path to the directory */ + FREE_BUF(); + if (res == FR_OK) { /* Follow completed */ + if (dp->dir) { /* It is not the origin directory itself */ + if (dp->dir[DIR_Attr] & AM_DIR) /* The object is a sub directory */ + dp->sclust = ld_clust(fs, dp->dir); + else /* The object is a file */ + res = FR_NO_PATH; + } + if (res == FR_OK) { + dp->id = fs->id; + res = dir_sdi(dp, 0); /* Rewind directory */ +#if _FS_LOCK + if (res == FR_OK) { + if (dp->sclust) { + dp->lockid = inc_lock(dp, 0); /* Lock the sub directory */ + if (!dp->lockid) + res = FR_TOO_MANY_OPEN_FILES; + } else { + dp->lockid = 0; /* Root directory need not to be locked */ + } + } +#endif + } + } + if (res == FR_NO_FILE) res = FR_NO_PATH; + } + if (res != FR_OK) dp->fs = 0; /* Invalidate the directory object if function faild */ + + LEAVE_FF(fs, res); +} + + + + +/*-----------------------------------------------------------------------*/ +/* Close Directory */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_closedir ( + FATFS_DIR *dp /* Pointer to the directory object to be closed */ +) +{ + FRESULT res; + + + res = validate(dp); + if (res == FR_OK) { +#if _FS_REENTRANT + FATFS *fs = dp->fs; +#endif +#if _FS_LOCK + if (dp->lockid) /* Decrement sub-directory open counter */ + res = dec_lock(dp->lockid); + if (res == FR_OK) +#endif + dp->fs = 0; /* Invalidate directory object */ +#if _FS_REENTRANT + unlock_fs(fs, FR_OK); /* Unlock volume */ +#endif + } + return res; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Read Directory Entries in Sequence */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_readdir ( + FATFS_DIR* dp, /* Pointer to the open directory object */ + FILINFO* fno /* Pointer to file information to return */ +) +{ + FRESULT res; + DEFINE_NAMEBUF; + + + res = validate(dp); /* Check validity of the object */ + if (res == FR_OK) { + if (!fno) { + res = dir_sdi(dp, 0); /* Rewind the directory object */ + } else { + INIT_BUF(*dp); + res = dir_read(dp, 0); /* Read an item */ + if (res == FR_NO_FILE) { /* Reached end of directory */ + dp->sect = 0; + res = FR_OK; + } + if (res == FR_OK) { /* A valid entry is found */ + get_fileinfo(dp, fno); /* Get the object information */ + res = dir_next(dp, 0); /* Increment index for next */ + if (res == FR_NO_FILE) { + dp->sect = 0; + res = FR_OK; + } + } + FREE_BUF(); + } + } + + LEAVE_FF(dp->fs, res); +} + + + +#if _USE_FIND +/*-----------------------------------------------------------------------*/ +/* Find next file */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_findnext ( + FATFS_DIR* dp, /* Pointer to the open directory object */ + FILINFO* fno /* Pointer to the file information structure */ +) +{ + FRESULT res; + + + for (;;) { + res = f_readdir(dp, fno); /* Get a directory item */ + if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */ +#if _USE_LFN + if (fno->lfname && pattern_matching(dp->pat, fno->lfname, 0, 0)) break; /* Test for LFN if exist */ +#endif + if (pattern_matching(dp->pat, fno->fname, 0, 0)) break; /* Test for SFN */ + } + return res; + +} + + + +/*-----------------------------------------------------------------------*/ +/* Find first file */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_findfirst ( + FATFS_DIR* dp, /* Pointer to the blank directory object */ + FILINFO* fno, /* Pointer to the file information structure */ + const TCHAR* path, /* Pointer to the directory to open */ + const TCHAR* pattern /* Pointer to the matching pattern */ +) +{ + FRESULT res; + + + dp->pat = pattern; /* Save pointer to pattern string */ + res = f_opendir(dp, path); /* Open the target directory */ + if (res == FR_OK) + res = f_findnext(dp, fno); /* Find the first item */ + return res; +} + +#endif /* _USE_FIND */ + + + +#if _FS_MINIMIZE == 0 +/*-----------------------------------------------------------------------*/ +/* Get File Status */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_stat ( + const TCHAR* path, /* Pointer to the file path */ + FILINFO* fno /* Pointer to file information to return */ +) +{ + FRESULT res; + FATFS_DIR dj; + DEFINE_NAMEBUF; + + + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 0); + if (res == FR_OK) { + INIT_BUF(dj); + res = follow_path(&dj, path); /* Follow the file path */ + if (res == FR_OK) { /* Follow completed */ + if (dj.dir) { /* Found an object */ + if (fno) get_fileinfo(&dj, fno); + } else { /* It is root directory */ + res = FR_INVALID_NAME; + } + } + FREE_BUF(); + } + + LEAVE_FF(dj.fs, res); +} + + + +#if !_FS_READONLY +/*-----------------------------------------------------------------------*/ +/* Get Number of Free Clusters */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_getfree ( + const TCHAR* path, /* Path name of the logical drive number */ + DWORD* nclst, /* Pointer to a variable to return number of free clusters */ + FATFS** fatfs /* Pointer to return pointer to corresponding file system object */ +) +{ + FRESULT res; + FATFS *fs; + DWORD nfree, clst, sect, stat; + UINT i; + BYTE fat, *p; + + + /* Get logical drive number */ + res = find_volume(fatfs, &path, 0); + fs = *fatfs; + if (res == FR_OK) { + /* If free_clust is valid, return it without full cluster scan */ + if (fs->free_clust <= fs->n_fatent - 2) { + *nclst = fs->free_clust; + } else { + /* Get number of free clusters */ + fat = fs->fs_type; + nfree = 0; + if (fat == FS_FAT12) { /* Sector unalighed entries: Search FAT via regular routine. */ + clst = 2; + do { + stat = get_fat(fs, clst); + if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; } + if (stat == 1) { res = FR_INT_ERR; break; } + if (stat == 0) nfree++; + } while (++clst < fs->n_fatent); + } else { /* Sector alighed entries: Accelerate the FAT search. */ + clst = fs->n_fatent; sect = fs->fatbase; + i = 0; p = 0; + do { + if (!i) { + res = move_window(fs, sect++); + if (res != FR_OK) break; + p = fs->win; + i = SS(fs); + } + if (fat == FS_FAT16) { + if (LD_WORD(p) == 0) nfree++; + p += 2; i -= 2; + } else { + if ((LD_DWORD(p) & 0x0FFFFFFF) == 0) nfree++; + p += 4; i -= 4; + } + } while (--clst); + } + fs->free_clust = nfree; /* free_clust is valid */ + fs->fsi_flag |= 1; /* FSInfo is to be updated */ + *nclst = nfree; /* Return the free clusters */ + } + } + LEAVE_FF(fs, res); +} + + + + +/*-----------------------------------------------------------------------*/ +/* Truncate File */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_truncate ( + FIL* fp /* Pointer to the file object */ +) +{ + FRESULT res; + DWORD ncl; + + + res = validate(fp); /* Check validity of the object */ + if (res == FR_OK) { + if (fp->err) { /* Check error */ + res = (FRESULT)fp->err; + } else { + if (!(fp->flag & FA_WRITE)) /* Check access mode */ + res = FR_DENIED; + } + } + if (res == FR_OK) { + if (fp->fsize > fp->fptr) { + fp->fsize = fp->fptr; /* Set file size to current R/W point */ + fp->flag |= FA__WRITTEN; + if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */ + res = remove_chain(fp->fs, fp->sclust); + fp->sclust = 0; + } else { /* When truncate a part of the file, remove remaining clusters */ + ncl = get_fat(fp->fs, fp->clust); + res = FR_OK; + if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR; + if (ncl == 1) res = FR_INT_ERR; + if (res == FR_OK && ncl < fp->fs->n_fatent) { + res = put_fat(fp->fs, fp->clust, 0x0FFFFFFF); + if (res == FR_OK) res = remove_chain(fp->fs, ncl); + } + } +#if !_FS_TINY + if (res == FR_OK && (fp->flag & FA__DIRTY)) { + if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) + res = FR_DISK_ERR; + else + fp->flag &= ~FA__DIRTY; + } +#endif + } + if (res != FR_OK) fp->err = (FRESULT)res; + } + + LEAVE_FF(fp->fs, res); +} + + + + +/*-----------------------------------------------------------------------*/ +/* Delete a File or Directory */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_unlink ( + const TCHAR* path /* Pointer to the file or directory path */ +) +{ + FRESULT res; + FATFS_DIR dj, sdj; + BYTE *dir; + DWORD dclst = 0; + DEFINE_NAMEBUF; + + + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 1); + if (res == FR_OK) { + INIT_BUF(dj); + res = follow_path(&dj, path); /* Follow the file path */ + if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) + res = FR_INVALID_NAME; /* Cannot remove dot entry */ +#if _FS_LOCK + if (res == FR_OK) res = chk_lock(&dj, 2); /* Cannot remove open object */ +#endif + if (res == FR_OK) { /* The object is accessible */ + dir = dj.dir; + if (!dir) { + res = FR_INVALID_NAME; /* Cannot remove the origin directory */ + } else { + if (dir[DIR_Attr] & AM_RDO) + res = FR_DENIED; /* Cannot remove R/O object */ + } + if (res == FR_OK) { + dclst = ld_clust(dj.fs, dir); + if (dclst && (dir[DIR_Attr] & AM_DIR)) { /* Is it a sub-directory ? */ +#if _FS_RPATH + if (dclst == dj.fs->cdir) { /* Is it the current directory? */ + res = FR_DENIED; + } else +#endif + { + mem_cpy(&sdj, &dj, sizeof (FATFS_DIR)); /* Open the sub-directory */ + sdj.sclust = dclst; + res = dir_sdi(&sdj, 2); + if (res == FR_OK) { + res = dir_read(&sdj, 0); /* Read an item (excluding dot entries) */ + if (res == FR_OK) res = FR_DENIED; /* Not empty? (cannot remove) */ + if (res == FR_NO_FILE) res = FR_OK; /* Empty? (can remove) */ + } + } + } + } + if (res == FR_OK) { + res = dir_remove(&dj); /* Remove the directory entry */ + if (res == FR_OK && dclst) /* Remove the cluster chain if exist */ + res = remove_chain(dj.fs, dclst); + if (res == FR_OK) res = sync_fs(dj.fs); + } + } + FREE_BUF(); + } + + LEAVE_FF(dj.fs, res); +} + + + + +/*-----------------------------------------------------------------------*/ +/* Create a Directory */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_mkdir ( + const TCHAR* path /* Pointer to the directory path */ +) +{ + FRESULT res; + FATFS_DIR dj; + BYTE *dir, n; + DWORD dsc, dcl, pcl, tm = GET_FATTIME(); + DEFINE_NAMEBUF; + + + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 1); + if (res == FR_OK) { + INIT_BUF(dj); + res = follow_path(&dj, path); /* Follow the file path */ + if (res == FR_OK) res = FR_EXIST; /* Any object with same name is already existing */ + if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT)) + res = FR_INVALID_NAME; + if (res == FR_NO_FILE) { /* Can create a new directory */ + dcl = create_chain(dj.fs, 0); /* Allocate a cluster for the new directory table */ + res = FR_OK; + if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster */ + if (dcl == 1) res = FR_INT_ERR; + if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR; + if (res == FR_OK) /* Flush FAT */ + res = sync_window(dj.fs); + if (res == FR_OK) { /* Initialize the new directory table */ + dsc = clust2sect(dj.fs, dcl); + dir = dj.fs->win; + mem_set(dir, 0, SS(dj.fs)); + mem_set(dir + DIR_Name, ' ', 11); /* Create "." entry */ + dir[DIR_Name] = '.'; + dir[DIR_Attr] = AM_DIR; + ST_DWORD(dir + DIR_WrtTime, tm); + st_clust(dir, dcl); + mem_cpy(dir + SZ_DIRE, dir, SZ_DIRE); /* Create ".." entry */ + dir[SZ_DIRE + 1] = '.'; pcl = dj.sclust; + if (dj.fs->fs_type == FS_FAT32 && pcl == dj.fs->dirbase) + pcl = 0; + st_clust(dir + SZ_DIRE, pcl); + for (n = dj.fs->csize; n; n--) { /* Write dot entries and clear following sectors */ + dj.fs->winsect = dsc++; + dj.fs->wflag = 1; + res = sync_window(dj.fs); + if (res != FR_OK) break; + mem_set(dir, 0, SS(dj.fs)); + } + } + if (res == FR_OK) res = dir_register(&dj); /* Register the object to the directoy */ + if (res != FR_OK) { + remove_chain(dj.fs, dcl); /* Could not register, remove cluster chain */ + } else { + dir = dj.dir; + dir[DIR_Attr] = AM_DIR; /* Attribute */ + ST_DWORD(dir + DIR_WrtTime, tm); /* Created time */ + st_clust(dir, dcl); /* Table start cluster */ + dj.fs->wflag = 1; + res = sync_fs(dj.fs); + } + } + FREE_BUF(); + } + + LEAVE_FF(dj.fs, res); +} + + + + +/*-----------------------------------------------------------------------*/ +/* Change Attribute */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_chmod ( + const TCHAR* path, /* Pointer to the file path */ + BYTE attr, /* Attribute bits */ + BYTE mask /* Attribute mask to change */ +) +{ + FRESULT res; + FATFS_DIR dj; + BYTE *dir; + DEFINE_NAMEBUF; + + + res = find_volume(&dj.fs, &path, 1); /* Get logical drive number */ + if (res == FR_OK) { + INIT_BUF(dj); + res = follow_path(&dj, path); /* Follow the file path */ + FREE_BUF(); + if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) + res = FR_INVALID_NAME; + if (res == FR_OK) { + dir = dj.dir; + if (!dir) { /* Is it a root directory? */ + res = FR_INVALID_NAME; + } else { /* File or sub directory */ + mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */ + dir[DIR_Attr] = (attr & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */ + dj.fs->wflag = 1; + res = sync_fs(dj.fs); + } + } + } + + LEAVE_FF(dj.fs, res); +} + + + + +/*-----------------------------------------------------------------------*/ +/* Rename File/Directory */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_rename ( + const TCHAR* path_old, /* Pointer to the object to be renamed */ + const TCHAR* path_new /* Pointer to the new name */ +) +{ + FRESULT res; + FATFS_DIR djo, djn; + BYTE buf[21], *dir; + DWORD dw; + DEFINE_NAMEBUF; + + + /* Get logical drive number of the source object */ + res = find_volume(&djo.fs, &path_old, 1); + if (res == FR_OK) { + djn.fs = djo.fs; + INIT_BUF(djo); + res = follow_path(&djo, path_old); /* Check old object */ + if (_FS_RPATH && res == FR_OK && (djo.fn[NSFLAG] & NS_DOT)) + res = FR_INVALID_NAME; +#if _FS_LOCK + if (res == FR_OK) res = chk_lock(&djo, 2); +#endif + if (res == FR_OK) { /* Old object is found */ + if (!djo.dir) { /* Is root dir? */ + res = FR_NO_FILE; + } else { + mem_cpy(buf, djo.dir + DIR_Attr, 21); /* Save information about object except name */ + mem_cpy(&djn, &djo, sizeof (FATFS_DIR)); /* Duplicate the directory object */ + if (get_ldnumber(&path_new) >= 0) /* Snip drive number off and ignore it */ + res = follow_path(&djn, path_new); /* and make sure if new object name is not conflicting */ + else + res = FR_INVALID_DRIVE; + if (res == FR_OK) res = FR_EXIST; /* The new object name is already existing */ + if (res == FR_NO_FILE) { /* It is a valid path and no name collision */ + res = dir_register(&djn); /* Register the new entry */ + if (res == FR_OK) { +/* Start of critical section where any interruption can cause a cross-link */ + dir = djn.dir; /* Copy information about object except name */ + mem_cpy(dir + 13, buf + 2, 19); + dir[DIR_Attr] = buf[0] | AM_ARC; + djo.fs->wflag = 1; + if ((dir[DIR_Attr] & AM_DIR) && djo.sclust != djn.sclust) { /* Update .. entry in the sub-directory if needed */ + dw = clust2sect(djo.fs, ld_clust(djo.fs, dir)); + if (!dw) { + res = FR_INT_ERR; + } else { + res = move_window(djo.fs, dw); + dir = djo.fs->win + SZ_DIRE * 1; /* Ptr to .. entry */ + if (res == FR_OK && dir[1] == '.') { + st_clust(dir, djn.sclust); + djo.fs->wflag = 1; + } + } + } + if (res == FR_OK) { + res = dir_remove(&djo); /* Remove old entry */ + if (res == FR_OK) + res = sync_fs(djo.fs); + } +/* End of critical section */ + } + } + } + } + FREE_BUF(); + } + + LEAVE_FF(djo.fs, res); +} + + + + +/*-----------------------------------------------------------------------*/ +/* Change Timestamp */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_utime ( + const TCHAR* path, /* Pointer to the file/directory name */ + const FILINFO* fno /* Pointer to the time stamp to be set */ +) +{ + FRESULT res; + FATFS_DIR dj; + BYTE *dir; + DEFINE_NAMEBUF; + + + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 1); + if (res == FR_OK) { + INIT_BUF(dj); + res = follow_path(&dj, path); /* Follow the file path */ + FREE_BUF(); + if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) + res = FR_INVALID_NAME; + if (res == FR_OK) { + dir = dj.dir; + if (!dir) { /* Root directory */ + res = FR_INVALID_NAME; + } else { /* File or sub-directory */ + ST_WORD(dir + DIR_WrtTime, fno->ftime); + ST_WORD(dir + DIR_WrtDate, fno->fdate); + dj.fs->wflag = 1; + res = sync_fs(dj.fs); + } + } + } + + LEAVE_FF(dj.fs, res); +} + +#endif /* !_FS_READONLY */ +#endif /* _FS_MINIMIZE == 0 */ +#endif /* _FS_MINIMIZE <= 1 */ +#endif /* _FS_MINIMIZE <= 2 */ + + + + +#if _USE_LABEL +/*-----------------------------------------------------------------------*/ +/* Get volume label */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_getlabel ( + const TCHAR* path, /* Path name of the logical drive number */ + TCHAR* label, /* Pointer to a buffer to return the volume label */ + DWORD* vsn /* Pointer to a variable to return the volume serial number */ +) +{ + FRESULT res; + FATFS_DIR dj; + UINT i, j; +#if _USE_LFN && _LFN_UNICODE + WCHAR w; +#endif + + + /* Get logical drive number */ + res = find_volume(&dj.fs, &path, 0); + + /* Get volume label */ + if (res == FR_OK && label) { + dj.sclust = 0; /* Open root directory */ + res = dir_sdi(&dj, 0); + if (res == FR_OK) { + res = dir_read(&dj, 1); /* Get an entry with AM_VOL */ + if (res == FR_OK) { /* A volume label is exist */ +#if _USE_LFN && _LFN_UNICODE + i = j = 0; + do { + w = (i < 11) ? dj.dir[i++] : ' '; + if (IsDBCS1(w) && i < 11 && IsDBCS2(dj.dir[i])) + w = w << 8 | dj.dir[i++]; + label[j++] = ff_convert(w, 1); /* OEM -> Unicode */ + } while (j < 11); +#else + mem_cpy(label, dj.dir, 11); +#endif + j = 11; + do { + label[j] = 0; + if (!j) break; + } while (label[--j] == ' '); + } + if (res == FR_NO_FILE) { /* No label, return nul string */ + label[0] = 0; + res = FR_OK; + } + } + } + + /* Get volume serial number */ + if (res == FR_OK && vsn) { + res = move_window(dj.fs, dj.fs->volbase); + if (res == FR_OK) { + i = dj.fs->fs_type == FS_FAT32 ? BS_VolID32 : BS_VolID; + *vsn = LD_DWORD(&dj.fs->win[i]); + } + } + + LEAVE_FF(dj.fs, res); +} + + + +#if !_FS_READONLY +/*-----------------------------------------------------------------------*/ +/* Set volume label */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_setlabel ( + const TCHAR* label /* Pointer to the volume label to set */ +) +{ + FRESULT res; + FATFS_DIR dj; + BYTE vn[11]; + UINT i, j, sl; + WCHAR w; + DWORD tm; + + + /* Get logical drive number */ + res = find_volume(&dj.fs, &label, 1); + if (res) LEAVE_FF(dj.fs, res); + + /* Create a volume label in directory form */ + vn[0] = 0; + for (sl = 0; label[sl]; sl++) ; /* Get name length */ + for ( ; sl && label[sl - 1] == ' '; sl--) ; /* Remove trailing spaces */ + if (sl) { /* Create volume label in directory form */ + i = j = 0; + do { +#if _USE_LFN && _LFN_UNICODE + w = ff_convert(ff_wtoupper(label[i++]), 0); +#else + w = (BYTE)label[i++]; + if (IsDBCS1(w)) + w = (j < 10 && i < sl && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0; +#if _USE_LFN + w = ff_convert(ff_wtoupper(ff_convert(w, 1)), 0); +#else + if (IsLower(w)) w -= 0x20; /* To upper ASCII characters */ +#ifdef _EXCVT + if (w >= 0x80) w = ExCvt[w - 0x80]; /* To upper extended characters (SBCS cfg) */ +#else + if (!_DF1S && w >= 0x80) w = 0; /* Reject extended characters (ASCII cfg) */ +#endif +#endif +#endif + if (!w || chk_chr("\"*+,.:;<=>\?[]|\x7F", w) || j >= (UINT)((w >= 0x100) ? 10 : 11)) /* Reject invalid characters for volume label */ + LEAVE_FF(dj.fs, FR_INVALID_NAME); + if (w >= 0x100) vn[j++] = (BYTE)(w >> 8); + vn[j++] = (BYTE)w; + } while (i < sl); + while (j < 11) vn[j++] = ' '; /* Fill remaining name field */ + if (vn[0] == DDEM) LEAVE_FF(dj.fs, FR_INVALID_NAME); /* Reject illegal name (heading DDEM) */ + } + + /* Set volume label */ + dj.sclust = 0; /* Open root directory */ + res = dir_sdi(&dj, 0); + if (res == FR_OK) { + res = dir_read(&dj, 1); /* Get an entry with AM_VOL */ + if (res == FR_OK) { /* A volume label is found */ + if (vn[0]) { + mem_cpy(dj.dir, vn, 11); /* Change the volume label name */ + tm = GET_FATTIME(); + ST_DWORD(dj.dir + DIR_WrtTime, tm); + } else { + dj.dir[0] = DDEM; /* Remove the volume label */ + } + dj.fs->wflag = 1; + res = sync_fs(dj.fs); + } else { /* No volume label is found or error */ + if (res == FR_NO_FILE) { + res = FR_OK; + if (vn[0]) { /* Create volume label as new */ + res = dir_alloc(&dj, 1); /* Allocate an entry for volume label */ + if (res == FR_OK) { + mem_set(dj.dir, 0, SZ_DIRE); /* Set volume label */ + mem_cpy(dj.dir, vn, 11); + dj.dir[DIR_Attr] = AM_VOL; + tm = GET_FATTIME(); + ST_DWORD(dj.dir + DIR_WrtTime, tm); + dj.fs->wflag = 1; + res = sync_fs(dj.fs); + } + } + } + } + } + + LEAVE_FF(dj.fs, res); +} + +#endif /* !_FS_READONLY */ +#endif /* _USE_LABEL */ + + + +/*-----------------------------------------------------------------------*/ +/* Forward data to the stream directly (available on only tiny cfg) */ +/*-----------------------------------------------------------------------*/ +#if _USE_FORWARD && _FS_TINY + +FRESULT f_forward ( + FIL* fp, /* Pointer to the file object */ + UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */ + UINT btf, /* Number of bytes to forward */ + UINT* bf /* Pointer to number of bytes forwarded */ +) +{ + FRESULT res; + DWORD remain, clst, sect; + UINT rcnt; + BYTE csect; + + + *bf = 0; /* Clear transfer byte counter */ + + res = validate(fp); /* Check validity of the object */ + if (res != FR_OK) LEAVE_FF(fp->fs, res); + if (fp->err) /* Check error */ + LEAVE_FF(fp->fs, (FRESULT)fp->err); + if (!(fp->flag & FA_READ)) /* Check access mode */ + LEAVE_FF(fp->fs, FR_DENIED); + + remain = fp->fsize - fp->fptr; + if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */ + + for ( ; btf && (*func)(0, 0); /* Repeat until all data transferred or stream becomes busy */ + fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) { + csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */ + if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */ + if (!csect) { /* On the cluster boundary? */ + clst = (fp->fptr == 0) ? /* On the top of the file? */ + fp->sclust : get_fat(fp->fs, fp->clust); + if (clst <= 1) ABORT(fp->fs, FR_INT_ERR); + if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR); + fp->clust = clst; /* Update current cluster */ + } + } + sect = clust2sect(fp->fs, fp->clust); /* Get current data sector */ + if (!sect) ABORT(fp->fs, FR_INT_ERR); + sect += csect; + if (move_window(fp->fs, sect) != FR_OK) /* Move sector window */ + ABORT(fp->fs, FR_DISK_ERR); + fp->dsect = sect; + rcnt = SS(fp->fs) - (WORD)(fp->fptr % SS(fp->fs)); /* Forward data from sector window */ + if (rcnt > btf) rcnt = btf; + rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % SS(fp->fs)], rcnt); + if (!rcnt) ABORT(fp->fs, FR_INT_ERR); + } + + LEAVE_FF(fp->fs, FR_OK); +} +#endif /* _USE_FORWARD */ + + + +#if _USE_MKFS && !_FS_READONLY +/*-----------------------------------------------------------------------*/ +/* Create file system on the logical drive */ +/*-----------------------------------------------------------------------*/ +#define N_ROOTDIR 512 /* Number of root directory entries for FAT12/16 */ +#define N_FATS 1 /* Number of FATs (1 or 2) */ + + +FRESULT f_mkfs ( + const TCHAR* path, /* Logical drive number */ + BYTE sfd, /* Partitioning rule 0:FDISK, 1:SFD */ + UINT au /* Size of allocation unit in unit of byte or sector */ +) +{ + static const WORD vst[] = { 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 0}; + static const WORD cst[] = {32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512}; + int vol; + BYTE fmt, md, sys, *tbl, pdrv, part; + DWORD n_clst, vs, n, wsect; + UINT i; + DWORD b_vol, b_fat, b_dir, b_data; /* LBA */ + DWORD n_vol, n_rsv, n_fat, n_dir; /* Size */ + FATFS *fs; + DSTATUS stat; +#if _USE_TRIM + DWORD eb[2]; +#endif + + + /* Check mounted drive and clear work area */ + if (sfd > 1) return FR_INVALID_PARAMETER; + vol = get_ldnumber(&path); + if (vol < 0) return FR_INVALID_DRIVE; + fs = FatFs[vol]; + if (!fs) return FR_NOT_ENABLED; + fs->fs_type = 0; + pdrv = LD2PD(vol); /* Physical drive */ + part = LD2PT(vol); /* Partition (0:auto detect, 1-4:get from partition table)*/ + + /* Get disk statics */ + stat = disk_initialize(pdrv); + if (stat & STA_NOINIT) return FR_NOT_READY; + if (stat & STA_PROTECT) return FR_WRITE_PROTECTED; +#if _MAX_SS != _MIN_SS /* Get disk sector size */ + if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > _MAX_SS || SS(fs) < _MIN_SS) + return FR_DISK_ERR; +#endif + if (_MULTI_PARTITION && part) { + /* Get partition information from partition table in the MBR */ + if (disk_read(pdrv, fs->win, 0, 1) != RES_OK) return FR_DISK_ERR; + if (LD_WORD(fs->win + BS_55AA) != 0xAA55) return FR_MKFS_ABORTED; + tbl = &fs->win[MBR_Table + (part - 1) * SZ_PTE]; + if (!tbl[4]) return FR_MKFS_ABORTED; /* No partition? */ + b_vol = LD_DWORD(tbl + 8); /* Volume start sector */ + n_vol = LD_DWORD(tbl + 12); /* Volume size */ + } else { + /* Create a partition in this function */ + if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &n_vol) != RES_OK || n_vol < 128) + return FR_DISK_ERR; + b_vol = (sfd) ? 0 : 63; /* Volume start sector */ + n_vol -= b_vol; /* Volume size */ + } + + if (au & (au - 1)) au = 0; + if (!au) { /* AU auto selection */ + vs = n_vol / (2000 / (SS(fs) / 512)); + for (i = 0; vs < vst[i]; i++) ; + au = cst[i]; + } + if (au >= _MIN_SS) au /= SS(fs); /* Number of sectors per cluster */ + if (!au) au = 1; + if (au > 128) au = 128; + + /* Pre-compute number of clusters and FAT sub-type */ + n_clst = n_vol / au; + fmt = FS_FAT12; + if (n_clst >= MIN_FAT16) fmt = FS_FAT16; + if (n_clst >= MIN_FAT32) fmt = FS_FAT32; + + /* Determine offset and size of FAT structure */ + if (fmt == FS_FAT32) { + n_fat = ((n_clst * 4) + 8 + SS(fs) - 1) / SS(fs); + n_rsv = 32; + n_dir = 0; + } else { + n_fat = (fmt == FS_FAT12) ? (n_clst * 3 + 1) / 2 + 3 : (n_clst * 2) + 4; + n_fat = (n_fat + SS(fs) - 1) / SS(fs); + n_rsv = 1; + n_dir = (DWORD)N_ROOTDIR * SZ_DIRE / SS(fs); + } + b_fat = b_vol + n_rsv; /* FAT area start sector */ + b_dir = b_fat + n_fat * N_FATS; /* Directory area start sector */ + b_data = b_dir + n_dir; /* Data area start sector */ + if (n_vol < b_data + au - b_vol) return FR_MKFS_ABORTED; /* Too small volume */ + + /* Align data start sector to erase block boundary (for flash memory media) */ + if (disk_ioctl(pdrv, GET_BLOCK_SIZE, &n) != RES_OK || !n || n > 32768) n = 1; + n = (b_data + n - 1) & ~(n - 1); /* Next nearest erase block from current data start */ + n = (n - b_data) / N_FATS; + if (fmt == FS_FAT32) { /* FAT32: Move FAT offset */ + n_rsv += n; + b_fat += n; + } else { /* FAT12/16: Expand FAT size */ + n_fat += n; + } + + /* Determine number of clusters and final check of validity of the FAT sub-type */ + n_clst = (n_vol - n_rsv - n_fat * N_FATS - n_dir) / au; + if ( (fmt == FS_FAT16 && n_clst < MIN_FAT16) + || (fmt == FS_FAT32 && n_clst < MIN_FAT32)) + return FR_MKFS_ABORTED; + + /* Determine system ID in the partition table */ + if (fmt == FS_FAT32) { + sys = 0x0C; /* FAT32X */ + } else { + if (fmt == FS_FAT12 && n_vol < 0x10000) { + sys = 0x01; /* FAT12(<65536) */ + } else { + sys = (n_vol < 0x10000) ? 0x04 : 0x06; /* FAT16(<65536) : FAT12/16(>=65536) */ + } + } + + if (_MULTI_PARTITION && part) { + /* Update system ID in the partition table */ + tbl = &fs->win[MBR_Table + (part - 1) * SZ_PTE]; + tbl[4] = sys; + if (disk_write(pdrv, fs->win, 0, 1) != RES_OK) /* Write it to teh MBR */ + return FR_DISK_ERR; + md = 0xF8; + } else { + if (sfd) { /* No partition table (SFD) */ + md = 0xF0; + } else { /* Create partition table (FDISK) */ + mem_set(fs->win, 0, SS(fs)); + tbl = fs->win + MBR_Table; /* Create partition table for single partition in the drive */ + tbl[1] = 1; /* Partition start head */ + tbl[2] = 1; /* Partition start sector */ + tbl[3] = 0; /* Partition start cylinder */ + tbl[4] = sys; /* System type */ + tbl[5] = 254; /* Partition end head */ + n = (b_vol + n_vol) / 63 / 255; + tbl[6] = (BYTE)(n >> 2 | 63); /* Partition end sector */ + tbl[7] = (BYTE)n; /* End cylinder */ + ST_DWORD(tbl + 8, 63); /* Partition start in LBA */ + ST_DWORD(tbl + 12, n_vol); /* Partition size in LBA */ + ST_WORD(fs->win + BS_55AA, 0xAA55); /* MBR signature */ + if (disk_write(pdrv, fs->win, 0, 1) != RES_OK) /* Write it to the MBR */ + return FR_DISK_ERR; + md = 0xF8; + } + } + + /* Create BPB in the VBR */ + tbl = fs->win; /* Clear sector */ + mem_set(tbl, 0, SS(fs)); + mem_cpy(tbl, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code, OEM name */ + i = SS(fs); /* Sector size */ + ST_WORD(tbl + BPB_BytsPerSec, i); + tbl[BPB_SecPerClus] = (BYTE)au; /* Sectors per cluster */ + ST_WORD(tbl + BPB_RsvdSecCnt, n_rsv); /* Reserved sectors */ + tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */ + i = (fmt == FS_FAT32) ? 0 : N_ROOTDIR; /* Number of root directory entries */ + ST_WORD(tbl + BPB_RootEntCnt, i); + if (n_vol < 0x10000) { /* Number of total sectors */ + ST_WORD(tbl + BPB_TotSec16, n_vol); + } else { + ST_DWORD(tbl + BPB_TotSec32, n_vol); + } + tbl[BPB_Media] = md; /* Media descriptor */ + ST_WORD(tbl + BPB_SecPerTrk, 63); /* Number of sectors per track */ + ST_WORD(tbl + BPB_NumHeads, 255); /* Number of heads */ + ST_DWORD(tbl + BPB_HiddSec, b_vol); /* Hidden sectors */ + n = GET_FATTIME(); /* Use current time as VSN */ + if (fmt == FS_FAT32) { + ST_DWORD(tbl + BS_VolID32, n); /* VSN */ + ST_DWORD(tbl + BPB_FATSz32, n_fat); /* Number of sectors per FAT */ + ST_DWORD(tbl + BPB_RootClus, 2); /* Root directory start cluster (2) */ + ST_WORD(tbl + BPB_FSInfo, 1); /* FSINFO record offset (VBR + 1) */ + ST_WORD(tbl + BPB_BkBootSec, 6); /* Backup boot record offset (VBR + 6) */ + tbl[BS_DrvNum32] = 0x80; /* Drive number */ + tbl[BS_BootSig32] = 0x29; /* Extended boot signature */ + mem_cpy(tbl + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */ + } else { + ST_DWORD(tbl + BS_VolID, n); /* VSN */ + ST_WORD(tbl + BPB_FATSz16, n_fat); /* Number of sectors per FAT */ + tbl[BS_DrvNum] = 0x80; /* Drive number */ + tbl[BS_BootSig] = 0x29; /* Extended boot signature */ + mem_cpy(tbl + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */ + } + ST_WORD(tbl + BS_55AA, 0xAA55); /* Signature (Offset is fixed here regardless of sector size) */ + if (disk_write(pdrv, tbl, b_vol, 1) != RES_OK) /* Write it to the VBR sector */ + return FR_DISK_ERR; + if (fmt == FS_FAT32) /* Write it to the backup VBR if needed (VBR + 6) */ + disk_write(pdrv, tbl, b_vol + 6, 1); + + /* Initialize FAT area */ + wsect = b_fat; + for (i = 0; i < N_FATS; i++) { /* Initialize each FAT copy */ + mem_set(tbl, 0, SS(fs)); /* 1st sector of the FAT */ + n = md; /* Media descriptor byte */ + if (fmt != FS_FAT32) { + n |= (fmt == FS_FAT12) ? 0x00FFFF00 : 0xFFFFFF00; + ST_DWORD(tbl + 0, n); /* Reserve cluster #0-1 (FAT12/16) */ + } else { + n |= 0xFFFFFF00; + ST_DWORD(tbl + 0, n); /* Reserve cluster #0-1 (FAT32) */ + ST_DWORD(tbl + 4, 0xFFFFFFFF); + ST_DWORD(tbl + 8, 0x0FFFFFFF); /* Reserve cluster #2 for root directory */ + } + if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK) + return FR_DISK_ERR; + mem_set(tbl, 0, SS(fs)); /* Fill following FAT entries with zero */ + for (n = 1; n < n_fat; n++) { /* This loop may take a time on FAT32 volume due to many single sector writes */ + if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK) + return FR_DISK_ERR; + } + } + + /* Initialize root directory */ + i = (fmt == FS_FAT32) ? au : (UINT)n_dir; + do { + if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK) + return FR_DISK_ERR; + } while (--i); + +#if _USE_TRIM /* Erase data area if needed */ + { + eb[0] = wsect; eb[1] = wsect + (n_clst - ((fmt == FS_FAT32) ? 1 : 0)) * au - 1; + disk_ioctl(pdrv, CTRL_TRIM, eb); + } +#endif + + /* Create FSINFO if needed */ + if (fmt == FS_FAT32) { + ST_DWORD(tbl + FSI_LeadSig, 0x41615252); + ST_DWORD(tbl + FSI_StrucSig, 0x61417272); + ST_DWORD(tbl + FSI_Free_Count, n_clst - 1); /* Number of free clusters */ + ST_DWORD(tbl + FSI_Nxt_Free, 2); /* Last allocated cluster# */ + ST_WORD(tbl + BS_55AA, 0xAA55); + disk_write(pdrv, tbl, b_vol + 1, 1); /* Write original (VBR + 1) */ + disk_write(pdrv, tbl, b_vol + 7, 1); /* Write backup (VBR + 7) */ + } + + return (disk_ioctl(pdrv, CTRL_SYNC, 0) == RES_OK) ? FR_OK : FR_DISK_ERR; +} + + + +#if _MULTI_PARTITION +/*-----------------------------------------------------------------------*/ +/* Create partition table on the physical drive */ +/*-----------------------------------------------------------------------*/ + +FRESULT f_fdisk ( + BYTE pdrv, /* Physical drive number */ + const DWORD szt[], /* Pointer to the size table for each partitions */ + void* work /* Pointer to the working buffer */ +) +{ + UINT i, n, sz_cyl, tot_cyl, b_cyl, e_cyl, p_cyl; + BYTE s_hd, e_hd, *p, *buf = (BYTE*)work; + DSTATUS stat; + DWORD sz_disk, sz_part, s_part; + + + stat = disk_initialize(pdrv); + if (stat & STA_NOINIT) return FR_NOT_READY; + if (stat & STA_PROTECT) return FR_WRITE_PROTECTED; + if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_disk)) return FR_DISK_ERR; + + /* Determine CHS in the table regardless of the drive geometry */ + for (n = 16; n < 256 && sz_disk / n / 63 > 1024; n *= 2) ; + if (n == 256) n--; + e_hd = n - 1; + sz_cyl = 63 * n; + tot_cyl = sz_disk / sz_cyl; + + /* Create partition table */ + mem_set(buf, 0, _MAX_SS); + p = buf + MBR_Table; b_cyl = 0; + for (i = 0; i < 4; i++, p += SZ_PTE) { + p_cyl = (szt[i] <= 100U) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl; + if (!p_cyl) continue; + s_part = (DWORD)sz_cyl * b_cyl; + sz_part = (DWORD)sz_cyl * p_cyl; + if (i == 0) { /* Exclude first track of cylinder 0 */ + s_hd = 1; + s_part += 63; sz_part -= 63; + } else { + s_hd = 0; + } + e_cyl = b_cyl + p_cyl - 1; + if (e_cyl >= tot_cyl) return FR_INVALID_PARAMETER; + + /* Set partition table */ + p[1] = s_hd; /* Start head */ + p[2] = (BYTE)((b_cyl >> 2) + 1); /* Start sector */ + p[3] = (BYTE)b_cyl; /* Start cylinder */ + p[4] = 0x06; /* System type (temporary setting) */ + p[5] = e_hd; /* End head */ + p[6] = (BYTE)((e_cyl >> 2) + 63); /* End sector */ + p[7] = (BYTE)e_cyl; /* End cylinder */ + ST_DWORD(p + 8, s_part); /* Start sector in LBA */ + ST_DWORD(p + 12, sz_part); /* Partition size */ + + /* Next partition */ + b_cyl += p_cyl; + } + ST_WORD(p, 0xAA55); + + /* Write it to the MBR */ + return (disk_write(pdrv, buf, 0, 1) != RES_OK || disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) ? FR_DISK_ERR : FR_OK; +} + + +#endif /* _MULTI_PARTITION */ +#endif /* _USE_MKFS && !_FS_READONLY */ + + + + +#if _USE_STRFUNC +/*-----------------------------------------------------------------------*/ +/* Get a string from the file */ +/*-----------------------------------------------------------------------*/ + +TCHAR* f_gets ( + TCHAR* buff, /* Pointer to the string buffer to read */ + int len, /* Size of string buffer (characters) */ + FIL* fp /* Pointer to the file object */ +) +{ + int n = 0; + TCHAR c, *p = buff; + BYTE s[2]; + UINT rc; + + + while (n < len - 1) { /* Read characters until buffer gets filled */ +#if _USE_LFN && _LFN_UNICODE +#if _STRF_ENCODE == 3 /* Read a character in UTF-8 */ + f_read(fp, s, 1, &rc); + if (rc != 1) break; + c = s[0]; + if (c >= 0x80) { + if (c < 0xC0) continue; /* Skip stray trailer */ + if (c < 0xE0) { /* Two-byte sequence */ + f_read(fp, s, 1, &rc); + if (rc != 1) break; + c = (c & 0x1F) << 6 | (s[0] & 0x3F); + if (c < 0x80) c = '?'; + } else { + if (c < 0xF0) { /* Three-byte sequence */ + f_read(fp, s, 2, &rc); + if (rc != 2) break; + c = c << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F); + if (c < 0x800) c = '?'; + } else { /* Reject four-byte sequence */ + c = '?'; + } + } + } +#elif _STRF_ENCODE == 2 /* Read a character in UTF-16BE */ + f_read(fp, s, 2, &rc); + if (rc != 2) break; + c = s[1] + (s[0] << 8); +#elif _STRF_ENCODE == 1 /* Read a character in UTF-16LE */ + f_read(fp, s, 2, &rc); + if (rc != 2) break; + c = s[0] + (s[1] << 8); +#else /* Read a character in ANSI/OEM */ + f_read(fp, s, 1, &rc); + if (rc != 1) break; + c = s[0]; + if (IsDBCS1(c)) { + f_read(fp, s, 1, &rc); + if (rc != 1) break; + c = (c << 8) + s[0]; + } + c = ff_convert(c, 1); /* OEM -> Unicode */ + if (!c) c = '?'; +#endif +#else /* Read a character without conversion */ + f_read(fp, s, 1, &rc); + if (rc != 1) break; + c = s[0]; +#endif + if (_USE_STRFUNC == 2 && c == '\r') continue; /* Strip '\r' */ + *p++ = c; + n++; + if (c == '\n') break; /* Break on EOL */ + } + *p = 0; + return n ? buff : 0; /* When no data read (eof or error), return with error. */ +} + + + + +#if !_FS_READONLY +#include <stdarg.h> +/*-----------------------------------------------------------------------*/ +/* Put a character to the file */ +/*-----------------------------------------------------------------------*/ + +typedef struct { + FIL* fp; + int idx, nchr; + BYTE buf[64]; +} putbuff; + + +static +void putc_bfd ( + putbuff* pb, + TCHAR c +) +{ + UINT bw; + int i; + + + if (_USE_STRFUNC == 2 && c == '\n') /* LF -> CRLF conversion */ + putc_bfd(pb, '\r'); + + i = pb->idx; /* Buffer write index (-1:error) */ + if (i < 0) return; + +#if _USE_LFN && _LFN_UNICODE +#if _STRF_ENCODE == 3 /* Write a character in UTF-8 */ + if (c < 0x80) { /* 7-bit */ + pb->buf[i++] = (BYTE)c; + } else { + if (c < 0x800) { /* 11-bit */ + pb->buf[i++] = (BYTE)(0xC0 | c >> 6); + } else { /* 16-bit */ + pb->buf[i++] = (BYTE)(0xE0 | c >> 12); + pb->buf[i++] = (BYTE)(0x80 | (c >> 6 & 0x3F)); + } + pb->buf[i++] = (BYTE)(0x80 | (c & 0x3F)); + } +#elif _STRF_ENCODE == 2 /* Write a character in UTF-16BE */ + pb->buf[i++] = (BYTE)(c >> 8); + pb->buf[i++] = (BYTE)c; +#elif _STRF_ENCODE == 1 /* Write a character in UTF-16LE */ + pb->buf[i++] = (BYTE)c; + pb->buf[i++] = (BYTE)(c >> 8); +#else /* Write a character in ANSI/OEM */ + c = ff_convert(c, 0); /* Unicode -> OEM */ + if (!c) c = '?'; + if (c >= 0x100) + pb->buf[i++] = (BYTE)(c >> 8); + pb->buf[i++] = (BYTE)c; +#endif +#else /* Write a character without conversion */ + pb->buf[i++] = (BYTE)c; +#endif + + if (i >= (int)(sizeof pb->buf) - 3) { /* Write buffered characters to the file */ + f_write(pb->fp, pb->buf, (UINT)i, &bw); + i = (bw == (UINT)i) ? 0 : -1; + } + pb->idx = i; + pb->nchr++; +} + + + +int f_putc ( + TCHAR c, /* A character to be output */ + FIL* fp /* Pointer to the file object */ +) +{ + putbuff pb; + UINT nw; + + + pb.fp = fp; /* Initialize output buffer */ + pb.nchr = pb.idx = 0; + + putc_bfd(&pb, c); /* Put a character */ + + if ( pb.idx >= 0 /* Flush buffered characters to the file */ + && f_write(pb.fp, pb.buf, (UINT)pb.idx, &nw) == FR_OK + && (UINT)pb.idx == nw) return pb.nchr; + return EOF; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Put a string to the file */ +/*-----------------------------------------------------------------------*/ + +int f_puts ( + const TCHAR* str, /* Pointer to the string to be output */ + FIL* fp /* Pointer to the file object */ +) +{ + putbuff pb; + UINT nw; + + + pb.fp = fp; /* Initialize output buffer */ + pb.nchr = pb.idx = 0; + + while (*str) /* Put the string */ + putc_bfd(&pb, *str++); + + if ( pb.idx >= 0 /* Flush buffered characters to the file */ + && f_write(pb.fp, pb.buf, (UINT)pb.idx, &nw) == FR_OK + && (UINT)pb.idx == nw) return pb.nchr; + return EOF; +} + + + + +/*-----------------------------------------------------------------------*/ +/* Put a formatted string to the file */ +/*-----------------------------------------------------------------------*/ + +int f_printf ( + FIL* fp, /* Pointer to the file object */ + const TCHAR* fmt, /* Pointer to the format string */ + ... /* Optional arguments... */ +) +{ + va_list arp; + BYTE f, r; + UINT nw, i, j, w; + DWORD v; + TCHAR c, d, s[16], *p; + putbuff pb; + + + pb.fp = fp; /* Initialize output buffer */ + pb.nchr = pb.idx = 0; + + va_start(arp, fmt); + + for (;;) { + c = *fmt++; + if (c == 0) break; /* End of string */ + if (c != '%') { /* Non escape character */ + putc_bfd(&pb, c); + continue; + } + w = f = 0; + c = *fmt++; + if (c == '0') { /* Flag: '0' padding */ + f = 1; c = *fmt++; + } else { + if (c == '-') { /* Flag: left justified */ + f = 2; c = *fmt++; + } + } + while (IsDigit(c)) { /* Precision */ + w = w * 10 + c - '0'; + c = *fmt++; + } + if (c == 'l' || c == 'L') { /* Prefix: Size is long int */ + f |= 4; c = *fmt++; + } + if (!c) break; + d = c; + if (IsLower(d)) d -= 0x20; + switch (d) { /* Type is... */ + case 'S' : /* String */ + p = va_arg(arp, TCHAR*); + for (j = 0; p[j]; j++) ; + if (!(f & 2)) { + while (j++ < w) putc_bfd(&pb, ' '); + } + while (*p) putc_bfd(&pb, *p++); + while (j++ < w) putc_bfd(&pb, ' '); + continue; + case 'C' : /* Character */ + putc_bfd(&pb, (TCHAR)va_arg(arp, int)); continue; + case 'B' : /* Binary */ + r = 2; break; + case 'O' : /* Octal */ + r = 8; break; + case 'D' : /* Signed decimal */ + case 'U' : /* Unsigned decimal */ + r = 10; break; + case 'X' : /* Hexdecimal */ + r = 16; break; + default: /* Unknown type (pass-through) */ + putc_bfd(&pb, c); continue; + } + + /* Get an argument and put it in numeral */ + v = (f & 4) ? (DWORD)va_arg(arp, long) : ((d == 'D') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int)); + if (d == 'D' && (v & 0x80000000)) { + v = 0 - v; + f |= 8; + } + i = 0; + do { + d = (TCHAR)(v % r); v /= r; + if (d > 9) d += (c == 'x') ? 0x27 : 0x07; + s[i++] = d + '0'; + } while (v && i < sizeof s / sizeof s[0]); + if (f & 8) s[i++] = '-'; + j = i; d = (f & 1) ? '0' : ' '; + while (!(f & 2) && j++ < w) putc_bfd(&pb, d); + do putc_bfd(&pb, s[--i]); while (i); + while (j++ < w) putc_bfd(&pb, d); + } + + va_end(arp); + + if ( pb.idx >= 0 /* Flush buffered characters to the file */ + && f_write(pb.fp, pb.buf, (UINT)pb.idx, &nw) == FR_OK + && (UINT)pb.idx == nw) return pb.nchr; + return EOF; +} + +#endif /* !_FS_READONLY */ +#endif /* _USE_STRFUNC */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/ChaN/ff.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,350 @@ +/*---------------------------------------------------------------------------/ +/ FatFs - FAT file system module include R0.11a (C)ChaN, 2015 +/----------------------------------------------------------------------------/ +/ FatFs module is a free software that opened under license policy of +/ following conditions. +/ +/ Copyright (C) 2015, ChaN, all right reserved. +/ +/ 1. Redistributions of source code must retain the above copyright notice, +/ this condition and the following disclaimer. +/ +/ This software is provided by the copyright holder and contributors "AS IS" +/ and any warranties related to this software are DISCLAIMED. +/ The copyright owner or contributors be NOT LIABLE for any damages caused +/ by use of this software. +/---------------------------------------------------------------------------*/ + + +#ifndef _FATFS +#define _FATFS 64180 /* Revision ID */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "integer.h" /* Basic integer types */ +#include "ffconf.h" /* FatFs configuration options */ +#if _FATFS != _FFCONF +#error Wrong configuration file (ffconf.h). +#endif + + + +/* Definitions of volume management */ + +#if _MULTI_PARTITION /* Multiple partition configuration */ +typedef struct { + BYTE pd; /* Physical drive number */ + BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */ +} PARTITION; +extern PARTITION VolToPart[]; /* Volume - Partition resolution table */ +#define LD2PD(vol) (VolToPart[vol].pd) /* Get physical drive number */ +#define LD2PT(vol) (VolToPart[vol].pt) /* Get partition index */ + +#else /* Single partition configuration */ +#define LD2PD(vol) (BYTE)(vol) /* Each logical drive is bound to the same physical drive number */ +#define LD2PT(vol) 0 /* Find first valid partition or in SFD */ + +#endif + + + +/* Type of path name strings on FatFs API */ + +#if _LFN_UNICODE /* Unicode string */ +#if !_USE_LFN +#error _LFN_UNICODE must be 0 at non-LFN cfg. +#endif +#ifndef _INC_TCHAR +typedef WCHAR TCHAR; +#define _T(x) L ## x +#define _TEXT(x) L ## x +#endif + +#else /* ANSI/OEM string */ +#ifndef _INC_TCHAR +typedef char TCHAR; +#define _T(x) x +#define _TEXT(x) x +#endif + +#endif + + + +/* File system object structure (FATFS) */ + +typedef struct { + BYTE fs_type; /* FAT sub-type (0:Not mounted) */ + BYTE drv; /* Physical drive number */ + BYTE csize; /* Sectors per cluster (1,2,4...128) */ + BYTE n_fats; /* Number of FAT copies (1 or 2) */ + BYTE wflag; /* win[] flag (b0:dirty) */ + BYTE fsi_flag; /* FSINFO flags (b7:disabled, b0:dirty) */ + WORD id; /* File system mount ID */ + WORD n_rootdir; /* Number of root directory entries (FAT12/16) */ +#if _MAX_SS != _MIN_SS + WORD ssize; /* Bytes per sector (512, 1024, 2048 or 4096) */ +#endif +#if _FS_REENTRANT + _SYNC_t sobj; /* Identifier of sync object */ +#endif +#if !_FS_READONLY + DWORD last_clust; /* Last allocated cluster */ + DWORD free_clust; /* Number of free clusters */ +#endif +#if _FS_RPATH + DWORD cdir; /* Current directory start cluster (0:root) */ +#endif + DWORD n_fatent; /* Number of FAT entries, = number of clusters + 2 */ + DWORD fsize; /* Sectors per FAT */ + DWORD volbase; /* Volume start sector */ + DWORD fatbase; /* FAT start sector */ + DWORD dirbase; /* Root directory start sector (FAT32:Cluster#) */ + DWORD database; /* Data start sector */ + DWORD winsect; /* Current sector appearing in the win[] */ + BYTE win[_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */ +} FATFS; + + + +/* File object structure (FIL) */ + +typedef struct { + FATFS* fs; /* Pointer to the related file system object (**do not change order**) */ + WORD id; /* Owner file system mount ID (**do not change order**) */ + BYTE flag; /* Status flags */ + BYTE err; /* Abort flag (error code) */ + DWORD fptr; /* File read/write pointer (Zeroed on file open) */ + DWORD fsize; /* File size */ + DWORD sclust; /* File start cluster (0:no cluster chain, always 0 when fsize is 0) */ + DWORD clust; /* Current cluster of fpter (not valid when fprt is 0) */ + DWORD dsect; /* Sector number appearing in buf[] (0:invalid) */ +#if !_FS_READONLY + DWORD dir_sect; /* Sector number containing the directory entry */ + BYTE* dir_ptr; /* Pointer to the directory entry in the win[] */ +#endif +#if _USE_FASTSEEK + DWORD* cltbl; /* Pointer to the cluster link map table (Nulled on file open) */ +#endif +#if _FS_LOCK + UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */ +#endif +#if !_FS_TINY + BYTE buf[_MAX_SS]; /* File private data read/write window */ +#endif +} FIL; + + + +/* Directory object structure (FATFS_DIR) */ + +typedef struct { + FATFS* fs; /* Pointer to the owner file system object (**do not change order**) */ + WORD id; /* Owner file system mount ID (**do not change order**) */ + WORD index; /* Current read/write index number */ + DWORD sclust; /* Table start cluster (0:Root dir) */ + DWORD clust; /* Current cluster */ + DWORD sect; /* Current sector */ + BYTE* dir; /* Pointer to the current SFN entry in the win[] */ + BYTE* fn; /* Pointer to the SFN (in/out) {file[8],ext[3],status[1]} */ +#if _FS_LOCK + UINT lockid; /* File lock ID (index of file semaphore table Files[]) */ +#endif +#if _USE_LFN + WCHAR* lfn; /* Pointer to the LFN working buffer */ + WORD lfn_idx; /* Last matched LFN index number (0xFFFF:No LFN) */ +#endif +#if _USE_FIND + const TCHAR* pat; /* Pointer to the name matching pattern */ +#endif +} FATFS_DIR; + + + +/* File information structure (FILINFO) */ + +typedef struct { + DWORD fsize; /* File size */ + WORD fdate; /* Last modified date */ + WORD ftime; /* Last modified time */ + BYTE fattrib; /* Attribute */ + TCHAR fname[13]; /* Short file name (8.3 format) */ +#if _USE_LFN + TCHAR* lfname; /* Pointer to the LFN buffer */ + UINT lfsize; /* Size of LFN buffer in TCHAR */ +#endif +} FILINFO; + + + +/* File function return code (FRESULT) */ + +typedef enum { + FR_OK = 0, /* (0) Succeeded */ + FR_DISK_ERR, /* (1) A hard error occurred in the low level disk I/O layer */ + FR_INT_ERR, /* (2) Assertion failed */ + FR_NOT_READY, /* (3) The physical drive cannot work */ + FR_NO_FILE, /* (4) Could not find the file */ + FR_NO_PATH, /* (5) Could not find the path */ + FR_INVALID_NAME, /* (6) The path name format is invalid */ + FR_DENIED, /* (7) Access denied due to prohibited access or directory full */ + FR_EXIST, /* (8) Access denied due to prohibited access */ + FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */ + FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */ + FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */ + FR_NOT_ENABLED, /* (12) The volume has no work area */ + FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume */ + FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any parameter error */ + FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */ + FR_LOCKED, /* (16) The operation is rejected according to the file sharing policy */ + FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */ + FR_TOO_MANY_OPEN_FILES, /* (18) Number of open files > _FS_LOCK */ + FR_INVALID_PARAMETER /* (19) Given parameter is invalid */ +} FRESULT; + + + +/*--------------------------------------------------------------*/ +/* FatFs module application interface */ + +FRESULT f_open (FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */ +FRESULT f_close (FIL* fp); /* Close an open file object */ +FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from a file */ +FRESULT f_write (FIL* fp, const void* buff, UINT btw, UINT* bw); /* Write data to a file */ +FRESULT f_forward (FIL* fp, UINT(*func)(const BYTE*,UINT), UINT btf, UINT* bf); /* Forward data to the stream */ +FRESULT f_lseek (FIL* fp, DWORD ofs); /* Move file pointer of a file object */ +FRESULT f_truncate (FIL* fp); /* Truncate file */ +FRESULT f_sync (FIL* fp); /* Flush cached data of a writing file */ +FRESULT f_opendir (FATFS_DIR* dp, const TCHAR* path); /* Open a directory */ +FRESULT f_closedir (FATFS_DIR* dp); /* Close an open directory */ +FRESULT f_readdir (FATFS_DIR* dp, FILINFO* fno); /* Read a directory item */ +FRESULT f_findfirst (FATFS_DIR* dp, FILINFO* fno, const TCHAR* path, const TCHAR* pattern); /* Find first file */ +FRESULT f_findnext (FATFS_DIR* dp, FILINFO* fno); /* Find next file */ +FRESULT f_mkdir (const TCHAR* path); /* Create a sub directory */ +FRESULT f_unlink (const TCHAR* path); /* Delete an existing file or directory */ +FRESULT f_rename (const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */ +FRESULT f_stat (const TCHAR* path, FILINFO* fno); /* Get file status */ +FRESULT f_chmod (const TCHAR* path, BYTE attr, BYTE mask); /* Change attribute of the file/dir */ +FRESULT f_utime (const TCHAR* path, const FILINFO* fno); /* Change times-tamp of the file/dir */ +FRESULT f_chdir (const TCHAR* path); /* Change current directory */ +FRESULT f_chdrive (const TCHAR* path); /* Change current drive */ +FRESULT f_getcwd (TCHAR* buff, UINT len); /* Get current directory */ +FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */ +FRESULT f_getlabel (const TCHAR* path, TCHAR* label, DWORD* vsn); /* Get volume label */ +FRESULT f_setlabel (const TCHAR* label); /* Set volume label */ +FRESULT f_mount (FATFS* fs, const TCHAR* path, BYTE opt); /* Mount/Unmount a logical drive */ +FRESULT f_mkfs (const TCHAR* path, BYTE sfd, UINT au); /* Create a file system on the volume */ +FRESULT f_fdisk (BYTE pdrv, const DWORD szt[], void* work); /* Divide a physical drive into some partitions */ +int f_putc (TCHAR c, FIL* fp); /* Put a character to the file */ +int f_puts (const TCHAR* str, FIL* cp); /* Put a string to the file */ +int f_printf (FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */ +TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the file */ + +#define f_eof(fp) ((int)((fp)->fptr == (fp)->fsize)) +#define f_error(fp) ((fp)->err) +#define f_tell(fp) ((fp)->fptr) +#define f_size(fp) ((fp)->fsize) +#define f_rewind(fp) f_lseek((fp), 0) +#define f_rewinddir(dp) f_readdir((dp), 0) + +#ifndef EOF +#define EOF (-1) +#endif + + + + +/*--------------------------------------------------------------*/ +/* Additional user defined functions */ + +/* RTC function */ +#if !_FS_READONLY && !_FS_NORTC +DWORD get_fattime (void); +#endif + +/* Unicode support functions */ +#if _USE_LFN /* Unicode - OEM code conversion */ +WCHAR ff_convert (WCHAR chr, UINT dir); /* OEM-Unicode bidirectional conversion */ +WCHAR ff_wtoupper (WCHAR chr); /* Unicode upper-case conversion */ +#if _USE_LFN == 3 /* Memory functions */ +void* ff_memalloc (UINT msize); /* Allocate memory block */ +void ff_memfree (void* mblock); /* Free memory block */ +#endif +#endif + +/* Sync functions */ +#if _FS_REENTRANT +int ff_cre_syncobj (BYTE vol, _SYNC_t* sobj); /* Create a sync object */ +int ff_req_grant (_SYNC_t sobj); /* Lock sync object */ +void ff_rel_grant (_SYNC_t sobj); /* Unlock sync object */ +int ff_del_syncobj (_SYNC_t sobj); /* Delete a sync object */ +#endif + + + + +/*--------------------------------------------------------------*/ +/* Flags and offset address */ + + +/* File access control and file status flags (FIL.flag) */ + +#define FA_READ 0x01 +#define FA_OPEN_EXISTING 0x00 + +#if !_FS_READONLY +#define FA_WRITE 0x02 +#define FA_CREATE_NEW 0x04 +#define FA_CREATE_ALWAYS 0x08 +#define FA_OPEN_ALWAYS 0x10 +#define FA__WRITTEN 0x20 +#define FA__DIRTY 0x40 +#endif + + +/* FAT sub type (FATFS.fs_type) */ + +#define FS_FAT12 1 +#define FS_FAT16 2 +#define FS_FAT32 3 + + +/* File attribute bits for directory entry */ + +#define AM_RDO 0x01 /* Read only */ +#define AM_HID 0x02 /* Hidden */ +#define AM_SYS 0x04 /* System */ +#define AM_VOL 0x08 /* Volume label */ +#define AM_LFN 0x0F /* LFN entry */ +#define AM_DIR 0x10 /* Directory */ +#define AM_ARC 0x20 /* Archive */ +#define AM_MASK 0x3F /* Mask of defined bits */ + + +/* Fast seek feature */ +#define CREATE_LINKMAP 0xFFFFFFFF + + + +/*--------------------------------*/ +/* Multi-byte word access macros */ + +#if _WORD_ACCESS == 1 /* Enable word access to the FAT structure */ +#define LD_WORD(ptr) (WORD)(*(WORD*)(BYTE*)(ptr)) +#define LD_DWORD(ptr) (DWORD)(*(DWORD*)(BYTE*)(ptr)) +#define ST_WORD(ptr,val) *(WORD*)(BYTE*)(ptr)=(WORD)(val) +#define ST_DWORD(ptr,val) *(DWORD*)(BYTE*)(ptr)=(DWORD)(val) +#else /* Use byte-by-byte access to the FAT structure */ +#define LD_WORD(ptr) (WORD)(((WORD)*((BYTE*)(ptr)+1)<<8)|(WORD)*(BYTE*)(ptr)) +#define LD_DWORD(ptr) (DWORD)(((DWORD)*((BYTE*)(ptr)+3)<<24)|((DWORD)*((BYTE*)(ptr)+2)<<16)|((WORD)*((BYTE*)(ptr)+1)<<8)|*(BYTE*)(ptr)) +#define ST_WORD(ptr,val) *(BYTE*)(ptr)=(BYTE)(val); *((BYTE*)(ptr)+1)=(BYTE)((WORD)(val)>>8) +#define ST_DWORD(ptr,val) *(BYTE*)(ptr)=(BYTE)(val); *((BYTE*)(ptr)+1)=(BYTE)((WORD)(val)>>8); *((BYTE*)(ptr)+2)=(BYTE)((DWORD)(val)>>16); *((BYTE*)(ptr)+3)=(BYTE)((DWORD)(val)>>24) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _FATFS */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/ChaN/ffconf.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,285 @@ +/*---------------------------------------------------------------------------/ +/ FatFs - FAT file system module configuration file R0.11a (C)ChaN, 2015 +/---------------------------------------------------------------------------*/ + +#define _FFCONF 64180 /* Revision ID */ + +#define FFS_DBG 0 + +/*---------------------------------------------------------------------------/ +/ Function Configurations +/---------------------------------------------------------------------------*/ + +#define _FS_READONLY 0 +/* This option switches read-only configuration. (0:Read/Write or 1:Read-only) +/ Read-only configuration removes writing API functions, f_write(), f_sync(), +/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree() +/ and optional writing functions as well. */ + + +#define _FS_MINIMIZE 0 +/* This option defines minimization level to remove some basic API functions. +/ +/ 0: All basic functions are enabled. +/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_chmod(), f_utime(), +/ f_truncate() and f_rename() function are removed. +/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1. +/ 3: f_lseek() function is removed in addition to 2. */ + + +#define _USE_STRFUNC 0 +/* This option switches string functions, f_gets(), f_putc(), f_puts() and +/ f_printf(). +/ +/ 0: Disable string functions. +/ 1: Enable without LF-CRLF conversion. +/ 2: Enable with LF-CRLF conversion. */ + + +#define _USE_FIND 0 +/* This option switches filtered directory read feature and related functions, +/ f_findfirst() and f_findnext(). (0:Disable or 1:Enable) */ + + +#define _USE_MKFS 1 +/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */ + + +#define _USE_FASTSEEK 0 +/* This option switches fast seek feature. (0:Disable or 1:Enable) */ + + +#define _USE_LABEL 0 +/* This option switches volume label functions, f_getlabel() and f_setlabel(). +/ (0:Disable or 1:Enable) */ + + +#define _USE_FORWARD 0 +/* This option switches f_forward() function. (0:Disable or 1:Enable) +/ To enable it, also _FS_TINY need to be set to 1. */ + + +/*---------------------------------------------------------------------------/ +/ Locale and Namespace Configurations +/---------------------------------------------------------------------------*/ + +#define _CODE_PAGE 850 +/* This option specifies the OEM code page to be used on the target system. +/ Incorrect setting of the code page can cause a file open failure. +/ +/ 1 - ASCII (No extended character. Non-LFN cfg. only) +/ 437 - U.S. +/ 720 - Arabic +/ 737 - Greek +/ 771 - KBL +/ 775 - Baltic +/ 850 - Latin 1 +/ 852 - Latin 2 +/ 855 - Cyrillic +/ 857 - Turkish +/ 860 - Portuguese +/ 861 - Icelandic +/ 862 - Hebrew +/ 863 - Canadian French +/ 864 - Arabic +/ 865 - Nordic +/ 866 - Russian +/ 869 - Greek 2 +/ 932 - Japanese (DBCS) +/ 936 - Simplified Chinese (DBCS) +/ 949 - Korean (DBCS) +/ 950 - Traditional Chinese (DBCS) +*/ + + +#define _USE_LFN 1 +#define _MAX_LFN 255 +/* The _USE_LFN option switches the LFN feature. +/ +/ 0: Disable LFN feature. _MAX_LFN has no effect. +/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe. +/ 2: Enable LFN with dynamic working buffer on the STACK. +/ 3: Enable LFN with dynamic working buffer on the HEAP. +/ +/ When enable the LFN feature, Unicode handling functions (option/unicode.c) must +/ be added to the project. The LFN working buffer occupies (_MAX_LFN + 1) * 2 bytes. +/ When use stack for the working buffer, take care on stack overflow. When use heap +/ memory for the working buffer, memory management functions, ff_memalloc() and +/ ff_memfree(), must be added to the project. */ + + +#define _LFN_UNICODE 0 +/* This option switches character encoding on the API. (0:ANSI/OEM or 1:Unicode) +/ To use Unicode string for the path name, enable LFN feature and set _LFN_UNICODE +/ to 1. This option also affects behavior of string I/O functions. */ + + +#define _STRF_ENCODE 3 +/* When _LFN_UNICODE is 1, this option selects the character encoding on the file to +/ be read/written via string I/O functions, f_gets(), f_putc(), f_puts and f_printf(). +/ +/ 0: ANSI/OEM +/ 1: UTF-16LE +/ 2: UTF-16BE +/ 3: UTF-8 +/ +/ When _LFN_UNICODE is 0, this option has no effect. */ + + +#define _FS_RPATH 0 +/* This option configures relative path feature. +/ +/ 0: Disable relative path feature and remove related functions. +/ 1: Enable relative path feature. f_chdir() and f_chdrive() are available. +/ 2: f_getcwd() function is available in addition to 1. +/ +/ Note that directory items read via f_readdir() are affected by this option. */ + + +/*---------------------------------------------------------------------------/ +/ Drive/Volume Configurations +/---------------------------------------------------------------------------*/ + +#define _VOLUMES 1 +/* Number of volumes (logical drives) to be used. */ + + +#define _STR_VOLUME_ID 0 +#define _VOLUME_STRS "RAM","NAND","CF","SD1","SD2","USB1","USB2","USB3" +/* _STR_VOLUME_ID option switches string volume ID feature. +/ When _STR_VOLUME_ID is set to 1, also pre-defined strings can be used as drive +/ number in the path name. _VOLUME_STRS defines the drive ID strings for each +/ logical drives. Number of items must be equal to _VOLUMES. Valid characters for +/ the drive ID strings are: A-Z and 0-9. */ + + +#define _MULTI_PARTITION 0 +/* This option switches multi-partition feature. By default (0), each logical drive +/ number is bound to the same physical drive number and only an FAT volume found on +/ the physical drive will be mounted. When multi-partition feature is enabled (1), +/ each logical drive number is bound to arbitrary physical drive and partition +/ listed in the VolToPart[]. Also f_fdisk() funciton will be available. */ + + +#define _MIN_SS 512 +#define _MAX_SS 512 +/* These options configure the range of sector size to be supported. (512, 1024, +/ 2048 or 4096) Always set both 512 for most systems, all type of memory cards and +/ harddisk. But a larger value may be required for on-board flash memory and some +/ type of optical media. When _MAX_SS is larger than _MIN_SS, FatFs is configured +/ to variable sector size and GET_SECTOR_SIZE command must be implemented to the +/ disk_ioctl() function. */ + + +#define _USE_TRIM 0 +/* This option switches ATA-TRIM feature. (0:Disable or 1:Enable) +/ To enable Trim feature, also CTRL_TRIM command should be implemented to the +/ disk_ioctl() function. */ + + +#define _FS_NOFSINFO 0 +/* If you need to know correct free space on the FAT32 volume, set bit 0 of this +/ option, and f_getfree() function at first time after volume mount will force +/ a full FAT scan. Bit 1 controls the use of last allocated cluster number. +/ +/ bit0=0: Use free cluster count in the FSINFO if available. +/ bit0=1: Do not trust free cluster count in the FSINFO. +/ bit1=0: Use last allocated cluster number in the FSINFO if available. +/ bit1=1: Do not trust last allocated cluster number in the FSINFO. +*/ + + + +/*---------------------------------------------------------------------------/ +/ System Configurations +/---------------------------------------------------------------------------*/ + +#define _FS_TINY 0 +/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny) +/ At the tiny configuration, size of the file object (FIL) is reduced _MAX_SS +/ bytes. Instead of private sector buffer eliminated from the file object, +/ common sector buffer in the file system object (FATFS) is used for the file +/ data transfer. */ + + +#define _FS_NORTC 0 +#define _NORTC_MON 1 +#define _NORTC_MDAY 1 +#define _NORTC_YEAR 2015 +/* The _FS_NORTC option switches timestamp feature. If the system does not have +/ an RTC function or valid timestamp is not needed, set _FS_NORTC to 1 to disable +/ the timestamp feature. All objects modified by FatFs will have a fixed timestamp +/ defined by _NORTC_MON, _NORTC_MDAY and _NORTC_YEAR. +/ When timestamp feature is enabled (_FS_NORTC == 0), get_fattime() function need +/ to be added to the project to read current time form RTC. _NORTC_MON, +/ _NORTC_MDAY and _NORTC_YEAR have no effect. +/ These options have no effect at read-only configuration (_FS_READONLY == 1). */ + + +#define _FS_LOCK 0 +/* The _FS_LOCK option switches file lock feature to control duplicated file open +/ and illegal operation to open objects. This option must be 0 when _FS_READONLY +/ is 1. +/ +/ 0: Disable file lock feature. To avoid volume corruption, application program +/ should avoid illegal open, remove and rename to the open objects. +/ >0: Enable file lock feature. The value defines how many files/sub-directories +/ can be opened simultaneously under file lock control. Note that the file +/ lock feature is independent of re-entrancy. */ + + +#define _FS_REENTRANT 0 +#define _FS_TIMEOUT 1000 +#define _SYNC_t HANDLE +/* The _FS_REENTRANT option switches the re-entrancy (thread safe) of the FatFs +/ module itself. Note that regardless of this option, file access to different +/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs() +/ and f_fdisk() function, are always not re-entrant. Only file/directory access +/ to the same volume is under control of this feature. +/ +/ 0: Disable re-entrancy. _FS_TIMEOUT and _SYNC_t have no effect. +/ 1: Enable re-entrancy. Also user provided synchronization handlers, +/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj() +/ function, must be added to the project. Samples are available in +/ option/syscall.c. +/ +/ The _FS_TIMEOUT defines timeout period in unit of time tick. +/ The _SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*, +/ SemaphoreHandle_t and etc.. A header file for O/S definitions needs to be +/ included somewhere in the scope of ff.c. */ + + +#define _WORD_ACCESS 0 +/* The _WORD_ACCESS option is an only platform dependent option. It defines +/ which access method is used to the word data on the FAT volume. +/ +/ 0: Byte-by-byte access. Always compatible with all platforms. +/ 1: Word access. Do not choose this unless under both the following conditions. +/ +/ * Address misaligned memory access is always allowed to ALL instructions. +/ * Byte order on the memory is little-endian. +/ +/ If it is the case, _WORD_ACCESS can also be set to 1 to reduce code size. +/ Following table shows allowable settings of some type of processors. +/ +/ ARM7TDMI 0 *2 ColdFire 0 *1 V850E 0 *2 +/ Cortex-M3 0 *3 Z80 0/1 V850ES 0/1 +/ Cortex-M0 0 *2 x86 0/1 TLCS-870 0/1 +/ AVR 0/1 RX600(LE) 0/1 TLCS-900 0/1 +/ AVR32 0 *1 RL78 0 *2 R32C 0 *2 +/ PIC18 0/1 SH-2 0 *1 M16C 0/1 +/ PIC24 0 *2 H8S 0 *1 MSP430 0 *2 +/ PIC32 0 *1 H8/300H 0 *1 8051 0/1 +/ +/ *1:Big-endian. +/ *2:Unaligned memory access is not supported. +/ *3:Some compilers generate LDM/STM for mem_cpy function. +*/ + +#define FLUSH_ON_NEW_CLUSTER 0 /* Sync the file on every new cluster */ +#define FLUSH_ON_NEW_SECTOR 1 /* Sync the file on every new sector */ +/* Only one of these two defines needs to be set to 1. If both are set to 0 + the file is only sync when closed. + Clusters are group of sectors (eg: 8 sectors). Flushing on new cluster means + it would be less often than flushing on new sector. Sectors are generally + 512 Bytes long. */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/ChaN/integer.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,33 @@ +/*-------------------------------------------*/ +/* Integer type definitions for FatFs module */ +/*-------------------------------------------*/ + +#ifndef _FF_INTEGER +#define _FF_INTEGER + +#ifdef _WIN32 /* Development platform */ + +#include <windows.h> +#include <tchar.h> + +#else /* Embedded platform */ + +/* This type MUST be 8-bit */ +typedef unsigned char BYTE; + +/* These types MUST be 16-bit */ +typedef short SHORT; +typedef unsigned short WORD; +typedef unsigned short WCHAR; + +/* These types MUST be 16-bit or 32-bit */ +typedef int INT; +typedef unsigned int UINT; + +/* These types MUST be 32-bit */ +typedef long LONG; +typedef unsigned long DWORD; + +#endif + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/FATDirHandle.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,89 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include <string.h> +#include "ff.h" +#include "FATDirHandle.h" + +using namespace mbed; + +FATDirHandle::FATDirHandle(const FATFS_DIR &the_dir) { + dir = the_dir; +} + +int FATDirHandle::closedir() { + int retval = f_closedir(&dir); + delete this; + return retval; +} + +struct dirent *FATDirHandle::readdir() { + FILINFO finfo; + +#if _USE_LFN + finfo.lfname = cur_entry.d_name; + finfo.lfsize = sizeof(cur_entry.d_name); +#endif // _USE_LFN + + FRESULT res = f_readdir(&dir, &finfo); + +#if _USE_LFN + if(res != 0 || finfo.fname[0]==0) { + return NULL; + } else { + if(cur_entry.d_name[0]==0) { + // No long filename so use short filename. + memcpy(cur_entry.d_name, finfo.fname, sizeof(finfo.fname)); + } + return &cur_entry; + } +#else + if(res != 0 || finfo.fname[0]==0) { + return NULL; + } else { + memcpy(cur_entry.d_name, finfo.fname, sizeof(finfo.fname)); + return &cur_entry; + } +#endif /* _USE_LFN */ +} + +void FATDirHandle::rewinddir() { + dir.index = 0; +} + +off_t FATDirHandle::telldir() { + return dir.index; +} + +void FATDirHandle::seekdir(off_t location) { + dir.index = location; +} + +ssize_t FATDirHandle::read(struct dirent *ent) { + struct dirent *temp = readdir(); + if (!temp) { + return 0; + } + + memcpy(ent, temp, sizeof(*ent)); + return 1; +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/FATDirHandle.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,51 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef MBED_FATDIRHANDLE_H +#define MBED_FATDIRHANDLE_H + +#include "DirHandle.h" + +using namespace mbed; + +class FATDirHandle : public DirHandle { + + public: + FATDirHandle(const FATFS_DIR &the_dir); + virtual int closedir(); + virtual struct dirent *readdir(); + virtual void rewinddir(); + virtual off_t telldir(); + virtual void seekdir(off_t location); + + virtual ssize_t read(struct dirent *ent); + virtual int close() { return closedir(); }; + virtual void seek(off_t offset) { seekdir(offset); }; + virtual off_t tell() { return telldir(); }; + virtual void rewind() { rewinddir(); }; + + private: + FATFS_DIR dir; + struct dirent cur_entry; + +}; + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/FATFileHandle.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,90 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "ff.h" +#include "ffconf.h" +#include "mbed_debug.h" + +#include "FATFileHandle.h" + +FATFileHandle::FATFileHandle(FIL fh) { + _fh = fh; +} + +int FATFileHandle::close() { + int retval = f_close(&_fh); + delete this; + return retval; +} + +ssize_t FATFileHandle::write(const void* buffer, size_t length) { + UINT n; + FRESULT res = f_write(&_fh, buffer, length, &n); + if (res) { + debug_if(FFS_DBG, "f_write() failed: %d", res); + return -1; + } + return n; +} + +ssize_t FATFileHandle::read(void* buffer, size_t length) { + debug_if(FFS_DBG, "read(%d)\n", length); + UINT n; + FRESULT res = f_read(&_fh, buffer, length, &n); + if (res) { + debug_if(FFS_DBG, "f_read() failed: %d\n", res); + return -1; + } + return n; +} + +int FATFileHandle::isatty() { + return 0; +} + +off_t FATFileHandle::lseek(off_t position, int whence) { + if (whence == SEEK_END) { + position += _fh.fsize; + } else if(whence==SEEK_CUR) { + position += _fh.fptr; + } + FRESULT res = f_lseek(&_fh, position); + if (res) { + debug_if(FFS_DBG, "lseek failed: %d\n", res); + return -1; + } else { + debug_if(FFS_DBG, "lseek OK, returning %i\n", _fh.fptr); + return _fh.fptr; + } +} + +int FATFileHandle::fsync() { + FRESULT res = f_sync(&_fh); + if (res) { + debug_if(FFS_DBG, "f_sync() failed: %d\n", res); + return -1; + } + return 0; +} + +off_t FATFileHandle::flen() { + return _fh.fsize; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/FATFileHandle.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,50 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef MBED_FATFILEHANDLE_H +#define MBED_FATFILEHANDLE_H + +#include "FileHandle.h" + +using namespace mbed; + +class FATFileHandle : public FileHandle { +public: + + FATFileHandle(FIL fh); + virtual int close(); + virtual ssize_t write(const void* buffer, size_t length); + virtual ssize_t read(void* buffer, size_t length); + virtual int isatty(); + virtual off_t lseek(off_t position, int whence); + virtual int fsync(); + virtual off_t flen(); + + virtual off_t seek(off_t position, int whence) { return lseek(position, whence); } + virtual off_t size() { return flen(); } + +protected: + + FIL _fh; + +}; + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/FATFileSystem.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,174 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "mbed.h" + +#include "ffconf.h" +#include "mbed_debug.h" + +#include "FATFileSystem.h" +#include "FATFileHandle.h" +#include "FATDirHandle.h" + +DWORD get_fattime(void) { + time_t rawtime; + time(&rawtime); + struct tm *ptm = localtime(&rawtime); + return (DWORD)(ptm->tm_year - 80) << 25 + | (DWORD)(ptm->tm_mon + 1 ) << 21 + | (DWORD)(ptm->tm_mday ) << 16 + | (DWORD)(ptm->tm_hour ) << 11 + | (DWORD)(ptm->tm_min ) << 5 + | (DWORD)(ptm->tm_sec/2 ); +} + +FATFileSystem *FATFileSystem::_ffs[_VOLUMES] = {0}; + +FATFileSystem::FATFileSystem(const char* n) : FileSystemLike(n) { + debug_if(FFS_DBG, "FATFileSystem(%s)\n", n); + for(int i=0; i<_VOLUMES; i++) { + if(_ffs[i] == 0) { + _ffs[i] = this; + _fsid[0] = '0' + i; + _fsid[1] = '\0'; + debug_if(FFS_DBG, "Mounting [%s] on ffs drive [%s]\n", getName(), _fsid); + f_mount(&_fs, _fsid, 0); + return; + } + } + error("Couldn't create %s in FATFileSystem::FATFileSystem\n", n); +} + +FATFileSystem::~FATFileSystem() { + for (int i=0; i<_VOLUMES; i++) { + if (_ffs[i] == this) { + _ffs[i] = 0; + f_mount(NULL, _fsid, 0); + } + } +} + +FileHandle *FATFileSystem::open(const char* name, int flags) { + debug_if(FFS_DBG, "open(%s) on filesystem [%s], drv [%s]\n", name, getName(), _fsid); + char n[64]; + sprintf(n, "%s:/%s", _fsid, name); + + /* POSIX flags -> FatFS open mode */ + BYTE openmode; + if (flags & O_RDWR) { + openmode = FA_READ|FA_WRITE; + } else if(flags & O_WRONLY) { + openmode = FA_WRITE; + } else { + openmode = FA_READ; + } + if(flags & O_CREAT) { + if(flags & O_TRUNC) { + openmode |= FA_CREATE_ALWAYS; + } else { + openmode |= FA_OPEN_ALWAYS; + } + } + + FIL fh; + FRESULT res = f_open(&fh, n, openmode); + if (res) { + debug_if(FFS_DBG, "f_open('w') failed: %d\n", res); + return NULL; + } + if (flags & O_APPEND) { + f_lseek(&fh, fh.fsize); + } + return new FATFileHandle(fh); +} + +int FATFileSystem::open(FileHandle **file, const char *name, int flags) { + FileHandle *temp = open(name, flags); + if (!temp) { + return -1; + } + + *file = temp; + return 0; +} + +int FATFileSystem::remove(const char *filename) { + FRESULT res = f_unlink(filename); + if (res) { + debug_if(FFS_DBG, "f_unlink() failed: %d\n", res); + return -1; + } + return 0; +} + +int FATFileSystem::rename(const char *oldname, const char *newname) { + FRESULT res = f_rename(oldname, newname); + if (res) { + debug_if(FFS_DBG, "f_rename() failed: %d\n", res); + return -1; + } + return 0; +} + +int FATFileSystem::format() { + FRESULT res = f_mkfs(_fsid, 0, 512); // Logical drive number, Partitioning rule, Allocation unit size (bytes per cluster) + if (res) { + debug_if(FFS_DBG, "f_mkfs() failed: %d\n", res); + return -1; + } + return 0; +} + +DirHandle *FATFileSystem::opendir(const char *name) { + FATFS_DIR dir; + FRESULT res = f_opendir(&dir, name); + if (res != 0) { + return NULL; + } + return new FATDirHandle(dir); +} + +int FATFileSystem::open(DirHandle **dir, const char *name) { + DirHandle *temp = opendir(name); + if (!temp) { + return -1; + } + + *dir = temp; + return 0; +} + +int FATFileSystem::mkdir(const char *name, mode_t mode) { + FRESULT res = f_mkdir(name); + return res == 0 ? 0 : -1; +} + +int FATFileSystem::mount() { + FRESULT res = f_mount(&_fs, _fsid, 1); + return res == 0 ? 0 : -1; +} + +int FATFileSystem::unmount() { + if (disk_sync()) + return -1; + FRESULT res = f_mount(NULL, _fsid, 0); + return res == 0 ? 0 : -1; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/FATFileSystem.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,96 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef MBED_FATFILESYSTEM_H +#define MBED_FATFILESYSTEM_H + +#include "FileSystemLike.h" +#include "FileHandle.h" +#include "ff.h" +#include <stdint.h> + +using namespace mbed; + +/** + * FATFileSystem based on ChaN's Fat Filesystem library v0.8 + */ +class FATFileSystem : public FileSystemLike { +public: + + FATFileSystem(const char* n); + virtual ~FATFileSystem(); + + static FATFileSystem * _ffs[_VOLUMES]; // FATFileSystem objects, as parallel to FatFs drives array + FATFS _fs; // Work area (file system object) for logical drive + char _fsid[2]; + + /** + * Opens a file on the filesystem + */ + virtual FileHandle *open(const char* name, int flags); + virtual int open(FileHandle **file, const char *name, int flags); + + /** + * Removes a file path + */ + virtual int remove(const char *filename); + + /** + * Renames a file + */ + virtual int rename(const char *oldname, const char *newname); + + /** + * Formats a logical drive, FDISK artitioning rule, 512 bytes per cluster + */ + virtual int format(); + + /** + * Opens a directory on the filesystem + */ + virtual DirHandle *opendir(const char *name); + virtual int open(DirHandle **dir, const char *name); + + /** + * Creates a directory path + */ + virtual int mkdir(const char *name, mode_t mode); + + /** + * Mounts the filesystem + */ + virtual int mount(); + + /** + * Unmounts the filesystem + */ + virtual int unmount(); + + virtual int disk_initialize() { return 0; } + virtual int disk_status() { return 0; } + virtual int disk_read(uint8_t *buffer, uint32_t sector, uint32_t count) = 0; + virtual int disk_write(const uint8_t *buffer, uint32_t sector, uint32_t count) = 0; + virtual int disk_sync() { return 0; } + virtual uint32_t disk_sectors() = 0; + +}; + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/FATFileSystem/MemFileSystem.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,77 @@ +/* mbed Microcontroller Library - MemFileSystem + * Copyright (c) 2008, sford + */ + + +#ifndef MBED_MEMFILESYSTEM_H +#define MBED_MEMFILESYSTEM_H + +#include "FATFileSystem.h" + +namespace mbed +{ + + class MemFileSystem : public FATFileSystem + { + public: + + // 2000 sectors, each 512 bytes (malloced as required) + char *sectors[2000]; + + MemFileSystem(const char* name) : FATFileSystem(name) { + memset(sectors, 0, sizeof(sectors)); + } + + virtual ~MemFileSystem() { + for(int i = 0; i < 2000; i++) { + if(sectors[i]) { + free(sectors[i]); + } + } + } + + // read a sector in to the buffer, return 0 if ok + virtual int disk_read(char *buffer, int sector) { + if(sectors[sector] == 0) { + // nothing allocated means sector is empty + memset(buffer, 0, 512); + } else { + memcpy(buffer, sectors[sector], 512); + } + return 0; + } + + // write a sector from the buffer, return 0 if ok + virtual int disk_write(const char *buffer, int sector) { + // if buffer is zero deallocate sector + char zero[512]; + memset(zero, 0, 512); + if(memcmp(zero, buffer, 512)==0) { + if(sectors[sector] != 0) { + free(sectors[sector]); + sectors[sector] = 0; + } + return 0; + } + // else allocate a sector if needed, and write + if(sectors[sector] == 0) { + char *sec = (char*)malloc(512); + if(sec==0) { + return 1; // out of memory + } + sectors[sector] = sec; + } + memcpy(sectors[sector], buffer, 512); + return 0; + } + + // return the number of sectors + virtual int disk_sectors() { + return sizeof(sectors)/sizeof(sectors[0]); + } + + }; + +} + +#endif \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost/IUSBEnumerator.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,36 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef IUSBENUMERATOR_H_ +#define IUSBENUMERATOR_H_ + +#include "stdint.h" +#include "USBEndpoint.h" + +/* +Generic interface to implement for "smart" USB enumeration +*/ + +class IUSBEnumerator +{ +public: + virtual void setVidPid(uint16_t vid, uint16_t pid) = 0; + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) = 0; //Must return true if the interface should be parsed + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) = 0; //Must return true if the endpoint will be used +}; + +#endif /*IUSBENUMERATOR_H_*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost/USBDeviceConnected.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,124 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "USBDeviceConnected.h" +#include "dbg.h" + +USBDeviceConnected::USBDeviceConnected() { + init(); +} + +void USBDeviceConnected::init() { + hub_nb = 0; + port = 0; + vid = 0; + pid = 0; + nb_interf = 0; + enumerated = false; + activeAddr = false; + sizeControlEndpoint = 8; + device_class = 0; + device_subclass = 0; + proto = 0; + speed = false; + for (int i = 0; i < MAX_INTF; i++) { + memset((void *)&intf[i], 0, sizeof(INTERFACE)); + intf[i].in_use = false; + for (int j = 0; j < MAX_ENDPOINT_PER_INTERFACE; j++) { + intf[i].ep[j] = NULL; + strcpy(intf[i].name, "Unknown"); + } + } + hub_parent = NULL; + hub = NULL; + nb_interf = 0; +} + +INTERFACE * USBDeviceConnected::getInterface(uint8_t index) { + if (index >= MAX_INTF) + return NULL; + + if (intf[index].in_use) + return &intf[index]; + + return NULL; +} + +bool USBDeviceConnected::addInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) { + if ((intf_nb >= MAX_INTF) || (intf[intf_nb].in_use)) { + return false; + } + intf[intf_nb].in_use = true; + intf[intf_nb].intf_class = intf_class; + intf[intf_nb].intf_subclass = intf_subclass; + intf[intf_nb].intf_protocol = intf_protocol; + intf[intf_nb].nb_endpoint = 0; + return true; +} + +bool USBDeviceConnected::addEndpoint(uint8_t intf_nb, USBEndpoint * ept) { + if ((intf_nb >= MAX_INTF) || (intf[intf_nb].in_use == false) || (intf[intf_nb].nb_endpoint >= MAX_ENDPOINT_PER_INTERFACE)) { + return false; + } + intf[intf_nb].nb_endpoint++; + + for (int i = 0; i < MAX_ENDPOINT_PER_INTERFACE; i++) { + if (intf[intf_nb].ep[i] == NULL) { + intf[intf_nb].ep[i] = ept; + return true; + } + } + return false; +} + +void USBDeviceConnected::init(uint8_t hub_, uint8_t port_, bool lowSpeed_) { + USB_DBG("init dev: %p", this); + init(); + hub_nb = hub_; + port = port_; + speed = lowSpeed_; +} + +void USBDeviceConnected::disconnect() { + for(int i = 0; i < MAX_INTF; i++) { + if (intf[i].detach) intf[i].detach.call(); + } + init(); +} + + +USBEndpoint * USBDeviceConnected::getEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir, uint8_t index) { + if (intf_nb >= MAX_INTF) { + return NULL; + } + for (int i = 0; i < MAX_ENDPOINT_PER_INTERFACE; i++) { + if ((intf[intf_nb].ep[i]->getType() == type) && (intf[intf_nb].ep[i]->getDir() == dir)) { + if(index) { + index--; + } else { + return intf[intf_nb].ep[i]; + } + } + } + return NULL; +} + +USBEndpoint * USBDeviceConnected::getEndpoint(uint8_t intf_nb, uint8_t index) { + if ((intf_nb >= MAX_INTF) || (index >= MAX_ENDPOINT_PER_INTERFACE)) { + return NULL; + } + return intf[intf_nb].ep[index]; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost/USBDeviceConnected.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,186 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBDEVICECONNECTED_H +#define USBDEVICECONNECTED_H + +#include "stdint.h" +#include "USBEndpoint.h" +#include "USBHostConf.h" +#include "rtos.h" +#include "Callback.h" + +class USBHostHub; + +typedef struct { + bool in_use; + uint8_t nb_endpoint; + uint8_t intf_class; + uint8_t intf_subclass; + uint8_t intf_protocol; + USBEndpoint * ep[MAX_ENDPOINT_PER_INTERFACE]; + Callback<void()> detach; + char name[10]; +} INTERFACE; + +/** +* USBDeviceConnected class +*/ +class USBDeviceConnected +{ +public: + + /** + * Constructor + */ + USBDeviceConnected(); + + /** + * Attach an USBEndpoint to this device + * + * @param intf_nb interface number + * @param ep pointeur on the USBEndpoint which will be attached + * @returns true if successful, false otherwise + */ + bool addEndpoint(uint8_t intf_nb, USBEndpoint * ep); + + /** + * Retrieve an USBEndpoint by its TYPE and DIRECTION + * + * @param intf_nb the interface on which to lookup the USBEndpoint + * @param type type of the USBEndpoint looked for + * @param dir direction of the USBEndpoint looked for + * @param index the index of the USBEndpoint whitin the interface + * @returns pointer on the USBEndpoint if found, NULL otherwise + */ + USBEndpoint * getEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir, uint8_t index = 0); + + /** + * Retrieve an USBEndpoint by its index + * + * @param intf_nb interface number + * @param index index of the USBEndpoint + * @returns pointer on the USBEndpoint if found, NULL otherwise + */ + USBEndpoint * getEndpoint(uint8_t intf_nb, uint8_t index); + + /** + * Add a new interface to this device + * + * @param intf_nb interface number + * @param intf_class interface class + * @param intf_subclass interface subclass + * @param intf_protocol interface protocol + * @returns true if successful, false otherwise + */ + bool addInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); + + /** + * Get a specific interface + * + * @param index index of the interface to be fetched + * @returns interface + */ + INTERFACE * getInterface(uint8_t index); + + /** + * Attach a member function to call when a the device has been disconnected + * + * @param intf_nb interface number + * @param tptr pointer to the object to call the member function on + * @param mptr pointer to the member function to be called + */ + template<typename T> + inline void onDisconnect(uint8_t intf_nb, T* tptr, void (T::*mptr)(void)) { + if ((mptr != NULL) && (tptr != NULL)) { + intf[intf_nb].detach.attach(tptr, mptr); + } + } + + /** + * Attach a callback called when the device has been disconnected + * + * @param intf_nb interface number + * @param fn function pointer + */ + inline void onDisconnect(uint8_t intf_nb, void (*fn)(void)) { + if (fn != NULL) { + intf[intf_nb].detach.attach(fn); + } + } + + /** + * Disconnect the device by calling a callback function registered by a driver + */ + void disconnect(); + + // setters + void init(uint8_t hub, uint8_t port, bool lowSpeed); + inline void setAddress(uint8_t addr_) { addr = addr_; }; + inline void setVid(uint16_t vid_) { vid = vid_; }; + inline void setPid(uint16_t pid_) { pid = pid_; }; + inline void setClass(uint8_t device_class_) { device_class = device_class_; }; + inline void setSubClass(uint8_t device_subclass_) { device_subclass = device_subclass_; }; + inline void setProtocol(uint8_t pr) { proto = pr; }; + inline void setSizeControlEndpoint(uint32_t size) { sizeControlEndpoint = size; }; + inline void activeAddress(bool active) { activeAddr = active; }; + inline void setEnumerated() { enumerated = true; }; + inline void setNbIntf(uint8_t nb_intf) {nb_interf = nb_intf; }; + inline void setHubParent(USBHostHub * hub) { hub_parent = hub; }; + inline void setName(const char * name_, uint8_t intf_nb) { strcpy(intf[intf_nb].name, name_); }; + + //getters + inline uint8_t getPort() { return port; }; + inline uint8_t getHub() { return hub_nb; }; + inline uint8_t getAddress() { return addr; }; + inline uint16_t getVid() { return vid; }; + inline uint16_t getPid() { return pid; }; + inline uint8_t getClass() { return device_class; }; + inline uint8_t getSubClass() { return device_subclass; }; + inline uint8_t getProtocol() { return proto; }; + inline bool getSpeed() { return speed; }; + inline uint32_t getSizeControlEndpoint() { return sizeControlEndpoint; }; + inline bool isActiveAddress() { return activeAddr; }; + inline bool isEnumerated() { return enumerated; }; + inline USBHostHub * getHubParent() { return hub_parent; }; + inline uint8_t getNbIntf() { return nb_interf; }; + inline const char * getName(uint8_t intf_nb) { return intf[intf_nb].name; }; + + // in case this device is a hub + USBHostHub * hub; + +private: + USBHostHub * hub_parent; + + INTERFACE intf[MAX_INTF]; + uint32_t sizeControlEndpoint; + uint8_t hub_nb; + uint8_t port; + uint16_t vid; + uint16_t pid; + uint8_t addr; + uint8_t device_class; + uint8_t device_subclass; + uint8_t proto; + bool speed; + volatile bool activeAddr; + volatile bool enumerated; + uint8_t nb_interf; + + void init(); +}; + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost/USBEndpoint.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,163 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "dbg.h" +#include "USBEndpoint.h" +#if !defined(USBHOST_OTHER) +void USBEndpoint::init(HCED * hced_, ENDPOINT_TYPE type_, ENDPOINT_DIRECTION dir_, uint32_t size, uint8_t ep_number, HCTD* td_list_[2]) +{ + hced = hced_; + type = type_; + dir = dir_; + setup = (type == CONTROL_ENDPOINT) ? true : false; + + //TDs have been allocated by the host + memcpy((HCTD**)td_list, td_list_, sizeof(HCTD*)*2); //TODO: Maybe should add a param for td_list size... at least a define + memset(td_list_[0], 0, sizeof(HCTD)); + memset(td_list_[1], 0, sizeof(HCTD)); + + td_list[0]->ep = this; + td_list[1]->ep = this; + + hced->control = 0; + //Empty queue + hced->tailTD = td_list[0]; + hced->headTD = td_list[0]; + hced->nextED = 0; + + address = (ep_number & 0x7F) | ((dir - 1) << 7); + + hced->control = ((ep_number & 0x7F) << 7) // Endpoint address + | (type != CONTROL_ENDPOINT ? ( dir << 11) : 0 ) // direction : Out = 1, 2 = In + | ((size & 0x3ff) << 16); // MaxPkt Size + + transfer_len = 0; + transferred = 0; + buf_start = 0; + nextEp = NULL; + + td_current = td_list[0]; + td_next = td_list[1]; + + intf_nb = 0; + + state = USB_TYPE_IDLE; +} + +void USBEndpoint::setSize(uint32_t size) +{ + hced->control &= ~(0x3ff << 16); + hced->control |= (size << 16); +} + + +void USBEndpoint::setDeviceAddress(uint8_t addr) +{ + hced->control &= ~(0x7f); + hced->control |= (addr & 0x7F); +} + +void USBEndpoint::setSpeed(uint8_t speed) +{ + hced->control &= ~(1 << 13); + hced->control |= (speed << 13); +} +#endif + +//Only for control Eps +void USBEndpoint::setNextToken(uint32_t token) +{ + switch (token) { + case TD_SETUP: + dir = OUT; + setup = true; + break; + case TD_IN: + dir = IN; + setup = false; + break; + case TD_OUT: + dir = OUT; + setup = false; + break; + } +} +struct { + USB_TYPE type; + const char * str; +} static type_string[] = { +/*0*/ {USB_TYPE_OK, "USB_TYPE_OK"}, + {USB_TYPE_CRC_ERROR, "USB_TYPE_CRC_ERROR"}, + {USB_TYPE_BIT_STUFFING_ERROR, "USB_TYPE_BIT_STUFFING_ERROR"}, + {USB_TYPE_DATA_TOGGLE_MISMATCH_ERROR, "USB_TYPE_DATA_TOGGLE_MISMATCH_ERROR"}, + {USB_TYPE_STALL_ERROR, "USB_TYPE_STALL_ERROR"}, +/*5*/ {USB_TYPE_DEVICE_NOT_RESPONDING_ERROR, "USB_TYPE_DEVICE_NOT_RESPONDING_ERROR"}, + {USB_TYPE_PID_CHECK_FAILURE_ERROR, "USB_TYPE_PID_CHECK_FAILURE_ERROR"}, + {USB_TYPE_UNEXPECTED_PID_ERROR, "USB_TYPE_UNEXPECTED_PID_ERROR"}, + {USB_TYPE_DATA_OVERRUN_ERROR, "USB_TYPE_DATA_OVERRUN_ERROR"}, + {USB_TYPE_DATA_UNDERRUN_ERROR, "USB_TYPE_DATA_UNDERRUN_ERROR"}, +/*10*/ {USB_TYPE_ERROR, "USB_TYPE_ERROR"}, + {USB_TYPE_ERROR, "USB_TYPE_ERROR"}, + {USB_TYPE_BUFFER_OVERRUN_ERROR, "USB_TYPE_BUFFER_OVERRUN_ERROR"}, + {USB_TYPE_BUFFER_UNDERRUN_ERROR, "USB_TYPE_BUFFER_UNDERRUN_ERROR"}, + {USB_TYPE_DISCONNECTED, "USB_TYPE_DISCONNECTED"}, +/*15*/ {USB_TYPE_FREE, "USB_TYPE_FREE"}, + {USB_TYPE_IDLE, "USB_TYPE_IDLE"}, + {USB_TYPE_PROCESSING, "USB_TYPE_PROCESSING"}, + {USB_TYPE_ERROR, "USB_TYPE_ERROR"} +}; +const char * USBEndpoint::getStateString() { + return type_string[state].str; +} + +#if !defined(USBHOST_OTHER) +void USBEndpoint::setState(uint8_t st) { + if (st > 18) + return; + state = type_string[st].type; +} + +USB_TYPE USBEndpoint::queueTransfer() +{ + transfer_len = (uint32_t)td_current->bufEnd - (uint32_t)td_current->currBufPtr + 1; + transferred = transfer_len; + buf_start = (uint8_t *)td_current->currBufPtr; + + //Now add this free TD at this end of the queue + state = USB_TYPE_PROCESSING; + td_current->nextTD = (hcTd*)td_next; + hced->tailTD = td_next; + return USB_TYPE_PROCESSING; +} + +void USBEndpoint::unqueueTransfer(volatile HCTD * td) +{ + td->control=0; + td->currBufPtr=0; + td->bufEnd=0; + td->nextTD=0; + hced->headTD = (HCTD *)((uint32_t)hced->tailTD | ((uint32_t)hced->headTD & 0x2)); //Carry bit + td_current = td_next; + td_next = td; +} + +void USBEndpoint::queueEndpoint(USBEndpoint * ed) +{ + nextEp = ed; + hced->nextED = (ed == NULL) ? 0 : (hcEd*)(ed->getHCED()); +} +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost/USBEndpoint.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,191 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBENDPOINT_H +#define USBENDPOINT_H + +#include "Callback.h" +#include "USBHostTypes.h" +#include "rtos.h" + +class USBDeviceConnected; + +/** +* USBEndpoint class +*/ +class USBEndpoint +{ +public: + /** + * Constructor + */ + USBEndpoint() { +#ifdef USBHOST_OTHER + speed = false; +#endif + state = USB_TYPE_FREE; + nextEp = NULL; + }; + + /** + * Initialize an endpoint + * + * @param hced hced associated to the endpoint + * @param type endpoint type + * @param dir endpoint direction + * @param size endpoint size + * @param ep_number endpoint number + * @param td_list array of two allocated transfer descriptors + */ + + void init(HCED * hced, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir, uint32_t size, uint8_t ep_number, HCTD* td_list[2]); + + /** + * Set next token. Warning: only useful for the control endpoint + * + * @param token IN, OUT or SETUP token + */ + void setNextToken(uint32_t token); + + /** + * Queue an endpoint + * + * @param endpoint endpoint which will be queued in the linked list + */ + void queueEndpoint(USBEndpoint * endpoint); + + + /** + * Queue a transfer on the endpoint + */ + USB_TYPE queueTransfer(); + + /** + * Unqueue a transfer from the endpoint + * + * @param td hctd which will be unqueued + */ + void unqueueTransfer(volatile HCTD * td); + + /** + * Attach a member function to call when a transfer is finished + * + * @param tptr pointer to the object to call the member function on + * @param mptr pointer to the member function to be called + */ + template<typename T> + inline void attach(T* tptr, void (T::*mptr)(void)) { + if((mptr != NULL) && (tptr != NULL)) { + rx.attach(tptr, mptr); + } + } + + /** + * Attach a callback called when a transfer is finished + * + * @param fptr function pointer + */ + inline void attach(void (*fptr)(void)) { + if(fptr != NULL) { + rx.attach(fptr); + } + } + + /** + * Call the handler associted to the end of a transfer + */ + inline void call() { + if (rx) + rx.call(); + }; + + + // setters +#ifdef USBHOST_OTHER + void setState(USB_TYPE st); +#else + inline void setState(USB_TYPE st) { state = st; } +#endif + void setState(uint8_t st); + void setDeviceAddress(uint8_t addr); + inline void setLengthTransferred(int len) { transferred = len; }; + void setSpeed(uint8_t speed); + void setSize(uint32_t size); + inline void setDir(ENDPOINT_DIRECTION d) { dir = d; } + inline void setIntfNb(uint8_t intf_nb_) { intf_nb = intf_nb_; }; + + // getters + const char * getStateString(); + inline USB_TYPE getState() { return state; } + inline ENDPOINT_TYPE getType() { return type; }; +#ifdef USBHOST_OTHER + inline uint8_t getDeviceAddress() { return device_address; }; + inline uint32_t getSize() { return size; }; +#else + inline uint8_t getDeviceAddress() { return hced->control & 0x7f; }; + inline uint32_t getSize() { return (hced->control >> 16) & 0x3ff; }; + inline volatile HCTD * getHeadTD() { return (volatile HCTD*) ((uint32_t)hced->headTD & ~0xF); }; +#endif + inline int getLengthTransferred() { return transferred; } + inline uint8_t * getBufStart() { return buf_start; } + inline uint8_t getAddress(){ return address; }; + inline volatile HCTD** getTDList() { return td_list; }; + inline volatile HCED * getHCED() { return hced; }; + inline ENDPOINT_DIRECTION getDir() { return dir; } + inline volatile HCTD * getProcessedTD() { return td_current; }; + inline volatile HCTD* getNextTD() { return td_current; }; + inline bool isSetup() { return setup; } + inline USBEndpoint * nextEndpoint() { return (USBEndpoint*)nextEp; }; + inline uint8_t getIntfNb() { return intf_nb; }; + + USBDeviceConnected * dev; + + Queue<uint8_t, 1> ep_queue; + +private: + ENDPOINT_TYPE type; + volatile USB_TYPE state; + ENDPOINT_DIRECTION dir; +#ifdef USBHOST_OTHER + uint32_t size; + uint32_t ep_number; + uint32_t speed; + uint8_t device_address; +#endif + bool setup; + + uint8_t address; + + int transfer_len; + int transferred; + uint8_t * buf_start; + + Callback<void()> rx; + + USBEndpoint* nextEp; + + // USBEndpoint descriptor + volatile HCED * hced; + + volatile HCTD * td_list[2]; + volatile HCTD * td_current; + volatile HCTD * td_next; + + uint8_t intf_nb; + +}; + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost/USBHALHost.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,173 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBHALHOST_H +#define USBHALHOST_H + +#include "USBHostTypes.h" +#include "USBHostConf.h" + +class USBHostHub; + +/** +* USBHALHost class +*/ +class USBHALHost { +protected: + + /** + * Constructor + * init variables and memory where will be stored HCCA, ED and TD + */ + USBHALHost(); + + /** + * Initialize host controller. Enable USB interrupts. This part is not in the constructor because, + * this function calls a virtual method if a device is already connected + */ + void init(); + + /** + * reset the root hub + */ + void resetRootHub(); + + /** + * return the value contained in the control HEAD ED register + * + * @returns address of the control Head ED + */ + uint32_t controlHeadED(); + + /** + * return the value contained in the bulk HEAD ED register + * + * @returns address of the bulk head ED + */ + uint32_t bulkHeadED(); + + /** + * return the value of the head interrupt ED contained in the HCCA + * + * @returns address of the head interrupt ED contained in the HCCA + */ + uint32_t interruptHeadED(); + + /** + * Update the head ED for control transfers + */ + void updateControlHeadED(uint32_t addr); + + /** + * Update the head ED for bulk transfers + */ + void updateBulkHeadED(uint32_t addr); + + /** + * Update the head ED for interrupt transfers + */ + void updateInterruptHeadED(uint32_t addr); + + /** + * Enable List for the specified endpoint type + * + * @param type enable the list of ENDPOINT_TYPE type + */ + void enableList(ENDPOINT_TYPE type); + + /** + * Disable List for the specified endpoint type + * + * @param type disable the list of ENDPOINT_TYPE type + */ + bool disableList(ENDPOINT_TYPE type); + + /** + * Virtual method called when a device has been connected + * + * @param hub hub number of the device + * @param port port number of the device + * @param lowSpeed 1 if low speed, 0 otherwise + * @param hub_parent reference to the hub where the device is connected (NULL if the hub parent is the root hub) + */ + virtual void deviceConnected(int hub, int port, bool lowSpeed, USBHostHub * hub_parent = NULL) = 0; + + /** + * Virtual method called when a device has been disconnected + * + * @param hub hub number of the device + * @param port port number of the device + * @param hub_parent reference to the hub where the device is connected (NULL if the hub parent is the root hub) + * @param addr list of the TDs which have been completed to dequeue freed TDs + */ + virtual void deviceDisconnected(int hub, int port, USBHostHub * hub_parent, volatile uint32_t addr) = 0; + + /** + * Virtual method called when a transfer has been completed + * + * @param addr list of the TDs which have been completed + */ + virtual void transferCompleted(volatile uint32_t addr) = 0; + + /** + * Find a memory section for a new ED + * + * @returns the address of the new ED + */ + volatile uint8_t * getED(); + + /** + * Find a memory section for a new TD + * + * @returns the address of the new TD + */ + volatile uint8_t * getTD(); + + /** + * Release a previous memory section reserved for an ED + * + * @param ed address of the ED + */ + void freeED(volatile uint8_t * ed); + + /** + * Release a previous memory section reserved for an TD + * + * @param td address of the TD + */ + void freeTD(volatile uint8_t * td); + +private: + static void _usbisr(void); + void UsbIrqhandler(); + + void memInit(); + + HCCA volatile * usb_hcca; //256 bytes aligned + uint8_t volatile * usb_edBuf; //4 bytes aligned + uint8_t volatile * usb_tdBuf; //4 bytes aligned + + static USBHALHost * instHost; + + bool volatile edBufAlloc[MAX_ENDPOINT]; + bool volatile tdBufAlloc[MAX_TD]; +#ifdef USBHOST_OTHER + int control_disable; +#endif + +}; + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost/USBHost.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,1295 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "USBHost.h" +#include "USBHostHub.h" + +USBHost * USBHost::instHost = NULL; + +#define DEVICE_CONNECTED_EVENT (1 << 0) +#define DEVICE_DISCONNECTED_EVENT (1 << 1) +#define TD_PROCESSED_EVENT (1 << 2) + +#define MAX_TRY_ENUMERATE_HUB 3 + +#define MIN(a, b) ((a > b) ? b : a) + +/** +* How interrupts are processed: +* - new device connected: +* - a message is queued in queue_usb_event with the id DEVICE_CONNECTED_EVENT +* - when the usb_thread receives the event, it: +* - resets the device +* - reads the device descriptor +* - sets the address of the device +* - if it is a hub, enumerates it +* - device disconnected: +* - a message is queued in queue_usb_event with the id DEVICE_DISCONNECTED_EVENT +* - when the usb_thread receives the event, it: +* - free the device and all its children (hub) +* - td processed +* - a message is queued in queue_usb_event with the id TD_PROCESSED_EVENT +* - when the usb_thread receives the event, it: +* - call the callback attached to the endpoint where the td is attached +*/ +void USBHost::usb_process() +{ + + bool controlListState; + bool bulkListState; + bool interruptListState; + USBEndpoint * ep; + uint8_t i, j, res, timeout_set_addr = 10; + uint8_t buf[8]; + bool too_many_hub; + int idx; + +#if DEBUG_TRANSFER + uint8_t * buf_transfer; +#endif + +#if MAX_HUB_NB + uint8_t k; +#endif + + while(1) { + osEvent evt = mail_usb_event.get(); + + if (evt.status == osEventMail) { + + message_t * usb_msg = (message_t*)evt.value.p; + + switch (usb_msg->event_id) { + + // a new device has been connected + case DEVICE_CONNECTED_EVENT: + too_many_hub = false; + buf[4] = 0; + + do { + Lock lock(this); + bool hub_unplugged = true; + + int idx = findDevice(usb_msg->hub, usb_msg->port, (USBHostHub *)(usb_msg->hub_parent)); + /* check that hub is connected to root port */ + if (usb_msg->hub_parent) { + /* a hub device must be present */ + for (k = 0; k < MAX_HUB_NB; k++) { + if ((&hubs[k] == usb_msg->hub_parent) && (hub_in_use[k])) { + hub_unplugged=false; + } + } + } else { + hub_unplugged = false; + } + + if (((idx!=-1) && deviceInUse[idx] ) || ((idx == -1) && hub_unplugged)) { + break; + } + + for (i =0 ; i < MAX_DEVICE_CONNECTED; i++) { + if (!deviceInUse[i]) { + USB_DBG_EVENT("new device connected: %p\r\n", &devices[i]); + devices[i].init(usb_msg->hub, usb_msg->port, usb_msg->lowSpeed); + deviceReset[i] = false; + deviceInited[i] = true; + break; + } + } + + if (i == MAX_DEVICE_CONNECTED) { + USB_ERR("Too many device connected!!\r\n"); + continue; + } + + if (!controlEndpointAllocated) { + control = newEndpoint(CONTROL_ENDPOINT, OUT, 0x08, 0x00); + addEndpoint(NULL, 0, (USBEndpoint*)control); + controlEndpointAllocated = true; + } + +#if MAX_HUB_NB + if (usb_msg->hub_parent) { + devices[i].setHubParent((USBHostHub *)(usb_msg->hub_parent)); + } +#endif + + for (j = 0; j < timeout_set_addr; j++) { + + resetDevice(&devices[i]); + + // set size of control endpoint + devices[i].setSizeControlEndpoint(8); + + devices[i].activeAddress(false); + + // get first 8 bit of device descriptor + // and check if we deal with a hub + USB_DBG("usb_thread read device descriptor on dev: %p\r\n", &devices[i]); + res = getDeviceDescriptor(&devices[i], buf, 8); + + if (res != USB_TYPE_OK) { + USB_ERR("usb_thread could not read dev descr"); + continue; + } + + // set size of control endpoint + devices[i].setSizeControlEndpoint(buf[7]); + + // second step: set an address to the device + res = setAddress(&devices[i], devices[i].getAddress()); + + if (res != USB_TYPE_OK) { + USB_ERR("SET ADDR FAILED"); + continue; + } + devices[i].activeAddress(true); + USB_DBG("Address of %p: %d", &devices[i], devices[i].getAddress()); + + // try to read again the device descriptor to check if the device + // answers to its new address + res = getDeviceDescriptor(&devices[i], buf, 8); + + if (res == USB_TYPE_OK) { + break; + } + + Thread::wait(100); + } + + USB_INFO("New device connected: %p [hub: %d - port: %d]", &devices[i], usb_msg->hub, usb_msg->port); + +#if MAX_HUB_NB + if (buf[4] == HUB_CLASS) { + for (k = 0; k < MAX_HUB_NB; k++) { + if (hub_in_use[k] == false) { + for (uint8_t j = 0; j < MAX_TRY_ENUMERATE_HUB; j++) { + if (hubs[k].connect(&devices[i])) { + devices[i].hub = &hubs[k]; + hub_in_use[k] = true; + break; + } + } + if (hub_in_use[k] == true) { + break; + } + } + } + + if (k == MAX_HUB_NB) { + USB_ERR("Too many hubs connected!!\r\n"); + too_many_hub = true; + } + } + + if (usb_msg->hub_parent) { + ((USBHostHub *)(usb_msg->hub_parent))->deviceConnected(&devices[i]); + } +#endif + + if ((i < MAX_DEVICE_CONNECTED) && !too_many_hub) { + deviceInUse[i] = true; + } + + } while(0); + + break; + + // a device has been disconnected + case DEVICE_DISCONNECTED_EVENT: + + do { + Lock lock(this); + + controlListState = disableList(CONTROL_ENDPOINT); + bulkListState = disableList(BULK_ENDPOINT); + interruptListState = disableList(INTERRUPT_ENDPOINT); + + idx = findDevice(usb_msg->hub, usb_msg->port, (USBHostHub *)(usb_msg->hub_parent)); + if (idx != -1) { + freeDevice((USBDeviceConnected*)&devices[idx]); + deviceInited[idx]=false; + } + + if (controlListState) { + enableList(CONTROL_ENDPOINT); + } + if (bulkListState) { + enableList(BULK_ENDPOINT); + } + if (interruptListState) { + enableList(INTERRUPT_ENDPOINT); + } + + } while(0); + + break; + + // a td has been processed + // call callback on the ed associated to the td + // we are not in ISR -> users can use printf in their callback method + case TD_PROCESSED_EVENT: + ep = (USBEndpoint *) ((HCTD *)usb_msg->td_addr)->ep; + if (usb_msg->td_state == USB_TYPE_IDLE) { + USB_DBG_EVENT("call callback on td %p [ep: %p state: %s - dev: %p - %s]", usb_msg->td_addr, ep, ep->getStateString(), ep->dev, ep->dev->getName(ep->getIntfNb())); + +#if DEBUG_TRANSFER + if (ep->getDir() == IN) { + buf_transfer = ep->getBufStart(); + printf("READ SUCCESS [%d bytes transferred - td: 0x%08X] on ep: [%p - addr: %02X]: ", ep->getLengthTransferred(), usb_msg->td_addr, ep, ep->getAddress()); + for (int i = 0; i < ep->getLengthTransferred(); i++) { + printf("%02X ", buf_transfer[i]); + } + printf("\r\n\r\n"); + } +#endif + ep->call(); + } else { + idx = findDevice(ep->dev); + if (idx != -1) { + if (deviceInUse[idx]) { + USB_WARN("td %p processed but not in idle state: %s [ep: %p - dev: %p - %s]", usb_msg->td_addr, ep->getStateString(), ep, ep->dev, ep->dev->getName(ep->getIntfNb())); + ep->setState(USB_TYPE_IDLE); + /* as error, on interrupt endpoint can be + * reported, call the call back registered , + * if device still in use, this call back + * shall ask again an interrupt request. + */ + ep->call(); + } + } + } + break; + } + + mail_usb_event.free(usb_msg); + } + } +} + +USBHost::USBHost() : usbThread(osPriorityNormal, USB_THREAD_STACK) +{ +#ifndef USBHOST_OTHER + headControlEndpoint = NULL; + headBulkEndpoint = NULL; + headInterruptEndpoint = NULL; + tailControlEndpoint = NULL; + tailBulkEndpoint = NULL; + tailInterruptEndpoint = NULL; +#endif + lenReportDescr = 0; + + controlEndpointAllocated = false; + + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { + deviceInUse[i] = false; + devices[i].setAddress(i + 1); + deviceReset[i] = false; + deviceInited[i] = false; + for (uint8_t j = 0; j < MAX_INTF; j++) { + deviceAttachedDriver[i][j] = false; + } + } + +#if MAX_HUB_NB + for (uint8_t i = 0; i < MAX_HUB_NB; i++) { + hubs[i].setHost(this); + hub_in_use[i] = false; + } +#endif + + usbThread.start(this, &USBHost::usb_process); +} + +USBHost::Lock::Lock(USBHost* pHost) : m_pHost(pHost) +{ + m_pHost->usb_mutex.lock(); +} + +USBHost::Lock::~Lock() +{ + m_pHost->usb_mutex.unlock(); +} + +void USBHost::transferCompleted(volatile uint32_t addr) +{ + uint8_t state; + + if(addr == 0) { + return; + } + + volatile HCTD* tdList = NULL; + + //First we must reverse the list order and dequeue each TD + do { + volatile HCTD* td = (volatile HCTD*)addr; + addr = (uint32_t)td->nextTD; //Dequeue from physical list + td->nextTD = (hcTd*)tdList; //Enqueue into reversed list + tdList = td; + } while(addr); + + while(tdList != NULL) { + volatile HCTD* td = tdList; + tdList = (volatile HCTD*)td->nextTD; //Dequeue element now as it could be modified below + if (td->ep != NULL) { + USBEndpoint * ep = (USBEndpoint *)(td->ep); + +#ifdef USBHOST_OTHER + state = ((HCTD *)td)->state; + if (state == USB_TYPE_IDLE) { + ep->setLengthTransferred((uint32_t)td->currBufPtr - (uint32_t)ep->getBufStart()); + } + +#else + if (((HCTD *)td)->control >> 28) { + state = ((HCTD *)td)->control >> 28; + } else { + if (td->currBufPtr) { + ep->setLengthTransferred((uint32_t)td->currBufPtr - (uint32_t)ep->getBufStart()); + } + state = 16 /*USB_TYPE_IDLE*/; + } +#endif + if (state == USB_TYPE_IDLE) { + ep->setLengthTransferred((uint32_t)td->currBufPtr - (uint32_t)ep->getBufStart()); + } + + ep->unqueueTransfer(td); + + if (ep->getType() != CONTROL_ENDPOINT) { + // callback on the processed td will be called from the usb_thread (not in ISR) + message_t * usb_msg = mail_usb_event.alloc(); + usb_msg->event_id = TD_PROCESSED_EVENT; + usb_msg->td_addr = (void *)td; + usb_msg->td_state = state; + mail_usb_event.put(usb_msg); + } + ep->setState((USB_TYPE)state); + ep->ep_queue.put((uint8_t*)1); + } + } +} + +USBHost * USBHost::getHostInst() +{ + if (instHost == NULL) { + instHost = new USBHost(); + instHost->init(); + } + return instHost; +} + + +/* + * Called when a device has been connected + * Called in ISR!!!! (no printf) + */ +/* virtual */ void USBHost::deviceConnected(int hub, int port, bool lowSpeed, USBHostHub * hub_parent) +{ + // be sure that the new device connected is not already connected... + int idx = findDevice(hub, port, hub_parent); + if (idx != -1) { + if (deviceInited[idx]) { + return; + } + } + + message_t * usb_msg = mail_usb_event.alloc(); + usb_msg->event_id = DEVICE_CONNECTED_EVENT; + usb_msg->hub = hub; + usb_msg->port = port; + usb_msg->lowSpeed = lowSpeed; + usb_msg->hub_parent = hub_parent; + mail_usb_event.put(usb_msg); +} + +/* + * Called when a device has been disconnected + * Called in ISR!!!! (no printf) + */ +/* virtual */ void USBHost::deviceDisconnected(int hub, int port, USBHostHub * hub_parent, volatile uint32_t addr) +{ + // be sure that the device disconnected is connected... + int idx = findDevice(hub, port, hub_parent); + if (idx != -1) { + if (!deviceInUse[idx]) { + return; + } + } else { + return; + } + + message_t * usb_msg = mail_usb_event.alloc(); + usb_msg->event_id = DEVICE_DISCONNECTED_EVENT; + usb_msg->hub = hub; + usb_msg->port = port; + usb_msg->hub_parent = hub_parent; + mail_usb_event.put(usb_msg); +} + +void USBHost::freeDevice(USBDeviceConnected * dev) +{ + USBEndpoint * ep = NULL; + HCED * ed = NULL; + +#if MAX_HUB_NB + if (dev->getClass() == HUB_CLASS) { + if (dev->hub == NULL) { + USB_ERR("HUB NULL!!!!!\r\n"); + } else { + dev->hub->hubDisconnected(); + for (uint8_t i = 0; i < MAX_HUB_NB; i++) { + if (dev->hub == &hubs[i]) { + hub_in_use[i] = false; + break; + } + } + } + } + + // notify hub parent that this device has been disconnected + if (dev->getHubParent()) { + dev->getHubParent()->deviceDisconnected(dev); + } + +#endif + + int idx = findDevice(dev); + if (idx != -1) { + deviceInUse[idx] = false; + deviceReset[idx] = false; + + for (uint8_t j = 0; j < MAX_INTF; j++) { + deviceAttachedDriver[idx][j] = false; + if (dev->getInterface(j) != NULL) { + USB_DBG("FREE INTF %d on dev: %p, %p, nb_endpot: %d, %s", j, (void *)dev->getInterface(j), dev, dev->getInterface(j)->nb_endpoint, dev->getName(j)); + for (int i = 0; i < dev->getInterface(j)->nb_endpoint; i++) { + if ((ep = dev->getEndpoint(j, i)) != NULL) { +#ifndef USBHOST_OTHER + ed = (HCED *)ep->getHCED(); + ed->control |= (1 << 14); //sKip bit +#endif + unqueueEndpoint(ep); + + freeTD((volatile uint8_t*)ep->getTDList()[0]); + freeTD((volatile uint8_t*)ep->getTDList()[1]); + + freeED((uint8_t *)ep->getHCED()); + } + printList(BULK_ENDPOINT); + printList(INTERRUPT_ENDPOINT); + } + USB_INFO("Device disconnected [%p - %s - hub: %d - port: %d]", dev, dev->getName(j), dev->getHub(), dev->getPort()); + } + } + dev->disconnect(); + } +} + + +void USBHost::unqueueEndpoint(USBEndpoint * ep) +{ +#ifdef USBHOST_OTHER + ep->setState(USB_TYPE_FREE); +#else + USBEndpoint * prec = NULL; + USBEndpoint * current = NULL; + + for (int i = 0; i < 2; i++) { + current = (i == 0) ? (USBEndpoint*)headBulkEndpoint : (USBEndpoint*)headInterruptEndpoint; + prec = current; + while (current != NULL) { + if (current == ep) { + if (current->nextEndpoint() != NULL) { + prec->queueEndpoint(current->nextEndpoint()); + if (current == headBulkEndpoint) { + updateBulkHeadED((uint32_t)current->nextEndpoint()->getHCED()); + headBulkEndpoint = current->nextEndpoint(); + } else if (current == headInterruptEndpoint) { + updateInterruptHeadED((uint32_t)current->nextEndpoint()->getHCED()); + headInterruptEndpoint = current->nextEndpoint(); + } + } + // here we are dequeuing the queue of ed + // we need to update the tail pointer + else { + prec->queueEndpoint(NULL); + if (current == headBulkEndpoint) { + updateBulkHeadED(0); + headBulkEndpoint = current->nextEndpoint(); + } else if (current == headInterruptEndpoint) { + updateInterruptHeadED(0); + headInterruptEndpoint = current->nextEndpoint(); + } + + // modify tail + switch (current->getType()) { + case BULK_ENDPOINT: + tailBulkEndpoint = prec; + break; + case INTERRUPT_ENDPOINT: + tailInterruptEndpoint = prec; + break; + default: + break; + } + } + current->setState(USB_TYPE_FREE); + return; + } + prec = current; + current = current->nextEndpoint(); + } + } +#endif +} + + +USBDeviceConnected * USBHost::getDevice(uint8_t index) +{ + if ((index >= MAX_DEVICE_CONNECTED) || (!deviceInUse[index])) { + return NULL; + } + return (USBDeviceConnected*)&devices[index]; +} + +// create an USBEndpoint descriptor. the USBEndpoint is not linked +USBEndpoint * USBHost::newEndpoint(ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir, uint32_t size, uint8_t addr) +{ + int i = 0; + HCED * ed = (HCED *)getED(); + HCTD* td_list[2] = { (HCTD*)getTD(), (HCTD*)getTD() }; + + memset((void *)td_list[0], 0x00, sizeof(HCTD)); + memset((void *)td_list[1], 0x00, sizeof(HCTD)); + + // search a free USBEndpoint + for (i = 0; i < MAX_ENDPOINT; i++) { + if (endpoints[i].getState() == USB_TYPE_FREE) { + endpoints[i].init(ed, type, dir, size, addr, td_list); + USB_DBG("USBEndpoint created (%p): type: %d, dir: %d, size: %d, addr: %d, state: %s", &endpoints[i], type, dir, size, addr, endpoints[i].getStateString()); + return &endpoints[i]; + } + } + USB_ERR("could not allocate more endpoints!!!!"); + return NULL; +} + + +USB_TYPE USBHost::resetDevice(USBDeviceConnected * dev) +{ + int index = findDevice(dev); + if (index != -1) { + USB_DBG("Resetting hub %d, port %d\n", dev->getHub(), dev->getPort()); + Thread::wait(100); + if (dev->getHub() == 0) { + resetRootHub(); + } +#if MAX_HUB_NB + else { + dev->getHubParent()->portReset(dev->getPort()); + } +#endif + Thread::wait(100); + deviceReset[index] = true; + return USB_TYPE_OK; + } + + return USB_TYPE_ERROR; +} + +// link the USBEndpoint to the linked list and attach an USBEndpoint to a device +bool USBHost::addEndpoint(USBDeviceConnected * dev, uint8_t intf_nb, USBEndpoint * ep) +{ + + if (ep == NULL) { + return false; + } + +#ifndef USBHOST_OTHER + HCED * prevEd; + +#endif + // set device address in the USBEndpoint descriptor + if (dev == NULL) { + ep->setDeviceAddress(0); + } else { + ep->setDeviceAddress(dev->getAddress()); + } + + if ((dev != NULL) && dev->getSpeed()) { + ep->setSpeed(dev->getSpeed()); + } + + ep->setIntfNb(intf_nb); + +#ifndef USBHOST_OTHER + // queue the new USBEndpoint on the ED list + switch (ep->getType()) { + + case CONTROL_ENDPOINT: + prevEd = ( HCED*) controlHeadED(); + if (!prevEd) { + updateControlHeadED((uint32_t) ep->getHCED()); + USB_DBG_TRANSFER("First control USBEndpoint: %08X", (uint32_t) ep->getHCED()); + headControlEndpoint = ep; + tailControlEndpoint = ep; + return true; + } + tailControlEndpoint->queueEndpoint(ep); + tailControlEndpoint = ep; + return true; + + case BULK_ENDPOINT: + prevEd = ( HCED*) bulkHeadED(); + if (!prevEd) { + updateBulkHeadED((uint32_t) ep->getHCED()); + USB_DBG_TRANSFER("First bulk USBEndpoint: %08X\r\n", (uint32_t) ep->getHCED()); + headBulkEndpoint = ep; + tailBulkEndpoint = ep; + break; + } + USB_DBG_TRANSFER("Queue BULK Ed %p after %p\r\n",ep->getHCED(), prevEd); + tailBulkEndpoint->queueEndpoint(ep); + tailBulkEndpoint = ep; + break; + + case INTERRUPT_ENDPOINT: + prevEd = ( HCED*) interruptHeadED(); + if (!prevEd) { + updateInterruptHeadED((uint32_t) ep->getHCED()); + USB_DBG_TRANSFER("First interrupt USBEndpoint: %08X\r\n", (uint32_t) ep->getHCED()); + headInterruptEndpoint = ep; + tailInterruptEndpoint = ep; + break; + } + USB_DBG_TRANSFER("Queue INTERRUPT Ed %p after %p\r\n",ep->getHCED(), prevEd); + tailInterruptEndpoint->queueEndpoint(ep); + tailInterruptEndpoint = ep; + break; + default: + return false; + } + +#endif + ep->dev = dev; + dev->addEndpoint(intf_nb, ep); + + return true; +} + + +int USBHost::findDevice(USBDeviceConnected * dev) +{ + for (int i = 0; i < MAX_DEVICE_CONNECTED; i++) { + if (dev == &devices[i]) { + return i; + } + } + return -1; +} + +int USBHost::findDevice(uint8_t hub, uint8_t port, USBHostHub * hub_parent) +{ + for (int i = 0; i < MAX_DEVICE_CONNECTED; i++) { + if (devices[i].getHub() == hub && devices[i].getPort() == port) { + if (hub_parent != NULL) { + if (hub_parent == devices[i].getHubParent()) { + return i; + } + } else { + return i; + } + } + } + return -1; +} + +void USBHost::printList(ENDPOINT_TYPE type) +{ +#if defined(DEBUG_EP_STATE) && !defined(USBHOST_OTHER) + volatile HCED * hced; + switch(type) { + case CONTROL_ENDPOINT: + hced = (HCED *)controlHeadED(); + break; + case BULK_ENDPOINT: + hced = (HCED *)bulkHeadED(); + break; + case INTERRUPT_ENDPOINT: + hced = (HCED *)interruptHeadED(); + break; + } + volatile HCTD * hctd = NULL; + const char * type_str = (type == BULK_ENDPOINT) ? "BULK" : + ((type == INTERRUPT_ENDPOINT) ? "INTERRUPT" : + ((type == CONTROL_ENDPOINT) ? "CONTROL" : "ISOCHRONOUS")); + printf("State of %s:\r\n", type_str); + while (hced != NULL) { + uint8_t dir = ((hced->control & (3 << 11)) >> 11); + printf("hced: %p [ADDR: %d, DIR: %s, EP_NB: 0x%X]\r\n", hced, + hced->control & 0x7f, + (dir == 1) ? "OUT" : ((dir == 0) ? "FROM_TD":"IN"), + (hced->control & (0xf << 7)) >> 7); + hctd = (HCTD *)((uint32_t)(hced->headTD) & ~(0xf)); + while (hctd != hced->tailTD) { + printf("\thctd: %p [DIR: %s]\r\n", hctd, ((hctd->control & (3 << 19)) >> 19) == 1 ? "OUT" : "IN"); + hctd = hctd->nextTD; + } + printf("\thctd: %p\r\n", hctd); + hced = hced->nextED; + } + printf("\r\n\r\n"); +#endif +} + + +// add a transfer on the TD linked list +USB_TYPE USBHost::addTransfer(USBEndpoint * ed, uint8_t * buf, uint32_t len) +{ + USB_TYPE ret=USB_TYPE_PROCESSING; + td_mutex.lock(); + + // allocate a TD which will be freed in TDcompletion + volatile HCTD * td = ed->getNextTD(); + if (td == NULL) { + return USB_TYPE_ERROR; + } + +#ifndef USBHOST_OTHER + uint32_t token = (ed->isSetup() ? TD_SETUP : ( (ed->getDir() == IN) ? TD_IN : TD_OUT )); + + uint32_t td_toggle; + + if (ed->getType() == CONTROL_ENDPOINT) { + if (ed->isSetup()) { + td_toggle = TD_TOGGLE_0; + } else { + td_toggle = TD_TOGGLE_1; + } + } else { + td_toggle = 0; + } + + td->control = (TD_ROUNDING | token | TD_DELAY_INT(0) | td_toggle | TD_CC); + td->currBufPtr = buf; + td->bufEnd = (buf + (len - 1)); + + ENDPOINT_TYPE type = ed->getType(); + + disableList(type); + ed->queueTransfer(); + printList(type); + enableList(type); +#else + /* call method specific for endpoint */ + td->currBufPtr = buf; + td->size = len; + ret = ed->queueTransfer(); +#endif + + td_mutex.unlock(); + + return ret; +} + + + +USB_TYPE USBHost::getDeviceDescriptor(USBDeviceConnected * dev, uint8_t * buf, uint16_t max_len_buf, uint16_t * len_dev_descr) +{ + USB_TYPE t = controlRead( dev, + USB_DEVICE_TO_HOST | USB_RECIPIENT_DEVICE, + GET_DESCRIPTOR, + (DEVICE_DESCRIPTOR << 8) | (0), + 0, buf, MIN(DEVICE_DESCRIPTOR_LENGTH, max_len_buf)); + if (len_dev_descr) { + *len_dev_descr = MIN(DEVICE_DESCRIPTOR_LENGTH, max_len_buf); + } + + return t; +} + +USB_TYPE USBHost::getConfigurationDescriptor(USBDeviceConnected * dev, uint8_t * buf, uint16_t max_len_buf, uint16_t * len_conf_descr) +{ + USB_TYPE res; + uint16_t total_conf_descr_length = 0; + + // fourth step: get the beginning of the configuration descriptor to have the total length of the conf descr + res = controlRead( dev, + USB_DEVICE_TO_HOST | USB_RECIPIENT_DEVICE, + GET_DESCRIPTOR, + (CONFIGURATION_DESCRIPTOR << 8) | (0), + 0, buf, CONFIGURATION_DESCRIPTOR_LENGTH); + + if (res != USB_TYPE_OK) { + USB_ERR("GET CONF 1 DESCR FAILED"); + return res; + } + total_conf_descr_length = buf[2] | (buf[3] << 8); + total_conf_descr_length = MIN(max_len_buf, total_conf_descr_length); + + if (len_conf_descr) { + *len_conf_descr = total_conf_descr_length; + } + + USB_DBG("TOTAL_LENGTH: %d \t NUM_INTERF: %d", total_conf_descr_length, buf[4]); + + return controlRead( dev, + USB_DEVICE_TO_HOST | USB_RECIPIENT_DEVICE, + GET_DESCRIPTOR, + (CONFIGURATION_DESCRIPTOR << 8) | (0), + 0, buf, total_conf_descr_length); +} + + +USB_TYPE USBHost::setAddress(USBDeviceConnected * dev, uint8_t address) +{ + return controlWrite( dev, + USB_HOST_TO_DEVICE | USB_RECIPIENT_DEVICE, + SET_ADDRESS, + address, + 0, NULL, 0); + +} + +USB_TYPE USBHost::setConfiguration(USBDeviceConnected * dev, uint8_t conf) +{ + return controlWrite( dev, + USB_HOST_TO_DEVICE | USB_RECIPIENT_DEVICE, + SET_CONFIGURATION, + conf, + 0, NULL, 0); +} + +uint8_t USBHost::numberDriverAttached(USBDeviceConnected * dev) +{ + int index = findDevice(dev); + uint8_t cnt = 0; + if (index == -1) { + return 0; + } + for (uint8_t i = 0; i < MAX_INTF; i++) { + if (deviceAttachedDriver[index][i]) { + cnt++; + } + } + return cnt; +} + +// enumerate a device with the control USBEndpoint +USB_TYPE USBHost::enumerate(USBDeviceConnected * dev, IUSBEnumerator* pEnumerator) +{ + uint16_t total_conf_descr_length = 0; + USB_TYPE res; + + do { + Lock lock(this); + + // don't enumerate a device which all interfaces are registered to a specific driver + int index = findDevice(dev); + + if (index == -1) { + return USB_TYPE_ERROR; + } + + uint8_t nb_intf_attached = numberDriverAttached(dev); + USB_DBG("dev: %p nb_intf: %d", dev, dev->getNbIntf()); + USB_DBG("dev: %p nb_intf_attached: %d", dev, nb_intf_attached); + if ((nb_intf_attached != 0) && (dev->getNbIntf() == nb_intf_attached)) { + USB_DBG("Don't enumerate dev: %p because all intf are registered with a driver", dev); + return USB_TYPE_OK; + } + + USB_DBG("Enumerate dev: %p", dev); + + // third step: get the whole device descriptor to see vid, pid + res = getDeviceDescriptor(dev, data, DEVICE_DESCRIPTOR_LENGTH); + + if (res != USB_TYPE_OK) { + USB_DBG("GET DEV DESCR FAILED"); + return res; + } + + dev->setClass(data[4]); + dev->setSubClass(data[5]); + dev->setProtocol(data[6]); + dev->setVid(data[8] | (data[9] << 8)); + dev->setPid(data[10] | (data[11] << 8)); + USB_DBG("CLASS: %02X \t VID: %04X \t PID: %04X", data[4], data[8] | (data[9] << 8), data[10] | (data[11] << 8)); + + pEnumerator->setVidPid( data[8] | (data[9] << 8), data[10] | (data[11] << 8) ); + + res = getConfigurationDescriptor(dev, data, sizeof(data), &total_conf_descr_length); + if (res != USB_TYPE_OK) { + return res; + } + +#if (DEBUG > 3) + USB_DBG("CONFIGURATION DESCRIPTOR:\r\n"); + for (int i = 0; i < total_conf_descr_length; i++) { + printf("%02X ", data[i]); + } + printf("\r\n\r\n"); +#endif + + // Parse the configuration descriptor + parseConfDescr(dev, data, total_conf_descr_length, pEnumerator); + + // only set configuration if not enumerated before + if (!dev->isEnumerated()) { + + USB_DBG("Set configuration 1 on dev: %p", dev); + // sixth step: set configuration (only 1 supported) + res = setConfiguration(dev, 1); + + if (res != USB_TYPE_OK) { + USB_DBG("SET CONF FAILED"); + return res; + } + } + + dev->setEnumerated(); + + // Now the device is enumerated! + USB_DBG("dev %p is enumerated\r\n", dev); + + } while(0); + + // Some devices may require this delay + Thread::wait(100); + + return USB_TYPE_OK; +} +// this method fills the USBDeviceConnected object: class,.... . It also add endpoints found in the descriptor. +void USBHost::parseConfDescr(USBDeviceConnected * dev, uint8_t * conf_descr, uint32_t len, IUSBEnumerator* pEnumerator) +{ + uint32_t index = 0; + uint32_t len_desc = 0; + uint8_t id = 0; + int nb_endpoints_used = 0; + USBEndpoint * ep = NULL; + uint8_t intf_nb = 0; + bool parsing_intf = false; + uint8_t current_intf = 0; + + while (index < len) { + len_desc = conf_descr[index]; + id = conf_descr[index+1]; + switch (id) { + case CONFIGURATION_DESCRIPTOR: + USB_DBG("dev: %p has %d intf", dev, conf_descr[4]); + dev->setNbIntf(conf_descr[4]); + break; + case INTERFACE_DESCRIPTOR: + if(pEnumerator->parseInterface(conf_descr[index + 2], conf_descr[index + 5], conf_descr[index + 6], conf_descr[index + 7])) { + if (intf_nb++ <= MAX_INTF) { + current_intf = conf_descr[index + 2]; + dev->addInterface(current_intf, conf_descr[index + 5], conf_descr[index + 6], conf_descr[index + 7]); + nb_endpoints_used = 0; + USB_DBG("ADD INTF %d on device %p: class: %d, subclass: %d, proto: %d", current_intf, dev, conf_descr[index + 5],conf_descr[index + 6],conf_descr[index + 7]); + } else { + USB_DBG("Drop intf..."); + } + parsing_intf = true; + } else { + parsing_intf = false; + } + break; + case ENDPOINT_DESCRIPTOR: + if (parsing_intf && (intf_nb <= MAX_INTF) ) { + if (nb_endpoints_used < MAX_ENDPOINT_PER_INTERFACE) { + if( pEnumerator->useEndpoint(current_intf, (ENDPOINT_TYPE)(conf_descr[index + 3] & 0x03), (ENDPOINT_DIRECTION)((conf_descr[index + 2] >> 7) + 1)) ) { + // if the USBEndpoint is isochronous -> skip it (TODO: fix this) + if ((conf_descr[index + 3] & 0x03) != ISOCHRONOUS_ENDPOINT) { + ep = newEndpoint((ENDPOINT_TYPE)(conf_descr[index+3] & 0x03), + (ENDPOINT_DIRECTION)((conf_descr[index + 2] >> 7) + 1), + conf_descr[index + 4] | (conf_descr[index + 5] << 8), + conf_descr[index + 2] & 0x0f); + USB_DBG("ADD USBEndpoint %p, on interf %d on device %p", ep, current_intf, dev); + if (ep != NULL && dev != NULL) { + addEndpoint(dev, current_intf, ep); + } else { + USB_DBG("EP NULL"); + } + nb_endpoints_used++; + } else { + USB_DBG("ISO USBEndpoint NOT SUPPORTED"); + } + } + } + } + break; + case HID_DESCRIPTOR: + lenReportDescr = conf_descr[index + 7] | (conf_descr[index + 8] << 8); + break; + default: + break; + } + index += len_desc; + } +} + + +USB_TYPE USBHost::bulkWrite(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking) +{ + return generalTransfer(dev, ep, buf, len, blocking, BULK_ENDPOINT, true); +} + +USB_TYPE USBHost::bulkRead(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking) +{ + return generalTransfer(dev, ep, buf, len, blocking, BULK_ENDPOINT, false); +} + +USB_TYPE USBHost::interruptWrite(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking) +{ + return generalTransfer(dev, ep, buf, len, blocking, INTERRUPT_ENDPOINT, true); +} + +USB_TYPE USBHost::interruptRead(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking) +{ + return generalTransfer(dev, ep, buf, len, blocking, INTERRUPT_ENDPOINT, false); +} + +USB_TYPE USBHost::generalTransfer(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking, ENDPOINT_TYPE type, bool write) +{ + +#if DEBUG_TRANSFER + const char * type_str = (type == BULK_ENDPOINT) ? "BULK" : ((type == INTERRUPT_ENDPOINT) ? "INTERRUPT" : "ISOCHRONOUS"); + USB_DBG_TRANSFER("----- %s %s [dev: %p - %s - hub: %d - port: %d - addr: %d - ep: %02X]------", type_str, (write) ? "WRITE" : "READ", dev, dev->getName(ep->getIntfNb()), dev->getHub(), dev->getPort(), dev->getAddress(), ep->getAddress()); +#endif + + Lock lock(this); + + USB_TYPE res; + ENDPOINT_DIRECTION dir = (write) ? OUT : IN; + + if (dev == NULL) { + USB_ERR("dev NULL"); + return USB_TYPE_ERROR; + } + + if (ep == NULL) { + USB_ERR("ep NULL"); + return USB_TYPE_ERROR; + } + + if (ep->getState() != USB_TYPE_IDLE) { + USB_WARN("[ep: %p - dev: %p - %s] NOT IDLE: %s", ep, ep->dev, ep->dev->getName(ep->getIntfNb()), ep->getStateString()); + return ep->getState(); + } + + if ((ep->getDir() != dir) || (ep->getType() != type)) { + USB_ERR("[ep: %p - dev: %p] wrong dir or bad USBEndpoint type", ep, ep->dev); + return USB_TYPE_ERROR; + } + + if (dev->getAddress() != ep->getDeviceAddress()) { + USB_ERR("[ep: %p - dev: %p] USBEndpoint addr and device addr don't match", ep, ep->dev); + return USB_TYPE_ERROR; + } + +#if DEBUG_TRANSFER + if (write) { + USB_DBG_TRANSFER("%s WRITE buffer", type_str); + for (int i = 0; i < ep->getLengthTransferred(); i++) { + printf("%02X ", buf[i]); + } + printf("\r\n\r\n"); + } +#endif + res = addTransfer(ep, buf, len); + + if ((blocking)&& (res == USB_TYPE_PROCESSING)) { +#ifdef USBHOST_OTHER + osEvent event = ep->ep_queue.get(TD_TIMEOUT); + if (event.status == osEventTimeout) { + /* control endpoint is confusing for merge on b */ + disableList(CONTROL_ENDPOINT); + ep->setState(USB_TYPE_ERROR); + ep->ep_queue.get(0); + ep->unqueueTransfer(ep->getProcessedTD()); + enableList(CONTROL_ENDPOINT); + } +#else + ep->ep_queue.get(); +#endif + res = ep->getState(); + + USB_DBG_TRANSFER("%s TRANSFER res: %s on ep: %p\r\n", type_str, ep->getStateString(), ep); + + if (res != USB_TYPE_IDLE) { + return res; + } + + return USB_TYPE_OK; + } + + return res; + +} + + +USB_TYPE USBHost::controlRead(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len) +{ + return controlTransfer(dev, requestType, request, value, index, buf, len, false); +} + +USB_TYPE USBHost::controlWrite(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len) +{ + return controlTransfer(dev, requestType, request, value, index, buf, len, true); +} + +USB_TYPE USBHost::controlTransfer(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len, bool write) +{ + Lock lock(this); + USB_DBG_TRANSFER("----- CONTROL %s [dev: %p - hub: %d - port: %d] ------", (write) ? "WRITE" : "READ", dev, dev->getHub(), dev->getPort()); + + int length_transfer = len; + USB_TYPE res; + uint32_t token; + + control->setSpeed(dev->getSpeed()); + control->setSize(dev->getSizeControlEndpoint()); + if (dev->isActiveAddress()) { + control->setDeviceAddress(dev->getAddress()); + } else { + control->setDeviceAddress(0); + } + + USB_DBG_TRANSFER("Control transfer on device: %d\r\n", control->getDeviceAddress()); + fillControlBuf(requestType, request, value, index, len); + +#if DEBUG_TRANSFER + USB_DBG_TRANSFER("SETUP PACKET: "); + for (int i = 0; i < 8; i++) { + printf("%01X ", setupPacket[i]); + } + printf("\r\n"); +#endif + + control->setNextToken(TD_SETUP); + res = addTransfer(control, (uint8_t*)setupPacket, 8); + + if (res == USB_TYPE_PROCESSING) +#ifdef USBHOST_OTHER + { + osEvent event = control->ep_queue.get(TD_TIMEOUT_CTRL); + if (event.status == osEventTimeout) { + disableList(CONTROL_ENDPOINT); + control->setState(USB_TYPE_ERROR); + control->ep_queue.get(0); + control->unqueueTransfer(control->getProcessedTD()); + enableList(CONTROL_ENDPOINT); + } + } +#else + control->ep_queue.get(); +#endif + res = control->getState(); + + USB_DBG_TRANSFER("CONTROL setup stage %s", control->getStateString()); + + if (res != USB_TYPE_IDLE) { + return res; + } + + if (length_transfer) { + token = (write) ? TD_OUT : TD_IN; + control->setNextToken(token); + res = addTransfer(control, (uint8_t *)buf, length_transfer); + + if (res == USB_TYPE_PROCESSING) +#ifdef USBHOST_OTHER + { + osEvent event = control->ep_queue.get(TD_TIMEOUT_CTRL); + if (event.status == osEventTimeout) { + disableList(CONTROL_ENDPOINT); + control->setState(USB_TYPE_ERROR); + control->ep_queue.get(0); + control->unqueueTransfer(control->getProcessedTD()); + enableList(CONTROL_ENDPOINT); + } + } +#else + control->ep_queue.get(); +#endif + res = control->getState(); + +#if DEBUG_TRANSFER + USB_DBG_TRANSFER("CONTROL %s stage %s", (write) ? "WRITE" : "READ", control->getStateString()); + if (write) { + USB_DBG_TRANSFER("CONTROL WRITE buffer"); + for (int i = 0; i < control->getLengthTransferred(); i++) { + printf("%02X ", buf[i]); + } + printf("\r\n\r\n"); + } else { + USB_DBG_TRANSFER("CONTROL READ SUCCESS [%d bytes transferred]", control->getLengthTransferred()); + for (int i = 0; i < control->getLengthTransferred(); i++) { + printf("%02X ", buf[i]); + } + printf("\r\n\r\n"); + } +#endif + + if (res != USB_TYPE_IDLE) { + return res; + } + } + + token = (write) ? TD_IN : TD_OUT; + control->setNextToken(token); + res = addTransfer(control, NULL, 0); + if (res == USB_TYPE_PROCESSING) +#ifdef USBHOST_OTHER + { + osEvent event = control->ep_queue.get(TD_TIMEOUT_CTRL); + if (event.status == osEventTimeout) { + disableList(CONTROL_ENDPOINT); + control->setState(USB_TYPE_ERROR); + control->ep_queue.get(0); + control->unqueueTransfer(control->getProcessedTD()); + enableList(CONTROL_ENDPOINT); + } + } +#else + control->ep_queue.get(); +#endif + res = control->getState(); + + USB_DBG_TRANSFER("CONTROL ack stage %s", control->getStateString()); + + if (res != USB_TYPE_IDLE) { + return res; + } + + return USB_TYPE_OK; +} + + +void USBHost::fillControlBuf(uint8_t requestType, uint8_t request, uint16_t value, uint16_t index, int len) +{ + setupPacket[0] = requestType; + setupPacket[1] = request; + setupPacket[2] = (uint8_t) value; + setupPacket[3] = (uint8_t) (value >> 8); + setupPacket[4] = (uint8_t) index; + setupPacket[5] = (uint8_t) (index >> 8); + setupPacket[6] = (uint8_t) len; + setupPacket[7] = (uint8_t) (len >> 8); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost/USBHost.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,396 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBHOST_H +#define USBHOST_H +#ifdef TARGET_STM +#include "mbed.h" +#endif +#include "USBHALHost.h" +#include "USBDeviceConnected.h" +#include "IUSBEnumerator.h" +#include "USBHostConf.h" +#include "rtos.h" +#include "dbg.h" +#include "USBHostHub.h" + +/** +* USBHost class +* This class is a singleton. All drivers have a reference on the static USBHost instance +*/ +class USBHost : public USBHALHost { +public: + /** + * Static method to create or retrieve the single USBHost instance + */ + static USBHost * getHostInst(); + + /** + * Control read: setup stage, data stage and status stage + * + * @param dev the control read will be done for this device + * @param requestType request type + * @param request request + * @param value value + * @param index index + * @param buf pointer on a buffer where will be store the data received + * @param len length of the transfer + * + * @returns status of the control read + */ + USB_TYPE controlRead(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len); + + /** + * Control write: setup stage, data stage and status stage + * + * @param dev the control write will be done for this device + * @param requestType request type + * @param request request + * @param value value + * @param index index + * @param buf pointer on a buffer which will be written + * @param len length of the transfer + * + * @returns status of the control write + */ + USB_TYPE controlWrite(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len); + + /** + * Bulk read + * + * @param dev the bulk transfer will be done for this device + * @param ep USBEndpoint which will be used to read a packet + * @param buf pointer on a buffer where will be store the data received + * @param len length of the transfer + * @param blocking if true, the read is blocking (wait for completion) + * + * @returns status of the bulk read + */ + USB_TYPE bulkRead(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking = true); + + /** + * Bulk write + * + * @param dev the bulk transfer will be done for this device + * @param ep USBEndpoint which will be used to write a packet + * @param buf pointer on a buffer which will be written + * @param len length of the transfer + * @param blocking if true, the write is blocking (wait for completion) + * + * @returns status of the bulk write + */ + USB_TYPE bulkWrite(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking = true); + + /** + * Interrupt read + * + * @param dev the bulk transfer will be done for this device + * @param ep USBEndpoint which will be used to write a packet + * @param buf pointer on a buffer which will be written + * @param len length of the transfer + * @param blocking if true, the read is blocking (wait for completion) + * + * @returns status of the interrupt read + */ + USB_TYPE interruptRead(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking = true); + + /** + * Interrupt write + * + * @param dev the bulk transfer will be done for this device + * @param ep USBEndpoint which will be used to write a packet + * @param buf pointer on a buffer which will be written + * @param len length of the transfer + * @param blocking if true, the write is blocking (wait for completion) + * + * @returns status of the interrupt write + */ + USB_TYPE interruptWrite(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking = true); + + /** + * Enumerate a device. + * + * @param dev device which will be enumerated + * + * @returns status of the enumeration + */ + USB_TYPE enumerate(USBDeviceConnected * dev, IUSBEnumerator* pEnumerator); + + /** + * reset a specific device + * + * @param dev device which will be resetted + */ + USB_TYPE resetDevice(USBDeviceConnected * dev); + + /** + * Get a device + * + * @param index index of the device which will be returned + * + * @returns pointer on the "index" device + */ + USBDeviceConnected * getDevice(uint8_t index); + + /* + * If there is a HID device connected, the host stores the length of the report descriptor. + * This avoid to the driver to re-ask the configuration descriptor to request the report descriptor + * + * @returns length of the report descriptor + */ + inline uint16_t getLengthReportDescr() { + return lenReportDescr; + }; + + /** + * register a driver into the host associated with a callback function called when the device is disconnected + * + * @param dev device + * @param intf interface number + * @param tptr pointer to the object to call the member function on + * @param mptr pointer to the member function to be called + */ + template<typename T> + inline void registerDriver(USBDeviceConnected * dev, uint8_t intf, T* tptr, void (T::*mptr)(void)) { + int index = findDevice(dev); + if ((index != -1) && (mptr != NULL) && (tptr != NULL)) { + USB_DBG("register driver for dev: %p on intf: %d", dev, intf); + deviceAttachedDriver[index][intf] = true; + dev->onDisconnect(intf, tptr, mptr); + } + } + + /** + * register a driver into the host associated with a callback function called when the device is disconnected + * + * @param dev device + * @param intf interface number + * @param fn callback called when the specified device has been disconnected + */ + inline void registerDriver(USBDeviceConnected * dev, uint8_t intf, void (*fn)(void)) { + int index = findDevice(dev); + if ((index != -1) && (fn != NULL)) { + USB_DBG("register driver for dev: %p on intf: %d", dev, intf); + deviceAttachedDriver[index][intf] = true; + dev->onDisconnect(intf, fn); + } + } + + /** + * Instantiate to protect USB thread from accessing shared objects (USBConnectedDevices and Interfaces) + */ + class Lock + { + public: + Lock(USBHost* pHost); + ~Lock(); + private: + USBHost* m_pHost; + }; + + friend class USBHostHub; + +protected: + + /** + * Virtual method called when a transfer has been completed + * + * @param addr list of the TDs which have been completed + */ + virtual void transferCompleted(volatile uint32_t addr); + + /** + * Virtual method called when a device has been connected + * + * @param hub hub number of the device + * @param port port number of the device + * @param lowSpeed 1 if low speed, 0 otherwise + * @param hub_parent reference on the parent hub + */ + virtual void deviceConnected(int hub, int port, bool lowSpeed, USBHostHub * hub_parent = NULL); + + /** + * Virtuel method called when a device has been disconnected + * + * @param hub hub number of the device + * @param port port number of the device + * @param addr list of the TDs which have been completed to dequeue freed TDs + */ + virtual void deviceDisconnected(int hub, int port, USBHostHub * hub_parent, volatile uint32_t addr); + + +private: + // singleton class -> constructor is private + USBHost(); + static USBHost * instHost; + uint16_t lenReportDescr; + + // endpoints + void unqueueEndpoint(USBEndpoint * ep) ; + USBEndpoint endpoints[MAX_ENDPOINT]; + USBEndpoint* volatile control; + + USBEndpoint* volatile headControlEndpoint; + USBEndpoint* volatile headBulkEndpoint; + USBEndpoint* volatile headInterruptEndpoint; + + USBEndpoint* volatile tailControlEndpoint; + USBEndpoint* volatile tailBulkEndpoint; + USBEndpoint* volatile tailInterruptEndpoint; + + bool controlEndpointAllocated; + + // devices connected + USBDeviceConnected devices[MAX_DEVICE_CONNECTED]; + bool deviceInUse[MAX_DEVICE_CONNECTED]; + bool deviceAttachedDriver[MAX_DEVICE_CONNECTED][MAX_INTF]; + bool deviceReset[MAX_DEVICE_CONNECTED]; + bool deviceInited[MAX_DEVICE_CONNECTED]; + +#if MAX_HUB_NB + USBHostHub hubs[MAX_HUB_NB]; + bool hub_in_use[MAX_HUB_NB]; +#endif + + // to store a setup packet + uint8_t setupPacket[8]; + + typedef struct { + uint8_t event_id; + void * td_addr; + uint8_t hub; + uint8_t port; + uint8_t lowSpeed; + uint8_t td_state; + void * hub_parent; + } message_t; + + Thread usbThread; + void usb_process(); + Mail<message_t, 10> mail_usb_event; + Mutex usb_mutex; + Mutex td_mutex; + + // buffer for conf descriptor + uint8_t data[415]; + + /** + * Add a transfer on the TD linked list associated to an ED + * + * @param ed the transfer is associated to this ed + * @param buf pointer on a buffer where will be read/write data to send or receive + * @param len transfer length + * + * @return status of the transfer + */ + USB_TYPE addTransfer(USBEndpoint * ed, uint8_t * buf, uint32_t len) ; + + /** + * Link the USBEndpoint to the linked list and attach an USBEndpoint this USBEndpoint to a device + * + * @param dev pointer on a USBDeviceConnected object + * @param ep pointer on the USBEndpoint which will be added + * + * return true if successful + */ + bool addEndpoint(USBDeviceConnected * dev, uint8_t intf_nb, USBEndpoint * ep) ; + + /** + * Create an USBEndpoint descriptor. Warning: the USBEndpoint is not linked. + * + * @param type USBEndpoint type (CONTROL_ENDPOINT, BULK_ENDPOINT, INTERRUPT_ENDPOINT) + * @param dir USBEndpoint direction (no meaning for CONTROL_ENDPOINT) + * @param size USBEndpoint max packet size + * @param addr USBEndpoint address + * + * @returns pointer on the USBEndpoint created + */ + USBEndpoint * newEndpoint(ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir, uint32_t size, uint8_t addr) ; + + /** + * Request the device descriptor + * + * @param dev request the device descriptor on this device + * @param buf buffer to store the device descriptor + * @param max_len_buf maximum size of buf + * @param len_dev_descr pointer to store the length of the packet transferred + */ + USB_TYPE getDeviceDescriptor(USBDeviceConnected * dev, uint8_t * buf, uint16_t max_len_buf, uint16_t * len_dev_descr = NULL); + + /** + * Request the configuration descriptor + * + * @param dev request the configuration descriptor on this device + * @param buf buffer to store the configuration descriptor + * @param max_len_buf maximum size of buf + * @param len_conf_descr pointer to store the length of the packet transferred + */ + USB_TYPE getConfigurationDescriptor(USBDeviceConnected * dev, uint8_t * buf, uint16_t max_len_buf, uint16_t * len_conf_descr = NULL); + + /** + * Set the address of a specific device + * + * @param dev device to set the address + * @param address address + */ + USB_TYPE setAddress(USBDeviceConnected * dev, uint8_t address); + + /** + * Set the configuration of a device + * + * @param dev device on which the specified configuration will be activated + * @param conf configuration number to activate (usually 1) + */ + USB_TYPE setConfiguration(USBDeviceConnected * dev, uint8_t conf); + + /** + * Free a specific device + * + * @param dev device to be freed + */ + void freeDevice(USBDeviceConnected * dev); + + USB_TYPE controlTransfer( USBDeviceConnected * dev, + uint8_t requestType, + uint8_t request, + uint32_t value, + uint32_t index, + uint8_t * buf, + uint32_t len, + bool write); + + USB_TYPE generalTransfer( USBDeviceConnected * dev, + USBEndpoint * ep, + uint8_t * buf, + uint32_t len, + bool blocking, + ENDPOINT_TYPE type, + bool write) ; + + void fillControlBuf(uint8_t requestType, uint8_t request, uint16_t value, uint16_t index, int len) ; + void parseConfDescr(USBDeviceConnected * dev, uint8_t * conf_descr, uint32_t len, IUSBEnumerator* pEnumerator) ; + int findDevice(USBDeviceConnected * dev) ; + int findDevice(uint8_t hub, uint8_t port, USBHostHub * hub_parent = NULL) ; + uint8_t numberDriverAttached(USBDeviceConnected * dev); + + ///////////////////////// + /// FOR DEBUG + ///////////////////////// + void printList(ENDPOINT_TYPE type); + +}; + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost/USBHostConf.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,154 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBHOST_CONF_H +#define USBHOST_CONF_H +#if defined(TARGET_STM) +/* +* Maximum number of devices that can be connected +* to the usb host +*/ +/* hub + 2 devices */ +#define MAX_DEVICE_CONNECTED 5 + +/* +* Maximum of Hub connected to the usb host +*/ +#define MAX_HUB_NB 3 + +/* +* Maximum number of ports on a USB hub +*/ +#define MAX_HUB_PORT 4 + +/* +* Enable USBHostMSD +*/ +#define USBHOST_MSD 1 + +/* +* Enable USBHostKeyboard +*/ +#define USBHOST_KEYBOARD 1 + +/* +* Enable USBHostMouse +*/ +#define USBHOST_MOUSE 1 + +/* +* Enable USBHostSerial or USBHostMultiSerial (if set > 1) +*/ +#define USBHOST_SERIAL 1 + +/* +* Enable USB3Gmodule +*/ +#define USBHOST_3GMODULE 1 + +/* +* Enable USB MIDI +*/ +#define USBHOST_MIDI 1 + +/* +* Maximum number of interfaces of a usb device +*/ +#define MAX_INTF 2 + +/* +* Maximum number of endpoints on each interface +*/ +#define MAX_ENDPOINT_PER_INTERFACE 2 + +/* +* Maximum number of endpoint descriptors that can be allocated +*/ +#define MAX_ENDPOINT 11 /* USB FS 11 channel */ + +#else +/* +* Maximum number of devices that can be connected +* to the usb host +*/ +#define MAX_DEVICE_CONNECTED 5 + +/* +* Maximum of Hub connected to the usb host +*/ +#define MAX_HUB_NB 2 + +/* +* Maximum number of ports on a USB hub +*/ +#define MAX_HUB_PORT 4 + +/* +* Enable USBHostMSD +*/ +#define USBHOST_MSD 1 + +/* +* Enable USBHostKeyboard +*/ +#define USBHOST_KEYBOARD 1 + +/* +* Enable USBHostMouse +*/ +#define USBHOST_MOUSE 1 + +/* +* Enable USBHostSerial or USBHostMultiSerial (if set > 1) +*/ +#define USBHOST_SERIAL 1 + +/* +* Enable USB3Gmodule +*/ +#define USBHOST_3GMODULE 1 + +/* +* Enable USB MIDI +*/ +#define USBHOST_MIDI 1 + +/* +* Maximum number of interfaces of a usb device +*/ +#define MAX_INTF 4 + +/* +* Maximum number of endpoints on each interface +*/ +#define MAX_ENDPOINT_PER_INTERFACE 3 + +/* +* Maximum number of endpoint descriptors that can be allocated +*/ +#define MAX_ENDPOINT (MAX_DEVICE_CONNECTED * MAX_INTF * MAX_ENDPOINT_PER_INTERFACE) +#endif +/* +* Maximum number of transfer descriptors that can be allocated +*/ +#define MAX_TD (MAX_ENDPOINT*2) + +/* +* usb_thread stack size +*/ +#define USB_THREAD_STACK (256*4 + 2*256*4) + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost/USBHostTypes.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,262 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_INC_H +#define USB_INC_H + +#include "mbed.h" +#include "mbed_toolchain.h" + +enum USB_TYPE { + USB_TYPE_OK = 0, + + // completion code + USB_TYPE_CRC_ERROR = 1, + USB_TYPE_BIT_STUFFING_ERROR = 2, + USB_TYPE_DATA_TOGGLE_MISMATCH_ERROR = 3, + USB_TYPE_STALL_ERROR = 4, + USB_TYPE_DEVICE_NOT_RESPONDING_ERROR = 5, + USB_TYPE_PID_CHECK_FAILURE_ERROR = 6, + USB_TYPE_UNEXPECTED_PID_ERROR = 7, + USB_TYPE_DATA_OVERRUN_ERROR = 8, + USB_TYPE_DATA_UNDERRUN_ERROR = 9, + USB_TYPE_RESERVED = 9, + USB_TYPE_RESERVED_ = 10, + USB_TYPE_BUFFER_OVERRUN_ERROR = 12, + USB_TYPE_BUFFER_UNDERRUN_ERROR = 13, + + // general usb state + USB_TYPE_DISCONNECTED = 14, + USB_TYPE_FREE = 15, + USB_TYPE_IDLE = 16, + USB_TYPE_PROCESSING = 17, + + USB_TYPE_ERROR = 18, +}; + + +enum ENDPOINT_DIRECTION { + OUT = 1, + IN +}; + +enum ENDPOINT_TYPE { + CONTROL_ENDPOINT = 0, + ISOCHRONOUS_ENDPOINT, + BULK_ENDPOINT, + INTERRUPT_ENDPOINT +}; + +#define AUDIO_CLASS 0x01 +#define CDC_CLASS 0x02 +#define HID_CLASS 0x03 +#define MSD_CLASS 0x08 +#define HUB_CLASS 0x09 +#define SERIAL_CLASS 0x0A + +#if !defined(USBHOST_OTHER) +// ------------------ HcControl Register --------------------- +#define OR_CONTROL_PLE 0x00000004 +#define OR_CONTROL_CLE 0x00000010 +#define OR_CONTROL_BLE 0x00000020 +#define OR_CONTROL_HCFS 0x000000C0 +#define OR_CONTROL_HC_RSET 0x00000000 +#define OR_CONTROL_HC_RES 0x00000040 +#define OR_CONTROL_HC_OPER 0x00000080 +#define OR_CONTROL_HC_SUSP 0x000000C0 +// ----------------- HcCommandStatus Register ----------------- +#define OR_CMD_STATUS_HCR 0x00000001 +#define OR_CMD_STATUS_CLF 0x00000002 +#define OR_CMD_STATUS_BLF 0x00000004 +// --------------- HcInterruptStatus Register ----------------- +#define OR_INTR_STATUS_WDH 0x00000002 +#define OR_INTR_STATUS_RHSC 0x00000040 +#define OR_INTR_STATUS_UE 0x00000010 +// --------------- HcInterruptEnable Register ----------------- +#define OR_INTR_ENABLE_WDH 0x00000002 +#define OR_INTR_ENABLE_RHSC 0x00000040 +#define OR_INTR_ENABLE_MIE 0x80000000 +// ---------------- HcRhDescriptorA Register ------------------ +#define OR_RH_STATUS_LPSC 0x00010000 +#define OR_RH_STATUS_DRWE 0x00008000 +// -------------- HcRhPortStatus[1:NDP] Register -------------- +#define OR_RH_PORT_CCS 0x00000001 +#define OR_RH_PORT_PRS 0x00000010 +#define OR_RH_PORT_CSC 0x00010000 +#define OR_RH_PORT_PRSC 0x00100000 +#define OR_RH_PORT_LSDA 0x00000200 +#define OR_RH_PORT_PESC 0x00020000 +#define OR_RH_PORT_OCIC 0x00080000 + +#define FI 0x2EDF // 12000 bits per frame (-1) +#define DEFAULT_FMINTERVAL ((((6 * (FI - 210)) / 7) << 16) | FI) + +#define ED_SKIP (uint32_t) (0x00001000) // Skip this ep in queue + +#define TD_ROUNDING (uint32_t) (0x00040000) // Buffer Rounding +#define TD_SETUP (uint32_t)(0) // Direction of Setup Packet +#define TD_IN (uint32_t)(0x00100000) // Direction In +#define TD_OUT (uint32_t)(0x00080000) // Direction Out +#define TD_DELAY_INT(x) (uint32_t)((x) << 21) // Delay Interrupt +#define TD_TOGGLE_0 (uint32_t)(0x02000000) // Toggle 0 +#define TD_TOGGLE_1 (uint32_t)(0x03000000) // Toggle 1 +#define TD_CC (uint32_t)(0xF0000000) // Completion Code + +#else + +#define TD_TIMEOUT_CTRL 100 +#define TD_TIMEOUT 2000 +#define TD_SETUP (uint32_t)(0) // Direction of Setup Packet +#define TD_IN (uint32_t)(0x00100000) // Direction In +#define TD_OUT (uint32_t)(0x00080000) // Direction Out + +#endif +#define DEVICE_DESCRIPTOR (1) +#define CONFIGURATION_DESCRIPTOR (2) +#define INTERFACE_DESCRIPTOR (4) +#define ENDPOINT_DESCRIPTOR (5) +#define HID_DESCRIPTOR (33) + +// ----------- Control RequestType Fields ----------- +#define USB_DEVICE_TO_HOST 0x80 +#define USB_HOST_TO_DEVICE 0x00 +#define USB_REQUEST_TYPE_CLASS 0x20 +#define USB_REQUEST_TYPE_STANDARD 0x00 +#define USB_RECIPIENT_DEVICE 0x00 +#define USB_RECIPIENT_INTERFACE 0x01 +#define USB_RECIPIENT_ENDPOINT 0x02 + +// -------------- USB Standard Requests -------------- +#define SET_ADDRESS 0x05 +#define GET_DESCRIPTOR 0x06 +#define SET_CONFIGURATION 0x09 +#define SET_INTERFACE 0x0b +#define CLEAR_FEATURE 0x01 + +// -------------- USB Descriptor Length -------------- +#define DEVICE_DESCRIPTOR_LENGTH 0x12 +#define CONFIGURATION_DESCRIPTOR_LENGTH 0x09 + +// ------------ HostController Transfer Descriptor ------------ +#if defined(USBHOST_OTHER) + +typedef struct hcTd { + __IO uint32_t state; + __IO uint8_t * currBufPtr; // Physical address of current buffer pointer + __IO hcTd * nextTD; // Physical pointer to next Transfer Descriptor + __IO uint32_t size; // size of buffer + void * ep; // ep address where a td is linked in + __IO uint32_t retry; + __IO uint32_t setup; +} PACKED HCTD; +// ----------- HostController EndPoint Descriptor ------------- +typedef struct hcEd { + uint8_t ch_num; + void *hhcd; +} PACKED HCED; +// ----------- Host Controller Communication Area ------------ +#define HCCA void + + +#else +// -------------OHCI register -------------------------------- +// ------------ HostController Transfer Descriptor ------------ +typedef struct hcTd { + __IO uint32_t control; // Transfer descriptor control + __IO uint8_t * currBufPtr; // Physical address of current buffer pointer + __IO hcTd * nextTD; // Physical pointer to next Transfer Descriptor + __IO uint8_t * bufEnd; // Physical address of end of buffer + void * ep; // ep address where a td is linked in + uint32_t dummy[3]; // padding +} PACKED HCTD; +// ----------- HostController EndPoint Descriptor ------------- +typedef struct hcEd { + __IO uint32_t control; // Endpoint descriptor control + __IO HCTD * tailTD; // Physical address of tail in Transfer descriptor list + __IO HCTD * headTD; // Physcial address of head in Transfer descriptor list + __IO hcEd * nextED; // Physical address of next Endpoint descriptor +} PACKED HCED; +// ----------- Host Controller Communication Area ------------ +typedef struct hcca { + __IO uint32_t IntTable[32]; // Interrupt Table + __IO uint32_t FrameNumber; // Frame Number + __IO uint32_t DoneHead; // Done Head + volatile uint8_t Reserved[116]; // Reserved for future use + volatile uint8_t Unknown[4]; // Unused +} PACKED HCCA; +#endif + +typedef struct { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bcdUSB; + uint8_t bDeviceClass; + uint8_t bDeviceSubClass; + uint8_t bDeviceProtocol; + uint8_t bMaxPacketSize; + uint16_t idVendor; + uint16_t idProduct; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + uint8_t bNumConfigurations; +} PACKED DeviceDescriptor; + +typedef struct { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t wTotalLength; + uint8_t bNumInterfaces; + uint8_t bConfigurationValue; + uint8_t iConfiguration; + uint8_t bmAttributes; + uint8_t bMaxPower; +} PACKED ConfigurationDescriptor; + +typedef struct { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bInterfaceNumber; + uint8_t bAlternateSetting; + uint8_t bNumEndpoints; + uint8_t bInterfaceClass; + uint8_t bInterfaceSubClass; + uint8_t bInterfaceProtocol; + uint8_t iInterface; +} InterfaceDescriptor; + +typedef struct { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bEndpointAddress; + uint8_t bmAttributes; + uint16_t wMaxPacketSize; + uint8_t bInterval; +} EndpointDescriptor; + +typedef struct { + uint8_t bDescLength; + uint8_t bDescriptorType; + uint8_t bNbrPorts; + uint16_t wHubCharacteristics; + uint8_t bPwrOn2PwrGood; + uint8_t bHubContrCurrent; + uint8_t DeviceRemovable; + uint8_t PortPweCtrlMak; +} HubDescriptor; + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost/dbg.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,66 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_DEBUG_H +#define USB_DEBUG_H + +//Debug is disabled by default +#define DEBUG 3 /*INFO,ERR,WARN*/ +#define DEBUG_TRANSFER 0 +#define DEBUG_EP_STATE 0 +#define DEBUG_EVENT 0 + +#if (DEBUG > 3) +#define USB_DBG(x, ...) std::printf("[USB_DBG: %s:%d]" x "\r\n", __FILE__, __LINE__, ##__VA_ARGS__); +#else +#define USB_DBG(x, ...) +#endif + +#if (DEBUG > 2) +#define USB_INFO(x, ...) std::printf("[USB_INFO: %s:%d]" x "\r\n", __FILE__, __LINE__, ##__VA_ARGS__); +#else +#define USB_INFO(x, ...) +#endif + +#if (DEBUG > 1) +#define USB_WARN(x, ...) std::printf("[USB_WARNING: %s:%d]" x "\r\n", __FILE__, __LINE__, ##__VA_ARGS__); +#else +#define USB_WARN(x, ...) +#endif + +#if (DEBUG > 0) +#define USB_ERR(x, ...) std::printf("[USB_ERR: %s:%d]" x "\r\n", __FILE__, __LINE__, ##__VA_ARGS__); +#else +#define USB_ERR(x, ...) +#endif + +#if (DEBUG_TRANSFER) +#define USB_DBG_TRANSFER(x, ...) std::printf("[USB_TRANSFER: %s:%d]" x "\r\n", __FILE__, __LINE__, ##__VA_ARGS__); +#else +#define USB_DBG_TRANSFER(x, ...) +#endif + +#if (DEBUG_EVENT) +#define USB_DBG_EVENT(x, ...) std::printf("[USB_EVENT: %s:%d]" x "\r\n", __FILE__, __LINE__, ##__VA_ARGS__); +#else +#define USB_DBG_EVENT(x, ...) +#endif + + +#endif + + +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost3GModule/IUSBHostSerial.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,95 @@ +/* IUSBHostSerial.h */ +/* Copyright (c) 2010-2012 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef IUSBHOSTSERIAL_H_ +#define IUSBHOSTSERIAL_H_ + +/** + * Generic interface to abstract 3G dongles' impl + */ + +#include "USBHostConf.h" + +#ifdef USBHOST_3GMODULE + +#include "IUSBHostSerialListener.h" + +// This is needed by some versions of GCC +#undef putc +#undef getc + +class IUSBHostSerial { +public: + + enum IrqType { + RxIrq, + TxIrq + }; + + /* + * Get a char from the dongle's serial interface + */ + virtual int getc() = 0; + + /* + * Put a char to the dongle's serial interface + */ + virtual int putc(int c) = 0; + + /* + * Read a packet from the dongle's serial interface, to be called after multiple getc() calls + */ + virtual int readPacket() = 0; + + /* + * Write a packet to the dongle's serial interface, to be called after multiple putc() calls + */ + virtual int writePacket() = 0; + + /** + * Check the number of bytes available. + * + * @returns the number of bytes available + */ + virtual int readable() = 0; + + /** + * Check the free space in output. + * + * @returns the number of bytes available + */ + virtual int writeable() = 0; + + /** + * Attach a handler to call when a packet is received / when a packet has been transmitted. + * + * @param pListener instance of the listener deriving from the IUSBHostSerialListener + */ + virtual void attach(IUSBHostSerialListener* pListener) = 0; + + /** + * Enable or disable readable/writeable callbacks + */ + virtual void setupIrq(bool en, IrqType irq = RxIrq) = 0; + +}; + +#endif /* USBHOST_3GMODULE */ + +#endif /* IUSBHOSTSERIAL_H_ */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost3GModule/IUSBHostSerialListener.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,37 @@ +/* IUSBHostSerialListener.h */ +/* Copyright (c) 2010-2012 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + + +#ifndef IUSBHOSTSERIALLISTENER_H_ +#define IUSBHOSTSERIALLISTENER_H_ + +#include "USBHostConf.h" + +#ifdef USBHOST_3GMODULE + +class IUSBHostSerialListener +{ +public: + virtual void readable() = 0; //Called when new data is available + virtual void writeable() = 0; //Called when new space is available +}; + +#endif /* USBHOST_3GMODULE */ + +#endif /* IUSBHOSTSERIALLISTENER_H_ */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost3GModule/WANDongle.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,235 @@ +/* Copyright (c) 2010-2012 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#include "USBHostConf.h" + +#ifdef USBHOST_3GMODULE + +#include "dbg.h" +#include <stdint.h> +#include "rtos.h" + +#include "WANDongle.h" +#include "WANDongleInitializer.h" + +WANDongle::WANDongle() : m_pInitializer(NULL), m_serialCount(0), m_totalInitializers(0) +{ + host = USBHost::getHostInst(); + init(); +} + + +bool WANDongle::connected() { + return dev_connected; +} + +bool WANDongle::tryConnect() +{ + //FIXME should run on USB thread + + USB_DBG("Trying to connect device"); + + if (dev_connected) { + USB_DBG("Device is already connected!"); + return true; + } + + m_pInitializer = NULL; + + //Protect from concurrent access from USB thread + USBHost::Lock lock(host); + + for (int i = 0; i < MAX_DEVICE_CONNECTED; i++) + { + if ((dev = host->getDevice(i)) != NULL) + { + m_pInitializer = NULL; //Will be set in setVidPid callback + + USB_DBG("Enumerate"); + int ret = host->enumerate(dev, this); + if(ret) + { + return false; + } + + USB_DBG("Device has VID:%04x PID:%04x", dev->getVid(), dev->getPid()); + + if(m_pInitializer) //If an initializer has been found + { + USB_DBG("m_pInitializer=%p", m_pInitializer); + USB_DBG("m_pInitializer->getSerialVid()=%04x", m_pInitializer->getSerialVid()); + USB_DBG("m_pInitializer->getSerialPid()=%04x", m_pInitializer->getSerialPid()); + if ((dev->getVid() == m_pInitializer->getSerialVid()) && (dev->getPid() == m_pInitializer->getSerialPid())) + { + USB_DBG("The dongle is in virtual serial mode"); + host->registerDriver(dev, 0, this, &WANDongle::init); + m_serialCount = m_pInitializer->getSerialPortCount(); + if( m_serialCount > WANDONGLE_MAX_SERIAL_PORTS ) + { + m_serialCount = WANDONGLE_MAX_SERIAL_PORTS; + } + for(int j = 0; j < m_serialCount; j++) + { + USB_DBG("Connecting serial port #%d", j+1); + USB_DBG("Ep %p", m_pInitializer->getEp(dev, j, false)); + USB_DBG("Ep %p", m_pInitializer->getEp(dev, j, true)); + m_serial[j].connect( dev, m_pInitializer->getEp(dev, j, false), m_pInitializer->getEp(dev, j, true) ); + } + + USB_DBG("Device connected"); + + dev_connected = true; + + + return true; + } + else if ((dev->getVid() == m_pInitializer->getMSDVid()) && (dev->getPid() == m_pInitializer->getMSDPid())) + { + USB_DBG("Vodafone K3370 dongle detected in MSD mode"); + //Try to switch + if( m_pInitializer->switchMode(dev) ) + { + USB_DBG("Switched OK"); + return false; //Will be connected on a next iteration + } + else + { + USB_ERR("Could not switch mode"); + return false; + } + } + } //if() + } //if() + } //for() + return false; +} + +bool WANDongle::disconnect() +{ + dev_connected = false; + for(int i = 0; i < WANDONGLE_MAX_SERIAL_PORTS; i++) + { + m_serial[i].disconnect(); + } + return true; +} + +int WANDongle::getDongleType() +{ + if( m_pInitializer != NULL ) + { + return m_pInitializer->getType(); + } + else + { + return WAN_DONGLE_TYPE_UNKNOWN; + } +} + +IUSBHostSerial& WANDongle::getSerial(int index) +{ + return m_serial[index]; +} + +int WANDongle::getSerialCount() +{ + return m_serialCount; +} + +//Private methods +void WANDongle::init() +{ + m_pInitializer = NULL; + dev_connected = false; + for(int i = 0; i < WANDONGLE_MAX_SERIAL_PORTS; i++) + { + m_serial[i].init(host); + } +} + + +/*virtual*/ void WANDongle::setVidPid(uint16_t vid, uint16_t pid) +{ + WANDongleInitializer* initializer; + + for(int i = 0; i < m_totalInitializers; i++) + { + initializer = m_Initializers[i]; + USB_DBG("initializer=%p", initializer); + USB_DBG("initializer->getSerialVid()=%04x", initializer->getSerialVid()); + USB_DBG("initializer->getSerialPid()=%04x", initializer->getSerialPid()); + if ((dev->getVid() == initializer->getSerialVid()) && (dev->getPid() == initializer->getSerialPid())) + { + USB_DBG("The dongle is in virtual serial mode"); + m_pInitializer = initializer; + break; + } + else if ((dev->getVid() == initializer->getMSDVid()) && (dev->getPid() == initializer->getMSDPid())) + { + USB_DBG("Dongle detected in MSD mode"); + m_pInitializer = initializer; + break; + } + initializer++; + } //for + if(m_pInitializer) + { + m_pInitializer->setVidPid(vid, pid); + } +} + +/*virtual*/ bool WANDongle::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed +{ + if(m_pInitializer) + { + return m_pInitializer->parseInterface(intf_nb, intf_class, intf_subclass, intf_protocol); + } + else + { + return false; + } +} + +/*virtual*/ bool WANDongle::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used +{ + if(m_pInitializer) + { + return m_pInitializer->useEndpoint(intf_nb, type, dir); + } + else + { + return false; + } +} + + +bool WANDongle::addInitializer(WANDongleInitializer* pInitializer) +{ + if (m_totalInitializers >= WANDONGLE_MAX_INITIALIZERS) + return false; + m_Initializers[m_totalInitializers++] = pInitializer; + return true; +} + +WANDongle::~WANDongle() +{ + for(int i = 0; i < m_totalInitializers; i++) + delete m_Initializers[i]; +} + +#endif /* USBHOST_3GMODULE */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost3GModule/WANDongle.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,108 @@ +/* Copyright (c) 2010-2012 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef WANDONGLE_H +#define WANDONGLE_H + +#include "USBHostConf.h" + +#ifdef USBHOST_3GMODULE + +#include "USBHost.h" +#include "IUSBHostSerial.h" + +#include "rtos.h" + +#include "WANDongleSerialPort.h" +#include "WANDongleInitializer.h" +#include "IUSBEnumerator.h" + +#define WANDONGLE_MAX_OUTEP_SIZE 64 +#define WANDONGLE_MAX_INEP_SIZE 64 + +/** A class to use a WAN (3G/LTE) access dongle + * + */ +class WANDongle : public IUSBEnumerator { +public: + /* + * Constructor + * + * @param rootdir mount name + */ + WANDongle(); + + /* + * Destructor + */ + virtual ~WANDongle(); + + /* + * Check if a serial port device is connected + * + * @return true if a serial device is connected + */ + bool connected(); + + /* + * Try to connect device + * + * * @return true if connection was successful + */ + bool tryConnect(); + + /* + * Disconnect device + * + * * @return true if disconnection was successful + */ + bool disconnect(); + + int getDongleType(); + + IUSBHostSerial& getSerial(int index); + int getSerialCount(); + bool addInitializer(WANDongleInitializer* pInitializer); + + //From IUSBEnumerator + + virtual void setVidPid(uint16_t vid, uint16_t pid); + + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed + + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used + +protected: + USBHost * host; + USBDeviceConnected * dev; + bool dev_connected; + + WANDongleInitializer* m_pInitializer; + + void init(); + + WANDongleSerialPort m_serial[WANDONGLE_MAX_SERIAL_PORTS]; + int m_serialCount; + + int m_totalInitializers; + WANDongleInitializer* m_Initializers[WANDONGLE_MAX_INITIALIZERS]; +}; + +#endif /* USBHOST_3GMODULE */ + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost3GModule/WANDongleInitializer.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,73 @@ +/* Copyright (c) 2010-2012 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef WANDONGLEINITIALIZER_H +#define WANDONGLEINITIALIZER_H + +#include "USBHostConf.h" + +#ifdef USBHOST_3GMODULE + +#include <stdint.h> + +#include "USBHost.h" +#include "IUSBEnumerator.h" + +// [TODO] move these declarations to a proper place +#define WANDONGLE_MAX_SERIAL_PORTS 2 +#define WANDONGLE_MAX_INITIALIZERS 6 + +#define WAN_DONGLE_TYPE_UNKNOWN (-1) + +class WANDongleInitializer : public IUSBEnumerator +{ +protected: + WANDongleInitializer(USBHost* pHost) { m_pHost = pHost; } + USBHost* m_pHost; + uint8_t m_serialIntfMap[WANDONGLE_MAX_SERIAL_PORTS]; + +public: + virtual ~WANDongleInitializer() {} + virtual uint16_t getMSDVid() = 0; + virtual uint16_t getMSDPid() = 0; + + virtual uint16_t getSerialVid() = 0; + virtual uint16_t getSerialPid() = 0; + + virtual bool switchMode(USBDeviceConnected* pDev) = 0; + + virtual USBEndpoint* getEp(USBDeviceConnected* pDev, int serialPortNumber, bool tx) { + return pDev->getEndpoint(m_serialIntfMap[serialPortNumber], BULK_ENDPOINT, tx ? OUT : IN, 0); + } + + virtual int getSerialPortCount() = 0; + + virtual void setVidPid(uint16_t vid, uint16_t pid) = 0; + + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) = 0; //Must return true if the interface should be parsed + + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) = 0; //Must return true if the endpoint will be used + + virtual int getType() = 0; + + virtual uint8_t getSerialIntf(int index) { return m_serialIntfMap[index]; } +}; + +#endif /* USBHOST_3GMODULE */ + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost3GModule/WANDongleSerialPort.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,340 @@ +/* Copyright (c) 2010-2012 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#include "USBHostConf.h" + +#ifdef USBHOST_3GMODULE + +#define __DEBUG__ 0 +#ifndef __MODULE__ +#define __MODULE__ "WANDongleSerialPort.cpp" +#endif + +#include "dbg.h" +#include <stdint.h> +#include "rtos.h" + +#include "WANDongleSerialPort.h" + +WANDongleSerialPort::WANDongleSerialPort() : cb_tx_en(false), cb_rx_en(false), listener(NULL) +{ + reset(); +} + +void WANDongleSerialPort::init(USBHost* pHost) +{ + host = pHost; +} + +void WANDongleSerialPort::reset() +{ + tx_mtx.lock(); + rx_mtx.lock(); + + bulk_in = NULL; + bulk_out = NULL; + + buf_out_len = 0; + max_out_size = 0; + lock_tx = false; + cb_tx_pending = false; + + buf_in_len = 0; + buf_in_read_pos = 0; + lock_rx = false; + cb_rx_pending = false; + + tx_mtx.unlock(); + rx_mtx.unlock(); +} + +int WANDongleSerialPort::readPacket() +{ + USB_DBG("Read packet on %p", this); + rx_mtx.lock(); + if(lock_rx) + { + USB_ERR("Fail"); + rx_mtx.unlock(); + return -1; + } + + if( bulk_in == NULL ) + { + USB_WARN("Port is disconnected"); + rx_mtx.unlock(); + return -1; + } + + lock_rx = true; //Receiving + rx_mtx.unlock(); +// USB_DBG("readPacket"); + //lock_rx.lock(); + USB_TYPE res = host->bulkRead(dev, (USBEndpoint *)bulk_in, buf_in, ((USBEndpoint *)bulk_in)->getSize(), false); //Queue transfer + if(res != USB_TYPE_PROCESSING) + { + //lock_rx.unlock(); + USB_ERR("host->bulkRead() returned %d", res); + Thread::wait(100); + return -1; + } + return 0; +} + +int WANDongleSerialPort::writePacket() +{ + tx_mtx.lock(); + if(lock_tx) + { + USB_ERR("Fail"); + tx_mtx.unlock(); + return -1; + } + + if( bulk_out == NULL ) + { + USB_WARN("Port is disconnected"); + tx_mtx.unlock(); + return -1; + } + + lock_tx = true; //Transmitting + tx_mtx.unlock(); +// USB_DBG("writePacket"); + + //lock_tx.lock(); + USB_TYPE res = host->bulkWrite(dev, (USBEndpoint *)bulk_out, buf_out, buf_out_len, false); //Queue transfer + if(res != USB_TYPE_PROCESSING) + { + //lock_tx.unlock(); + USB_ERR("host->bulkWrite() returned %d", res); + Thread::wait(100); + return -1; + } + return 0; +} + +int WANDongleSerialPort::putc(int c) +{ + tx_mtx.lock(); + if(!lock_tx) + { + if(buf_out_len < max_out_size) + { + buf_out[buf_out_len] = (uint8_t)c; + buf_out_len++; + } + } + else + { + USB_ERR("CAN'T WRITE!"); + } + tx_mtx.unlock(); + return c; +} + +int WANDongleSerialPort::getc() +{ + rx_mtx.lock(); + int c = 0; + if(!lock_rx) + { + if(buf_in_read_pos < buf_in_len) + { + c = (int)buf_in[buf_in_read_pos]; + buf_in_read_pos++; + } + } + else + { + USB_ERR("CAN'T READ!"); + } + rx_mtx.unlock(); + return c; +} + +int WANDongleSerialPort::readable() +{ + rx_mtx.lock(); + if (lock_rx) + { + rx_mtx.unlock(); + return 0; + } + + /* if( !lock_rx.trylock() ) + { + return 0; + }*/ + int res = buf_in_len - buf_in_read_pos; + //lock_rx.unlock(); + rx_mtx.unlock(); + return res; +} + +int WANDongleSerialPort::writeable() +{ + tx_mtx.lock(); + if (lock_tx) + { + tx_mtx.unlock(); + return 0; + } + + /*if( !lock_tx.trylock() ) + { + return 0; + }*/ + int res = max_out_size - buf_out_len; + tx_mtx.unlock(); + //lock_tx.unlock(); + return res; +} + +void WANDongleSerialPort::attach(IUSBHostSerialListener* pListener) +{ + if(pListener == NULL) + { + setupIrq(false, RxIrq); + setupIrq(false, TxIrq); + } + listener = pListener; + if(pListener != NULL) + { + setupIrq(true, RxIrq); + setupIrq(true, TxIrq); + } +} + +void WANDongleSerialPort::setupIrq(bool en, IrqType irq /*= RxIrq*/) +{ + switch(irq) + { + case RxIrq: + rx_mtx.lock(); + cb_rx_en = en; + if(en && cb_rx_pending) + { + cb_rx_pending = false; + rx_mtx.unlock(); + listener->readable(); //Process the interrupt that was raised + } + else + { + rx_mtx.unlock(); + } + break; + case TxIrq: + tx_mtx.lock(); + cb_tx_en = en; + if(en && cb_tx_pending) + { + cb_tx_pending = false; + tx_mtx.unlock(); + listener->writeable(); //Process the interrupt that was raised + } + else + { + tx_mtx.unlock(); + } + break; + } +} + + +void WANDongleSerialPort::connect( USBDeviceConnected* pDev, USBEndpoint* pInEp, USBEndpoint* pOutEp ) +{ + dev = pDev; + bulk_in = pInEp; + bulk_out = pOutEp; + max_out_size = bulk_out->getSize(); + if( max_out_size > WANDONGLE_MAX_OUTEP_SIZE ) + { + max_out_size = WANDONGLE_MAX_OUTEP_SIZE; + } + bulk_in->attach(this, &WANDongleSerialPort::rxHandler); + bulk_out->attach(this, &WANDongleSerialPort::txHandler); + readPacket(); //Start receiving data +} + +void WANDongleSerialPort::disconnect( ) +{ + reset(); +} + +//Private methods + + +void WANDongleSerialPort::rxHandler() +{ + if (((USBEndpoint *) bulk_in)->getState() == USB_TYPE_IDLE) //Success + { + buf_in_read_pos = 0; + buf_in_len = ((USBEndpoint *) bulk_in)->getLengthTransferred(); //Update length + //lock_rx.unlock(); + rx_mtx.lock(); + lock_rx = false; //Transmission complete + if(cb_rx_en) + { + rx_mtx.unlock(); + listener->readable(); //Call handler from the IRQ context + //readPacket() should be called by the handler subsequently once the buffer has been emptied + } + else + { + cb_rx_pending = true; //Queue the callback + rx_mtx.unlock(); + } + + } + else //Error, try reading again + { + //lock_rx.unlock(); + USB_DBG("Trying again"); + readPacket(); + } +} + +void WANDongleSerialPort::txHandler() +{ + if (((USBEndpoint *) bulk_out)->getState() == USB_TYPE_IDLE) //Success + { + tx_mtx.lock(); + buf_out_len = 0; //Reset length + lock_tx = false; //Transmission complete + //lock_tx.unlock(); + if(cb_tx_en) + { + tx_mtx.unlock(); + listener->writeable(); //Call handler from the IRQ context + //writePacket() should be called by the handler subsequently once the buffer has been filled + } + else + { + cb_tx_pending = true; //Queue the callback + tx_mtx.unlock(); + } + } + else //Error, try reading again + { + //lock_tx.unlock(); + writePacket(); + } +} + +#endif /* USBHOST_3GMODULE */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHost3GModule/WANDongleSerialPort.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,133 @@ +/* Copyright (c) 2010-2012 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef WANDONGLESERIALPORT_H +#define WANDONGLESERIALPORT_H + +#include "USBHostConf.h" + +#ifdef USBHOST_3GMODULE + +#include "USBHost.h" +#include "IUSBHostSerial.h" + +#include "rtos.h" + + +#define WANDONGLE_MAX_OUTEP_SIZE 64 +#define WANDONGLE_MAX_INEP_SIZE 64 + +/** A class to use a WAN (3G/LTE) access dongle + * + */ +class WANDongleSerialPort : public IUSBHostSerial { +public: + /* + * Constructor + * + */ + WANDongleSerialPort(); + + void init( USBHost* pHost ); + + void connect( USBDeviceConnected* pDev, USBEndpoint* pInEp, USBEndpoint* pOutEp ); + + void disconnect( ); + + /* + * Get a char from the dongle's serial interface + */ + virtual int getc(); + + /* + * Put a char to the dongle's serial interface + */ + virtual int putc(int c); + + /* + * Read a packet from the dongle's serial interface, to be called after multiple getc() calls + */ + virtual int readPacket(); + + /* + * Write a packet to the dongle's serial interface, to be called after multiple putc() calls + */ + virtual int writePacket(); + + /** + * Check the number of bytes available. + * + * @returns the number of bytes available + */ + virtual int readable(); + + /** + * Check the free space in output. + * + * @returns the number of bytes available + */ + virtual int writeable(); + + /** + * Attach a handler to call when a packet is received / when a packet has been transmitted. + * + * @param pListener instance of the listener deriving from the IUSBHostSerialListener + */ + virtual void attach(IUSBHostSerialListener* pListener); + + /** + * Enable or disable readable/writeable callbacks + */ + virtual void setupIrq(bool en, IrqType irq = RxIrq); + + +protected: + USBEndpoint * bulk_in; + USBEndpoint * bulk_out; + USBHost * host; + USBDeviceConnected * dev; + + uint8_t buf_out[WANDONGLE_MAX_OUTEP_SIZE]; + volatile uint32_t buf_out_len; + uint32_t max_out_size; + volatile bool lock_tx; + volatile bool cb_tx_en; + volatile bool cb_tx_pending; + Mutex tx_mtx; + + uint8_t buf_in[WANDONGLE_MAX_INEP_SIZE]; + volatile uint32_t buf_in_len; + volatile uint32_t buf_in_read_pos; + volatile bool lock_rx; + volatile bool cb_rx_en; + volatile bool cb_rx_pending; + Mutex rx_mtx; + + IUSBHostSerialListener* listener; + + void reset(); + + void rxHandler(); + void txHandler(); + +}; + +#endif /* USBHOST_3GMODULE */ + +#endif +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostHID/USBHostKeyboard.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,207 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "USBHostKeyboard.h" + +#if USBHOST_KEYBOARD + +static uint8_t keymap[4][0x39] = { + { + 0, 0, 0, 0, 'a', 'b' /*0x05*/, + 'c', 'd', 'e', 'f', 'g' /*0x0a*/, + 'h', 'i', 'j', 'k', 'l'/*0x0f*/, + 'm', 'n', 'o', 'p', 'q'/*0x14*/, + 'r', 's', 't', 'u', 'v'/*0x19*/, + 'w', 'x', 'y', 'z', '1'/*0x1E*/, + '2', '3', '4', '5', '6'/*0x23*/, + '7', '8', '9', '0', 0x0A /*enter*/, /*0x28*/ + 0x1B /*escape*/, 0x08 /*backspace*/, 0x09/*tab*/, 0x20/*space*/, '-', /*0x2d*/ + '=', '[', ']', '\\', '#', /*0x32*/ + ';', '\'', 0, ',', '.', /*0x37*/ + '/' + }, + + /* CTRL MODIFIER */ + { + 0, 0, 0, 0, 0, 0 /*0x05*/, + 0, 0, 0, 0, 0 /*0x0a*/, + 0, 0, 0, 0, 0/*0x0f*/, + 0, 0, 0, 0, 0/*0x14*/, + 0, 0, 0, 0, 0/*0x19*/, + 0, 0, 0, 0, 0/*0x1E*/, + 0, 0, 0, 0, 0/*0x23*/, + 0, 0, 0, 0, 0 /*enter*/, /*0x28*/ + 0, 0, 0, 0, 0, /*0x2d*/ + 0, 0, 0, 0, 0, /*0x32*/ + 0, 0, 0, 0, 0, /*0x37*/ + 0 + }, + + /* SHIFT MODIFIER */ + { + 0, 0, 0, 0, 'A', 'B' /*0x05*/, + 'C', 'D', 'E', 'F', 'G' /*0x0a*/, + 'H', 'I', 'J', 'K', 'L'/*0x0f*/, + 'M', 'N', 'O', 'P', 'Q'/*0x14*/, + 'R', 'S', 'T', 'U', 'V'/*0x19*/, + 'W', 'X', 'Y', 'Z', '!'/*0x1E*/, + '@', '#', '$', '%', '^'/*0x23*/, + '&', '*', '(', ')', 0, /*0x28*/ + 0, 0, 0, 0, 0, /*0x2d*/ + '+', '{', '}', '|', '~', /*0x32*/ + ':', '"', 0, '<', '>', /*0x37*/ + '?' + }, + + /* ALT MODIFIER */ + { + 0, 0, 0, 0, 0, 0 /*0x05*/, + 0, 0, 0, 0, 0 /*0x0a*/, + 0, 0, 0, 0, 0/*0x0f*/, + 0, 0, 0, 0, 0/*0x14*/, + 0, 0, 0, 0, 0/*0x19*/, + 0, 0, 0, 0, 0/*0x1E*/, + 0, 0, 0, 0, 0/*0x23*/, + 0, 0, 0, 0, 0 /*enter*/, /*0x28*/ + 0, 0, 0, 0, 0, /*0x2d*/ + 0, 0, 0, 0, 0, /*0x32*/ + 0, 0, 0, 0, 0, /*0x37*/ + 0 + } + +}; + + +USBHostKeyboard::USBHostKeyboard() +{ + host = USBHost::getHostInst(); + init(); +} + + +void USBHostKeyboard::init() +{ + dev = NULL; + int_in = NULL; + report_id = 0; + onKey = NULL; + onKeyCode = NULL; + dev_connected = false; + keyboard_intf = -1; + keyboard_device_found = false; +} + +bool USBHostKeyboard::connected() +{ + return dev_connected; +} + + +bool USBHostKeyboard::connect() +{ + + if (dev_connected) { + return true; + } + + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { + if ((dev = host->getDevice(i)) != NULL) { + + if (host->enumerate(dev, this)) { + break; + } + + if (keyboard_device_found) { + { + /* As this is done in a specific thread + * this lock is taken to avoid to process the device + * disconnect in usb process during the device registering */ + USBHost::Lock Lock(host); + + int_in = dev->getEndpoint(keyboard_intf, INTERRUPT_ENDPOINT, IN); + + if (!int_in) { + break; + } + + USB_INFO("New Keyboard device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, keyboard_intf); + dev->setName("Keyboard", keyboard_intf); + host->registerDriver(dev, keyboard_intf, this, &USBHostKeyboard::init); + + int_in->attach(this, &USBHostKeyboard::rxHandler); + } + host->interruptRead(dev, int_in, report, int_in->getSize(), false); + + dev_connected = true; + return true; + } + } + } + init(); + return false; +} + +void USBHostKeyboard::rxHandler() +{ + int len = int_in->getLengthTransferred(); + int index = (len == 9) ? 1 : 0; + int len_listen = int_in->getSize(); + uint8_t key = 0; + if (len == 8 || len == 9) { + uint8_t modifier = (report[index] == 4) ? 3 : report[index]; + len_listen = len; + key = keymap[modifier][report[index + 2]]; + if (key && onKey) { + (*onKey)(key); + } + if ((report[index + 2] || modifier) && onKeyCode) { + (*onKeyCode)(report[index + 2], modifier); + } + } + if (dev && int_in) { + host->interruptRead(dev, int_in, report, len_listen, false); + } +} + +/*virtual*/ void USBHostKeyboard::setVidPid(uint16_t vid, uint16_t pid) +{ + // we don't check VID/PID for keyboard driver +} + +/*virtual*/ bool USBHostKeyboard::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed +{ + if ((keyboard_intf == -1) && + (intf_class == HID_CLASS) && + (intf_subclass == 0x01) && + (intf_protocol == 0x01)) { + keyboard_intf = intf_nb; + return true; + } + return false; +} + +/*virtual*/ bool USBHostKeyboard::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used +{ + if (intf_nb == keyboard_intf) { + if (type == INTERRUPT_ENDPOINT && dir == IN) { + keyboard_device_found = true; + return true; + } + } + return false; +} + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostHID/USBHostKeyboard.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,105 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBHOSTKEYBOARD_H +#define USBHOSTKEYBOARD_H + +#include "USBHostConf.h" + +#if USBHOST_KEYBOARD + +#include "USBHost.h" + +/** + * A class to communicate a USB keyboard + */ +class USBHostKeyboard : public IUSBEnumerator +{ +public: + + /** + * Constructor + */ + USBHostKeyboard(); + + /** + * Try to connect a keyboard device + * + * @return true if connection was successful + */ + bool connect(); + + /** + * Check if a keyboard is connected + * + * @returns true if a keyboard is connected + */ + bool connected(); + + /** + * Attach a callback called when a keyboard event is received + * + * @param ptr function pointer + */ + inline void attach(void (*ptr)(uint8_t key)) + { + if (ptr != NULL) { + onKey = ptr; + } + } + + /** + * Attach a callback called when a keyboard event is received + * + * @param ptr function pointer + */ + inline void attach(void (*ptr)(uint8_t keyCode, uint8_t modifier)) + { + if (ptr != NULL) { + onKeyCode = ptr; + } + } + +protected: + //From IUSBEnumerator + virtual void setVidPid(uint16_t vid, uint16_t pid); + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used + +private: + USBHost * host; + USBDeviceConnected * dev; + USBEndpoint * int_in; + uint8_t report[9]; + int keyboard_intf; + bool keyboard_device_found; + + bool dev_connected; + + void rxHandler(); + + void (*onKey)(uint8_t key); + void (*onKeyCode)(uint8_t key, uint8_t modifier); + + int report_id; + + void init(); + +}; + +#endif + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostHID/USBHostMouse.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,174 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "USBHostMouse.h" + +#if USBHOST_MOUSE + +USBHostMouse::USBHostMouse() +{ + host = USBHost::getHostInst(); + init(); +} + +void USBHostMouse::init() +{ + dev = NULL; + int_in = NULL; + onUpdate = NULL; + onButtonUpdate = NULL; + onXUpdate = NULL; + onYUpdate = NULL; + onZUpdate = NULL; + report_id = 0; + dev_connected = false; + mouse_device_found = false; + mouse_intf = -1; + + buttons = 0; + x = 0; + y = 0; + z = 0; +} + +bool USBHostMouse::connected() +{ + return dev_connected; +} + +bool USBHostMouse::connect() +{ + int len_listen; + + if (dev_connected) { + return true; + } + + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { + if ((dev = host->getDevice(i)) != NULL) { + + if(host->enumerate(dev, this)) { + break; + } + if (mouse_device_found) { + { + /* As this is done in a specific thread + * this lock is taken to avoid to process the device + * disconnect in usb process during the device registering */ + USBHost::Lock Lock(host); + int_in = dev->getEndpoint(mouse_intf, INTERRUPT_ENDPOINT, IN); + if (!int_in) { + break; + } + + USB_INFO("New Mouse device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, mouse_intf); + dev->setName("Mouse", mouse_intf); + host->registerDriver(dev, mouse_intf, this, &USBHostMouse::init); + + int_in->attach(this, &USBHostMouse::rxHandler); + len_listen = int_in->getSize(); + if (len_listen > sizeof(report)) { + len_listen = sizeof(report); + } + } + int ret=host->interruptRead(dev, int_in, report, len_listen, false); + MBED_ASSERT((ret==USB_TYPE_OK) || (ret ==USB_TYPE_PROCESSING) || (ret == USB_TYPE_FREE)); + if ((ret==USB_TYPE_OK) || (ret ==USB_TYPE_PROCESSING)) { + dev_connected = true; + } + if (ret == USB_TYPE_FREE) { + dev_connected = false; + } + return true; + } + } + } + init(); + return false; +} + +void USBHostMouse::rxHandler() +{ + int len_listen = int_in->getLengthTransferred(); + if (len_listen !=0) { + + if (onUpdate) { + (*onUpdate)(report[0] & 0x07, report[1], report[2], report[3]); + } + + if (onButtonUpdate && (buttons != (report[0] & 0x07))) { + (*onButtonUpdate)(report[0] & 0x07); + } + + if (onXUpdate && (x != report[1])) { + (*onXUpdate)(report[1]); + } + + if (onYUpdate && (y != report[2])) { + (*onYUpdate)(report[2]); + } + + if (onZUpdate && (z != report[3])) { + (*onZUpdate)(report[3]); + } + + // update mouse state + buttons = report[0] & 0x07; + x = report[1]; + y = report[2]; + z = report[3]; + } + /* set again the maximum value */ + len_listen = int_in->getSize(); + + if (len_listen > sizeof(report)) { + len_listen = sizeof(report); + } + + if (dev) { + host->interruptRead(dev, int_in, report, len_listen, false); + } +} + +/*virtual*/ void USBHostMouse::setVidPid(uint16_t vid, uint16_t pid) +{ + // we don't check VID/PID for mouse driver +} + +/*virtual*/ bool USBHostMouse::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed +{ + if ((mouse_intf == -1) && + (intf_class == HID_CLASS) && + (intf_subclass == 0x01) && + (intf_protocol == 0x02)) { + mouse_intf = intf_nb; + return true; + } + return false; +} + +/*virtual*/ bool USBHostMouse::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used +{ + if (intf_nb == mouse_intf) { + if (type == INTERRUPT_ENDPOINT && dir == IN) { + mouse_device_found = true; + return true; + } + } + return false; +} + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostHID/USBHostMouse.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,144 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBHOSTMOUSE_H +#define USBHOSTMOUSE_H + +#include "USBHostConf.h" + +#if USBHOST_MOUSE + +#include "USBHost.h" + +/** + * A class to communicate a USB mouse + */ +class USBHostMouse : public IUSBEnumerator +{ +public: + + /** + * Constructor + */ + USBHostMouse(); + + /** + * Try to connect a mouse device + * + * @return true if connection was successful + */ + bool connect(); + + /** + * Check if a mouse is connected + * + * @returns true if a mouse is connected + */ + bool connected(); + + /** + * Attach a callback called when a mouse event is received + * + * @param ptr function pointer + */ + inline void attachEvent(void (*ptr)(uint8_t buttons, int8_t x, int8_t y, int8_t z)) + { + if (ptr != NULL) { + onUpdate = ptr; + } + } + + /** + * Attach a callback called when the button state changes + * + * @param ptr function pointer + */ + inline void attachButtonEvent(void (*ptr)(uint8_t buttons)) + { + if (ptr != NULL) { + onButtonUpdate = ptr; + } + } + + /** + * Attach a callback called when the X axis value changes + * + * @param ptr function pointer + */ + inline void attachXEvent(void (*ptr)(int8_t x)) + { + if (ptr != NULL) { + onXUpdate = ptr; + } + } + + /** + * Attach a callback called when the Y axis value changes + * + * @param ptr function pointer + */ + inline void attachYEvent(void (*ptr)(int8_t y)) + { + if (ptr != NULL) { + onYUpdate = ptr; + } + } + + /** + * Attach a callback called when the Z axis value changes (scrolling) + * + * @param ptr function pointer + */ + inline void attachZEvent(void (*ptr)(int8_t z)) + { + if (ptr != NULL) { + onZUpdate = ptr; + } + } + +protected: + //From IUSBEnumerator + virtual void setVidPid(uint16_t vid, uint16_t pid); + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used + +private: + USBHost * host; + USBDeviceConnected * dev; + USBEndpoint * int_in; + uint8_t report[64]; + bool dev_connected; + bool mouse_device_found; + int mouse_intf; + + uint8_t buttons; + int8_t x; + int8_t y; + int8_t z; + + void rxHandler(); + void (*onUpdate)(uint8_t buttons, int8_t x, int8_t y, int8_t z); + void (*onButtonUpdate)(uint8_t buttons); + void (*onXUpdate)(int8_t x); + void (*onYUpdate)(int8_t y); + void (*onZUpdate)(int8_t z); + int report_id; + void init(); +}; + +#endif + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostHub/USBHostHub.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,291 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "USBHostHub.h" + +#if MAX_HUB_NB + +#include "USBHost.h" +#include "dbg.h" + +#define GET_STATUS 0x00 +#define CLEAR_FEATURE 0x01 +#define GET_STATE 0x02 +#define SET_FEATURE 0x03 +#define GET_DESCRIPTOR 0x06 + +#define PORT_CONNECTION_FEATURE (0x00) +#define PORT_ENABLE_FEATURE (0x01) +#define PORT_RESET_FEATURE (0x04) +#define PORT_POWER_FEATURE (0x08) + +#define C_PORT_CONNECTION_FEATURE (16) +#define C_PORT_ENABLE_FEATURE (17) +#define C_PORT_RESET_FEATURE (20) + +#define PORT_CONNECTION (1 << 0) +#define PORT_ENABLE (1 << 1) +#define PORT_SUSPEND (1 << 2) +#define PORT_OVER_CURRENT (1 << 3) +#define PORT_RESET (1 << 4) +#define PORT_POWER (1 << 8) +#define PORT_LOW_SPEED (1 << 9) + +#define C_PORT_CONNECTION (1 << 16) +#define C_PORT_ENABLE (1 << 17) +#define C_PORT_SUSPEND (1 << 18) +#define C_PORT_OVER_CURRENT (1 << 19) +#define C_PORT_RESET (1 << 20) + +USBHostHub::USBHostHub() +{ + host = NULL; + init(); +} + +void USBHostHub::init() +{ + dev_connected = false; + dev = NULL; + int_in = NULL; + dev_connected = false; + hub_intf = -1; + hub_device_found = false; + nb_port = 0; + hub_characteristics = 0; + + for (int i = 0; i < MAX_HUB_PORT; i++) { + device_children[i] = NULL; + } +} + +void USBHostHub::setHost(USBHost * host_) +{ + host = host_; +} + +bool USBHostHub::connected() +{ + return dev_connected; +} + +bool USBHostHub::connect(USBDeviceConnected * dev) +{ + if (dev_connected) { + return true; + } + + if(host->enumerate(dev, this)) { + init(); + return false; + } + + if (hub_device_found) { + this->dev = dev; + + int_in = dev->getEndpoint(hub_intf, INTERRUPT_ENDPOINT, IN); + + if (!int_in) { + init(); + return false; + } + + USB_INFO("New HUB: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, hub_intf); + dev->setName("Hub", hub_intf); + host->registerDriver(dev, hub_intf, this, &USBHostHub::disconnect); + + int_in->attach(this, &USBHostHub::rxHandler); + + // get HUB descriptor + host->controlRead( dev, + USB_DEVICE_TO_HOST | USB_REQUEST_TYPE_CLASS, + GET_DESCRIPTOR, + 0x29 << 8, 0, buf, sizeof(HubDescriptor)); + nb_port = buf[2]; + hub_characteristics = buf[3]; + + USB_DBG("Hub has %d port", nb_port); + + for (uint8_t j = 1; j <= nb_port; j++) { + setPortFeature(PORT_POWER_FEATURE, j); + } + wait_ms(buf[5]*2); + + host->interruptRead(dev, int_in, buf, 1, false); + dev_connected = true; + return true; + } + + return false; +} + +void USBHostHub::disconnect() +{ + init(); +} + +/*virtual*/ void USBHostHub::setVidPid(uint16_t vid, uint16_t pid) +{ + // we don't check VID/PID for MSD driver +} + +/*virtual*/ bool USBHostHub::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed +{ + if ((hub_intf == -1) && + (intf_class == HUB_CLASS) && + (intf_subclass == 0) && + (intf_protocol == 0)) { + hub_intf = intf_nb; + return true; + } + return false; +} + +/*virtual*/ bool USBHostHub::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used +{ + if (intf_nb == hub_intf) { + if ((type == INTERRUPT_ENDPOINT) && (dir == IN)) { + hub_device_found = true; + return true; + } + } + return false; +} + +void USBHostHub::deviceConnected(USBDeviceConnected * dev) +{ + device_children[dev->getPort() - 1] = dev; +} + +void USBHostHub::deviceDisconnected(USBDeviceConnected * dev) +{ + device_children[dev->getPort() - 1] = NULL; +} + +void USBHostHub::hubDisconnected() +{ + for (uint8_t i = 0; i < MAX_HUB_PORT; i++) { + if (device_children[i] != NULL) { + host->freeDevice(device_children[i]); + } + } +} + +void USBHostHub::rxHandler() +{ + uint32_t status; + if (int_in) { + if ((int_in->getLengthTransferred())&&(int_in->getState() == USB_TYPE_IDLE)) { + for (int port = 1; port <= nb_port; port++) { + status = getPortStatus(port); + USB_DBG("[hub handler hub: %d] status port %d [hub: %p]: 0x%X", dev->getHub(), port, dev, status); + + // if connection status has changed + if (status & C_PORT_CONNECTION) { + if (status & PORT_CONNECTION) { + USB_DBG("[hub handler hub: %d - port: %d] new device connected", dev->getHub(), port); + host->deviceConnected(dev->getHub() + 1, port, status & PORT_LOW_SPEED, this); + } else { + USB_DBG("[hub handler hub: %d - port: %d] device disconnected", dev->getHub(), port); + host->deviceDisconnected(dev->getHub() + 1, port, this, 0); + } + + clearPortFeature(C_PORT_CONNECTION_FEATURE, port); + } + + if (status & C_PORT_RESET) { + clearPortFeature(C_PORT_RESET_FEATURE, port); + } + + if (status & C_PORT_ENABLE) { + clearPortFeature(C_PORT_ENABLE_FEATURE, port); + } + + if ((status & PORT_OVER_CURRENT)) { + USB_ERR("OVER CURRENT DETECTED\r\n"); + clearPortFeature(PORT_OVER_CURRENT, port); + host->deviceDisconnected(dev->getHub() + 1, port, this, 0); + } + } + } + host->interruptRead(dev, int_in, buf, 1, false); + } +} + +void USBHostHub::portReset(uint8_t port) +{ + // reset port + uint32_t status; + USB_DBG("reset port %d on hub: %p [this: %p]", port, dev, this) + setPortFeature(PORT_RESET_FEATURE, port); +#if defined(TARGET_RZ_A1H) + Thread::wait(50); // Reset release waiting for Hi-Speed check. +#endif + while(1) { + status = getPortStatus(port); + /* disconnection since reset request */ + if (!(status & PORT_CONNECTION)) { + break; + } + if (status & (PORT_ENABLE | PORT_RESET)) { + break; + } + if (status & PORT_OVER_CURRENT) { + USB_ERR("OVER CURRENT DETECTED\r\n"); + clearPortFeature(PORT_OVER_CURRENT, port); + host->deviceDisconnected(dev->getHub() + 1, port, this, 0); + break; + } + Thread::wait(10); + } +} + +void USBHostHub::setPortFeature(uint32_t feature, uint8_t port) +{ + host->controlWrite( dev, + USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_CLASS | USB_RECIPIENT_INTERFACE | USB_RECIPIENT_ENDPOINT, + SET_FEATURE, + feature, + port, + NULL, + 0); +} + +void USBHostHub::clearPortFeature(uint32_t feature, uint8_t port) +{ + host->controlWrite( dev, + USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_CLASS | USB_RECIPIENT_INTERFACE | USB_RECIPIENT_ENDPOINT, + CLEAR_FEATURE, + feature, + port, + NULL, + 0); +} + +uint32_t USBHostHub::getPortStatus(uint8_t port) +{ + uint32_t st; + host->controlRead( dev, + USB_DEVICE_TO_HOST | USB_REQUEST_TYPE_CLASS | USB_RECIPIENT_INTERFACE | USB_RECIPIENT_ENDPOINT, + GET_STATUS, + 0, + port, + (uint8_t *)&st, + 4); + return st; +} + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostHub/USBHostHub.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,126 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBHOSTHUB_H +#define USBHOSTHUB_H + +#include "USBHostConf.h" + +#if MAX_HUB_NB + +#include "USBHostTypes.h" +#include "IUSBEnumerator.h" + +class USBHost; +class USBDeviceConnected; +class USBEndpoint; + +/** + * A class to use a USB Hub + */ +class USBHostHub : public IUSBEnumerator +{ +public: + /** + * Constructor + */ + USBHostHub(); + + /** + * Check if a USB Hub is connected + * + * @return true if a serial device is connected + */ + bool connected(); + + /** + * Try to connect device + * + * @param dev device to connect + * @return true if connection was successful + */ + bool connect(USBDeviceConnected * dev); + + /** + * Automatically called by USBHost when a device + * has been enumerated by usb_thread + * + * @param dev device connected + */ + void deviceConnected(USBDeviceConnected * dev); + + /** + * Automatically called by USBHost when a device + * has been disconnected from this hub + * + * @param dev device disconnected + */ + void deviceDisconnected(USBDeviceConnected * dev); + + /** + * Rest a specific port + * + * @param port port number + */ + void portReset(uint8_t port); + + /* + * Called by USBHost to set the instance of USBHost + * + * @param host host instance + */ + void setHost(USBHost * host); + + /** + * Called by USBhost when a hub has been disconnected + */ + void hubDisconnected(); + +protected: + //From IUSBEnumerator + virtual void setVidPid(uint16_t vid, uint16_t pid); + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used + +private: + USBHost * host; + USBDeviceConnected * dev; + bool dev_connected; + USBEndpoint * int_in; + uint8_t nb_port; + uint8_t hub_characteristics; + + void rxHandler(); + + uint8_t buf[sizeof(HubDescriptor)]; + + int hub_intf; + bool hub_device_found; + + void setPortFeature(uint32_t feature, uint8_t port); + void clearPortFeature(uint32_t feature, uint8_t port); + uint32_t getPortStatus(uint8_t port); + + USBDeviceConnected * device_children[MAX_HUB_PORT]; + + void init(); + void disconnect(); + +}; + +#endif + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostMIDI/USBHostMIDI.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,362 @@ +/* Copyright (c) 2014 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "USBHostMIDI.h" + +#if USBHOST_MIDI + +#include "dbg.h" + +#define SET_LINE_CODING 0x20 + +USBHostMIDI::USBHostMIDI() { + host = USBHost::getHostInst(); + size_bulk_in = 0; + size_bulk_out = 0; + init(); +} + +void USBHostMIDI::init() { + dev = NULL; + bulk_in = NULL; + bulk_out = NULL; + dev_connected = false; + midi_intf = -1; + midi_device_found = false; + sysExBufferPos = 0; +} + +bool USBHostMIDI::connected() { + return dev_connected; +} + +bool USBHostMIDI::connect() { + if (dev_connected) { + return true; + } + + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { + if ((dev = host->getDevice(i)) != NULL) { + + USB_DBG("Trying to connect MIDI device\r\n"); + + if (host->enumerate(dev, this)) { + break; + } + + if (midi_device_found) { + bulk_in = dev->getEndpoint(midi_intf, BULK_ENDPOINT, IN); + bulk_out = dev->getEndpoint(midi_intf, BULK_ENDPOINT, OUT); + + if (!bulk_in || !bulk_out) { + break; + } + + USB_INFO("New MIDI device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, midi_intf); + dev->setName("MIDI", midi_intf); + host->registerDriver(dev, midi_intf, this, &USBHostMIDI::init); + + size_bulk_in = bulk_in->getSize(); + size_bulk_out = bulk_out->getSize(); + + bulk_in->attach(this, &USBHostMIDI::rxHandler); + + host->bulkRead(dev, bulk_in, buf, size_bulk_in, false); + dev_connected = true; + return true; + } + } + } + + init(); + return false; +} + +void USBHostMIDI::rxHandler() { + uint8_t *midi; + if (bulk_in) { + int length = bulk_in->getLengthTransferred(); + if (bulk_in->getState() == USB_TYPE_IDLE || bulk_in->getState() == USB_TYPE_FREE) { + // MIDI event handling + for (int i = 0; i < length; i += 4) { + if (i + 4 > length) { + // length shortage, ignored. + break; + } + + // read each four bytes + midi = &buf[i]; + // process MIDI message + // switch by code index number + switch (midi[0] & 0xf) { + case 0: // miscellaneous function codes + miscellaneousFunctionCode(midi[1], midi[2], midi[3]); + break; + case 1: // cable events + cableEvent(midi[1], midi[2], midi[3]); + break; + case 2: // two bytes system common messages + systemCommonTwoBytes(midi[1], midi[2]); + break; + case 3: // three bytes system common messages + systemCommonThreeBytes(midi[1], midi[2], midi[3]); + break; + case 4: // SysEx starts or continues + sysExBuffer[sysExBufferPos++] = midi[1]; + if (sysExBufferPos >= 64) { + systemExclusive(sysExBuffer, sysExBufferPos, true); + sysExBufferPos = 0; + } + sysExBuffer[sysExBufferPos++] = midi[2]; + if (sysExBufferPos >= 64) { + systemExclusive(sysExBuffer, sysExBufferPos, true); + sysExBufferPos = 0; + } + sysExBuffer[sysExBufferPos++] = midi[3]; + // SysEx continues. don't send + break; + case 5: // SysEx ends with single byte + sysExBuffer[sysExBufferPos++] = midi[1]; + systemExclusive(sysExBuffer, sysExBufferPos, false); + sysExBufferPos = 0; + break; + case 6: // SysEx ends with two bytes + sysExBuffer[sysExBufferPos++] = midi[1]; + if (sysExBufferPos >= 64) { + systemExclusive(sysExBuffer, sysExBufferPos, true); + sysExBufferPos = 0; + } + sysExBuffer[sysExBufferPos++] = midi[2]; + systemExclusive(sysExBuffer, sysExBufferPos, false); + sysExBufferPos = 0; + break; + case 7: // SysEx ends with three bytes + sysExBuffer[sysExBufferPos++] = midi[1]; + if (sysExBufferPos >= 64) { + systemExclusive(sysExBuffer, sysExBufferPos, true); + sysExBufferPos = 0; + } + sysExBuffer[sysExBufferPos++] = midi[2]; + if (sysExBufferPos >= 64) { + systemExclusive(sysExBuffer, sysExBufferPos, true); + sysExBufferPos = 0; + } + sysExBuffer[sysExBufferPos++] = midi[3]; + systemExclusive(sysExBuffer, sysExBufferPos, false); + sysExBufferPos = 0; + break; + case 8: + noteOff(midi[1] & 0xf, midi[2], midi[3]); + break; + case 9: + if (midi[3]) { + noteOn(midi[1] & 0xf, midi[2], midi[3]); + } else { + noteOff(midi[1] & 0xf, midi[2], midi[3]); + } + break; + case 10: + polyKeyPress(midi[1] & 0xf, midi[2], midi[3]); + break; + case 11: + controlChange(midi[1] & 0xf, midi[2], midi[3]); + break; + case 12: + programChange(midi[1] & 0xf, midi[2]); + break; + case 13: + channelPressure(midi[1] & 0xf, midi[2]); + break; + case 14: + pitchBend(midi[1] & 0xf, midi[2] | (midi[3] << 7)); + break; + case 15: + singleByte(midi[1]); + break; + } + } + + // read another message + host->bulkRead(dev, bulk_in, buf, size_bulk_in, false); + } + } +} + +bool USBHostMIDI::sendMidiBuffer(uint8_t data0, uint8_t data1, uint8_t data2, uint8_t data3) { + if (bulk_out) { + uint8_t midi[4]; + + midi[0] = data0; + midi[1] = data1; + midi[2] = data2; + midi[3] = data3; + if (host->bulkWrite(dev, bulk_out, (uint8_t *)midi, 4) == USB_TYPE_OK) { + return true; + } + } + return false; +} + +bool USBHostMIDI::sendMiscellaneousFunctionCode(uint8_t data1, uint8_t data2, uint8_t data3) { + return sendMidiBuffer(0, data1, data2, data3); +} + +bool USBHostMIDI::sendCableEvent(uint8_t data1, uint8_t data2, uint8_t data3) { + return sendMidiBuffer(1, data1, data2, data3); +} + +bool USBHostMIDI::sendSystemCommmonTwoBytes(uint8_t data1, uint8_t data2) { + return sendMidiBuffer(2, data1, data2, 0); +} + +bool USBHostMIDI::sendSystemCommmonThreeBytes(uint8_t data1, uint8_t data2, uint8_t data3) { + return sendMidiBuffer(3, data1, data2, 0); +} + +bool USBHostMIDI::sendSystemExclusive(uint8_t *buffer, int length) { + uint8_t midi[64]; + int midiLength; + int midiPos; + if (bulk_out) { + for (int i = 0; i < length; i += 48) { + if (i + 48 >= length) { + // contains last data + midiLength = (((length - i) + 2) / 3) * 4; + for (int pos = i; pos < length; pos += 3) { + midiPos = (pos + 2) / 3 * 4; + if (pos + 3 >= length) { + // last data + switch (pos % 3) { + case 0: + midi[midiPos ] = 7; + midi[midiPos + 1] = buffer[pos ]; + midi[midiPos + 2] = buffer[pos + 1]; + midi[midiPos + 3] = buffer[pos + 2]; + break; + case 1: + midi[midiPos ] = 5; + midi[midiPos + 1] = buffer[pos ]; + midi[midiPos + 2] = 0; + midi[midiPos + 3] = 0; + break; + case 2: + midi[midiPos ] = 6; + midi[midiPos + 1] = buffer[pos ]; + midi[midiPos + 2] = buffer[pos + 1]; + midi[midiPos + 3] = 0; + break; + } + } else { + // has more data + midi[midiPos ] = 4; + midi[midiPos + 1] = buffer[pos ]; + midi[midiPos + 2] = buffer[pos + 1]; + midi[midiPos + 3] = buffer[pos + 2]; + } + } + } else { + // has more data + midiLength = 64; + for (int pos = i; pos < length; pos += 3) { + midiPos = (pos + 2) / 3 * 4; + midi[midiPos ] = 4; + midi[midiPos + 1] = buffer[pos ]; + midi[midiPos + 2] = buffer[pos + 1]; + midi[midiPos + 3] = buffer[pos + 2]; + } + } + + if (host->bulkWrite(dev, bulk_out, (uint8_t *)midi, midiLength) != USB_TYPE_OK) { + return false; + } + } + return true; + } + return false; +} + +bool USBHostMIDI::sendNoteOff(uint8_t channel, uint8_t note, uint8_t velocity) { + return sendMidiBuffer(8, channel & 0xf | 0x80, note & 0x7f, velocity & 0x7f); +} + +bool USBHostMIDI::sendNoteOn(uint8_t channel, uint8_t note, uint8_t velocity) { + return sendMidiBuffer(9, channel & 0xf | 0x90, note & 0x7f, velocity & 0x7f); +} + +bool USBHostMIDI::sendPolyKeyPress(uint8_t channel, uint8_t note, uint8_t pressure) { + return sendMidiBuffer(10, channel & 0xf | 0xa0, note & 0x7f, pressure & 0x7f); +} + +bool USBHostMIDI::sendControlChange(uint8_t channel, uint8_t key, uint8_t value) { + return sendMidiBuffer(11, channel & 0xf | 0xb0, key & 0x7f, value & 0x7f); +} + +bool USBHostMIDI::sendProgramChange(uint8_t channel, uint8_t program) { + return sendMidiBuffer(12, channel & 0xf | 0xc0, program & 0x7f, 0); +} + +bool USBHostMIDI::sendChannelPressure(uint8_t channel, uint8_t pressure) { + return sendMidiBuffer(13, channel & 0xf | 0xd0, pressure & 0x7f, 0); +} + +bool USBHostMIDI::sendPitchBend(uint8_t channel, uint16_t value) { + return sendMidiBuffer(14, channel & 0xf | 0xe0, value & 0x7f, (value >> 7) & 0x7f); +} + +bool USBHostMIDI::sendSingleByte(uint8_t data) { + return sendMidiBuffer(15, data, 0, 0); +} + +/*virtual*/ void USBHostMIDI::setVidPid(uint16_t vid, uint16_t pid) +{ + // we don't check VID/PID for this driver +} + +/*virtual*/ bool USBHostMIDI::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed +{ + // USB MIDI class/subclass + if ((midi_intf == -1) && + (intf_class == AUDIO_CLASS) && + (intf_subclass == 0x03)) { + midi_intf = intf_nb; + return true; + } + + // vendor specific device + if ((midi_intf == -1) && + (intf_class == 0xff) && + (intf_subclass == 0x03)) { + midi_intf = intf_nb; + return true; + } + + return false; +} + +/*virtual*/ bool USBHostMIDI::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used +{ + if (intf_nb == midi_intf) { + if (type == BULK_ENDPOINT) { + midi_device_found = true; + return true; + } + } + return false; +} + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostMIDI/USBHostMIDI.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,353 @@ +/* Copyright (c) 2014 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef USBHOSTMIDI_H +#define USBHOSTMIDI_H + +#include "USBHostConf.h" + +#if USBHOST_MIDI + +#include "USBHost.h" + +/** + * A class to communicate a USB MIDI device + */ +class USBHostMIDI : public IUSBEnumerator { +public: + /** + * Constructor + */ + USBHostMIDI(); + + /** + * Check if a USB MIDI device is connected + * + * @returns true if a midi device is connected + */ + bool connected(); + + /** + * Try to connect a midi device + * + * @return true if connection was successful + */ + bool connect(); + + /** + * Attach a callback called when miscellaneous function code is received + * + * @param ptr function pointer + * prototype: void onMiscellaneousFunctionCode(uint8_t data1, uint8_t data2, uint8_t data3); + */ + inline void attachMiscellaneousFunctionCode(void (*fn)(uint8_t, uint8_t, uint8_t)) { + miscellaneousFunctionCode = fn; + } + + /** + * Attach a callback called when cable event is received + * + * @param ptr function pointer + * prototype: void onCableEvent(uint8_t data1, uint8_t data2, uint8_t data3); + */ + inline void attachCableEvent(void (*fn)(uint8_t, uint8_t, uint8_t)) { + cableEvent = fn; + } + + /** + * Attach a callback called when system exclusive is received + * + * @param ptr function pointer + * prototype: void onSystemCommonTwoBytes(uint8_t data1, uint8_t data2); + */ + inline void attachSystemCommonTwoBytes(void (*fn)(uint8_t, uint8_t)) { + systemCommonTwoBytes = fn; + } + + /** + * Attach a callback called when system exclusive is received + * + * @param ptr function pointer + * prototype: void onSystemCommonThreeBytes(uint8_t data1, uint8_t data2, uint8_t data3); + */ + inline void attachSystemCommonThreeBytes(void (*fn)(uint8_t, uint8_t, uint8_t)) { + systemCommonThreeBytes = fn; + } + + /** + * Attach a callback called when system exclusive is received + * + * @param ptr function pointer + * prototype: void onSystemExclusive(uint8_t *data, uint16_t length, bool hasNextData); + */ + inline void attachSystemExclusive(void (*fn)(uint8_t *, uint16_t, bool)) { + systemExclusive = fn; + } + + /** + * Attach a callback called when note on is received + * + * @param ptr function pointer + * prototype: void onNoteOn(uint8_t channel, uint8_t note, uint8_t velocity); + */ + inline void attachNoteOn(void (*fn)(uint8_t, uint8_t, uint8_t)) { + noteOn = fn; + } + + /** + * Attach a callback called when note off is received + * + * @param ptr function pointer + * prototype: void onNoteOff(uint8_t channel, uint8_t note, uint8_t velocity); + */ + inline void attachNoteOff(void (*fn)(uint8_t, uint8_t, uint8_t)) { + noteOff = fn; + } + + /** + * Attach a callback called when poly keypress is received + * + * @param ptr function pointer + * prototype: void onPolyKeyPress(uint8_t channel, uint8_t note, uint8_t pressure); + */ + inline void attachPolyKeyPress(void (*fn)(uint8_t, uint8_t, uint8_t)) { + polyKeyPress = fn; + } + + /** + * Attach a callback called when control change is received + * + * @param ptr function pointer + * prototype: void onControlChange(uint8_t channel, uint8_t key, uint8_t value); + */ + inline void attachControlChange(void (*fn)(uint8_t, uint8_t, uint8_t)) { + controlChange = fn; + } + + /** + * Attach a callback called when program change is received + * + * @param ptr function pointer + * prototype: void onProgramChange(uint8_t channel, uint8_t program); + */ + inline void attachProgramChange(void (*fn)(uint8_t, uint8_t)) { + programChange = fn; + } + + /** + * Attach a callback called when channel pressure is received + * + * @param ptr function pointer + * prototype: void onChannelPressure(uint8_t channel, uint8_t pressure); + */ + inline void attachChannelPressure(void (*fn)(uint8_t, uint8_t)) { + channelPressure = fn; + } + + /** + * Attach a callback called when pitch bend is received + * + * @param ptr function pointer + * prototype: void onPitchBend(uint8_t channel, uint16_t value); + */ + inline void attachPitchBend(void (*fn)(uint8_t, uint16_t)) { + pitchBend = fn; + } + + /** + * Attach a callback called when single byte is received + * + * @param ptr function pointer + * prototype: void onSingleByte(uint8_t value); + */ + inline void attachSingleByte(void (*fn)(uint8_t)) { + singleByte = fn; + } + + /** + * Send a cable event with 3 bytes event + * + * @param data1 0-255 + * @param data2 0-255 + * @param data3 0-255 + * @return true if message sent successfully + */ + bool sendMiscellaneousFunctionCode(uint8_t data1, uint8_t data2, uint8_t data3); + + /** + * Send a cable event with 3 bytes event + * + * @param data1 0-255 + * @param data2 0-255 + * @param data3 0-255 + * @return true if message sent successfully + */ + bool sendCableEvent(uint8_t data1, uint8_t data2, uint8_t data3); + + /** + * Send a system common message with 2 bytes event + * + * @param data1 0-255 + * @param data2 0-255 + * @return true if message sent successfully + */ + bool sendSystemCommmonTwoBytes(uint8_t data1, uint8_t data2); + + /** + * Send a system common message with 3 bytes event + * + * @param data1 0-255 + * @param data2 0-255 + * @param data3 0-255 + * @return true if message sent successfully + */ + bool sendSystemCommmonThreeBytes(uint8_t data1, uint8_t data2, uint8_t data3); + + /** + * Send a system exclusive event + * + * @param buffer, starts with 0xF0, and end with 0xf7 + * @param length + * @return true if message sent successfully + */ + bool sendSystemExclusive(uint8_t *buffer, int length); + + /** + * Send a note off event + * + * @param channel 0-15 + * @param note 0-127 + * @param velocity 0-127 + * @return true if message sent successfully + */ + bool sendNoteOff(uint8_t channel, uint8_t note, uint8_t velocity); + + /** + * Send a note on event + * + * @param channel 0-15 + * @param note 0-127 + * @param velocity 0-127 (0 means note off) + * @return true if message sent successfully + */ + bool sendNoteOn(uint8_t channel, uint8_t note, uint8_t velocity); + + /** + * Send a poly keypress event + * + * @param channel 0-15 + * @param note 0-127 + * @param pressure 0-127 + * @return true if message sent successfully + */ + bool sendPolyKeyPress(uint8_t channel, uint8_t note, uint8_t pressure); + + /** + * Send a control change event + * + * @param channel 0-15 + * @param key 0-127 + * @param value 0-127 + * @return true if message sent successfully + */ + bool sendControlChange(uint8_t channel, uint8_t key, uint8_t value); + + /** + * Send a program change event + * + * @param channel 0-15 + * @param program 0-127 + * @return true if message sent successfully + */ + bool sendProgramChange(uint8_t channel, uint8_t program); + + /** + * Send a channel pressure event + * + * @param channel 0-15 + * @param pressure 0-127 + * @return true if message sent successfully + */ + bool sendChannelPressure(uint8_t channel, uint8_t pressure); + + /** + * Send a control change event + * + * @param channel 0-15 + * @param key 0(lower)-8191(center)-16383(higher) + * @return true if message sent successfully + */ + bool sendPitchBend(uint8_t channel, uint16_t value); + + /** + * Send a single byte event + * + * @param data 0-255 + * @return true if message sent successfully + */ + bool sendSingleByte(uint8_t data); + +protected: + //From IUSBEnumerator + virtual void setVidPid(uint16_t vid, uint16_t pid); + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used + +private: + USBHost * host; + USBDeviceConnected * dev; + USBEndpoint * bulk_in; + USBEndpoint * bulk_out; + uint32_t size_bulk_in; + uint32_t size_bulk_out; + + bool dev_connected; + + void init(); + + uint8_t buf[64]; + + void rxHandler(); + + uint16_t sysExBufferPos; + uint8_t sysExBuffer[64]; + + void (*miscellaneousFunctionCode)(uint8_t, uint8_t, uint8_t); + void (*cableEvent)(uint8_t, uint8_t, uint8_t); + void (*systemCommonTwoBytes)(uint8_t, uint8_t); + void (*systemCommonThreeBytes)(uint8_t, uint8_t, uint8_t); + void (*systemExclusive)(uint8_t *, uint16_t, bool); + void (*noteOff)(uint8_t, uint8_t, uint8_t); + void (*noteOn)(uint8_t, uint8_t, uint8_t); + void (*polyKeyPress)(uint8_t, uint8_t, uint8_t); + void (*controlChange)(uint8_t, uint8_t, uint8_t); + void (*programChange)(uint8_t, uint8_t); + void (*channelPressure)(uint8_t, uint8_t); + void (*pitchBend)(uint8_t, uint16_t); + void (*singleByte)(uint8_t); + + bool sendMidiBuffer(uint8_t data0, uint8_t data1, uint8_t data2, uint8_t data3); + + int midi_intf; + bool midi_device_found; + +}; + +#endif /* USBHOST_MIDI */ + +#endif /* USBHOSTMIDI_H */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostMSD/USBHostMSD.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,379 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "USBHostMSD.h" + +#if USBHOST_MSD + +#include "dbg.h" + +#define CBW_SIGNATURE 0x43425355 +#define CSW_SIGNATURE 0x53425355 + +#define DEVICE_TO_HOST 0x80 +#define HOST_TO_DEVICE 0x00 + +#define GET_MAX_LUN (0xFE) +#define BO_MASS_STORAGE_RESET (0xFF) + +USBHostMSD::USBHostMSD(const char * rootdir) : FATFileSystem(rootdir) +{ + host = USBHost::getHostInst(); + init(); +} + +void USBHostMSD::init() { + dev_connected = false; + dev = NULL; + bulk_in = NULL; + bulk_out = NULL; + dev_connected = false; + blockSize = 0; + blockCount = 0; + msd_intf = -1; + msd_device_found = false; + disk_init = false; + dev_connected = false; + nb_ep = 0; +} + + +bool USBHostMSD::connected() +{ + return dev_connected; +} + +bool USBHostMSD::connect() +{ + + if (dev_connected) { + return true; + } + + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { + if ((dev = host->getDevice(i)) != NULL) { + + USB_DBG("Trying to connect MSD device\r\n"); + + if(host->enumerate(dev, this)) + break; + + if (msd_device_found) { + /* As this is done in a specific thread + * this lock is taken to avoid to process a disconnection in + * usb process during the device registering */ + USBHost::Lock Lock(host); + + bulk_in = dev->getEndpoint(msd_intf, BULK_ENDPOINT, IN); + bulk_out = dev->getEndpoint(msd_intf, BULK_ENDPOINT, OUT); + + if (!bulk_in || !bulk_out) + continue; + + USB_INFO("New MSD device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, msd_intf); + dev->setName("MSD", msd_intf); + host->registerDriver(dev, msd_intf, this, &USBHostMSD::init); + + dev_connected = true; + return true; + } + } //if() + } //for() + init(); + return false; +} + +/*virtual*/ void USBHostMSD::setVidPid(uint16_t vid, uint16_t pid) +{ + // we don't check VID/PID for MSD driver +} + +/*virtual*/ bool USBHostMSD::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed +{ + if ((msd_intf == -1) && + (intf_class == MSD_CLASS) && + (intf_subclass == 0x06) && + (intf_protocol == 0x50)) { + msd_intf = intf_nb; + return true; + } + return false; +} + +/*virtual*/ bool USBHostMSD::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used +{ + if (intf_nb == msd_intf) { + if (type == BULK_ENDPOINT) { + nb_ep++; + if (nb_ep == 2) + msd_device_found = true; + return true; + } + } + return false; +} + + +int USBHostMSD::testUnitReady() +{ + USB_DBG("Test unit ready"); + return SCSITransfer(NULL, 6, DEVICE_TO_HOST, 0, 0); +} + + +int USBHostMSD::readCapacity() +{ + USB_DBG("Read capacity"); + uint8_t cmd[10] = {0x25,0,0,0,0,0,0,0,0,0}; + uint8_t result[8]; + int status = SCSITransfer(cmd, 10, DEVICE_TO_HOST, result, 8); + if (status == 0) { + blockCount = (result[0] << 24) | (result[1] << 16) | (result[2] << 8) | result[3]; + blockSize = (result[4] << 24) | (result[5] << 16) | (result[6] << 8) | result[7]; + USB_INFO("MSD [dev: %p] - blockCount: %lld, blockSize: %d, Capacity: %lld\r\n", dev, blockCount, blockSize, blockCount*blockSize); + } + return status; +} + + +int USBHostMSD::SCSIRequestSense() +{ + USB_DBG("Request sense"); + uint8_t cmd[6] = {0x03,0,0,0,18,0}; + uint8_t result[18]; + int status = SCSITransfer(cmd, 6, DEVICE_TO_HOST, result, 18); + return status; +} + + +int USBHostMSD::inquiry(uint8_t lun, uint8_t page_code) +{ + USB_DBG("Inquiry"); + uint8_t evpd = (page_code == 0) ? 0 : 1; + uint8_t cmd[6] = {0x12, uint8_t((lun << 5) | evpd), page_code, 0, 36, 0}; + uint8_t result[36]; + int status = SCSITransfer(cmd, 6, DEVICE_TO_HOST, result, 36); + if (status == 0) { + char vid_pid[17]; + memcpy(vid_pid, &result[8], 8); + vid_pid[8] = 0; + USB_INFO("MSD [dev: %p] - Vendor ID: %s", dev, vid_pid); + + memcpy(vid_pid, &result[16], 16); + vid_pid[16] = 0; + USB_INFO("MSD [dev: %p] - Product ID: %s", dev, vid_pid); + + memcpy(vid_pid, &result[32], 4); + vid_pid[4] = 0; + USB_INFO("MSD [dev: %p] - Product rev: %s", dev, vid_pid); + } + return status; +} + +int USBHostMSD::checkResult(uint8_t res, USBEndpoint * ep) +{ + // if ep stalled: send clear feature + if (res == USB_TYPE_STALL_ERROR) { + res = host->controlWrite( dev, + USB_RECIPIENT_ENDPOINT | USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_STANDARD, + CLEAR_FEATURE, + 0, ep->getAddress(), NULL, 0); + // set state to IDLE if clear feature successful + if (res == USB_TYPE_OK) { + ep->setState(USB_TYPE_IDLE); + } + } + + if (res != USB_TYPE_OK) + return -1; + + return 0; +} + + +int USBHostMSD::SCSITransfer(uint8_t * cmd, uint8_t cmd_len, int flags, uint8_t * data, uint32_t transfer_len) +{ + + int res = 0; + + cbw.Signature = CBW_SIGNATURE; + cbw.Tag = 0; + cbw.DataLength = transfer_len; + cbw.Flags = flags; + cbw.LUN = 0; + cbw.CBLength = cmd_len; + memset(cbw.CB,0,sizeof(cbw.CB)); + if (cmd) { + memcpy(cbw.CB,cmd,cmd_len); + } + + // send the cbw + USB_DBG("Send CBW"); + res = host->bulkWrite(dev, bulk_out,(uint8_t *)&cbw, 31); + if (checkResult(res, bulk_out)) + return -1; + + // data stage if needed + if (data) { + USB_DBG("data stage"); + if (flags == HOST_TO_DEVICE) { + + res = host->bulkWrite(dev, bulk_out, data, transfer_len); + if (checkResult(res, bulk_out)) + return -1; + + } else if (flags == DEVICE_TO_HOST) { + + res = host->bulkRead(dev, bulk_in, data, transfer_len); + if (checkResult(res, bulk_in)) + return -1; + } + } + + // status stage + csw.Signature = 0; + USB_DBG("Read CSW"); + res = host->bulkRead(dev, bulk_in,(uint8_t *)&csw, 13); + if (checkResult(res, bulk_in)) + return -1; + + if (csw.Signature != CSW_SIGNATURE) { + return -1; + } + + USB_DBG("recv csw: status: %d", csw.Status); + + // ModeSense? + if ((csw.Status == 1) && (cmd[0] != 0x03)) { + USB_DBG("request mode sense"); + return SCSIRequestSense(); + } + + // perform reset recovery + if ((csw.Status == 2) && (cmd[0] != 0x03)) { + + // send Bulk-Only Mass Storage Reset request + res = host->controlWrite( dev, + USB_RECIPIENT_INTERFACE | USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_CLASS, + BO_MASS_STORAGE_RESET, + 0, msd_intf, NULL, 0); + + // unstall both endpoints + res = host->controlWrite( dev, + USB_RECIPIENT_ENDPOINT | USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_STANDARD, + CLEAR_FEATURE, + 0, bulk_in->getAddress(), NULL, 0); + + res = host->controlWrite( dev, + USB_RECIPIENT_ENDPOINT | USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_STANDARD, + CLEAR_FEATURE, + 0, bulk_out->getAddress(), NULL, 0); + + } + + return csw.Status; +} + + +int USBHostMSD::dataTransfer(uint8_t * buf, uint32_t block, uint8_t nbBlock, int direction) +{ + uint8_t cmd[10]; + memset(cmd,0,10); + cmd[0] = (direction == DEVICE_TO_HOST) ? 0x28 : 0x2A; + + cmd[2] = (block >> 24) & 0xff; + cmd[3] = (block >> 16) & 0xff; + cmd[4] = (block >> 8) & 0xff; + cmd[5] = block & 0xff; + + cmd[7] = (nbBlock >> 8) & 0xff; + cmd[8] = nbBlock & 0xff; + + return SCSITransfer(cmd, 10, direction, buf, blockSize*nbBlock); +} + +int USBHostMSD::getMaxLun() +{ + uint8_t buf[1], res; + res = host->controlRead( dev, USB_RECIPIENT_INTERFACE | USB_DEVICE_TO_HOST | USB_REQUEST_TYPE_CLASS, + 0xfe, 0, msd_intf, buf, 1); + USB_DBG("max lun: %d", buf[0]); + return res; +} + +int USBHostMSD::disk_initialize() { + USB_DBG("FILESYSTEM: init"); + uint16_t i, timeout = 10; + + getMaxLun(); + + for (i = 0; i < timeout; i++) { + Thread::wait(100); + if (!testUnitReady()) + break; + } + + if (i == timeout) { + disk_init = false; + return -1; + } + + inquiry(0, 0); + disk_init = 1; + return readCapacity(); +} + +int USBHostMSD::disk_write(const uint8_t* buffer, uint32_t block_number, uint32_t count) { + USB_DBG("FILESYSTEM: write block: %lld, count: %d", block_number, count); + if (!disk_init) { + disk_initialize(); + } + if (!disk_init) + return -1; + for (uint32_t b = block_number; b < block_number + count; b++) { + if (dataTransfer((uint8_t*)buffer, b, 1, HOST_TO_DEVICE)) + return -1; + buffer += 512; + } + return 0; +} + +int USBHostMSD::disk_read(uint8_t* buffer, uint32_t block_number, uint32_t count) { + USB_DBG("FILESYSTEM: read block: %lld, count: %d", block_number, count); + if (!disk_init) { + disk_initialize(); + } + if (!disk_init) + return -1; + for (uint32_t b = block_number; b < block_number + count; b++) { + if (dataTransfer((uint8_t*)buffer, b, 1, DEVICE_TO_HOST)) + return -1; + buffer += 512; + } + return 0; +} + +uint32_t USBHostMSD::disk_sectors() { + USB_DBG("FILESYSTEM: sectors"); + if (!disk_init) { + disk_initialize(); + } + if (!disk_init) + return 0; + return blockCount; +} + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostMSD/USBHostMSD.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,119 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBHOSTMSD_H +#define USBHOSTMSD_H + +#include "USBHostConf.h" + +#if USBHOST_MSD + +#include "USBHost.h" +#include "FATFileSystem.h" + +/** + * A class to communicate a USB flash disk + */ +class USBHostMSD : public IUSBEnumerator, public FATFileSystem { +public: + /** + * Constructor + * + * @param rootdir mount name + */ + USBHostMSD(const char * rootdir); + + /** + * Check if a MSD device is connected + * + * @return true if a MSD device is connected + */ + bool connected(); + + /** + * Try to connect to a MSD device + * + * @return true if connection was successful + */ + bool connect(); + +protected: + //From IUSBEnumerator + virtual void setVidPid(uint16_t vid, uint16_t pid); + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used + + // From FATFileSystem + virtual int disk_initialize(); + virtual int disk_status() {return 0;}; + virtual int disk_read(uint8_t* buffer, uint32_t sector, uint32_t count); + virtual int disk_write(const uint8_t* buffer, uint32_t sector, uint32_t count); + virtual int disk_sync() {return 0;}; + virtual uint32_t disk_sectors(); + +private: + USBHost * host; + USBDeviceConnected * dev; + bool dev_connected; + USBEndpoint * bulk_in; + USBEndpoint * bulk_out; + uint8_t nb_ep; + + // Bulk-only CBW + typedef struct { + uint32_t Signature; + uint32_t Tag; + uint32_t DataLength; + uint8_t Flags; + uint8_t LUN; + uint8_t CBLength; + uint8_t CB[16]; + } PACKED CBW; + + // Bulk-only CSW + typedef struct { + uint32_t Signature; + uint32_t Tag; + uint32_t DataResidue; + uint8_t Status; + } PACKED CSW; + + CBW cbw; + CSW csw; + + int SCSITransfer(uint8_t * cmd, uint8_t cmd_len, int flags, uint8_t * data, uint32_t transfer_len); + int testUnitReady(); + int readCapacity(); + int inquiry(uint8_t lun, uint8_t page_code); + int SCSIRequestSense(); + int dataTransfer(uint8_t * buf, uint32_t block, uint8_t nbBlock, int direction); + int checkResult(uint8_t res, USBEndpoint * ep); + int getMaxLun(); + + int blockSize; + uint32_t blockCount; + + int msd_intf; + bool msd_device_found; + bool disk_init; + + void init(); + +}; + +#endif + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostSerial/MtxCircBuffer.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,89 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MTXCIRCBUFFER_H +#define MTXCIRCBUFFER_H + +#include "stdint.h" +#include "rtos.h" + +//Mutex protected circular buffer +template<typename T, int size> +class MtxCircBuffer { +public: + + MtxCircBuffer() { + write = 0; + read = 0; + } + + bool isFull() { + mtx.lock(); + bool r = (((write + 1) % size) == read); + mtx.unlock(); + return r; + } + + bool isEmpty() { + mtx.lock(); + bool r = (read == write); + mtx.unlock(); + return r; + } + + void flush() { + write = 0; + read = 0; + } + + void queue(T k) { + mtx.lock(); + while (((write + 1) % size) == read) { + mtx.unlock(); + Thread::wait(10); + mtx.lock(); + } + buf[write++] = k; + write %= size; + mtx.unlock(); + } + + uint16_t available() { + mtx.lock(); + uint16_t a = (write >= read) ? (write - read) : (size - read + write); + mtx.unlock(); + return a; + } + + bool dequeue(T * c) { + mtx.lock(); + bool empty = (read == write); + if (!empty) { + *c = buf[read++]; + read %= size; + } + mtx.unlock(); + return (!empty); + } + +private: + volatile uint16_t write; + volatile uint16_t read; + volatile T buf[size]; + Mutex mtx; +}; + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostSerial/USBHostSerial.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,345 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "USBHostSerial.h" + +#if USBHOST_SERIAL + +#include "dbg.h" + +#define CHECK_INTERFACE(cls,subcls,proto) \ + (((cls == 0xFF) && (subcls == 0xFF) && (proto == 0xFF)) /* QUALCOM CDC */ || \ + ((cls == SERIAL_CLASS) && (subcls == 0x00) && (proto == 0x00)) /* STANDARD CDC */ ) + +#if (USBHOST_SERIAL <= 1) + +USBHostSerial::USBHostSerial() +{ + host = USBHost::getHostInst(); + ports_found = 0; + dev_connected = false; +} + +bool USBHostSerial::connected() +{ + return dev_connected; +} + +void USBHostSerial::disconnect(void) +{ + ports_found = 0; + dev = NULL; +} + +bool USBHostSerial::connect() { + + if (dev) + { + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) + { + USBDeviceConnected* d = host->getDevice(i); + if (dev == d) + return true; + } + disconnect(); + } + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) + { + USBDeviceConnected* d = host->getDevice(i); + if (d != NULL) { + + USB_DBG("Trying to connect serial device \r\n"); + if(host->enumerate(d, this)) + break; + + USBEndpoint* bulk_in = d->getEndpoint(port_intf, BULK_ENDPOINT, IN); + USBEndpoint* bulk_out = d->getEndpoint(port_intf, BULK_ENDPOINT, OUT); + if (bulk_in && bulk_out) + { + USBHostSerialPort::connect(host,d,port_intf,bulk_in, bulk_out); + dev = d; + dev_connected = true; + } + } + } + return dev != NULL; +} + +/*virtual*/ void USBHostSerial::setVidPid(uint16_t vid, uint16_t pid) +{ + // we don't check VID/PID for MSD driver +} + +/*virtual*/ bool USBHostSerial::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed +{ + if (!ports_found && + CHECK_INTERFACE(intf_class, intf_subclass, intf_protocol)) { + port_intf = intf_nb; + ports_found = true; + return true; + } + return false; +} + +/*virtual*/ bool USBHostSerial::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used +{ + if (ports_found && (intf_nb == port_intf)) { + if (type == BULK_ENDPOINT) + return true; + } + return false; +} + +#else // (USBHOST_SERIAL > 1) + +//------------------------------------------------------------------------------ + +USBHostMultiSerial::USBHostMultiSerial() +{ + host = USBHost::getHostInst(); + dev = NULL; + memset(ports, NULL, sizeof(ports)); + ports_found = 0; + dev_connected = false; +} + +USBHostMultiSerial::~USBHostMultiSerial() +{ + disconnect(); +} + +bool USBHostMultiSerial::connected() +{ + return dev_connected; +} + +void USBHostMultiSerial::disconnect(void) +{ + for (int port = 0; port < USBHOST_SERIAL; port ++) + { + if (ports[port]) + { + delete ports[port]; + ports[port] = NULL; + } + } + ports_found = 0; + dev = NULL; +} + +bool USBHostMultiSerial::connect() { + + if (dev) + { + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) + { + USBDeviceConnected* d = host->getDevice(i); + if (dev == d) + return true; + } + disconnect(); + } + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) + { + USBDeviceConnected* d = host->getDevice(i); + if (d != NULL) { + + USB_DBG("Trying to connect serial device \r\n"); + if(host->enumerate(d, this)) + break; + + for (int port = 0; port < ports_found; port ++) + { + USBEndpoint* bulk_in = d->getEndpoint(port_intf[port], BULK_ENDPOINT, IN); + USBEndpoint* bulk_out = d->getEndpoint(port_intf[port], BULK_ENDPOINT, OUT); + if (bulk_in && bulk_out) + { + ports[port] = new USBHostSerialPort(); + if (ports[port]) + { + ports[port]->connect(host,d,port_intf[port],bulk_in, bulk_out); + dev = d; + dev_connected = true; + } + } + } + } + } + return dev != NULL; +} + +/*virtual*/ void USBHostMultiSerial::setVidPid(uint16_t vid, uint16_t pid) +{ + // we don't check VID/PID for MSD driver +} + +/*virtual*/ bool USBHostMultiSerial::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed +{ + if ((ports_found < USBHOST_SERIAL) && + CHECK_INTERFACE(intf_class, intf_subclass, intf_protocol)) { + port_intf[ports_found++] = intf_nb; + return true; + } + return false; +} + +/*virtual*/ bool USBHostMultiSerial::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used +{ + if ((ports_found > 0) && (intf_nb == port_intf[ports_found-1])) { + if (type == BULK_ENDPOINT) + return true; + } + return false; +} + +#endif + +//------------------------------------------------------------------------------ + +#define SET_LINE_CODING 0x20 + +USBHostSerialPort::USBHostSerialPort(): circ_buf() +{ + init(); +} + +void USBHostSerialPort::init(void) +{ + host = NULL; + dev = NULL; + serial_intf = NULL; + size_bulk_in = 0; + size_bulk_out = 0; + bulk_in = NULL; + bulk_out = NULL; + line_coding.baudrate = 9600; + line_coding.data_bits = 8; + line_coding.parity = None; + line_coding.stop_bits = 1; + circ_buf.flush(); +} + +void USBHostSerialPort::connect(USBHost* _host, USBDeviceConnected * _dev, + uint8_t _serial_intf, USBEndpoint* _bulk_in, USBEndpoint* _bulk_out) +{ + host = _host; + dev = _dev; + serial_intf = _serial_intf; + bulk_in = _bulk_in; + bulk_out = _bulk_out; + + USB_INFO("New Serial device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, serial_intf); + dev->setName("Serial", serial_intf); + host->registerDriver(dev, serial_intf, this, &USBHostSerialPort::init); + baud(9600); + size_bulk_in = bulk_in->getSize(); + size_bulk_out = bulk_out->getSize(); + bulk_in->attach(this, &USBHostSerialPort::rxHandler); + bulk_out->attach(this, &USBHostSerialPort::txHandler); + host->bulkRead(dev, bulk_in, buf, size_bulk_in, false); +} + +void USBHostSerialPort::rxHandler() { + if (bulk_in) { + int len = bulk_in->getLengthTransferred(); + if (bulk_in->getState() == USB_TYPE_IDLE) { + for (int i = 0; i < len; i++) { + circ_buf.queue(buf[i]); + } + rx.call(); + host->bulkRead(dev, bulk_in, buf, size_bulk_in, false); + } + } +} + +void USBHostSerialPort::txHandler() { + if (bulk_out) { + if (bulk_out->getState() == USB_TYPE_IDLE) { + tx.call(); + } + } +} + +int USBHostSerialPort::_putc(int c) { + if (bulk_out) { + if (host->bulkWrite(dev, bulk_out, (uint8_t *)&c, 1) == USB_TYPE_OK) { + return 1; + } + } + return -1; +} + +void USBHostSerialPort::baud(int baudrate) { + line_coding.baudrate = baudrate; + format(line_coding.data_bits, (Parity)line_coding.parity, line_coding.stop_bits); +} + +void USBHostSerialPort::format(int bits, Parity parity, int stop_bits) { + line_coding.data_bits = bits; + line_coding.parity = parity; + line_coding.stop_bits = (stop_bits == 1) ? 0 : 2; + + // set line coding + host->controlWrite( dev, + USB_RECIPIENT_INTERFACE | USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_CLASS, + SET_LINE_CODING, + 0, serial_intf, (uint8_t *)&line_coding, 7); +} + +int USBHostSerialPort::_getc() { + uint8_t c = 0; + if (bulk_in == NULL) { + init(); + return -1; + } + while (circ_buf.isEmpty()); + circ_buf.dequeue(&c); + return c; +} + +int USBHostSerialPort::writeBuf(const char* b, int s) +{ + int c = 0; + if (bulk_out) + { + while (c < s) + { + int i = (s < size_bulk_out) ? s : size_bulk_out; + if (host->bulkWrite(dev, bulk_out, (uint8_t *)(b+c), i) == USB_TYPE_OK) + c += i; + } + } + return s; +} + +int USBHostSerialPort::readBuf(char* b, int s) +{ + int i = 0; + if (bulk_in) + { + for (i = 0; i < s; ) + b[i++] = getc(); + } + return i; +} + +uint8_t USBHostSerialPort::available() { + return circ_buf.available(); +} + + + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/USBHostSerial/USBHostSerial.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,232 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBHOSTSERIAL_H +#define USBHOSTSERIAL_H + +#include "USBHostConf.h" + +#if USBHOST_SERIAL + +#include "USBHost.h" +#include "Stream.h" +#include "MtxCircBuffer.h" +#include "Callback.h" + +/** + * A class to communicate a USB virtual serial port + */ +class USBHostSerialPort : public Stream { +public: + /** + * Constructor + */ + USBHostSerialPort(); + + enum IrqType { + RxIrq, + TxIrq + }; + + enum Parity { + None = 0, + Odd, + Even, + Mark, + Space + }; + + void connect(USBHost* _host, USBDeviceConnected * _dev, + uint8_t _serial_intf, USBEndpoint* _bulk_in, USBEndpoint* _bulk_out); + + /** + * Check the number of bytes available. + * + * @returns the number of bytes available + */ + uint8_t available(); + + /** + * Attach a member function to call when a packet is received. + * + * @param tptr pointer to the object to call the member function on + * @param mptr pointer to the member function to be called + * @param irq irq type + */ + template<typename T> + inline void attach(T* tptr, void (T::*mptr)(void), IrqType irq = RxIrq) { + if ((mptr != NULL) && (tptr != NULL)) { + if (irq == RxIrq) { + rx.attach(tptr, mptr); + } else { + tx.attach(tptr, mptr); + } + } + } + + /** + * Attach a callback called when a packet is received + * + * @param ptr function pointer + */ + inline void attach(void (*fn)(void), IrqType irq = RxIrq) { + if (fn != NULL) { + if (irq == RxIrq) { + rx.attach(fn); + } else { + tx.attach(fn); + } + } + } + + /** Set the baud rate of the serial port + * + * @param baudrate The baudrate of the serial port (default = 9600). + */ + void baud(int baudrate = 9600); + + /** Set the transmission format used by the Serial port + * + * @param bits The number of bits in a word (default = 8) + * @param parity The parity used (USBHostSerialPort::None, USBHostSerialPort::Odd, USBHostSerialPort::Even, USBHostSerialPort::Mark, USBHostSerialPort::Space; default = USBHostSerialPort::None) + * @param stop The number of stop bits (1 or 2; default = 1) + */ + void format(int bits = 8, Parity parity = USBHostSerialPort::None, int stop_bits = 1); + virtual int writeBuf(const char* b, int s); + virtual int readBuf(char* b, int s); + +protected: + virtual int _getc(); + virtual int _putc(int c); + +private: + USBHost * host; + USBDeviceConnected * dev; + + USBEndpoint * bulk_in; + USBEndpoint * bulk_out; + uint32_t size_bulk_in; + uint32_t size_bulk_out; + + void init(); + + MtxCircBuffer<uint8_t, 128> circ_buf; + + uint8_t buf[64]; + + typedef struct { + uint32_t baudrate; + uint8_t stop_bits; + uint8_t parity; + uint8_t data_bits; + } PACKED LINE_CODING; + + LINE_CODING line_coding; + + void rxHandler(); + void txHandler(); + Callback<void()> rx; + Callback<void()> tx; + + uint8_t serial_intf; +}; + +#if (USBHOST_SERIAL <= 1) + +class USBHostSerial : public IUSBEnumerator, public USBHostSerialPort +{ +public: + USBHostSerial(); + + /** + * Try to connect a serial device + * + * @return true if connection was successful + */ + bool connect(); + + void disconnect(); + + /** + * Check if a any serial port is connected + * + * @returns true if a serial device is connected + */ + bool connected(); + +protected: + USBHost* host; + USBDeviceConnected* dev; + uint8_t port_intf; + int ports_found; + + //From IUSBEnumerator + virtual void setVidPid(uint16_t vid, uint16_t pid); + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used + +private: + bool dev_connected; +}; + +#else // (USBHOST_SERIAL > 1) + +class USBHostMultiSerial : public IUSBEnumerator { +public: + USBHostMultiSerial(); + virtual ~USBHostMultiSerial(); + + USBHostSerialPort* getPort(int port) + { + return port < USBHOST_SERIAL ? ports[port] : NULL; + } + + /** + * Try to connect a serial device + * + * @return true if connection was successful + */ + bool connect(); + + void disconnect(); + + /** + * Check if a any serial port is connected + * + * @returns true if a serial device is connected + */ + bool connected(); + +protected: + USBHost* host; + USBDeviceConnected* dev; + USBHostSerialPort* ports[USBHOST_SERIAL]; + uint8_t port_intf[USBHOST_SERIAL]; + int ports_found; + + //From IUSBEnumerator + virtual void setVidPid(uint16_t vid, uint16_t pid); + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used + +private: + bool dev_connected; +}; +#endif // (USBHOST_SERIAL <= 1) + +#endif + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/Mail.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,113 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef MAIL_H +#define MAIL_H + +#include <stdint.h> +#include <string.h> + +#include "cmsis_os.h" + +namespace rtos { +/** \addtogroup rtos */ +/** @{*/ + +/** The Mail class allow to control, send, receive, or wait for mail. + A mail is a memory block that is send to a thread or interrupt service routine. + @tparam T data type of a single message element. + @tparam queue_sz maximum number of messages in queue. +*/ +template<typename T, uint32_t queue_sz> +class Mail { +public: + /** Create and Initialise Mail queue. */ + Mail() { + #ifdef CMSIS_OS_RTX + memset(_mail_q, 0, sizeof(_mail_q)); + _mail_p[0] = _mail_q; + + memset(_mail_m, 0, sizeof(_mail_m)); + _mail_p[1] = _mail_m; + + _mail_def.pool = _mail_p; + _mail_def.queue_sz = queue_sz; + _mail_def.item_sz = sizeof(T); + #endif + _mail_id = osMailCreate(&_mail_def, NULL); + } + + /** Allocate a memory block of type T + @param millisec timeout value or 0 in case of no time-out. (default: 0). + @return pointer to memory block that can be filled with mail or NULL in case error. + */ + T* alloc(uint32_t millisec=0) { + return (T*)osMailAlloc(_mail_id, millisec); + } + + /** Allocate a memory block of type T and set memory block to zero. + @param millisec timeout value or 0 in case of no time-out. (default: 0). + @return pointer to memory block that can be filled with mail or NULL in case error. + */ + T* calloc(uint32_t millisec=0) { + return (T*)osMailCAlloc(_mail_id, millisec); + } + + /** Put a mail in the queue. + @param mptr memory block previously allocated with Mail::alloc or Mail::calloc. + @return status code that indicates the execution status of the function. + */ + osStatus put(T *mptr) { + return osMailPut(_mail_id, (void*)mptr); + } + + /** Get a mail from a queue. + @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever). + @return event that contains mail information or error code. + */ + osEvent get(uint32_t millisec=osWaitForever) { + return osMailGet(_mail_id, millisec); + } + + /** Free a memory block from a mail. + @param mptr pointer to the memory block that was obtained with Mail::get. + @return status code that indicates the execution status of the function. + */ + osStatus free(T *mptr) { + return osMailFree(_mail_id, (void*)mptr); + } + +private: + osMailQId _mail_id; + osMailQDef_t _mail_def; +#ifdef CMSIS_OS_RTX + uint32_t _mail_q[4+(queue_sz)]; + uint32_t _mail_m[3+((sizeof(T)+3)/4)*(queue_sz)]; + void *_mail_p[2]; +#endif +}; + +} + +#endif + + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/MemoryPool.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,86 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef MEMORYPOOL_H +#define MEMORYPOOL_H + +#include <stdint.h> +#include <string.h> + +#include "cmsis_os.h" + +namespace rtos { +/** \addtogroup rtos */ +/** @{*/ + +/** Define and manage fixed-size memory pools of objects of a given type. + @tparam T data type of a single object (element). + @tparam queue_sz maximum number of objects (elements) in the memory pool. +*/ +template<typename T, uint32_t pool_sz> +class MemoryPool { +public: + /** Create and Initialize a memory pool. */ + MemoryPool() { + #ifdef CMSIS_OS_RTX + memset(_pool_m, 0, sizeof(_pool_m)); + _pool_def.pool = _pool_m; + + _pool_def.pool_sz = pool_sz; + _pool_def.item_sz = sizeof(T); + #endif + _pool_id = osPoolCreate(&_pool_def); + } + + /** Allocate a memory block of type T from a memory pool. + @return address of the allocated memory block or NULL in case of no memory available. + */ + T* alloc(void) { + return (T*)osPoolAlloc(_pool_id); + } + + /** Allocate a memory block of type T from a memory pool and set memory block to zero. + @return address of the allocated memory block or NULL in case of no memory available. + */ + T* calloc(void) { + return (T*)osPoolCAlloc(_pool_id); + } + + /** Return an allocated memory block back to a specific memory pool. + @param address of the allocated memory block that is returned to the memory pool. + @return status code that indicates the execution status of the function. + */ + osStatus free(T *block) { + return osPoolFree(_pool_id, (void*)block); + } + +private: + osPoolId _pool_id; + osPoolDef_t _pool_def; +#ifdef CMSIS_OS_RTX + uint32_t _pool_m[3+((sizeof(T)+3)/4)*(pool_sz)]; +#endif +}; + +} +#endif + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/Mutex.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,56 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "rtos/Mutex.h" + +#include <string.h> +#include "platform/mbed_error.h" + +namespace rtos { + +Mutex::Mutex() { +#ifdef CMSIS_OS_RTX + memset(_mutex_data, 0, sizeof(_mutex_data)); + _osMutexDef.mutex = _mutex_data; +#endif + _osMutexId = osMutexCreate(&_osMutexDef); + if (_osMutexId == NULL) { + error("Error initializing the mutex object\n"); + } +} + +osStatus Mutex::lock(uint32_t millisec) { + return osMutexWait(_osMutexId, millisec); +} + +bool Mutex::trylock() { + return (osMutexWait(_osMutexId, 0) == osOK); +} + +osStatus Mutex::unlock() { + return osMutexRelease(_osMutexId); +} + +Mutex::~Mutex() { + osMutexDelete(_osMutexId); +} + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/Mutex.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,73 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef MUTEX_H +#define MUTEX_H + +#include <stdint.h> +#include "cmsis_os.h" + +namespace rtos { +/** \addtogroup rtos */ +/** @{*/ + +/** The Mutex class is used to synchronise the execution of threads. + This is for example used to protect access to a shared resource. +*/ +class Mutex { +public: + /** Create and Initialize a Mutex object */ + Mutex(); + + /** Wait until a Mutex becomes available. + @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever) + @return status code that indicates the execution status of the function. + */ + osStatus lock(uint32_t millisec=osWaitForever); + + /** Try to lock the mutex, and return immediately + @return true if the mutex was acquired, false otherwise. + */ + bool trylock(); + + /** Unlock the mutex that has previously been locked by the same thread + @return status code that indicates the execution status of the function. + */ + osStatus unlock(); + + ~Mutex(); + +private: + osMutexId _osMutexId; + osMutexDef_t _osMutexDef; +#ifdef CMSIS_OS_RTX +#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM) + int32_t _mutex_data[4]; +#else + int32_t _mutex_data[3]; +#endif +#endif +}; + +} +#endif + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/Queue.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,85 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef QUEUE_H +#define QUEUE_H + +#include <stdint.h> +#include <string.h> + +#include "cmsis_os.h" +#include "platform/mbed_error.h" + +namespace rtos { +/** \addtogroup rtos */ +/** @{*/ + +/** The Queue class allow to control, send, receive, or wait for messages. + A message can be a integer or pointer value to a certain type T that is send + to a thread or interrupt service routine. + @tparam T data type of a single message element. + @tparam queue_sz maximum number of messages in queue. +*/ +template<typename T, uint32_t queue_sz> +class Queue { +public: + /** Create and initialise a message Queue. */ + Queue() { + #ifdef CMSIS_OS_RTX + memset(_queue_q, 0, sizeof(_queue_q)); + _queue_def.pool = _queue_q; + _queue_def.queue_sz = queue_sz; + #endif + _queue_id = osMessageCreate(&_queue_def, NULL); + if (_queue_id == NULL) { + error("Error initialising the queue object\n"); + } + } + + /** Put a message in a Queue. + @param data message pointer. + @param millisec timeout value or 0 in case of no time-out. (default: 0) + @return status code that indicates the execution status of the function. + */ + osStatus put(T* data, uint32_t millisec=0) { + return osMessagePut(_queue_id, (uint32_t)data, millisec); + } + + /** Get a message or Wait for a message from a Queue. + @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever). + @return event information that includes the message and the status code. + */ + osEvent get(uint32_t millisec=osWaitForever) { + return osMessageGet(_queue_id, millisec); + } + +private: + osMessageQId _queue_id; + osMessageQDef_t _queue_def; +#ifdef CMSIS_OS_RTX + uint32_t _queue_q[4+(queue_sz)]; +#endif +}; + +} +#endif + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/RtosTimer.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,55 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "rtos/RtosTimer.h" + +#include <string.h> + +#include "mbed.h" +#include "cmsis_os.h" +#include "platform/mbed_error.h" + +namespace rtos { + +void RtosTimer::constructor(mbed::Callback<void()> func, os_timer_type type) { +#ifdef CMSIS_OS_RTX + _timer.ptimer = (void (*)(const void *))Callback<void()>::thunk; + + memset(_timer_data, 0, sizeof(_timer_data)); + _timer.timer = _timer_data; +#endif + _function = func; + _timer_id = osTimerCreate(&_timer, type, &_function); +} + +osStatus RtosTimer::start(uint32_t millisec) { + return osTimerStart(_timer_id, millisec); +} + +osStatus RtosTimer::stop(void) { + return osTimerStop(_timer_id); +} + +RtosTimer::~RtosTimer() { + osTimerDelete(_timer_id); +} + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/RtosTimer.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,111 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef RTOS_TIMER_H +#define RTOS_TIMER_H + +#include <stdint.h> +#include "cmsis_os.h" +#include "platform/Callback.h" +#include "platform/toolchain.h" + +namespace rtos { +/** \addtogroup rtos */ +/** @{*/ + +/** The RtosTimer class allow creating and and controlling of timer functions in the system. + A timer function is called when a time period expires whereby both on-shot and + periodic timers are possible. A timer can be started, restarted, or stopped. + + Timers are handled in the thread osTimerThread. + Callback functions run under control of this thread and may use CMSIS-RTOS API calls. +*/ +class RtosTimer { +public: + /** Create timer. + @param func function to be executed by this timer. + @param type osTimerOnce for one-shot or osTimerPeriodic for periodic behaviour. (default: osTimerPeriodic) + @param argument argument to the timer call back function. (default: NULL) + @deprecated Replaced with RtosTimer(Callback<void()>, os_timer_type) + */ + MBED_DEPRECATED_SINCE("mbed-os-5.1", + "Replaced with RtosTimer(Callback<void()>, os_timer_type)") + RtosTimer(void (*func)(void const *argument), os_timer_type type=osTimerPeriodic, void *argument=NULL) { + constructor(mbed::callback((void (*)(void *))func, argument), type); + } + + /** Create timer. + @param func function to be executed by this timer. + @param type osTimerOnce for one-shot or osTimerPeriodic for periodic behaviour. (default: osTimerPeriodic) + */ + RtosTimer(mbed::Callback<void()> func, os_timer_type type=osTimerPeriodic) { + constructor(func, type); + } + + /** Create timer. + @param obj pointer to the object to call the member function on. + @param method member function to be executed by this timer. + @param type osTimerOnce for one-shot or osTimerPeriodic for periodic behaviour. (default: osTimerPeriodic) + @deprecated + The RtosTimer constructor does not support cv-qualifiers. Replaced by + RtosTimer(callback(obj, method), os_timer_type). + */ + template <typename T, typename M> + MBED_DEPRECATED_SINCE("mbed-os-5.1", + "The RtosTimer constructor does not support cv-qualifiers. Replaced by " + "RtosTimer(callback(obj, method), os_timer_type).") + RtosTimer(T *obj, M method, os_timer_type type=osTimerPeriodic) { + constructor(mbed::callback(obj, method), type); + } + + /** Stop the timer. + @return status code that indicates the execution status of the function. + */ + osStatus stop(void); + + /** Start the timer. + @param millisec time delay value of the timer. + @return status code that indicates the execution status of the function. + */ + osStatus start(uint32_t millisec); + + ~RtosTimer(); + +private: + // Required to share definitions without + // delegated constructors + void constructor(mbed::Callback<void()> func, os_timer_type type); + + mbed::Callback<void()> _function; + osTimerId _timer_id; + osTimerDef_t _timer; +#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM) + uint32_t _timer_data[5]; +#else + uint32_t _timer_data[6]; +#endif +}; + +} + +#endif + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/Semaphore.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,48 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "rtos/Semaphore.h" + +#include <string.h> + +namespace rtos { + +Semaphore::Semaphore(int32_t count) { +#ifdef CMSIS_OS_RTX + memset(_semaphore_data, 0, sizeof(_semaphore_data)); + _osSemaphoreDef.semaphore = _semaphore_data; +#endif + _osSemaphoreId = osSemaphoreCreate(&_osSemaphoreDef, count); +} + +int32_t Semaphore::wait(uint32_t millisec) { + return osSemaphoreWait(_osSemaphoreId, millisec); +} + +osStatus Semaphore::release(void) { + return osSemaphoreRelease(_osSemaphoreId); +} + +Semaphore::~Semaphore() { + osSemaphoreDelete(_osSemaphoreId); +} + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/Semaphore.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,64 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef SEMAPHORE_H +#define SEMAPHORE_H + +#include <stdint.h> +#include "cmsis_os.h" + +namespace rtos { +/** \addtogroup rtos */ +/** @{*/ + +/** The Semaphore class is used to manage and protect access to a set of shared resources. */ +class Semaphore { +public: + /** Create and Initialize a Semaphore object used for managing resources. + @param number of available resources; maximum index value is (count-1). (default: 0). + */ + Semaphore(int32_t count=0); + + /** Wait until a Semaphore resource becomes available. + @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever). + @return number of available tokens, or -1 in case of incorrect parameters + */ + int32_t wait(uint32_t millisec=osWaitForever); + + /** Release a Semaphore resource that was obtain with Semaphore::wait. + @return status code that indicates the execution status of the function. + */ + osStatus release(void); + + ~Semaphore(); + +private: + osSemaphoreId _osSemaphoreId; + osSemaphoreDef_t _osSemaphoreDef; +#ifdef CMSIS_OS_RTX + uint32_t _semaphore_data[2]; +#endif +}; + +} +#endif + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/Thread.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,374 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#include "rtos/Thread.h" + +#include "mbed.h" +#include "rtos/rtos_idle.h" + +// rt_tid2ptcb is an internal function which we exposed to get TCB for thread id +#undef NULL //Workaround for conflicting macros in rt_TypeDef.h and stdio.h +#include "rt_TypeDef.h" + +extern "C" P_TCB rt_tid2ptcb(osThreadId thread_id); + + +static void (*terminate_hook)(osThreadId id) = 0; +extern "C" void thread_terminate_hook(osThreadId id) +{ + if (terminate_hook != (void (*)(osThreadId))NULL) { + terminate_hook(id); + } +} + +namespace rtos { + +void Thread::constructor(osPriority priority, + uint32_t stack_size, unsigned char *stack_pointer) { + _tid = 0; + _dynamic_stack = (stack_pointer == NULL); + +#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM) + _thread_def.tpriority = priority; + _thread_def.stacksize = stack_size; + _thread_def.stack_pointer = (uint32_t*)stack_pointer; +#endif +} + +void Thread::constructor(Callback<void()> task, + osPriority priority, uint32_t stack_size, unsigned char *stack_pointer) { + constructor(priority, stack_size, stack_pointer); + + switch (start(task)) { + case osErrorResource: + error("OS ran out of threads!\n"); + break; + case osErrorParameter: + error("Thread already running!\n"); + break; + case osErrorNoMemory: + error("Error allocating the stack memory\n"); + default: + break; + } +} + +osStatus Thread::start(Callback<void()> task) { + _mutex.lock(); + + if (_tid != 0) { + _mutex.unlock(); + return osErrorParameter; + } + +#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM) + _thread_def.pthread = Thread::_thunk; + if (_thread_def.stack_pointer == NULL) { + _thread_def.stack_pointer = new uint32_t[_thread_def.stacksize/sizeof(uint32_t)]; + MBED_ASSERT(_thread_def.stack_pointer != NULL); + } + + //Fill the stack with a magic word for maximum usage checking + for (uint32_t i = 0; i < (_thread_def.stacksize / sizeof(uint32_t)); i++) { + _thread_def.stack_pointer[i] = 0xE25A2EA5; + } +#endif + _task = task; + _tid = osThreadCreate(&_thread_def, this); + if (_tid == NULL) { + if (_dynamic_stack) { + delete[] (_thread_def.stack_pointer); + _thread_def.stack_pointer = (uint32_t*)NULL; + } + _mutex.unlock(); + _join_sem.release(); + return osErrorResource; + } + + _mutex.unlock(); + return osOK; +} + +osStatus Thread::terminate() { + osStatus ret; + _mutex.lock(); + + // Set the Thread's tid to NULL and + // release the semaphore before terminating + // since this thread could be terminating itself + osThreadId local_id = _tid; + _join_sem.release(); + _tid = (osThreadId)NULL; + + ret = osThreadTerminate(local_id); + + _mutex.unlock(); + return ret; +} + +osStatus Thread::join() { + int32_t ret = _join_sem.wait(); + if (ret < 0) { + return osErrorOS; + } + + // The semaphore has been released so this thread is being + // terminated or has been terminated. Once the mutex has + // been locked it is ensured that the thread is deleted. + _mutex.lock(); + MBED_ASSERT(NULL == _tid); + _mutex.unlock(); + + // Release sem so any other threads joining this thread wake up + _join_sem.release(); + return osOK; +} + +osStatus Thread::set_priority(osPriority priority) { + osStatus ret; + _mutex.lock(); + + ret = osThreadSetPriority(_tid, priority); + + _mutex.unlock(); + return ret; +} + +osPriority Thread::get_priority() { + osPriority ret; + _mutex.lock(); + + ret = osThreadGetPriority(_tid); + + _mutex.unlock(); + return ret; +} + +int32_t Thread::signal_set(int32_t signals) { + // osSignalSet is thread safe as long as the underlying + // thread does not get terminated or return from main + return osSignalSet(_tid, signals); +} + +int32_t Thread::signal_clr(int32_t signals) { + // osSignalClear is thread safe as long as the underlying + // thread does not get terminated or return from main + return osSignalClear(_tid, signals); +} + +Thread::State Thread::get_state() { +#if !defined(__MBED_CMSIS_RTOS_CA9) && !defined(__MBED_CMSIS_RTOS_CM) +#ifdef CMSIS_OS_RTX + State status = Deleted; + _mutex.lock(); + + if (_tid != NULL) { + status = (State)_thread_def.tcb.state; + } + + _mutex.unlock(); + return status; +#endif +#else + State status = Deleted; + _mutex.lock(); + + if (_tid != NULL) { + status = (State)osThreadGetState(_tid); + } + + _mutex.unlock(); + return status; +#endif +} + +uint32_t Thread::stack_size() { +#ifndef __MBED_CMSIS_RTOS_CA9 +#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM) + uint32_t size = 0; + _mutex.lock(); + + if (_tid != NULL) { + size = _thread_def.tcb.priv_stack; + } + + _mutex.unlock(); + return size; +#else + uint32_t size = 0; + _mutex.lock(); + + if (_tid != NULL) { + P_TCB tcb = rt_tid2ptcb(_tid); + size = tcb->priv_stack; + } + + _mutex.unlock(); + return size; +#endif +#else + return 0; +#endif +} + +uint32_t Thread::free_stack() { +#ifndef __MBED_CMSIS_RTOS_CA9 +#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM) + uint32_t size = 0; + _mutex.lock(); + + if (_tid != NULL) { + uint32_t bottom = (uint32_t)_thread_def.tcb.stack; + size = _thread_def.tcb.tsk_stack - bottom; + } + + _mutex.unlock(); + return size; +#else + uint32_t size = 0; + _mutex.lock(); + + if (_tid != NULL) { + P_TCB tcb = rt_tid2ptcb(_tid); + uint32_t bottom = (uint32_t)tcb->stack; + size = tcb->tsk_stack - bottom; + } + + _mutex.unlock(); + return size; +#endif +#else + return 0; +#endif +} + +uint32_t Thread::used_stack() { +#ifndef __MBED_CMSIS_RTOS_CA9 +#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM) + uint32_t size = 0; + _mutex.lock(); + + if (_tid != NULL) { + uint32_t top = (uint32_t)_thread_def.tcb.stack + _thread_def.tcb.priv_stack; + size = top - _thread_def.tcb.tsk_stack; + } + + _mutex.unlock(); + return size; +#else + uint32_t size = 0; + _mutex.lock(); + + if (_tid != NULL) { + P_TCB tcb = rt_tid2ptcb(_tid); + uint32_t top = (uint32_t)tcb->stack + tcb->priv_stack; + size = top - tcb->tsk_stack; + } + + _mutex.unlock(); + return size; +#endif +#else + return 0; +#endif +} + +uint32_t Thread::max_stack() { +#ifndef __MBED_CMSIS_RTOS_CA9 +#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM) + uint32_t size = 0; + _mutex.lock(); + + if (_tid != NULL) { + uint32_t high_mark = 0; + while (_thread_def.tcb.stack[high_mark] == 0xE25A2EA5) + high_mark++; + size = _thread_def.tcb.priv_stack - (high_mark * 4); + } + + _mutex.unlock(); + return size; +#else + uint32_t size = 0; + _mutex.lock(); + + if (_tid != NULL) { + P_TCB tcb = rt_tid2ptcb(_tid); + uint32_t high_mark = 0; + while (tcb->stack[high_mark] == 0xE25A2EA5) + high_mark++; + size = tcb->priv_stack - (high_mark * 4); + } + + _mutex.unlock(); + return size; +#endif +#else + return 0; +#endif +} + +osEvent Thread::signal_wait(int32_t signals, uint32_t millisec) { + return osSignalWait(signals, millisec); +} + +osStatus Thread::wait(uint32_t millisec) { + return osDelay(millisec); +} + +osStatus Thread::yield() { + return osThreadYield(); +} + +osThreadId Thread::gettid() { + return osThreadGetId(); +} + +void Thread::attach_idle_hook(void (*fptr)(void)) { + rtos_attach_idle_hook(fptr); +} + +void Thread::attach_terminate_hook(void (*fptr)(osThreadId id)) { + terminate_hook = fptr; +} + +Thread::~Thread() { + // terminate is thread safe + terminate(); +#ifdef __MBED_CMSIS_RTOS_CM + if (_dynamic_stack) { + delete[] (_thread_def.stack_pointer); + _thread_def.stack_pointer = (uint32_t*)NULL; + } +#endif +} + +void Thread::_thunk(const void * thread_ptr) +{ + Thread *t = (Thread*)thread_ptr; + t->_task(); + t->_mutex.lock(); + t->_tid = (osThreadId)NULL; + t->_join_sem.release(); + // rtos will release the mutex automatically +} + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/Thread.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,355 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef THREAD_H +#define THREAD_H + +#include <stdint.h> +#include "cmsis_os.h" +#include "platform/Callback.h" +#include "platform/toolchain.h" +#include "rtos/Semaphore.h" +#include "rtos/Mutex.h" + +namespace rtos { +/** \addtogroup rtos */ +/** @{*/ + +/** The Thread class allow defining, creating, and controlling thread functions in the system. + * + * Example: + * @code + * #include "mbed.h" + * #include "rtos.h" + * + * Thread thread; + * DigitalOut led1(LED1); + * volatile bool running = true; + * + * // Blink function toggles the led in a long running loop + * void blink(DigitalOut *led) { + * while (running) { + * *led = !*led; + * Thread::wait(1000); + * } + * } + * + * // Spawns a thread to run blink for 5 seconds + * int main() { + * thread.start(led1, blink); + * Thread::wait(5000); + * running = false; + * thread.join(); + * } + * @endcode + */ +class Thread { +public: + /** Allocate a new thread without starting execution + @param priority initial priority of the thread function. (default: osPriorityNormal). + @param stack_size stack size (in bytes) requirements for the thread function. (default: DEFAULT_STACK_SIZE). + @param stack_pointer pointer to the stack area to be used by this thread (default: NULL). + */ + Thread(osPriority priority=osPriorityNormal, + uint32_t stack_size=DEFAULT_STACK_SIZE, + unsigned char *stack_pointer=NULL) { + constructor(priority, stack_size, stack_pointer); + } + + /** Create a new thread, and start it executing the specified function. + @param task function to be executed by this thread. + @param argument pointer that is passed to the thread function as start argument. (default: NULL). + @param priority initial priority of the thread function. (default: osPriorityNormal). + @param stack_size stack size (in bytes) requirements for the thread function. (default: DEFAULT_STACK_SIZE). + @param stack_pointer pointer to the stack area to be used by this thread (default: NULL). + @deprecated + Thread-spawning constructors hide errors. Replaced by thread.start(task). + + @code + Thread thread(priority, stack_size, stack_pointer); + + osStatus status = thread.start(task); + if (status != osOK) { + error("oh no!"); + } + @endcode + */ + MBED_DEPRECATED_SINCE("mbed-os-5.1", + "Thread-spawning constructors hide errors. " + "Replaced by thread.start(task).") + Thread(mbed::Callback<void()> task, + osPriority priority=osPriorityNormal, + uint32_t stack_size=DEFAULT_STACK_SIZE, + unsigned char *stack_pointer=NULL) { + constructor(task, priority, stack_size, stack_pointer); + } + + /** Create a new thread, and start it executing the specified function. + @param obj argument to task. + @param method function to be executed by this thread. + @param argument pointer that is passed to the thread function as start argument. (default: NULL). + @param priority initial priority of the thread function. (default: osPriorityNormal). + @param stack_size stack size (in bytes) requirements for the thread function. (default: DEFAULT_STACK_SIZE). + @param stack_pointer pointer to the stack area to be used by this thread (default: NULL). + @deprecated + Thread-spawning constructors hide errors. Replaced by thread.start(callback(task, argument)). + + @code + Thread thread(priority, stack_size, stack_pointer); + + osStatus status = thread.start(callback(task, argument)); + if (status != osOK) { + error("oh no!"); + } + @endcode + */ + template <typename T> + MBED_DEPRECATED_SINCE("mbed-os-5.1", + "Thread-spawning constructors hide errors. " + "Replaced by thread.start(callback(task, argument)).") + Thread(T *argument, void (T::*task)(), + osPriority priority=osPriorityNormal, + uint32_t stack_size=DEFAULT_STACK_SIZE, + unsigned char *stack_pointer=NULL) { + constructor(mbed::callback(task, argument), + priority, stack_size, stack_pointer); + } + + /** Create a new thread, and start it executing the specified function. + @param obj argument to task. + @param method function to be executed by this thread. + @param argument pointer that is passed to the thread function as start argument. (default: NULL). + @param priority initial priority of the thread function. (default: osPriorityNormal). + @param stack_size stack size (in bytes) requirements for the thread function. (default: DEFAULT_STACK_SIZE). + @param stack_pointer pointer to the stack area to be used by this thread (default: NULL). + @deprecated + Thread-spawning constructors hide errors. Replaced by thread.start(callback(task, argument)). + + @code + Thread thread(priority, stack_size, stack_pointer); + + osStatus status = thread.start(callback(task, argument)); + if (status != osOK) { + error("oh no!"); + } + @endcode + */ + template <typename T> + MBED_DEPRECATED_SINCE("mbed-os-5.1", + "Thread-spawning constructors hide errors. " + "Replaced by thread.start(callback(task, argument)).") + Thread(T *argument, void (*task)(T *), + osPriority priority=osPriorityNormal, + uint32_t stack_size=DEFAULT_STACK_SIZE, + unsigned char *stack_pointer=NULL) { + constructor(mbed::callback(task, argument), + priority, stack_size, stack_pointer); + } + + /** Create a new thread, and start it executing the specified function. + Provided for backwards compatibility + @param task function to be executed by this thread. + @param argument pointer that is passed to the thread function as start argument. (default: NULL). + @param priority initial priority of the thread function. (default: osPriorityNormal). + @param stack_size stack size (in bytes) requirements for the thread function. (default: DEFAULT_STACK_SIZE). + @param stack_pointer pointer to the stack area to be used by this thread (default: NULL). + @deprecated + Thread-spawning constructors hide errors. Replaced by thread.start(callback(task, argument)). + + @code + Thread thread(priority, stack_size, stack_pointer); + + osStatus status = thread.start(callback(task, argument)); + if (status != osOK) { + error("oh no!"); + } + @endcode + */ + MBED_DEPRECATED_SINCE("mbed-os-5.1", + "Thread-spawning constructors hide errors. " + "Replaced by thread.start(callback(task, argument)).") + Thread(void (*task)(void const *argument), void *argument=NULL, + osPriority priority=osPriorityNormal, + uint32_t stack_size=DEFAULT_STACK_SIZE, + unsigned char *stack_pointer=NULL) { + constructor(mbed::callback((void (*)(void *))task, argument), + priority, stack_size, stack_pointer); + } + + /** Starts a thread executing the specified function. + @param task function to be executed by this thread. + @return status code that indicates the execution status of the function. + */ + osStatus start(mbed::Callback<void()> task); + + /** Starts a thread executing the specified function. + @param obj argument to task + @param method function to be executed by this thread. + @return status code that indicates the execution status of the function. + @deprecated + The start function does not support cv-qualifiers. Replaced by start(callback(obj, method)). + */ + template <typename T, typename M> + MBED_DEPRECATED_SINCE("mbed-os-5.1", + "The start function does not support cv-qualifiers. " + "Replaced by thread.start(callback(obj, method)).") + osStatus start(T *obj, M method) { + return start(mbed::callback(obj, method)); + } + + /** Wait for thread to terminate + @return status code that indicates the execution status of the function. + @note not callable from interrupt + */ + osStatus join(); + + /** Terminate execution of a thread and remove it from Active Threads + @return status code that indicates the execution status of the function. + */ + osStatus terminate(); + + /** Set priority of an active thread + @param priority new priority value for the thread function. + @return status code that indicates the execution status of the function. + */ + osStatus set_priority(osPriority priority); + + /** Get priority of an active thread + @return current priority value of the thread function. + */ + osPriority get_priority(); + + /** Set the specified Signal Flags of an active thread. + @param signals specifies the signal flags of the thread that should be set. + @return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. + */ + int32_t signal_set(int32_t signals); + + /** Clears the specified Signal Flags of an active thread. + @param signals specifies the signal flags of the thread that should be cleared. + @return resultant signal flags of the specified thread or 0x80000000 in case of incorrect parameters. + */ + int32_t signal_clr(int32_t signals); + + /** State of the Thread */ + enum State { + Inactive, /**< Not created or terminated */ + Ready, /**< Ready to run */ + Running, /**< Running */ + WaitingDelay, /**< Waiting for a delay to occur */ + WaitingInterval, /**< Waiting for an interval to occur */ + WaitingOr, /**< Waiting for one event in a set to occur */ + WaitingAnd, /**< Waiting for multiple events in a set to occur */ + WaitingSemaphore, /**< Waiting for a semaphore event to occur */ + WaitingMailbox, /**< Waiting for a mailbox event to occur */ + WaitingMutex, /**< Waiting for a mutex event to occur */ + + /* Not in sync with RTX below here */ + Deleted, /**< The task has been deleted */ + }; + + /** State of this Thread + @return the State of this Thread + */ + State get_state(); + + /** Get the total stack memory size for this Thread + @return the total stack memory size in bytes + */ + uint32_t stack_size(); + + /** Get the currently unused stack memory for this Thread + @return the currently unused stack memory in bytes + */ + uint32_t free_stack(); + + /** Get the currently used stack memory for this Thread + @return the currently used stack memory in bytes + */ + uint32_t used_stack(); + + /** Get the maximum stack memory usage to date for this Thread + @return the maximum stack memory usage to date in bytes + */ + uint32_t max_stack(); + + /** Wait for one or more Signal Flags to become signaled for the current RUNNING thread. + @param signals wait until all specified signal flags set or 0 for any single signal flag. + @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever). + @return event flag information or error code. + @note not callable from interrupt + */ + static osEvent signal_wait(int32_t signals, uint32_t millisec=osWaitForever); + + /** Wait for a specified time period in millisec: + @param millisec time delay value + @return status code that indicates the execution status of the function. + @note not callable from interrupt + */ + static osStatus wait(uint32_t millisec); + + /** Pass control to next thread that is in state READY. + @return status code that indicates the execution status of the function. + @note not callable from interrupt + */ + static osStatus yield(); + + /** Get the thread id of the current running thread. + @return thread ID for reference by other functions or NULL in case of error. + */ + static osThreadId gettid(); + + /** Attach a function to be called by the RTOS idle task + @param fptr pointer to the function to be called + */ + static void attach_idle_hook(void (*fptr)(void)); + + /** Attach a function to be called when a task is killed + @param fptr pointer to the function to be called + */ + static void attach_terminate_hook(void (*fptr)(osThreadId id)); + + virtual ~Thread(); + +private: + // Required to share definitions without + // delegated constructors + void constructor(osPriority priority=osPriorityNormal, + uint32_t stack_size=DEFAULT_STACK_SIZE, + unsigned char *stack_pointer=NULL); + void constructor(mbed::Callback<void()> task, + osPriority priority=osPriorityNormal, + uint32_t stack_size=DEFAULT_STACK_SIZE, + unsigned char *stack_pointer=NULL); + static void _thunk(const void * thread_ptr); + + mbed::Callback<void()> _task; + osThreadId _tid; + osThreadDef_t _thread_def; + bool _dynamic_stack; + Semaphore _join_sem; + Mutex _mutex; +}; + +} +#endif + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/rtos.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,49 @@ + +/** \addtogroup rtos */ +/** @{*/ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef RTOS_H +#define RTOS_H + +#include "rtos/Thread.h" +#include "rtos/Mutex.h" +#include "rtos/RtosTimer.h" +#include "rtos/Semaphore.h" +#include "rtos/Mail.h" +#include "rtos/MemoryPool.h" +#include "rtos/Queue.h" + +using namespace rtos; + +/* Get mbed lib version number, as RTOS depends on mbed lib features + like mbed_error, Callback and others. +*/ +#include "mbed.h" + +#if (MBED_LIBRARY_VERSION < 122) +#error "This version of RTOS requires mbed library version > 121" +#endif + +#endif + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/rtos_idle.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,51 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "rtos/rtos_idle.h" + +static void default_idle_hook(void) +{ + /* Sleep: ideally, we should put the chip to sleep. + Unfortunately, this usually requires disconnecting the interface chip (debugger). + This can be done, but it would break the local file system. + */ + // sleep(); +} +static void (*idle_hook_fptr)(void) = &default_idle_hook; + +void rtos_attach_idle_hook(void (*fptr)(void)) +{ + //Attach the specified idle hook, or the default idle hook in case of a NULL pointer + if (fptr != NULL) { + idle_hook_fptr = fptr; + } else { + idle_hook_fptr = default_idle_hook; + } +} + +void rtos_idle_loop(void) +{ + //Continuously call the idle hook function pointer + while (1) { + idle_hook_fptr(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtos/rtos_idle.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,42 @@ + +/** \addtogroup rtos */ +/** @{*/ +/* mbed Microcontroller Library + * Copyright (c) 2006-2012 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef RTOS_IDLE_H +#define RTOS_IDLE_H + +#include <stddef.h> + +#ifdef __cplusplus +extern "C" { +#endif + +void rtos_attach_idle_hook(void (*fptr)(void)); + +#ifdef __cplusplus +} +#endif + +#endif + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/ARM7/TOOLCHAIN_GCC/HAL_CM0.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,329 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM0.S + * Purpose: Hardware Abstraction Layer for ARM7TDMI + * Rev.: V1.0 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + + .file "HAL_CM0.S" + .syntax unified + + .equ TCB_TSTACK, 40 + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + .arm + + .section ".text" + .align 2 + +/*-------------------------- Save Context --------------------------------*/ +/* MUST be called the first */ +.macro SaveContext + + /* Push R0 as we are going to use the register. */ \ + STMDB SP!, {R0} + + /* Set R0 to SP(user) */ + STMDB SP,{SP}^ + NOP + SUB SP, SP, #4 + LDMIA SP!,{R0} + + /* Push the LR return address onto the user stack. */ + STMDB R0!, {LR} + + /* Now we have saved LR we can use it instead of R0. */ + MOV LR, R0 + + /* Pop R0 so we can save it onto the system mode stack. */ + LDMIA SP!, {R0} + + /* Push all the system mode registers onto the task stack. */ + STMDB LR,{R0-R12,LR}^ /* LR can not be changed because user's LR is used*/ + NOP /* pass 1 cycle before changing LR */ + SUB LR, LR, #14*4 /* change LR now -15 dwords (R0-R14)*/ + + /* Push the SPSR onto the task stack. */ + MRS R0, SPSR + STMDB LR!, {R0} + + /* Store the new top of stack for the task. */ + LDR R0,=os_tsk + LDR R0, [R0] /* R0 = (tcb) os_tsk.run */ + STR LR, [R0, TCB_TSTACK] /* tcb.tsk_stack = SP(user) */ +.endm + +/*-------------------------- Restore Context --------------------------------*/ + .type RestoreContext, %function + .global RestoreContext +RestoreContext: + .fnstart + .cantunwind + /* Set the LR to the task stack. */ + LDR R0,=os_tsk + LDR R1, [R0, 4] /* R1 = (tcb) os_tsk.new */ + STR R1, [R0] /* os_tsk.run = os_tsk_newk */ + LDR LR, [R1, TCB_TSTACK] /* LR = tcb.tsk_stack */ + + /* Get the SPSR from the stack. */ + LDMFD LR!, {R0} /* SPSR */ + MSR SPSR, R0 + + /* Restore all system mode registers for the task. */ + LDMFD LR, {R0-R12,LR}^ + NOP + + ADD LR, LR, 15*4 /* increase stack pointer */ + /* Set SP(user) to LR */ + STMDB SP!,{LR} + LDMIA SP,{SP}^ + NOP + ADD SP, SP, #4 + + /* Restore the return address. */ + LDR LR, [LR,#-4] /* last dword is task's PC register */ + + /* And return - correcting the offset in the LR to obtain the */ + /* correct address. */ + SUBS PC, LR, #4 + +/*-------------------------- End --------------------------------*/ + .fnend + .size RestoreContext, .-RestoreContext + + + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +# void rt_set_PSP (U32 stack); + + .type rt_set_PSP, %function + .global rt_set_PSP +rt_set_PSP: + .fnstart + .cantunwind + + MOV SP,R0 + BX LR + + .fnend + .size rt_set_PSP, .-rt_set_PSP + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +# U32 rt_get_PSP (void); + + .type rt_get_PSP, %function + .global rt_get_PSP +rt_get_PSP: + .fnstart + .cantunwind + + MOV R0,SP + BX LR + + .fnend + .size rt_get_PSP, .-rt_get_PSP + + + +/*--------------------------- _alloc_box ------------------------------------*/ + +# void *_alloc_box (void *box_mem); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .type _alloc_box, %function + .global _alloc_box +_alloc_box: + .fnstart + .cantunwind + + LDR R3,=rt_alloc_box + MOV R12, R3 + MRS R3, CPSR + AND R3, 0x1F + CMP R3, 0x12 /* IRQ mode*/ + BNE PrivilegedA + CMP R3, 0x1F /* System mode*/ + BNE PrivilegedA + SVC 0 + BX LR +PrivilegedA: + BX R12 + + .fnend + .size _alloc_box, .-_alloc_box + + +/*--------------------------- _free_box -------------------------------------*/ + +# int _free_box (void *box_mem, void *box); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .type _free_box, %function + .global _free_box +_free_box: + .fnstart + .cantunwind + + LDR R3,=rt_free_box + MOV R12, R3 + MRS R3, CPSR + AND R3, 0x1F + CMP R3, 0x12 /* IRQ mode*/ + BNE PrivilegedA + CMP R3, 0x1F /* System mode*/ + BNE PrivilegedA + SVC 0 + BX LR +PrivilegedF: + BX R12 + + .fnend + .size _free_box, .-_free_box + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +# void SVC_Handler (void); + + .type SVC_Handler, %function + .global SVC_Handler +SVC_Handler: + .fnstart + .cantunwind + /* Within an IRQ ISR the link register has an offset from the true return + address, but an SWI ISR does not. Add the offset manually so the same + ISR return code can be used in both cases. */ + + STMFD SP!, {R0,LR} /* Store registers. */ + ADD LR, LR, #4 /* Align LR with IRQ handler */ + SaveContext + MOV R11, LR /* Save Task Stack Pointer */ + LDMFD SP!, {R0,LR} /* Restore registers and return. */ + STMFD SP!, {R11} /* Save Task Stack Pointer */ + + LDR R5, [LR,#-4] /* Calculate address of SWI instruction and load it into r5. */ + BIC R5, R5,#0xff000000 /* Mask off top 8 bits of instruction to give SWI number. */ + + CMP R5, #0 + BNE SVC_User /* User SVC Number > 0 */ + MOV LR, PC /* set LR to return address */ + BX R12 /* Call SVC Function */ + + LDMFD SP!, {R11} /* Load Task Stack Pointer */ + STMIB R11!, {R0-R3} /* Store return values to Task stack */ + +SVC_Exit: + B RestoreContext /* return to the task */ + + /*------------------- User SVC ------------------------------*/ + +SVC_User: + LDR R6,=SVC_Count + LDR R6,[R6] + CMP R5,R6 + LDMFDHI SP!, {R11} + BHI SVC_Done /* Overflow */ + + LDR R4,=SVC_Table - 4 + LSLS R5,R5,#2 + LDR R4,[R4,R5] /* Load SVC Function Address */ + /* R0-R3,R12 are unchanged */ + MOV LR, PC /* set LR to return address */ + BX R4 /* Call SVC Function */ + + LDMFD SP!, {R11} /* Load Task Stack Pointer */ + BEQ SVC_Exit /* no need in return values */ + + STMIB R11!, {R0-R3} /* Store return values to Task stack */ +SVC_Done: + B RestoreContext /* return to the task */ + + .fnend + .size SVC_Handler, .-SVC_Handler + + +/*-------------------------- IRQ_Handler ---------------------------------*/ + +# void IRQ_Handler (void); + + .type IRQ_Handler, %function + .global IRQ_Handler +IRQ_Handler: + .fnstart + .cantunwind + + SaveContext + + MOV R0, #0xFFFFFF00 + LDR R0, [R0] /* Load address of raised IRQ handler*/ + + MOV LR, PC + BX R0 + + MOV R0, #0xFFFFFF00 + STR R0, [R0] /* Clear interrupt */ + + B RestoreContext + + .fnend + .size IRQ_Handler, .-IRQ_Handler + +/*-------------------------- SysTick_Handler --------------------------------*/ + +# void SysTick_Handler (void); + + .type SysTick_Handler, %function + .global SysTick_Handler +SysTick_Handler: + .fnstart + .cantunwind + + PUSH {LR} + BL rt_systick + POP {LR} + BX LR /* return to IRQ handler */ + +/*-------------------------- End --------------------------------*/ + .fnend + .size SysTick_Handler, .-SysTick_Handler + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + +.end \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/ARM7/TOOLCHAIN_GCC/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,56 @@ +;/*---------------------------------------------------------------------------- +; * RL-ARM - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.60 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2015 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. +; *---------------------------------------------------------------------------*/ + + + .file "SVC_Table.S" + + + .section ".svc_table" + + .global SVC_Table +SVC_Table: +/* Insert user SVC functions here. SVC 0 used by RTL Kernel. */ +# .long __SVC_1 /* user SVC function */ +SVC_End: + + .global SVC_Count +SVC_Count: + .long (SVC_End-SVC_Table)/4 + + + .end + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/HAL_CM.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,161 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM.C + * Purpose: Hardware Abstraction Layer for ARM7TDMI + * Rev.: V1.0 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +#ifdef DBG_MSG +BIT dbg_msg; +#endif + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_init_stack ---------------------------------*/ + +void rt_init_stack (P_TCB p_TCB, FUNCP task_body) { + /* Prepare TCB and saved context for a first time start of a task. */ + U32 *stk,i,size; + + /* Prepare a complete interrupt frame for first task start */ + size = p_TCB->priv_stack >> 2; + + /* Write to the top of stack. */ + stk = &p_TCB->stack[size]; + + /* Auto correct to 8-byte ARM stack alignment. */ + if ((U32)stk & 0x04) { + stk--; + } + + stk -= 16; + + /* Default xPSR and initial PC */ + stk[15] = (U32)task_body + 4; /* add 4 byte offset because SUB PC, LR - 4 */ + stk[0] = INITIAL_xPSR; + + /* Clear R0-R13/LR registers. */ + for (i = 1; i < 14; i++) { + stk[i] = 0; + } + + /* Assign a void pointer to R0. */ + stk[TCB_STACK_R0_OFFSET_DWORDS] = (U32)p_TCB->msg; + + /* Initial Task stack pointer. */ + p_TCB->tsk_stack = (U32)stk; + + /* Task entry point. */ + p_TCB->ptask = task_body; + + /* Set a magic word for checking of stack overflow. + For the main thread (ID: 0x01) the stack is in a memory area shared with the + heap, therefore the last word of the stack is a moving target. + We want to do stack/heap collision detection instead. + */ + if (p_TCB->task_id != 0x01) + p_TCB->stack[0] = MAGIC_WORD; +} + + +/*--------------------------- rt_ret_val ----------------------------------*/ + +static __inline U32 *rt_ret_regs (P_TCB p_TCB) { + /* Get pointer to task return value registers (R0..R3) in Stack */ + + /* Stack Frame: CPSR,R0-R13,PC */ + return (U32 *)(p_TCB->tsk_stack + TCB_STACK_R0_OFFSET_BYTES); +} + +void rt_ret_val (P_TCB p_TCB, U32 v0) { + U32 *ret; + + ret = rt_ret_regs(p_TCB); + ret[0] = v0; +} + +void rt_ret_val2(P_TCB p_TCB, U32 v0, U32 v1) { + U32 *ret; + + ret = rt_ret_regs(p_TCB); + ret[0] = v0; + ret[1] = v1; +} + + +/*--------------------------- dbg_init --------------------------------------*/ + +#ifdef DBG_MSG +void dbg_init (void) { + if ((DEMCR & DEMCR_TRCENA) && + (ITM_CONTROL & ITM_ITMENA) && + (ITM_ENABLE & (1UL << 31))) { + dbg_msg = __TRUE; + } +} +#endif + +/*--------------------------- dbg_task_notify -------------------------------*/ + +#ifdef DBG_MSG +void dbg_task_notify (P_TCB p_tcb, BOOL create) { + while (ITM_PORT31_U32 == 0); + ITM_PORT31_U32 = (U32)p_tcb->ptask; + while (ITM_PORT31_U32 == 0); + ITM_PORT31_U16 = (create << 8) | p_tcb->task_id; +} +#endif + +/*--------------------------- dbg_task_switch -------------------------------*/ + +#ifdef DBG_MSG +void dbg_task_switch (U32 task_id) { + while (ITM_PORT31_U32 == 0); + ITM_PORT31_U8 = task_id; +} +#endif + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/RTX_CM_lib.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,401 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RTX_CM_LIB.H + * Purpose: RTX Kernel System Configuration + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ +#include "mbed_error.h" + +#if defined (__CC_ARM) +#pragma O3 +#define __USED __attribute__((used)) +#elif defined (__GNUC__) +#pragma GCC optimize ("O3") +#define __USED __attribute__((used)) +#elif defined (__ICCARM__) +#define __USED __root +#endif + + +/*---------------------------------------------------------------------------- + * Definitions + *---------------------------------------------------------------------------*/ + +#define _declare_box(pool,size,cnt) uint32_t pool[(((size)+3)/4)*(cnt) + 3] +#define _declare_box8(pool,size,cnt) uint64_t pool[(((size)+7)/8)*(cnt) + 2] + +#define OS_TCB_SIZE 48 +#define OS_TMR_SIZE 8 + +#if defined (__CC_ARM) && !defined (__MICROLIB) + +typedef void *OS_ID; +typedef uint32_t OS_TID; +typedef uint32_t OS_MUT[3]; +typedef uint32_t OS_RESULT; + +#define runtask_id() rt_tsk_self() +#define mutex_init(m) rt_mut_init(m) +#define mutex_wait(m) os_mut_wait(m,0xFFFF) +#define mutex_rel(m) os_mut_release(m) + +extern OS_TID rt_tsk_self (void); +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, uint16_t timeout); + +#define os_mut_wait(mutex,timeout) _os_mut_wait((uint32_t)rt_mut_wait,mutex,timeout) +#define os_mut_release(mutex) _os_mut_release((uint32_t)rt_mut_release,mutex) + +OS_RESULT _os_mut_release (uint32_t p, OS_ID mutex) __svc_indirect(0); +OS_RESULT _os_mut_wait (uint32_t p, OS_ID mutex, uint16_t timeout) __svc_indirect(0); + +#endif + + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +#if (OS_TIMERS != 0) +#define OS_TASK_CNT (OS_TASKCNT + 1) +#else +#define OS_TASK_CNT OS_TASKCNT +#endif + +uint16_t const os_maxtaskrun = OS_TASK_CNT; +uint32_t const os_rrobin = (OS_ROBIN << 16) | OS_ROBINTOUT; +uint32_t const os_trv = OS_TRV; +uint8_t const os_flags = OS_RUNPRIV; + +/* Export following defines to uVision debugger. */ +__USED uint32_t const os_clockrate = OS_TICK; +__USED uint32_t const os_timernum = 0; + +/* Stack for the os_idle_demon */ +unsigned int idle_task_stack[OS_IDLESTKSIZE]; +unsigned short const idle_task_stack_size = OS_IDLESTKSIZE; + +#ifndef OS_FIFOSZ + #define OS_FIFOSZ 16 +#endif + +/* Fifo Queue buffer for ISR requests.*/ +uint32_t os_fifo[OS_FIFOSZ*2+1]; +uint8_t const os_fifo_size = OS_FIFOSZ; + +/* An array of Active task pointers. */ +void *os_active_TCB[OS_TASK_CNT]; + +/* User Timers Resources */ +#if (OS_TIMERS != 0) +extern void osTimerThread (void const *argument); +osThreadDef(osTimerThread, (osPriority)(OS_TIMERPRIO-3), 4*OS_TIMERSTKSZ); +osThreadId osThreadId_osTimerThread; +osMessageQDef(osTimerMessageQ, OS_TIMERCBQS, void *); +osMessageQId osMessageQId_osTimerMessageQ; +#else +osThreadDef_t os_thread_def_osTimerThread = { NULL }; +osThreadId osThreadId_osTimerThread; +osMessageQDef(osTimerMessageQ, 0, void *); +osMessageQId osMessageQId_osTimerMessageQ; +#endif + + +/*---------------------------------------------------------------------------- + * RTX Optimizations (empty functions) + *---------------------------------------------------------------------------*/ + +#if OS_ROBIN == 0 + void rt_init_robin (void) {;} + void rt_chk_robin (void) {;} +#endif + +#if OS_STKCHECK == 0 + void rt_stk_check (void) {;} +#endif + + +/*---------------------------------------------------------------------------- + * Standard Library multithreading interface + *---------------------------------------------------------------------------*/ + +#if defined (__CC_ARM) && !defined (__MICROLIB) + static OS_MUT std_libmutex[OS_MUTEXCNT]; + static uint32_t nr_mutex; + + /*--------------------------- _mutex_initialize -----------------------------*/ + +int _mutex_initialize (OS_ID *mutex) { + /* Allocate and initialize a system mutex. */ + + if (nr_mutex >= OS_MUTEXCNT) { + /* If you are here, you need to increase the number OS_MUTEXCNT. */ + error("Not enough stdlib mutexes\n"); + } + *mutex = &std_libmutex[nr_mutex++]; + mutex_init (*mutex); + return (1); +} + + +/*--------------------------- _mutex_acquire --------------------------------*/ + +__attribute__((used)) void _mutex_acquire (OS_ID *mutex) { + /* Acquire a system mutex, lock stdlib resources. */ + if (runtask_id ()) { + /* RTX running, acquire a mutex. */ + mutex_wait (*mutex); + } +} + + +/*--------------------------- _mutex_release --------------------------------*/ + +__attribute__((used)) void _mutex_release (OS_ID *mutex) { + /* Release a system mutex, unlock stdlib resources. */ + if (runtask_id ()) { + /* RTX running, release a mutex. */ + mutex_rel (*mutex); + } +} + +#endif + + +/*---------------------------------------------------------------------------- + * RTX Startup + *---------------------------------------------------------------------------*/ + +/* Main Thread definition */ +extern void pre_main (void); +osThreadDef_t os_thread_def_main = {(os_pthread)pre_main, osPriorityNormal, 0, NULL}; + +#ifndef INITIAL_SP + #error "no target defined" +#endif + +#ifdef __CC_ARM +extern unsigned char Image$$RW_IRAM1$$ZI$$Limit[]; +#define HEAP_START (Image$$RW_IRAM1$$ZI$$Limit) +#elif defined(__GNUC__) +extern unsigned char __end__[]; +#define HEAP_START (__end__) +#elif defined(__ICCARM__) +#pragma section="HEAP" +#define HEAP_START (void *)__section_begin("HEAP") +#endif + +void set_main_stack(void) { + // That is the bottom of the main stack block: no collision detection + os_thread_def_main.stack_pointer = HEAP_START; + + // Leave OS_SCHEDULERSTKSIZE words for the scheduler and interrupts + os_thread_def_main.stacksize = (INITIAL_SP - (unsigned int)HEAP_START) - (OS_SCHEDULERSTKSIZE * 4); +} + +#if defined (__CC_ARM) +#ifdef __MICROLIB + +int main(void); +void _main_init (void) __attribute__((section(".ARM.Collect$$$$000000FF"))); +void $Super$$__cpp_initialize__aeabi_(void); + +void _main_init (void) { + osKernelInitialize(); + set_main_stack(); + osThreadCreate(&os_thread_def_main, NULL); + osKernelStart(); + for (;;); +} + +void $Sub$$__cpp_initialize__aeabi_(void) +{ + // this should invoke C++ initializers prior _main_init, we keep this empty and + // invoke them after _main_init (=starts RTX kernel) +} + +void pre_main() +{ + $Super$$__cpp_initialize__aeabi_(); + main(); +} + +#else + +void * armcc_heap_base; +void * armcc_heap_top; + +__asm void pre_main (void) +{ + IMPORT __rt_lib_init + IMPORT main + IMPORT armcc_heap_base + IMPORT armcc_heap_top + + LDR R0,=armcc_heap_base + LDR R1,=armcc_heap_top + LDR R0,[R0] + LDR R1,[R1] + /* Save link register (keep 8 byte alignment with dummy R4) */ + PUSH {R4, LR} + BL __rt_lib_init + BL main + /* Return to the thread destroy function. + */ + POP {R4, PC} + ALIGN +} + +/* The single memory model is checking for stack collision at run time, verifing + that the heap pointer is underneath the stack pointer. + + With the RTOS there is not only one stack above the heap, there are multiple + stacks and some of them are underneath the heap pointer. +*/ +#pragma import(__use_two_region_memory) + +__asm void __rt_entry (void) { + + IMPORT __user_setup_stackheap + IMPORT armcc_heap_base + IMPORT armcc_heap_top + IMPORT os_thread_def_main + IMPORT osKernelInitialize + IMPORT set_main_stack + IMPORT osKernelStart + IMPORT osThreadCreate + + /* __user_setup_stackheap returns: + * - Heap base in r0 (if the program uses the heap). + * - Stack base in sp. + * - Heap limit in r2 (if the program uses the heap and uses two-region memory). + * + * More info can be found in: + * ARM Compiler ARM C and C++ Libraries and Floating-Point Support User Guide + */ + BL __user_setup_stackheap + LDR R3,=armcc_heap_base + LDR R4,=armcc_heap_top + STR R0,[R3] + STR R2,[R4] + BL osKernelInitialize + BL set_main_stack + LDR R0,=os_thread_def_main + MOVS R1,#0 + BL osThreadCreate + BL osKernelStart + /* osKernelStart should not return */ + B . + + ALIGN +} + +#endif + +#elif defined (__GNUC__) + +extern int atexit(void (*func)(void)); +extern void __libc_fini_array(void); +extern void __libc_init_array (void); +extern int main(int argc, char **argv); + +void pre_main(void) { + atexit(__libc_fini_array); + __libc_init_array(); + main(0, NULL); +} + +__attribute__((naked)) void software_init_hook_rtos (void) { + __asm ( + ".syntax unified\n" + ".thumb\n" + "bl osKernelInitialize\n" + "bl set_main_stack\n" + "ldr r0,=os_thread_def_main\n" + "movs r1,#0\n" + "bl osThreadCreate\n" + "bl osKernelStart\n" + /* osKernelStart should not return */ + "B .\n" + ); +} + +#elif defined (__ICCARM__) + +extern void* __vector_table; +extern int __low_level_init(void); +extern void __iar_data_init3(void); +extern __weak void __iar_init_core( void ); +extern __weak void __iar_init_vfp( void ); +extern void __iar_dynamic_initialization(void); +extern void mbed_sdk_init(void); +extern void exit(int arg); + +static uint8_t low_level_init_needed; + +void pre_main(void) { + if (low_level_init_needed) { + __iar_dynamic_initialization(); + } + main(); +} + +#pragma required=__vector_table +void __iar_program_start( void ) +{ + __iar_init_core(); + __iar_init_vfp(); + + uint8_t low_level_init_needed_local; + + low_level_init_needed_local = __low_level_init(); + if (low_level_init_needed_local) { + __iar_data_init3(); + mbed_sdk_init(); + } + /* Store in a global variable after RAM has been initialized */ + low_level_init_needed = low_level_init_needed_local; + osKernelInitialize(); + set_main_stack(); + osThreadCreate(&os_thread_def_main, NULL); + osKernelStart(); + /* osKernelStart should not return */ + while (1); +} + +#endif + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/RTX_Conf.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,72 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RTX_CONFIG.H + * Purpose: Exported functions of RTX_Config.c + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + + +/* Error Codes */ +#define OS_ERR_STK_OVF 1 +#define OS_ERR_FIFO_OVF 2 +#define OS_ERR_MBX_OVF 3 + +/* Definitions */ +#define BOX_ALIGN_8 0x80000000 +#define _declare_box(pool,size,cnt) U32 pool[(((size)+3)/4)*(cnt) + 3] +#define _declare_box8(pool,size,cnt) U64 pool[(((size)+7)/8)*(cnt) + 2] +#define _init_box8(pool,size,bsize) _init_box (pool,size,(bsize) | BOX_ALIGN_8) + +/* Variables */ +extern U32 idle_task_stack[]; +extern U32 os_fifo[]; +extern void *os_active_TCB[]; + +/* Constants */ +extern U16 const os_maxtaskrun; +extern U32 const os_trv; +extern U8 const os_flags; +extern U32 const os_rrobin; +extern U32 const os_clockrate; +extern U32 const os_timernum; +extern U16 const idle_task_stack_size; + +extern U8 const os_fifo_size; + +/* Functions */ +extern void os_idle_demon (void); +extern int os_tick_init (void); +extern void os_tick_irqack (void); +extern void os_tmr_call (U16 info); +extern void os_error (U32 err_code); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/RTX_Conf_CM.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,228 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RTX_Conf_CM.C + * Purpose: Configuration of CMSIS RTX Kernel for ARM7TDMI + * Rev.: V1.0 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "cmsis_os.h" + + +/*---------------------------------------------------------------------------- + * RTX User configuration part BEGIN + *---------------------------------------------------------------------------*/ + +// Include per-target RTX config file +#include "mbed_rtx4.h" + +//-------- <<< Use Configuration Wizard in Context Menu >>> ----------------- +// +// <h>Thread Configuration +// ======================= +// +// <o>Number of concurrent running threads <0-250> +// <i> Defines max. number of threads that will run at the same time. +// counting "main", but not counting "osTimerThread" +// <i> Default: 6 +#ifndef OS_TASKCNT + #error "no target defined" +#endif + +// <o>Scheduler (+ interrupts) stack size [bytes] <64-4096:8><#/4> +#ifndef OS_SCHEDULERSTKSIZE + #error "no target defined" +#endif + +// <o>Idle stack size [bytes] <64-4096:8><#/4> +// <i> Defines default stack size for the Idle thread. +#ifndef OS_IDLESTKSIZE + #define OS_IDLESTKSIZE 136 +#endif + +// <o>Timer Thread stack size [bytes] <64-4096:8><#/4> +// <i> Defines stack size for Timer thread. +// <i> Default: 200 +#ifndef OS_TIMERSTKSZ + #define OS_TIMERSTKSZ WORDS_STACK_SIZE +#endif + +// <q>Check for stack overflow +// <i> Includes the stack checking code for stack overflow. +// <i> Note that additional code reduces the Kernel performance. +#ifndef OS_STKCHECK + #define OS_STKCHECK 1 +#endif + +// <o>Processor mode for thread execution +// <0=> Unprivileged mode +// <1=> Privileged mode +// <i> Default: Privileged mode +#ifndef OS_RUNPRIV + #define OS_RUNPRIV 1 +#endif + +// </h> +// <h>SysTick Timer Configuration +// ============================== +// +// <o>Timer clock value [Hz] <1-1000000000> +// <i> Defines the timer clock value. +// <i> Default: 6000000 (6MHz) +#ifndef OS_CLOCK + #error "no target defined" +#endif + +// <o>Timer tick value [us] <1-1000000> +// <i> Defines the timer tick value. +// <i> Default: 1000 (1ms) +#ifndef OS_TICK + #define OS_TICK 1000 +#endif + +// </h> + +// <h>System Configuration +// ======================= +// +// <e>Round-Robin Thread switching +// =============================== +// +// <i> Enables Round-Robin Thread switching. +#ifndef OS_ROBIN + #define OS_ROBIN 1 +#endif + +// <o>Round-Robin Timeout [ticks] <1-1000> +// <i> Defines how long a thread will execute before a thread switch. +// <i> Default: 5 +#ifndef OS_ROBINTOUT + #define OS_ROBINTOUT 5 +#endif + +// </e> + +// <e>User Timers +// ============== +// <i> Enables user Timers +#ifndef OS_TIMERS + #define OS_TIMERS 1 +#endif + +// <o>Timer Thread Priority +// <1=> Low +// <2=> Below Normal +// <3=> Normal +// <4=> Above Normal +// <5=> High +// <6=> Realtime (highest) +// <i> Defines priority for Timer Thread +// <i> Default: High +#ifndef OS_TIMERPRIO + #define OS_TIMERPRIO 5 +#endif + +// <o>Timer Callback Queue size <1-32> +// <i> Number of concurrent active timer callback functions. +// <i> Default: 4 +#ifndef OS_TIMERCBQSZ + #define OS_TIMERCBQS 4 +#endif + +// </e> + +// <o>ISR FIFO Queue size<4=> 4 entries <8=> 8 entries +// <12=> 12 entries <16=> 16 entries +// <24=> 24 entries <32=> 32 entries +// <48=> 48 entries <64=> 64 entries +// <96=> 96 entries +// <i> ISR functions store requests to this buffer, +// <i> when they are called from the interrupt handler. +// <i> Default: 16 entries +#ifndef OS_FIFOSZ + #define OS_FIFOSZ 16 +#endif + +// </h> + +//------------- <<< end of configuration section >>> ----------------------- + +// Standard library system mutexes +// =============================== +// Define max. number system mutexes that are used to protect +// the arm standard runtime library. For microlib they are not used. +#ifndef OS_MUTEXCNT + #define OS_MUTEXCNT 12 +#endif + +/*---------------------------------------------------------------------------- + * RTX User configuration part END + *---------------------------------------------------------------------------*/ + +#define OS_TRV ((uint32_t)(((double)OS_CLOCK*(double)OS_TICK)/1E6)-1) + + +/*---------------------------------------------------------------------------- + * OS Idle daemon + *---------------------------------------------------------------------------*/ +extern void rtos_idle_loop(void); + +void os_idle_demon (void) { + /* The idle demon is a system thread, running when no other thread is */ + /* ready to run. */ + rtos_idle_loop(); +} + +/*---------------------------------------------------------------------------- + * RTX Errors + *---------------------------------------------------------------------------*/ +extern void mbed_die(void); + +void os_error (uint32_t err_code) { + /* This function is called when a runtime error is detected. Parameter */ + /* 'err_code' holds the runtime error code (defined in RTX_Conf.h). */ + mbed_die(); +} + +void sysThreadError(osStatus status) { + if (status != osOK) { + mbed_die(); + } +} + +/*---------------------------------------------------------------------------- + * RTX Configuration Functions + *---------------------------------------------------------------------------*/ + +#include "RTX_CM_lib.h" + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/cmsis_os.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,774 @@ +/* ---------------------------------------------------------------------- + * Copyright (C) 2015 ARM Limited. All rights reserved. + * + * $Date: 5. June 2012 + * $Revision: V1.01 + * + * Project: CMSIS-RTOS API + * Title: cmsis_os.h RTX header file + * + * Version 0.02 + * Initial Proposal Phase + * Version 0.03 + * osKernelStart added, optional feature: main started as thread + * osSemaphores have standard behavior + * osTimerCreate does not start the timer, added osTimerStart + * osThreadPass is renamed to osThreadYield + * Version 1.01 + * Support for C++ interface + * - const attribute removed from the osXxxxDef_t typedef's + * - const attribute added to the osXxxxDef macros + * Added: osTimerDelete, osMutexDelete, osSemaphoreDelete + * Added: osKernelInitialize + * -------------------------------------------------------------------- */ + +/** +\page cmsis_os_h Header File Template: cmsis_os.h + +The file \b cmsis_os.h is a template header file for a CMSIS-RTOS compliant Real-Time Operating System (RTOS). +Each RTOS that is compliant with CMSIS-RTOS shall provide a specific \b cmsis_os.h header file that represents +its implementation. + +The file cmsis_os.h contains: + - CMSIS-RTOS API function definitions + - struct definitions for parameters and return types + - status and priority values used by CMSIS-RTOS API functions + - macros for defining threads and other kernel objects + + +<b>Name conventions and header file modifications</b> + +All definitions are prefixed with \b os to give an unique name space for CMSIS-RTOS functions. +Definitions that are prefixed \b os_ are not used in the application code but local to this header file. +All definitions and functions that belong to a module are grouped and have a common prefix, i.e. \b osThread. + +Definitions that are marked with <b>CAN BE CHANGED</b> can be adapted towards the needs of the actual CMSIS-RTOS implementation. +These definitions can be specific to the underlying RTOS kernel. + +Definitions that are marked with <b>MUST REMAIN UNCHANGED</b> cannot be altered. Otherwise the CMSIS-RTOS implementation is no longer +compliant to the standard. Note that some functions are optional and need not to be provided by every CMSIS-RTOS implementation. + + +<b>Function calls from interrupt service routines</b> + +The following CMSIS-RTOS functions can be called from threads and interrupt service routines (ISR): + - \ref osSignalSet + - \ref osSemaphoreRelease + - \ref osPoolAlloc, \ref osPoolCAlloc, \ref osPoolFree + - \ref osMessagePut, \ref osMessageGet + - \ref osMailAlloc, \ref osMailCAlloc, \ref osMailGet, \ref osMailPut, \ref osMailFree + +Functions that cannot be called from an ISR are verifying the interrupt status and return in case that they are called +from an ISR context the status code \b osErrorISR. In some implementations this condition might be caught using the HARD FAULT vector. + +Some CMSIS-RTOS implementations support CMSIS-RTOS function calls from multiple ISR at the same time. +If this is impossible, the CMSIS-RTOS rejects calls by nested ISR functions with the status code \b osErrorISRRecursive. + + +<b>Define and reference object definitions</b> + +With <b>\#define osObjectsExternal</b> objects are defined as external symbols. This allows to create a consistent header file +that is used throughout a project as shown below: + +<i>Header File</i> +\code +#include <cmsis_os.h> // CMSIS RTOS header file + +// Thread definition +extern void thread_sample (void const *argument); // function prototype +osThreadDef (thread_sample, osPriorityBelowNormal, 1, 100); + +// Pool definition +osPoolDef(MyPool, 10, long); +\endcode + + +This header file defines all objects when included in a C/C++ source file. When <b>\#define osObjectsExternal</b> is +present before the header file, the objects are defined as external symbols. A single consistent header file can therefore be +used throughout the whole project. + +<i>Example</i> +\code +#include "osObjects.h" // Definition of the CMSIS-RTOS objects +\endcode + +\code +#define osObjectExternal // Objects will be defined as external symbols +#include "osObjects.h" // Reference to the CMSIS-RTOS objects +\endcode + +*/ + +#ifndef _CMSIS_OS_H +#define _CMSIS_OS_H + +/// \note MUST REMAIN UNCHANGED: \b osCMSIS identifies the CMSIS-RTOS API version. +#define osCMSIS 0x10001 ///< API version (main [31:16] .sub [15:0]) + +/// \note CAN BE CHANGED: \b osCMSIS_KERNEL identifies the underlying RTOS kernel and version number. +#define osCMSIS_RTX ((4<<16)|61) ///< RTOS identification and version (main [31:16] .sub [15:0]) + +/// \note MUST REMAIN UNCHANGED: \b osKernelSystemId shall be consistent in every CMSIS-RTOS. +#define osKernelSystemId "RTX V4.61" ///< RTOS identification string + + +#define CMSIS_OS_RTX + +// The stack space occupied is mainly dependent on the underling C standard library +#if defined(TOOLCHAIN_GCC) || defined(TOOLCHAIN_ARM_STD) || defined(TOOLCHAIN_IAR) +# define WORDS_STACK_SIZE 512 +#elif defined(TOOLCHAIN_ARM_MICRO) +# define WORDS_STACK_SIZE 128 +#endif + +#define DEFAULT_STACK_SIZE (WORDS_STACK_SIZE*4) + + +/// \note MUST REMAIN UNCHANGED: \b osFeature_xxx shall be consistent in every CMSIS-RTOS. +#define osFeature_MainThread 1 ///< main thread 1=main can be thread, 0=not available +#define osFeature_Pool 1 ///< Memory Pools: 1=available, 0=not available +#define osFeature_MailQ 1 ///< Mail Queues: 1=available, 0=not available +#define osFeature_MessageQ 1 ///< Message Queues: 1=available, 0=not available +#define osFeature_Signals 16 ///< maximum number of Signal Flags available per thread +#define osFeature_Semaphore 65535 ///< maximum count for \ref osSemaphoreCreate function +#define osFeature_Wait 0 ///< osWait function: 1=available, 0=not available + +#if defined (__CC_ARM) +#define os_InRegs __value_in_regs // Compiler specific: force struct in registers +#elif defined (__ICCARM__) +#define os_InRegs __value_in_regs // Compiler specific: force struct in registers +#else +#define os_InRegs +#endif + +#include <stdint.h> +#include <stddef.h> + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "os_tcb.h" + +// ==== Enumeration, structures, defines ==== + +/// Priority used for thread control. +/// \note MUST REMAIN UNCHANGED: \b osPriority shall be consistent in every CMSIS-RTOS. +typedef enum { + osPriorityIdle = -3, ///< priority: idle (lowest) + osPriorityLow = -2, ///< priority: low + osPriorityBelowNormal = -1, ///< priority: below normal + osPriorityNormal = 0, ///< priority: normal (default) + osPriorityAboveNormal = +1, ///< priority: above normal + osPriorityHigh = +2, ///< priority: high + osPriorityRealtime = +3, ///< priority: realtime (highest) + osPriorityError = 0x84 ///< system cannot determine priority or thread has illegal priority +} osPriority; + +/// Timeout value. +/// \note MUST REMAIN UNCHANGED: \b osWaitForever shall be consistent in every CMSIS-RTOS. +#define osWaitForever 0xFFFFFFFF ///< wait forever timeout value + +/// Status code values returned by CMSIS-RTOS functions. +/// \note MUST REMAIN UNCHANGED: \b osStatus shall be consistent in every CMSIS-RTOS. +typedef enum { + osOK = 0, ///< function completed; no error or event occurred. + osEventSignal = 0x08, ///< function completed; signal event occurred. + osEventMessage = 0x10, ///< function completed; message event occurred. + osEventMail = 0x20, ///< function completed; mail event occurred. + osEventTimeout = 0x40, ///< function completed; timeout occurred. + osErrorParameter = 0x80, ///< parameter error: a mandatory parameter was missing or specified an incorrect object. + osErrorResource = 0x81, ///< resource not available: a specified resource was not available. + osErrorTimeoutResource = 0xC1, ///< resource not available within given time: a specified resource was not available within the timeout period. + osErrorISR = 0x82, ///< not allowed in ISR context: the function cannot be called from interrupt service routines. + osErrorISRRecursive = 0x83, ///< function called multiple times from ISR with same object. + osErrorPriority = 0x84, ///< system cannot determine priority or thread has illegal priority. + osErrorNoMemory = 0x85, ///< system is out of memory: it was impossible to allocate or reserve memory for the operation. + osErrorValue = 0x86, ///< value of a parameter is out of range. + osErrorOS = 0xFF, ///< unspecified RTOS error: run-time error but no other error message fits. + os_status_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization. +} osStatus; + + +/// Timer type value for the timer definition. +/// \note MUST REMAIN UNCHANGED: \b os_timer_type shall be consistent in every CMSIS-RTOS. +typedef enum { + osTimerOnce = 0, ///< one-shot timer + osTimerPeriodic = 1 ///< repeating timer +} os_timer_type; + +/// Entry point of a thread. +/// \note MUST REMAIN UNCHANGED: \b os_pthread shall be consistent in every CMSIS-RTOS. +typedef void (*os_pthread) (void const *argument); + +/// Entry point of a timer call back function. +/// \note MUST REMAIN UNCHANGED: \b os_ptimer shall be consistent in every CMSIS-RTOS. +typedef void (*os_ptimer) (void const *argument); + +// >>> the following data type definitions may shall adapted towards a specific RTOS + +/// Thread ID identifies the thread (pointer to a thread control block). +/// \note CAN BE CHANGED: \b os_thread_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_thread_cb *osThreadId; + +/// Timer ID identifies the timer (pointer to a timer control block). +/// \note CAN BE CHANGED: \b os_timer_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_timer_cb *osTimerId; + +/// Mutex ID identifies the mutex (pointer to a mutex control block). +/// \note CAN BE CHANGED: \b os_mutex_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_mutex_cb *osMutexId; + +/// Semaphore ID identifies the semaphore (pointer to a semaphore control block). +/// \note CAN BE CHANGED: \b os_semaphore_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_semaphore_cb *osSemaphoreId; + +/// Pool ID identifies the memory pool (pointer to a memory pool control block). +/// \note CAN BE CHANGED: \b os_pool_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_pool_cb *osPoolId; + +/// Message ID identifies the message queue (pointer to a message queue control block). +/// \note CAN BE CHANGED: \b os_messageQ_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_messageQ_cb *osMessageQId; + +/// Mail ID identifies the mail queue (pointer to a mail queue control block). +/// \note CAN BE CHANGED: \b os_mailQ_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_mailQ_cb *osMailQId; + + +/// Thread Definition structure contains startup information of a thread. +/// \note CAN BE CHANGED: \b os_thread_def is implementation specific in every CMSIS-RTOS. +typedef struct os_thread_def { + os_pthread pthread; ///< start address of thread function + osPriority tpriority; ///< initial thread priority + uint32_t stacksize; ///< stack size requirements in bytes + uint32_t *stack_pointer; ///< pointer to the stack memory block + struct OS_TCB tcb; +} osThreadDef_t; + +/// Timer Definition structure contains timer parameters. +/// \note CAN BE CHANGED: \b os_timer_def is implementation specific in every CMSIS-RTOS. +typedef struct os_timer_def { + os_ptimer ptimer; ///< start address of a timer function + void *timer; ///< pointer to internal data +} osTimerDef_t; + +/// Mutex Definition structure contains setup information for a mutex. +/// \note CAN BE CHANGED: \b os_mutex_def is implementation specific in every CMSIS-RTOS. +typedef struct os_mutex_def { + void *mutex; ///< pointer to internal data +} osMutexDef_t; + +/// Semaphore Definition structure contains setup information for a semaphore. +/// \note CAN BE CHANGED: \b os_semaphore_def is implementation specific in every CMSIS-RTOS. +typedef struct os_semaphore_def { + void *semaphore; ///< pointer to internal data +} osSemaphoreDef_t; + +/// Definition structure for memory block allocation. +/// \note CAN BE CHANGED: \b os_pool_def is implementation specific in every CMSIS-RTOS. +typedef struct os_pool_def { + uint32_t pool_sz; ///< number of items (elements) in the pool + uint32_t item_sz; ///< size of an item + void *pool; ///< pointer to memory for pool +} osPoolDef_t; + +/// Definition structure for message queue. +/// \note CAN BE CHANGED: \b os_messageQ_def is implementation specific in every CMSIS-RTOS. +typedef struct os_messageQ_def { + uint32_t queue_sz; ///< number of elements in the queue + void *pool; ///< memory array for messages +} osMessageQDef_t; + +/// Definition structure for mail queue. +/// \note CAN BE CHANGED: \b os_mailQ_def is implementation specific in every CMSIS-RTOS. +typedef struct os_mailQ_def { + uint32_t queue_sz; ///< number of elements in the queue + uint32_t item_sz; ///< size of an item + void *pool; ///< memory array for mail +} osMailQDef_t; + +/// Event structure contains detailed information about an event. +/// \note MUST REMAIN UNCHANGED: \b os_event shall be consistent in every CMSIS-RTOS. +/// However the struct may be extended at the end. +typedef struct { + osStatus status; ///< status code: event or error information + union { + uint32_t v; ///< message as 32-bit value + void *p; ///< message or mail as void pointer + int32_t signals; ///< signal flags + } value; ///< event value + union { + osMailQId mail_id; ///< mail id obtained by \ref osMailCreate + osMessageQId message_id; ///< message id obtained by \ref osMessageCreate + } def; ///< event definition +} osEvent; + + +// ==== Kernel Control Functions ==== + +/// Initialize the RTOS Kernel for creating objects. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osKernelInitialize shall be consistent in every CMSIS-RTOS. +osStatus osKernelInitialize (void); + +/// Start the RTOS Kernel. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osKernelStart shall be consistent in every CMSIS-RTOS. +osStatus osKernelStart (void); + +/// Check if the RTOS kernel is already started. +/// \note MUST REMAIN UNCHANGED: \b osKernelRunning shall be consistent in every CMSIS-RTOS. +/// \return 0 RTOS is not started, 1 RTOS is started. +int32_t osKernelRunning(void); + + +// ==== Thread Management ==== + +/// Create a Thread Definition with function, priority, and stack requirements. +/// \param name name of the thread function. +/// \param priority initial priority of the thread function. +/// \param stacksz stack size (in bytes) requirements for the thread function. +/// \note CAN BE CHANGED: The parameters to \b osThreadDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osThreadDef(name, priority, stacksz) \ +extern osThreadDef_t os_thread_def_##name +#else // define the object +#define osThreadDef(name, priority, stacksz) \ +uint32_t os_thread_def_stack_##name [stacksz / sizeof(uint32_t)]; \ +osThreadDef_t os_thread_def_##name = \ +{ (name), (priority), (stacksz), (os_thread_def_stack_##name)} +#endif + +/// Access a Thread definition. +/// \param name name of the thread definition object. +/// \note CAN BE CHANGED: The parameter to \b osThread shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osThread(name) \ +&os_thread_def_##name + +/// Create a thread and add it to Active Threads and set it to state READY. +/// \param[in] thread_def thread definition referenced with \ref osThread. +/// \param[in] argument pointer that is passed to the thread function as start argument. +/// \return thread ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osThreadCreate shall be consistent in every CMSIS-RTOS. +osThreadId osThreadCreate (osThreadDef_t *thread_def, void *argument); + +/// Return the thread ID of the current running thread. +/// \return thread ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osThreadGetId shall be consistent in every CMSIS-RTOS. +osThreadId osThreadGetId (void); + +/// Terminate execution of a thread and remove it from Active Threads. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osThreadTerminate shall be consistent in every CMSIS-RTOS. +osStatus osThreadTerminate (osThreadId thread_id); + +/// Pass control to next thread that is in state \b READY. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osThreadYield shall be consistent in every CMSIS-RTOS. +osStatus osThreadYield (void); + +/// Change priority of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] priority new priority value for the thread function. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osThreadSetPriority shall be consistent in every CMSIS-RTOS. +osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority); + +/// Get current priority of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return current priority value of the thread function. +/// \note MUST REMAIN UNCHANGED: \b osThreadGetPriority shall be consistent in every CMSIS-RTOS. +osPriority osThreadGetPriority (osThreadId thread_id); + + +// ==== Generic Wait Functions ==== + +/// Wait for Timeout (Time Delay). +/// \param[in] millisec time delay value +/// \return status code that indicates the execution status of the function. +osStatus osDelay (uint32_t millisec); + +#if (defined (osFeature_Wait) && (osFeature_Wait != 0)) // Generic Wait available + +/// Wait for Signal, Message, Mail, or Timeout. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return event that contains signal, message, or mail information or error code. +/// \note MUST REMAIN UNCHANGED: \b osWait shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osWait (uint32_t millisec); + +#endif // Generic Wait available + + +// ==== Timer Management Functions ==== +/// Define a Timer object. +/// \param name name of the timer object. +/// \param function name of the timer call back function. +/// \note CAN BE CHANGED: The parameter to \b osTimerDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osTimerDef(name, function) \ +extern osTimerDef_t os_timer_def_##name +#else // define the object +#define osTimerDef(name, function) \ +uint32_t os_timer_cb_##name[5]; \ +osTimerDef_t os_timer_def_##name = \ +{ (function), (os_timer_cb_##name) } +#endif + +/// Access a Timer definition. +/// \param name name of the timer object. +/// \note CAN BE CHANGED: The parameter to \b osTimer shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osTimer(name) \ +&os_timer_def_##name + +/// Create a timer. +/// \param[in] timer_def timer object referenced with \ref osTimer. +/// \param[in] type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior. +/// \param[in] argument argument to the timer call back function. +/// \return timer ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osTimerCreate shall be consistent in every CMSIS-RTOS. +osTimerId osTimerCreate (osTimerDef_t *timer_def, os_timer_type type, void *argument); + +/// Start or restart a timer. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \param[in] millisec time delay value of the timer. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osTimerStart shall be consistent in every CMSIS-RTOS. +osStatus osTimerStart (osTimerId timer_id, uint32_t millisec); + +/// Stop the timer. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osTimerStop shall be consistent in every CMSIS-RTOS. +osStatus osTimerStop (osTimerId timer_id); + +/// Delete a timer that was created by \ref osTimerCreate. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osTimerDelete shall be consistent in every CMSIS-RTOS. +osStatus osTimerDelete (osTimerId timer_id); + + +// ==== Signal Management ==== + +/// Set the specified Signal Flags of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] signals specifies the signal flags of the thread that should be set. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. +/// \note MUST REMAIN UNCHANGED: \b osSignalSet shall be consistent in every CMSIS-RTOS. +int32_t osSignalSet (osThreadId thread_id, int32_t signals); + +/// Clear the specified Signal Flags of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] signals specifies the signal flags of the thread that shall be cleared. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. +/// \note MUST REMAIN UNCHANGED: \b osSignalClear shall be consistent in every CMSIS-RTOS. +int32_t osSignalClear (osThreadId thread_id, int32_t signals); + +/// Get Signal Flags status of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. +/// \note MUST REMAIN UNCHANGED: \b osSignalGet shall be consistent in every CMSIS-RTOS. +int32_t osSignalGet (osThreadId thread_id); + +/// Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread. +/// \param[in] signals wait until all specified signal flags set or 0 for any single signal flag. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return event flag information or error code. +/// \note MUST REMAIN UNCHANGED: \b osSignalWait shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec); + + +// ==== Mutex Management ==== + +/// Define a Mutex. +/// \param name name of the mutex object. +/// \note CAN BE CHANGED: The parameter to \b osMutexDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osMutexDef(name) \ +extern osMutexDef_t os_mutex_def_##name +#else // define the object +#define osMutexDef(name) \ +uint32_t os_mutex_cb_##name[3]; \ +osMutexDef_t os_mutex_def_##name = { (os_mutex_cb_##name) } +#endif + +/// Access a Mutex definition. +/// \param name name of the mutex object. +/// \note CAN BE CHANGED: The parameter to \b osMutex shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osMutex(name) \ +&os_mutex_def_##name + +/// Create and Initialize a Mutex object. +/// \param[in] mutex_def mutex definition referenced with \ref osMutex. +/// \return mutex ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMutexCreate shall be consistent in every CMSIS-RTOS. +osMutexId osMutexCreate (osMutexDef_t *mutex_def); + +/// Wait until a Mutex becomes available. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMutexWait shall be consistent in every CMSIS-RTOS. +osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec); + +/// Release a Mutex that was obtained by \ref osMutexWait. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMutexRelease shall be consistent in every CMSIS-RTOS. +osStatus osMutexRelease (osMutexId mutex_id); + +/// Delete a Mutex that was created by \ref osMutexCreate. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMutexDelete shall be consistent in every CMSIS-RTOS. +osStatus osMutexDelete (osMutexId mutex_id); + + +// ==== Semaphore Management Functions ==== + +#if (defined (osFeature_Semaphore) && (osFeature_Semaphore != 0)) // Semaphore available + +/// Define a Semaphore object. +/// \param name name of the semaphore object. +/// \note CAN BE CHANGED: The parameter to \b osSemaphoreDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osSemaphoreDef(name) \ +extern osSemaphoreDef_t os_semaphore_def_##name +#else // define the object +#define osSemaphoreDef(name) \ +uint32_t os_semaphore_cb_##name[2]; \ +osSemaphoreDef_t os_semaphore_def_##name = { (os_semaphore_cb_##name) } +#endif + +/// Access a Semaphore definition. +/// \param name name of the semaphore object. +/// \note CAN BE CHANGED: The parameter to \b osSemaphore shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osSemaphore(name) \ +&os_semaphore_def_##name + +/// Create and Initialize a Semaphore object used for managing resources. +/// \param[in] semaphore_def semaphore definition referenced with \ref osSemaphore. +/// \param[in] count number of available resources. +/// \return semaphore ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreCreate shall be consistent in every CMSIS-RTOS. +osSemaphoreId osSemaphoreCreate (osSemaphoreDef_t *semaphore_def, int32_t count); + +/// Wait until a Semaphore token becomes available. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return number of available tokens, or -1 in case of incorrect parameters. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreWait shall be consistent in every CMSIS-RTOS. +int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec); + +/// Release a Semaphore token. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreRelease shall be consistent in every CMSIS-RTOS. +osStatus osSemaphoreRelease (osSemaphoreId semaphore_id); + +/// Delete a Semaphore that was created by \ref osSemaphoreCreate. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreDelete shall be consistent in every CMSIS-RTOS. +osStatus osSemaphoreDelete (osSemaphoreId semaphore_id); + +#endif // Semaphore available + + +// ==== Memory Pool Management Functions ==== + +#if (defined (osFeature_Pool) && (osFeature_Pool != 0)) // Memory Pool Management available + +/// \brief Define a Memory Pool. +/// \param name name of the memory pool. +/// \param no maximum number of blocks (objects) in the memory pool. +/// \param type data type of a single block (object). +/// \note CAN BE CHANGED: The parameter to \b osPoolDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osPoolDef(name, no, type) \ +extern osPoolDef_t os_pool_def_##name +#else // define the object +#define osPoolDef(name, no, type) \ +uint32_t os_pool_m_##name[3+((sizeof(type)+3)/4)*(no)]; \ +osPoolDef_t os_pool_def_##name = \ +{ (no), sizeof(type), (os_pool_m_##name) } +#endif + +/// \brief Access a Memory Pool definition. +/// \param name name of the memory pool +/// \note CAN BE CHANGED: The parameter to \b osPool shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osPool(name) \ +&os_pool_def_##name + +/// Create and Initialize a memory pool. +/// \param[in] pool_def memory pool definition referenced with \ref osPool. +/// \return memory pool ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osPoolCreate shall be consistent in every CMSIS-RTOS. +osPoolId osPoolCreate (osPoolDef_t *pool_def); + +/// Allocate a memory block from a memory pool. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \return address of the allocated memory block or NULL in case of no memory available. +/// \note MUST REMAIN UNCHANGED: \b osPoolAlloc shall be consistent in every CMSIS-RTOS. +void *osPoolAlloc (osPoolId pool_id); + +/// Allocate a memory block from a memory pool and set memory block to zero. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \return address of the allocated memory block or NULL in case of no memory available. +/// \note MUST REMAIN UNCHANGED: \b osPoolCAlloc shall be consistent in every CMSIS-RTOS. +void *osPoolCAlloc (osPoolId pool_id); + +/// Return an allocated memory block back to a specific memory pool. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \param[in] block address of the allocated memory block that is returned to the memory pool. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osPoolFree shall be consistent in every CMSIS-RTOS. +osStatus osPoolFree (osPoolId pool_id, void *block); + +#endif // Memory Pool Management available + + +// ==== Message Queue Management Functions ==== + +#if (defined (osFeature_MessageQ) && (osFeature_MessageQ != 0)) // Message Queues available + +/// \brief Create a Message Queue Definition. +/// \param name name of the queue. +/// \param queue_sz maximum number of messages in the queue. +/// \param type data type of a single message element (for debugger). +/// \note CAN BE CHANGED: The parameter to \b osMessageQDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osMessageQDef(name, queue_sz, type) \ +extern osMessageQDef_t os_messageQ_def_##name +#else // define the object +#define osMessageQDef(name, queue_sz, type) \ +uint32_t os_messageQ_q_##name[4+(queue_sz)]; \ +osMessageQDef_t os_messageQ_def_##name = \ +{ (queue_sz), (os_messageQ_q_##name) } +#endif + +/// \brief Access a Message Queue Definition. +/// \param name name of the queue +/// \note CAN BE CHANGED: The parameter to \b osMessageQ shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osMessageQ(name) \ +&os_messageQ_def_##name + +/// Create and Initialize a Message Queue. +/// \param[in] queue_def queue definition referenced with \ref osMessageQ. +/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. +/// \return message queue ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMessageCreate shall be consistent in every CMSIS-RTOS. +osMessageQId osMessageCreate (osMessageQDef_t *queue_def, osThreadId thread_id); + +/// Put a Message to a Queue. +/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. +/// \param[in] info message information. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMessagePut shall be consistent in every CMSIS-RTOS. +osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec); + +/// Get a Message or Wait for a Message from a Queue. +/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return event information that includes status code. +/// \note MUST REMAIN UNCHANGED: \b osMessageGet shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec); + +#endif // Message Queues available + + +// ==== Mail Queue Management Functions ==== + +#if (defined (osFeature_MailQ) && (osFeature_MailQ != 0)) // Mail Queues available + +/// \brief Create a Mail Queue Definition. +/// \param name name of the queue +/// \param queue_sz maximum number of messages in queue +/// \param type data type of a single message element +/// \note CAN BE CHANGED: The parameter to \b osMailQDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osMailQDef(name, queue_sz, type) \ +extern osMailQDef_t os_mailQ_def_##name +#else // define the object +#define osMailQDef(name, queue_sz, type) \ +uint32_t os_mailQ_q_##name[4+(queue_sz)]; \ +uint32_t os_mailQ_m_##name[3+((sizeof(type)+3)/4)*(queue_sz)]; \ +void * os_mailQ_p_##name[2] = { (os_mailQ_q_##name), os_mailQ_m_##name }; \ +osMailQDef_t os_mailQ_def_##name = \ +{ (queue_sz), sizeof(type), (os_mailQ_p_##name) } +#endif + +/// \brief Access a Mail Queue Definition. +/// \param name name of the queue +/// \note CAN BE CHANGED: The parameter to \b osMailQ shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osMailQ(name) \ +&os_mailQ_def_##name + +/// Create and Initialize mail queue. +/// \param[in] queue_def reference to the mail queue definition obtain with \ref osMailQ +/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. +/// \return mail queue ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMailCreate shall be consistent in every CMSIS-RTOS. +osMailQId osMailCreate (osMailQDef_t *queue_def, osThreadId thread_id); + +/// Allocate a memory block from a mail. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return pointer to memory block that can be filled with mail or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMailAlloc shall be consistent in every CMSIS-RTOS. +void *osMailAlloc (osMailQId queue_id, uint32_t millisec); + +/// Allocate a memory block from a mail and set memory block to zero. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return pointer to memory block that can be filled with mail or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMailCAlloc shall be consistent in every CMSIS-RTOS. +void *osMailCAlloc (osMailQId queue_id, uint32_t millisec); + +/// Put a mail to a queue. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMailPut shall be consistent in every CMSIS-RTOS. +osStatus osMailPut (osMailQId queue_id, void *mail); + +/// Get a mail from a queue. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return event that contains mail information or error code. +/// \note MUST REMAIN UNCHANGED: \b osMailGet shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec); + +/// Free a memory block from a mail. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] mail pointer to the memory block that was obtained with \ref osMailGet. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMailFree shall be consistent in every CMSIS-RTOS. +osStatus osMailFree (osMailQId queue_id, void *mail); + +#endif // Mail Queues available + + +#ifdef __cplusplus +} +#endif + +#endif // _CMSIS_OS_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/os_tcb.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,55 @@ +#ifndef OS_TCB_H +#define OS_TCB_H + +/* Types */ +typedef char S8; +typedef unsigned char U8; +typedef short S16; +typedef unsigned short U16; +typedef int S32; +typedef unsigned int U32; +typedef long long S64; +typedef unsigned long long U64; +typedef unsigned char BIT; +typedef unsigned int BOOL; +typedef void (*FUNCP)(void); +#define TCB_STACK_LR_OFFSET_BYTES (14*4) // prelast DWORD +#define TCB_STACK_LR_OFFSET_DWORDS (14) // prelast DWORD +#define TCB_STACK_R0_OFFSET_BYTES (1*4) // second DWORD +#define TCB_STACK_R0_OFFSET_DWORDS (1) // second DWORD + +typedef struct OS_TCB { + /* General part: identical for all implementations. */ + U8 cb_type; /* Control Block Type */ + U8 state; /* Task state */ + U8 prio; /* Execution priority */ + U8 task_id; /* Task ID value for optimized TCB access */ + struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */ + struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */ + struct OS_TCB *p_dlnk; /* Link pointer for delay list */ + struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */ + U16 delta_time; /* Time until time out */ + U16 interval_time; /* Time interval for periodic waits */ + U16 events; /* Event flags */ + U16 waits; /* Wait flags */ + void **msg; /* Direct message passing when task waits */ + + /* Hardware dependant part: specific for CM processor */ + U8 stack_frame; /* Stack frame: 0=Basic, 1=Extended */ + U8 reserved1; + U16 reserved2; + U32 priv_stack; /* Private stack size in bytes */ + U32 tsk_stack; /* Current task Stack pointer (R13) */ + U32 *stack; /* Pointer to Task Stack memory block */ + + /* Library dependant part */ +#if defined (__CC_ARM) && !defined (__MICROLIB) + /* A memory space for arm standard library. */ + U32 std_libspace[96/4]; +#endif + + /* Task entry point used for uVision debugger */ + FUNCP ptask; /* Task entry address */ +} *P_TCB; + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_CMSIS.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,1853 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: rt_CMSIS.c + * Purpose: CMSIS RTOS API + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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 + +#include "core_arm7.h" + +#include "rt_TypeDef.h" +#include "RTX_Conf.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_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_osStatus __r0 +#define RET_osPriority __r0 +#define RET_osEvent {(osStatus)__r0, {(uint32_t)__r1}, {(void *)__r2}} +#define RET_osCallback {(void *)__r0, (void *)__r1} + +#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} + +#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)) || defined (__CORTEX_M0PLUS) +#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 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 RET_osEvent osEvent +#define RET_osCallback osCallback + +#define SVC_Setup(f) \ + __asm( \ + "mov r12,%0\n" \ + :: "r"(&f): "r12" \ + ); + + +#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 SVC_1_1 +#define SVC_1_3 SVC_1_1 +#define SVC_2_3 SVC_2_1 + +#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 Timers external resources +extern osThreadDef_t os_thread_def_osTimerThread; +extern osThreadId osThreadId_osTimerThread; +extern osMessageQDef_t os_messageQ_def_osTimerMessageQ; +extern osMessageQId osMessageQId_osTimerMessageQ; + + +// ==== 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; +} + + +// ==== 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) + +extern void sysThreadError (osStatus status); +osThreadId svcThreadCreate (osThreadDef_t *thread_def, void *argument); +osMessageQId svcMessageCreate (osMessageQDef_t *queue_def, osThreadId thread_id); + +// Kernel Control Service Calls + +/// Initialize the RTOS Kernel for creating objects +osStatus svcKernelInitialize (void) { + if (os_initialized) return osOK; + + rt_sys_init(); // RTX System Initialization + os_tsk.run->prio = 255; // Highest priority + + sysThreadError(osOK); + + os_initialized = 1; + + return osOK; +} + +/// Start the RTOS Kernel +osStatus svcKernelStart (void) { + + if (os_running) return osOK; + + // Create OS Timers resources (Message Queue & Thread) + osMessageQId_osTimerMessageQ = svcMessageCreate (&os_messageQ_def_osTimerMessageQ, NULL); + osThreadId_osTimerThread = svcThreadCreate(&os_thread_def_osTimerThread, NULL); + + rt_tsk_prio(0, 0); // Lowest priority +// __set_SP(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 (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + if (__get_CONTROL() == MODE_SUPERVISOR) { // Privileged mode + return svcKernelInitialize(); + } else { + return __svcKernelInitialize(); + } +} + +/// Start the RTOS Kernel +osStatus osKernelStart (void) { + + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + switch (__get_CONTROL()) { + case MODE_SUPERVISOR: // Privileged mode + break; + case MODE_USER: + case MODE_SYSTEM: // Unprivileged mode + return osErrorOS; + default: // Other invalid modes + return osErrorOS; + break; + } + return svcKernelStart(); +} + +/// Check if the RTOS kernel is already started +int32_t osKernelRunning(void) { + if ((__get_CONTROL() == MODE_IRQ) || (__get_CONTROL() == MODE_SUPERVISOR)) { + // in ISR or Privileged + return os_running; + } else { + return __svcKernelRunning(); + } +} + + +// ==== Thread Management ==== + +__NO_RETURN void osThreadExit (void); + +// Thread Service Calls declarations +SVC_2_1(svcThreadCreate, osThreadId, 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 +extern OS_TID rt_get_TID (void); +extern void rt_init_context (P_TCB p_TCB, U8 priority, FUNCP task_body); + +/// Create a thread and add it to Active Threads and set it to state READY +osThreadId svcThreadCreate (osThreadDef_t *thread_def, void *argument) { + P_TCB ptcb; + + if ((thread_def == NULL) || + (thread_def->pthread == NULL) || + (thread_def->tpriority < osPriorityIdle) || + (thread_def->tpriority > osPriorityRealtime) || + (thread_def->stacksize == 0) || + (thread_def->stack_pointer == NULL) ) { + sysThreadError(osErrorParameter); + return NULL; + } + + U8 priority = thread_def->tpriority - osPriorityIdle + 1; + P_TCB task_context = &thread_def->tcb; + + /* Utilize the user provided stack. */ + task_context->stack = (U32*)thread_def->stack_pointer; + task_context->priv_stack = thread_def->stacksize; + /* Find a free entry in 'os_active_TCB' table. */ + OS_TID tsk = rt_get_TID (); + os_active_TCB[tsk-1] = task_context; + task_context->task_id = tsk; + /* Pass parameter 'argv' to 'rt_init_context' */ + task_context->msg = argument; + /* For 'size == 0' system allocates the user stack from the memory pool. */ + rt_init_context (task_context, priority, (FUNCP)thread_def->pthread); + + /* Dispatch this task to the scheduler for execution. */ + DBG_TASK_NOTIFY(task_context, __TRUE); + rt_dispatch (task_context); + + ptcb = (P_TCB)os_active_TCB[tsk - 1]; // TCB pointer + + *((uint32_t *)ptcb->tsk_stack + TCB_STACK_LR_OFFSET_DWORDS) = (uint32_t)osThreadExit; /* LR = 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; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) return osErrorParameter; + + res = rt_tsk_delete(ptcb->task_id); // Delete task + + if (res == OS_R_NOK) return osErrorResource; // Delete task failed + + 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 (osThreadDef_t *thread_def, void *argument) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (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 (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + return __svcThreadGetId(); +} + +/// Terminate execution of a thread and remove it from ActiveThreads +osStatus osThreadTerminate (osThreadId thread_id) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcThreadTerminate(thread_id); +} + +/// Pass control to next thread that is in state READY +osStatus osThreadYield (void) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcThreadYield(); +} + +/// Change priority of an active thread +osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcThreadSetPriority(thread_id, priority); +} + +/// Get current priority of an active thread +osPriority osThreadGetPriority (osThreadId thread_id) { + if (__get_CONTROL() == MODE_IRQ) 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 +} + + +// ==== 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; + return osEvent_ret_status; + } + + /* To Do: osEventSignal, osEventMessage, osEventMail */ + rt_dly_wait(rt_ms2tick(millisec)); + ret.status = osEventTimeout; + + return osEvent_ret_status; +} +#endif + + +// Generic Wait API + +/// Wait for Timeout (Time Delay) +osStatus osDelay (uint32_t millisec) { + if (__get_CONTROL() == MODE_IRQ) 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 (__get_CONTROL() == MODE_IRQ) { // 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 + 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, 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 (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; + return osCallback_ret; + } + + ret.fp = (void *)pt->timer->ptimer; + ret.arg = pt->arg; + + return osCallback_ret; +} + +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 (osTimerDef_t *timer_def, os_timer_type type, void *argument) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (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 (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcTimerStart(timer_id, millisec); +} + +/// Stop timer +osStatus osTimerStop (osTimerId timer_id) { + if (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcTimerStop(timer_id); +} + +/// Delete timer +osStatus osTimerDelete (osTimerId timer_id) { + if (__get_CONTROL() == MODE_IRQ) 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; + return osEvent_ret_status; + } + + 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; + } + + return osEvent_ret_value; +} + + +// 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 (__get_CONTROL() == MODE_IRQ) { // 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 (__get_CONTROL() == MODE_IRQ) 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 (__get_CONTROL() == MODE_IRQ) 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 (__get_CONTROL() == MODE_IRQ) { // Not allowed in ISR + ret.status = osErrorISR; + return ret; + } + return __svcSignalWait(signals, millisec); +} + + +// ==== Mutex Management ==== + +// Mutex Service Calls declarations +SVC_1_1(svcMutexCreate, osMutexId, 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 (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 (osMutexDef_t *mutex_def) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (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 (__get_CONTROL() == MODE_IRQ) 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 (__get_CONTROL() == MODE_IRQ) return osErrorISR; // Not allowed in ISR + return __svcMutexRelease(mutex_id); +} + +/// Delete a Mutex that was created by osMutexCreate +osStatus osMutexDelete (osMutexId mutex_id) { + if (__get_CONTROL() == MODE_IRQ) 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 (osSemaphoreDef_t *semaphore_def, int32_t count) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (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 (__get_CONTROL() == MODE_IRQ) return -1; // Not allowed in ISR + return __svcSemaphoreWait(semaphore_id, millisec); +} + +/// Release a Semaphore +osStatus osSemaphoreRelease (osSemaphoreId semaphore_id) { + if (__get_CONTROL() == MODE_IRQ) { // 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 (__get_CONTROL() == MODE_IRQ) 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 (osPoolDef_t *pool_def) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (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_CONTROL() == MODE_IRQ) || (__get_CONTROL() == MODE_SUPERVISOR)) { // 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_CONTROL() == MODE_IRQ) || (__get_CONTROL() == MODE_SUPERVISOR)) { // 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_CONTROL() == MODE_IRQ) || (__get_CONTROL() == MODE_SUPERVISOR)) { // 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, 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 (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; + return osEvent_ret_status; + } + + if (((P_MCB)queue_id)->cb_type != MCB) { + ret.status = osErrorParameter; + return osEvent_ret_status; + } + + res = rt_mbx_wait(queue_id, &ret.value.p, rt_ms2tick(millisec)); + + if (res == OS_R_TMO) { + ret.status = millisec ? osEventTimeout : osOK; + return osEvent_ret_value; + } + + ret.status = osEventMessage; + + return osEvent_ret_value; +} + + +// 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 (osMessageQDef_t *queue_def, osThreadId thread_id) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (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 (__get_CONTROL() == MODE_IRQ) { // 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 (__get_CONTROL() == MODE_IRQ) { // 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, 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 (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 (osMailQDef_t *queue_def, osThreadId thread_id) { + if (__get_CONTROL() == MODE_IRQ) return NULL; // Not allowed in ISR + if ((__get_CONTROL() == MODE_SUPERVISOR) && (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 (__get_CONTROL() == MODE_IRQ) { // 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 (__get_CONTROL() == MODE_IRQ) { // 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 (__get_CONTROL() == MODE_IRQ) { // 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); +} + +/// 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; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Event.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,190 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_EVENT.C + * Purpose: Implements waits and wake-ups for event flags + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_evt_wait -----------------------------------*/ + +OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait) { + /* Wait for one or more event flags with optional time-out. */ + /* "wait_flags" identifies the flags to wait for. */ + /* "timeout" is the time-out limit in system ticks (0xffff if no time-out) */ + /* "and_wait" specifies the AND-ing of "wait_flags" as condition to be met */ + /* to complete the wait. (OR-ing if set to 0). */ + U32 block_state; + + if (and_wait) { + /* Check for AND-connected events */ + if ((os_tsk.run->events & wait_flags) == wait_flags) { + os_tsk.run->events &= ~wait_flags; + return (OS_R_EVT); + } + block_state = WAIT_AND; + } + else { + /* Check for OR-connected events */ + if (os_tsk.run->events & wait_flags) { + os_tsk.run->waits = os_tsk.run->events & wait_flags; + os_tsk.run->events &= ~wait_flags; + return (OS_R_EVT); + } + block_state = WAIT_OR; + } + /* Task has to wait */ + os_tsk.run->waits = wait_flags; + rt_block (timeout, (U8)block_state); + return (OS_R_TMO); +} + + +/*--------------------------- rt_evt_set ------------------------------------*/ + +void rt_evt_set (U16 event_flags, OS_TID task_id) { + /* Set one or more event flags of a selectable task. */ + P_TCB p_tcb; + + p_tcb = os_active_TCB[task_id-1]; + if (p_tcb == NULL) { + return; + } + p_tcb->events |= event_flags; + event_flags = p_tcb->waits; + /* If the task is not waiting for an event, it should not be put */ + /* to ready state. */ + if (p_tcb->state == WAIT_AND) { + /* Check for AND-connected events */ + if ((p_tcb->events & event_flags) == event_flags) { + goto wkup; + } + } + if (p_tcb->state == WAIT_OR) { + /* Check for OR-connected events */ + if (p_tcb->events & event_flags) { + p_tcb->waits &= p_tcb->events; +wkup: p_tcb->events &= ~event_flags; + rt_rmv_dly (p_tcb); + p_tcb->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val2(p_tcb, 0x08/*osEventSignal*/, p_tcb->waits); +#else + rt_ret_val (p_tcb, OS_R_EVT); +#endif + rt_dispatch (p_tcb); + } + } +} + + +/*--------------------------- rt_evt_clr ------------------------------------*/ + +void rt_evt_clr (U16 clear_flags, OS_TID task_id) { + /* Clear one or more event flags (identified by "clear_flags") of a */ + /* selectable task (identified by "task"). */ + P_TCB task = os_active_TCB[task_id-1]; + + if (task == NULL) { + return; + } + task->events &= ~clear_flags; +} + + +/*--------------------------- isr_evt_set -----------------------------------*/ + +void isr_evt_set (U16 event_flags, OS_TID task_id) { + /* Same function as "os_evt_set", but to be called by ISRs. */ + P_TCB p_tcb = os_active_TCB[task_id-1]; + + if (p_tcb == NULL) { + return; + } + rt_psq_enq (p_tcb, event_flags); + rt_psh_req (); +} + + +/*--------------------------- rt_evt_get ------------------------------------*/ + +U16 rt_evt_get (void) { + /* Get events of a running task after waiting for OR connected events. */ + return (os_tsk.run->waits); +} + + +/*--------------------------- rt_evt_psh ------------------------------------*/ + +void rt_evt_psh (P_TCB p_CB, U16 set_flags) { + /* Check if task has to be waken up */ + U16 event_flags; + + p_CB->events |= set_flags; + event_flags = p_CB->waits; + if (p_CB->state == WAIT_AND) { + /* Check for AND-connected events */ + if ((p_CB->events & event_flags) == event_flags) { + goto rdy; + } + } + if (p_CB->state == WAIT_OR) { + /* Check for OR-connected events */ + if (p_CB->events & event_flags) { + p_CB->waits &= p_CB->events; +rdy: p_CB->events &= ~event_flags; + rt_rmv_dly (p_CB); + p_CB->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val2(p_CB, 0x08/*osEventSignal*/, p_CB->waits); +#else + rt_ret_val (p_CB, OS_R_EVT); +#endif + rt_put_prio (&os_rdy, p_CB); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Event.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_EVENT.H + * Purpose: Implements waits and wake-ups for event flags + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait); +extern void rt_evt_set (U16 event_flags, OS_TID task_id); +extern void rt_evt_clr (U16 clear_flags, OS_TID task_id); +extern void isr_evt_set (U16 event_flags, OS_TID task_id); +extern U16 rt_evt_get (void); +extern void rt_evt_psh (P_TCB p_CB, U16 set_flags); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_HAL_CM.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,216 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_HAL_CM.H + * Purpose: Hardware Abstraction Layer for Cortex-M definitions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "cmsis.h" +/* Definitions */ +#define INITIAL_xPSR 0x10000000 +#define DEMCR_TRCENA 0x01000000 +#define ITM_ITMENA 0x00000001 +#define MAGIC_WORD 0xE25A2EA5 + +#define SYS_TICK_IRQn TIMER0_IRQn + +extern void rt_set_PSP (U32 stack); +extern U32 rt_get_PSP (void); +extern void os_set_env (void); +extern void SysTick_Handler (void); +extern void *_alloc_box (void *box_mem); +extern int _free_box (void *box_mem, void *box); + +extern void rt_init_stack (P_TCB p_TCB, FUNCP task_body); +extern void rt_ret_val (P_TCB p_TCB, U32 v0); +extern void rt_ret_val2 (P_TCB p_TCB, U32 v0, U32 v1); + +extern void dbg_init (void); +extern void dbg_task_notify (P_TCB p_tcb, BOOL create); +extern void dbg_task_switch (U32 task_id); + + +#if defined (__CC_ARM) /* ARM Compiler */ + +#if ((__TARGET_ARCH_7_M || __TARGET_ARCH_7E_M) && !NO_EXCLUSIVE_ACCESS) + #define __USE_EXCLUSIVE_ACCESS +#else + #undef __USE_EXCLUSIVE_ACCESS +#endif + +#elif defined (__GNUC__) /* GNU Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if defined (__CORTEX_M0) || defined (__CORTEX_M0PLUS) +#define __TARGET_ARCH_6S_M 1 +#else +#define __TARGET_ARCH_6S_M 0 +#endif + +#if defined (__VFP_FP__) && !defined(__SOFTFP__) +#define __TARGET_FPU_VFP 1 +#else +#define __TARGET_FPU_VFP 0 +#endif + +#define __inline inline +#define __weak __attribute__((weak)) + + +#elif defined (__ICCARM__) /* IAR Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if (__CORE__ == __ARM6M__) +#define __TARGET_ARCH_6S_M 1 +#else +#define __TARGET_ARCH_6S_M 0 +#endif + +#if defined __ARMVFP__ +#define __TARGET_FPU_VFP 1 +#else +#define __TARGET_FPU_VFP 0 +#endif + +#define __inline inline + +#endif + + +/* NVIC registers */ + +#define OS_PEND_IRQ() NVIC_PendIRQ(SYS_TICK_IRQn) +#define OS_PENDING NVIC_PendingIRQ(SYS_TICK_IRQn) +#define OS_UNPEND(fl) NVIC_UnpendIRQ(SYS_TICK_IRQn) +#define OS_PEND(fl,p) NVIC_PendIRQ(SYS_TICK_IRQn) +#define OS_LOCK() NVIC_DisableIRQ(SYS_TICK_IRQn) +#define OS_UNLOCK() NVIC_EnableIRQ(SYS_TICK_IRQn) + +#define OS_X_PENDING NVIC_PendingIRQ(SYS_TICK_IRQn) +#define OS_X_UNPEND(fl) NVIC_UnpendIRQ(SYS_TICK_IRQn) +#define OS_X_PEND(fl,p) NVIC_PendIRQ(SYS_TICK_IRQn) + +#define OS_X_INIT(n) NVIC_EnableIRQ(n) +#define OS_X_LOCK(n) NVIC_DisableIRQ(n) +#define OS_X_UNLOCK(n) NVIC_EnableIRQ(n) + +/* Variables */ +extern BIT dbg_msg; + +/* Functions */ +#ifdef __USE_EXCLUSIVE_ACCESS + #define rt_inc(p) while(__strex((__ldrex(p)+1),p)) + #define rt_dec(p) while(__strex((__ldrex(p)-1),p)) +#else + #define rt_inc(p) __disable_irq();(*p)++;__enable_irq(); + #define rt_dec(p) __disable_irq();(*p)--;__enable_irq(); +#endif + +__inline static U32 rt_inc_qi (U32 size, U8 *count, U8 *first) { + U32 cnt,c2; +#ifdef __USE_EXCLUSIVE_ACCESS + do { + if ((cnt = __ldrex(count)) == size) { + __clrex(); + return (cnt); } + } while (__strex(cnt+1, count)); + do { + c2 = (cnt = __ldrex(first)) + 1; + if (c2 == size) c2 = 0; + } while (__strex(c2, first)); +#else + __disable_irq(); + if ((cnt = *count) < size) { + *count = cnt+1; + c2 = (cnt = *first) + 1; + if (c2 == size) c2 = 0; + *first = c2; + } + __enable_irq (); +#endif + return (cnt); +} + +__inline static void rt_systick_init (void) { +#if SYS_TICK_IRQn == TIMER0_IRQn + #define SYS_TICK_TIMER LPC_TIM0 + LPC_SC->PCONP |= (1 << PCTIM0); + LPC_SC->PCLKSEL0 = (LPC_SC->PCLKSEL0 & (~(1<<3))) | (1<<2); //PCLK == CPUCLK +#elif SYS_TICK_IRQn == TIMER1_IRQn + #define SYS_TICK_TIMER LPC_TIM1 + LPC_SC->PCONP |= (1 << PCTIM1); + LPC_SC->PCLKSEL0 = (LPC_SC->PCLKSEL0 & (~(1<<5))) | (1<<4); //PCLK == CPUCLK +#elif SYS_TICK_IRQn == TIMER2_IRQn + #define SYS_TICK_TIMER LPC_TIM2 + LPC_SC->PCONP |= (1 << PCTIM2); + LPC_SC->PCLKSEL1 = (LPC_SC->PCLKSEL1 & (~(1<<13))) | (1<<12); //PCLK == CPUCLK +#else + #define SYS_TICK_TIMER LPC_TIM3 + LPC_SC->PCONP |= (1 << PCTIM3); + LPC_SC->PCLKSEL1 = (LPC_SC->PCLKSEL1 & (~(1<<15))) | (1<<14); //PCLK == CPUCLK +#endif + + // setup Timer to count forever + //interrupt_reg + SYS_TICK_TIMER->TCR = 2; // reset & disable timer 0 + SYS_TICK_TIMER->TC = os_trv; + SYS_TICK_TIMER->PR = 0; // set the prescale divider + //Reset of TC and Interrupt when MR3 MR2 matches TC + SYS_TICK_TIMER->MCR = (1 << 9) |(1 << 10); //TMCR_MR3_R_Msk | TMCR_MR3_I_Msk + SYS_TICK_TIMER->MR3 = os_trv; // match registers + SYS_TICK_TIMER->CCR = 0; // disable compare registers + SYS_TICK_TIMER->EMR = 0; // disable external match register + // initialize the interrupt vector + NVIC_SetVector(SYS_TICK_IRQn, (uint32_t)&SysTick_Handler); + SYS_TICK_TIMER->TCR = 1; // enable timer 0 +} + +__inline static void rt_svc_init (void) { +// TODO: add svcInit + +} + +#ifdef DBG_MSG +#define DBG_INIT() dbg_init() +#define DBG_TASK_NOTIFY(p_tcb,create) if (dbg_msg) dbg_task_notify(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) if (dbg_msg && (os_tsk.new_tsk != os_tsk.run)) \ + dbg_task_switch(task_id) +#else +#define DBG_INIT() +#define DBG_TASK_NOTIFY(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_List.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,320 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_LIST.C + * Purpose: Functions for the management of different lists + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Time.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* List head of chained ready tasks */ +struct OS_XCB os_rdy; +/* List head of chained delay tasks */ +struct OS_XCB os_dly; + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_put_prio -----------------------------------*/ + +void rt_put_prio (P_XCB p_CB, P_TCB p_task) { + /* Put task identified with "p_task" into list ordered by priority. */ + /* "p_CB" points to head of list; list has always an element at end with */ + /* a priority less than "p_task->prio". */ + P_TCB p_CB2; + U32 prio; + BOOL sem_mbx = __FALSE; + + if (p_CB->cb_type == SCB || p_CB->cb_type == MCB || p_CB->cb_type == MUCB) { + sem_mbx = __TRUE; + } + prio = p_task->prio; + p_CB2 = p_CB->p_lnk; + /* Search for an entry in the list */ + while (p_CB2 != NULL && prio <= p_CB2->prio) { + p_CB = (P_XCB)p_CB2; + p_CB2 = p_CB2->p_lnk; + } + /* Entry found, insert the task into the list */ + p_task->p_lnk = p_CB2; + p_CB->p_lnk = p_task; + if (sem_mbx) { + if (p_CB2 != NULL) { + p_CB2->p_rlnk = p_task; + } + p_task->p_rlnk = (P_TCB)p_CB; + } + else { + p_task->p_rlnk = NULL; + } +} + + +/*--------------------------- rt_get_first ----------------------------------*/ + +P_TCB rt_get_first (P_XCB p_CB) { + /* Get task at head of list: it is the task with highest priority. */ + /* "p_CB" points to head of list. */ + P_TCB p_first; + + p_first = p_CB->p_lnk; + p_CB->p_lnk = p_first->p_lnk; + if (p_CB->cb_type == SCB || p_CB->cb_type == MCB || p_CB->cb_type == MUCB) { + if (p_first->p_lnk != NULL) { + p_first->p_lnk->p_rlnk = (P_TCB)p_CB; + p_first->p_lnk = NULL; + } + p_first->p_rlnk = NULL; + } + else { + p_first->p_lnk = NULL; + } + return (p_first); +} + + +/*--------------------------- rt_put_rdy_first ------------------------------*/ + +void rt_put_rdy_first (P_TCB p_task) { + /* Put task identified with "p_task" at the head of the ready list. The */ + /* task must have at least a priority equal to highest priority in list. */ + p_task->p_lnk = os_rdy.p_lnk; + p_task->p_rlnk = NULL; + os_rdy.p_lnk = p_task; +} + + +/*--------------------------- rt_get_same_rdy_prio --------------------------*/ + +P_TCB rt_get_same_rdy_prio (void) { + /* Remove a task of same priority from ready list if any exists. Other- */ + /* wise return NULL. */ + P_TCB p_first; + + p_first = os_rdy.p_lnk; + if (p_first->prio == os_tsk.run->prio) { + os_rdy.p_lnk = os_rdy.p_lnk->p_lnk; + return (p_first); + } + return (NULL); +} + + +/*--------------------------- rt_resort_prio --------------------------------*/ + +void rt_resort_prio (P_TCB p_task) { + /* Re-sort ordered lists after the priority of 'p_task' has changed. */ + P_TCB p_CB; + + if (p_task->p_rlnk == NULL) { + if (p_task->state == READY) { + /* Task is chained into READY list. */ + p_CB = (P_TCB)&os_rdy; + goto res; + } + } + else { + p_CB = p_task->p_rlnk; + while (p_CB->cb_type == TCB) { + /* Find a header of this task chain list. */ + p_CB = p_CB->p_rlnk; + } +res:rt_rmv_list (p_task); + rt_put_prio ((P_XCB)p_CB, p_task); + } +} + + +/*--------------------------- rt_put_dly ------------------------------------*/ + +void rt_put_dly (P_TCB p_task, U16 delay) { + /* Put a task identified with "p_task" into chained delay wait list using */ + /* a delay value of "delay". */ + P_TCB p; + U32 delta,idelay = delay; + + p = (P_TCB)&os_dly; + if (p->p_dlnk == NULL) { + /* Delay list empty */ + delta = 0; + goto last; + } + delta = os_dly.delta_time; + while (delta < idelay) { + if (p->p_dlnk == NULL) { + /* End of list found */ +last: p_task->p_dlnk = NULL; + p->p_dlnk = p_task; + p_task->p_blnk = p; + p->delta_time = (U16)(idelay - delta); + p_task->delta_time = 0; + return; + } + p = p->p_dlnk; + delta += p->delta_time; + } + /* Right place found */ + p_task->p_dlnk = p->p_dlnk; + p->p_dlnk = p_task; + p_task->p_blnk = p; + if (p_task->p_dlnk != NULL) { + p_task->p_dlnk->p_blnk = p_task; + } + p_task->delta_time = (U16)(delta - idelay); + p->delta_time -= p_task->delta_time; +} + + +/*--------------------------- rt_dec_dly ------------------------------------*/ + +void rt_dec_dly (void) { + /* Decrement delta time of list head: remove tasks having a value of zero.*/ + P_TCB p_rdy; + + if (os_dly.p_dlnk == NULL) { + return; + } + os_dly.delta_time--; + while ((os_dly.delta_time == 0) && (os_dly.p_dlnk != NULL)) { + p_rdy = os_dly.p_dlnk; + if (p_rdy->p_rlnk != NULL) { + /* Task is really enqueued, remove task from semaphore/mailbox */ + /* timeout waiting list. */ + p_rdy->p_rlnk->p_lnk = p_rdy->p_lnk; + if (p_rdy->p_lnk != NULL) { + p_rdy->p_lnk->p_rlnk = p_rdy->p_rlnk; + p_rdy->p_lnk = NULL; + } + p_rdy->p_rlnk = NULL; + } + rt_put_prio (&os_rdy, p_rdy); + os_dly.delta_time = p_rdy->delta_time; + if (p_rdy->state == WAIT_ITV) { + /* Calculate the next time for interval wait. */ + p_rdy->delta_time = p_rdy->interval_time + (U16)os_time; + } + p_rdy->state = READY; + os_dly.p_dlnk = p_rdy->p_dlnk; + if (p_rdy->p_dlnk != NULL) { + p_rdy->p_dlnk->p_blnk = (P_TCB)&os_dly; + p_rdy->p_dlnk = NULL; + } + p_rdy->p_blnk = NULL; + } +} + + +/*--------------------------- rt_rmv_list -----------------------------------*/ + +void rt_rmv_list (P_TCB p_task) { + /* Remove task identified with "p_task" from ready, semaphore or mailbox */ + /* waiting list if enqueued. */ + P_TCB p_b; + + if (p_task->p_rlnk != NULL) { + /* A task is enqueued in semaphore / mailbox waiting list. */ + p_task->p_rlnk->p_lnk = p_task->p_lnk; + if (p_task->p_lnk != NULL) { + p_task->p_lnk->p_rlnk = p_task->p_rlnk; + } + return; + } + + p_b = (P_TCB)&os_rdy; + while (p_b != NULL) { + /* Search the ready list for task "p_task" */ + if (p_b->p_lnk == p_task) { + p_b->p_lnk = p_task->p_lnk; + return; + } + p_b = p_b->p_lnk; + } +} + + +/*--------------------------- rt_rmv_dly ------------------------------------*/ + +void rt_rmv_dly (P_TCB p_task) { + /* Remove task identified with "p_task" from delay list if enqueued. */ + P_TCB p_b; + + p_b = p_task->p_blnk; + if (p_b != NULL) { + /* Task is really enqueued */ + p_b->p_dlnk = p_task->p_dlnk; + if (p_task->p_dlnk != NULL) { + /* 'p_task' is in the middle of list */ + p_b->delta_time += p_task->delta_time; + p_task->p_dlnk->p_blnk = p_b; + p_task->p_dlnk = NULL; + } + else { + /* 'p_task' is at the end of list */ + p_b->delta_time = 0; + } + p_task->p_blnk = NULL; + } +} + + +/*--------------------------- rt_psq_enq ------------------------------------*/ + +void rt_psq_enq (OS_ID entry, U32 arg) { + /* Insert post service request "entry" into ps-queue. */ + U32 idx; + + idx = rt_inc_qi (os_psq->size, &os_psq->count, &os_psq->first); + if (idx < os_psq->size) { + os_psq->q[idx].id = entry; + os_psq->q[idx].arg = arg; + } + else { + os_error (OS_ERR_FIFO_OVF); + } +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_List.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,67 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_LIST.H + * Purpose: Functions for the management of different lists + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Definitions */ + +/* Values for 'cb_type' */ +#define TCB 0 +#define MCB 1 +#define SCB 2 +#define MUCB 3 +#define HCB 4 + +/* Variables */ +extern struct OS_XCB os_rdy; +extern struct OS_XCB os_dly; + +/* Functions */ +extern void rt_put_prio (P_XCB p_CB, P_TCB p_task); +extern P_TCB rt_get_first (P_XCB p_CB); +extern void rt_put_rdy_first (P_TCB p_task); +extern P_TCB rt_get_same_rdy_prio (void); +extern void rt_resort_prio (P_TCB p_task); +extern void rt_put_dly (P_TCB p_task, U16 delay); +extern void rt_dec_dly (void); +extern void rt_rmv_list (P_TCB p_task); +extern void rt_rmv_dly (P_TCB p_task); +extern void rt_psq_enq (OS_ID entry, U32 arg); + +/* This is a fast macro generating in-line code */ +#define rt_rdy_prio(void) (os_rdy.p_lnk->prio) + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Mailbox.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,292 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MAILBOX.C + * Purpose: Implements waits and wake-ups for mailbox messages + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Mailbox.h" +#include "rt_MemBox.h" +#include "rt_Task.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_mbx_init -----------------------------------*/ + +void rt_mbx_init (OS_ID mailbox, U16 mbx_size) { + /* Initialize a mailbox */ + P_MCB p_MCB = mailbox; + + p_MCB->cb_type = MCB; + p_MCB->state = 0; + p_MCB->isr_st = 0; + p_MCB->p_lnk = NULL; + p_MCB->first = 0; + p_MCB->last = 0; + p_MCB->count = 0; + p_MCB->size = (mbx_size + sizeof(void *) - sizeof(struct OS_MCB)) / + (U32)sizeof (void *); +} + + +/*--------------------------- rt_mbx_send -----------------------------------*/ + +OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout) { + /* Send message to a mailbox */ + P_MCB p_MCB = mailbox; + P_TCB p_TCB; + + if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 1)) { + /* A task is waiting for message */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val2(p_TCB, 0x10/*osEventMessage*/, (U32)p_msg); +#else + *p_TCB->msg = p_msg; + rt_ret_val (p_TCB, OS_R_MBX); +#endif + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + /* Store message in mailbox queue */ + if (p_MCB->count == p_MCB->size) { + /* No free message entry, wait for one. If message queue is full, */ + /* then no task is waiting for message. The 'p_MCB->p_lnk' list */ + /* pointer can now be reused for send message waits task list. */ + if (timeout == 0) { + return (OS_R_TMO); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + /* Task is waiting to send a message */ + p_MCB->state = 2; + } + os_tsk.run->msg = p_msg; + rt_block (timeout, WAIT_MBX); + return (OS_R_TMO); + } + /* Yes, there is a free entry in a mailbox. */ + p_MCB->msg[p_MCB->first] = p_msg; + rt_inc (&p_MCB->count); + if (++p_MCB->first == p_MCB->size) { + p_MCB->first = 0; + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mbx_wait -----------------------------------*/ + +OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout) { + /* Receive a message; possibly wait for it */ + P_MCB p_MCB = mailbox; + P_TCB p_TCB; + + /* If a message is available in the fifo buffer */ + /* remove it from the fifo buffer and return. */ + if (p_MCB->count) { + *message = p_MCB->msg[p_MCB->last]; + if (++p_MCB->last == p_MCB->size) { + p_MCB->last = 0; + } + if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 2)) { + /* A task is waiting to send message */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_OK); +#endif + p_MCB->msg[p_MCB->first] = p_TCB->msg; + if (++p_MCB->first == p_MCB->size) { + p_MCB->first = 0; + } + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + rt_dec (&p_MCB->count); + } + return (OS_R_OK); + } + /* No message available: wait for one */ + if (timeout == 0) { + return (OS_R_TMO); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + /* Task is waiting to receive a message */ + p_MCB->state = 1; + } + rt_block(timeout, WAIT_MBX); +#ifndef __CMSIS_RTOS + os_tsk.run->msg = message; +#endif + return (OS_R_TMO); +} + + +/*--------------------------- rt_mbx_check ----------------------------------*/ + +OS_RESULT rt_mbx_check (OS_ID mailbox) { + /* Check for free space in a mailbox. Returns the number of messages */ + /* that can be stored to a mailbox. It returns 0 when mailbox is full. */ + P_MCB p_MCB = mailbox; + + return (p_MCB->size - p_MCB->count); +} + + +/*--------------------------- isr_mbx_send ----------------------------------*/ + +void isr_mbx_send (OS_ID mailbox, void *p_msg) { + /* Same function as "os_mbx_send", but to be called by ISRs. */ + P_MCB p_MCB = mailbox; + + rt_psq_enq (p_MCB, (U32)p_msg); + rt_psh_req (); +} + + +/*--------------------------- isr_mbx_receive -------------------------------*/ + +OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message) { + /* Receive a message in the interrupt function. The interrupt function */ + /* should not wait for a message since this would block the rtx os. */ + P_MCB p_MCB = mailbox; + + if (p_MCB->count) { + /* A message is available in the fifo buffer. */ + *message = p_MCB->msg[p_MCB->last]; + if (p_MCB->state == 2) { + /* A task is locked waiting to send message */ + rt_psq_enq (p_MCB, 0); + rt_psh_req (); + } + rt_dec (&p_MCB->count); + if (++p_MCB->last == p_MCB->size) { + p_MCB->last = 0; + } + return (OS_R_MBX); + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mbx_psh ------------------------------------*/ + +void rt_mbx_psh (P_MCB p_CB, void *p_msg) { + /* Store the message to the mailbox queue or pass it to task directly. */ + P_TCB p_TCB; + void *mem; + + if (p_CB->p_lnk != NULL) switch (p_CB->state) { +#ifdef __CMSIS_RTOS + case 3: + /* Task is waiting to allocate memory, remove it from the waiting list */ + mem = rt_alloc_box(p_msg); + if (mem == NULL) break; + p_TCB = rt_get_first ((P_XCB)p_CB); + rt_ret_val(p_TCB, (U32)mem); + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; +#endif + case 2: + /* Task is waiting to send a message, remove it from the waiting list */ + p_TCB = rt_get_first ((P_XCB)p_CB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_OK); +#endif + p_CB->msg[p_CB->first] = p_TCB->msg; + rt_inc (&p_CB->count); + if (++p_CB->first == p_CB->size) { + p_CB->first = 0; + } + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; + case 1: + /* Task is waiting for a message, pass the message to the task directly */ + p_TCB = rt_get_first ((P_XCB)p_CB); +#ifdef __CMSIS_RTOS + rt_ret_val2(p_TCB, 0x10/*osEventMessage*/, (U32)p_msg); +#else + *p_TCB->msg = p_msg; + rt_ret_val (p_TCB, OS_R_MBX); +#endif + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; + } else { + /* No task is waiting for a message, store it to the mailbox queue */ + if (p_CB->count < p_CB->size) { + p_CB->msg[p_CB->first] = p_msg; + rt_inc (&p_CB->count); + if (++p_CB->first == p_CB->size) { + p_CB->first = 0; + } + } + else { + os_error (OS_ERR_MBX_OVF); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Mailbox.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,48 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MAILBOX.H + * Purpose: Implements waits and wake-ups for mailbox messages + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_mbx_init (OS_ID mailbox, U16 mbx_size); +extern OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout); +extern OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout); +extern OS_RESULT rt_mbx_check (OS_ID mailbox); +extern void isr_mbx_send (OS_ID mailbox, void *p_msg); +extern OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message); +extern void rt_mbx_psh (P_MCB p_CB, void *p_msg); + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_MemBox.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,166 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMBOX.C + * Purpose: Interface functions for fixed memory block management system + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_MemBox.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- _init_box -------------------------------------*/ + +int _init_box (void *box_mem, U32 box_size, U32 blk_size) { + /* Initialize memory block system, returns 0 if OK, 1 if fails. */ + void *end; + void *blk; + void *next; + U32 sizeof_bm; + + /* Create memory structure. */ + if (blk_size & BOX_ALIGN_8) { + /* Memory blocks 8-byte aligned. */ + blk_size = ((blk_size & ~BOX_ALIGN_8) + 7) & ~7; + sizeof_bm = (sizeof (struct OS_BM) + 7) & ~7; + } + else { + /* Memory blocks 4-byte aligned. */ + blk_size = (blk_size + 3) & ~3; + sizeof_bm = sizeof (struct OS_BM); + } + if (blk_size == 0) { + return (1); + } + if ((blk_size + sizeof_bm) > box_size) { + return (1); + } + /* Create a Memory structure. */ + blk = ((U8 *) box_mem) + sizeof_bm; + ((P_BM) box_mem)->free = blk; + end = ((U8 *) box_mem) + box_size; + ((P_BM) box_mem)->end = end; + ((P_BM) box_mem)->blk_size = blk_size; + + /* Link all free blocks using offsets. */ + end = ((U8 *) end) - blk_size; + while (1) { + next = ((U8 *) blk) + blk_size; + if (next > end) break; + *((void **)blk) = next; + blk = next; + } + /* end marker */ + *((void **)blk) = 0; + return (0); +} + +/*--------------------------- rt_alloc_box ----------------------------------*/ + +void *rt_alloc_box (void *box_mem) { + /* Allocate a memory block and return start address. */ + void **free; +#ifndef __USE_EXCLUSIVE_ACCESS + int irq_dis; + + irq_dis = __disable_irq (); + free = ((P_BM) box_mem)->free; + if (free) { + ((P_BM) box_mem)->free = *free; + } + if (!irq_dis) __enable_irq (); +#else + do { + if ((free = (void **)__ldrex(&((P_BM) box_mem)->free)) == 0) { + __clrex(); + break; + } + } while (__strex((U32)*free, &((P_BM) box_mem)->free)); +#endif + return (free); +} + + +/*--------------------------- _calloc_box -----------------------------------*/ + +void *_calloc_box (void *box_mem) { + /* Allocate a 0-initialized memory block and return start address. */ + void *free; + U32 *p; + U32 i; + + free = _alloc_box (box_mem); + if (free) { + p = free; + for (i = ((P_BM) box_mem)->blk_size; i; i -= 4) { + *p = 0; + p++; + } + } + return (free); +} + + +/*--------------------------- rt_free_box -----------------------------------*/ + +int rt_free_box (void *box_mem, void *box) { + /* Free a memory block, returns 0 if OK, 1 if box does not belong to box_mem */ +#ifndef __USE_EXCLUSIVE_ACCESS + int irq_dis; +#endif + + if (box < box_mem || box >= ((P_BM) box_mem)->end) { + return (1); + } + +#ifndef __USE_EXCLUSIVE_ACCESS + irq_dis = __disable_irq (); + *((void **)box) = ((P_BM) box_mem)->free; + ((P_BM) box_mem)->free = box; + if (!irq_dis) __enable_irq (); +#else + do { + *((void **)box) = (void *)__ldrex(&((P_BM) box_mem)->free); + } while (__strex ((U32)box, &((P_BM) box_mem)->free)); +#endif + return (0); +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_MemBox.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMBOX.H + * Purpose: Interface functions for fixed memory block management system + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +#define rt_init_box _init_box +#define rt_calloc_box _calloc_box +extern int _init_box (void *box_mem, U32 box_size, U32 blk_size); +extern void *rt_alloc_box (void *box_mem); +extern void * _calloc_box (void *box_mem); +extern int rt_free_box (void *box_mem, void *box); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Mutex.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,197 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MUTEX.C + * Purpose: Implements mutex synchronization objects + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Mutex.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_mut_init -----------------------------------*/ + +void rt_mut_init (OS_ID mutex) { + /* Initialize a mutex object */ + P_MUCB p_MCB = mutex; + + p_MCB->cb_type = MUCB; + p_MCB->prio = 0; + p_MCB->level = 0; + p_MCB->p_lnk = NULL; + p_MCB->owner = NULL; +} + + +/*--------------------------- rt_mut_delete ---------------------------------*/ + +#ifdef __CMSIS_RTOS +OS_RESULT rt_mut_delete (OS_ID mutex) { + /* Delete a mutex object */ + P_MUCB p_MCB = mutex; + P_TCB p_TCB; + + /* Restore owner task's priority. */ + if (p_MCB->level != 0) { + p_MCB->owner->prio = p_MCB->prio; + if (p_MCB->owner != os_tsk.run) { + rt_resort_prio (p_MCB->owner); + } + } + + while (p_MCB->p_lnk != NULL) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); + rt_ret_val(p_TCB, 0/*osOK*/); + rt_rmv_dly(p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + } + + if (os_rdy.p_lnk && (os_rdy.p_lnk->prio > os_tsk.run->prio)) { + /* preempt running task */ + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + + p_MCB->cb_type = 0; + + return (OS_R_OK); +} +#endif + + +/*--------------------------- rt_mut_release --------------------------------*/ + +OS_RESULT rt_mut_release (OS_ID mutex) { + /* Release a mutex object */ + P_MUCB p_MCB = mutex; + P_TCB p_TCB; + + if (p_MCB->level == 0 || p_MCB->owner != os_tsk.run) { + /* Unbalanced mutex release or task is not the owner */ + return (OS_R_NOK); + } + if (--p_MCB->level != 0) { + return (OS_R_OK); + } + /* Restore owner task's priority. */ + os_tsk.run->prio = p_MCB->prio; + if (p_MCB->p_lnk != NULL) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_MUT); +#endif + rt_rmv_dly (p_TCB); + /* A waiting task becomes the owner of this mutex. */ + p_MCB->level = 1; + p_MCB->owner = p_TCB; + p_MCB->prio = p_TCB->prio; + /* Priority inversion, check which task continues. */ + if (os_tsk.run->prio >= rt_rdy_prio()) { + rt_dispatch (p_TCB); + } + else { + /* Ready task has higher priority than running task. */ + rt_put_prio (&os_rdy, os_tsk.run); + rt_put_prio (&os_rdy, p_TCB); + os_tsk.run->state = READY; + p_TCB->state = READY; + rt_dispatch (NULL); + } + } + else { + /* Check if own priority raised by priority inversion. */ + if (rt_rdy_prio() > os_tsk.run->prio) { + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mut_wait -----------------------------------*/ + +OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout) { + /* Wait for a mutex, continue when mutex is free. */ + P_MUCB p_MCB = mutex; + + if (p_MCB->level == 0) { + p_MCB->owner = os_tsk.run; + p_MCB->prio = os_tsk.run->prio; + goto inc; + } + if (p_MCB->owner == os_tsk.run) { + /* OK, running task is the owner of this mutex. */ +inc:p_MCB->level++; + return (OS_R_OK); + } + /* Mutex owned by another task, wait until released. */ + if (timeout == 0) { + return (OS_R_TMO); + } + /* Raise the owner task priority if lower than current priority. */ + /* This priority inversion is called priority inheritance. */ + if (p_MCB->prio < os_tsk.run->prio) { + p_MCB->owner->prio = os_tsk.run->prio; + rt_resort_prio (p_MCB->owner); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + } + rt_block(timeout, WAIT_MUT); + return (OS_R_TMO); +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Mutex.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,44 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MUTEX.H + * Purpose: Implements mutex synchronization objects + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_delete (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Robin.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,84 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_ROBIN.C + * Purpose: Round Robin Task switching + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Time.h" +#include "rt_Robin.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +struct OS_ROBIN os_robin; + + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +/*--------------------------- rt_init_robin ---------------------------------*/ + +__weak void rt_init_robin (void) { + /* Initialize Round Robin variables. */ + os_robin.task = NULL; + os_robin.tout = (U16)os_rrobin; +} + +/*--------------------------- rt_chk_robin ----------------------------------*/ + +__weak void rt_chk_robin (void) { + /* Check if Round Robin timeout expired and switch to the next ready task.*/ + P_TCB p_new; + + if (os_robin.task != os_rdy.p_lnk) { + /* New task was suspended, reset Round Robin timeout. */ + os_robin.task = os_rdy.p_lnk; + os_robin.time = (U16)os_time + os_robin.tout - 1; + } + if (os_robin.time == (U16)os_time) { + /* Round Robin timeout has expired, swap Robin tasks. */ + os_robin.task = NULL; + p_new = rt_get_first (&os_rdy); + rt_put_prio ((P_XCB)&os_rdy, p_new); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Robin.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,45 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_ROBIN.H + * Purpose: Round Robin Task switching definitions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern struct OS_ROBIN os_robin; + +/* Functions */ +extern void rt_init_robin (void); +extern void rt_chk_robin (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Semaphore.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,183 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SEMAPHORE.C + * Purpose: Implements binary and counting semaphores + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Semaphore.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_sem_init -----------------------------------*/ + +void rt_sem_init (OS_ID semaphore, U16 token_count) { + /* Initialize a semaphore */ + P_SCB p_SCB = semaphore; + + p_SCB->cb_type = SCB; + p_SCB->p_lnk = NULL; + p_SCB->tokens = token_count; +} + + +/*--------------------------- rt_sem_delete ---------------------------------*/ + +#ifdef __CMSIS_RTOS +OS_RESULT rt_sem_delete (OS_ID semaphore) { + /* Delete semaphore */ + P_SCB p_SCB = semaphore; + P_TCB p_TCB; + + while (p_SCB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_SCB); + rt_ret_val(p_TCB, 0); + rt_rmv_dly(p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + } + + if (os_rdy.p_lnk && (os_rdy.p_lnk->prio > os_tsk.run->prio)) { + /* preempt running task */ + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + + p_SCB->cb_type = 0; + + return (OS_R_OK); +} +#endif + + +/*--------------------------- rt_sem_send -----------------------------------*/ + +OS_RESULT rt_sem_send (OS_ID semaphore) { + /* Return a token to semaphore */ + P_SCB p_SCB = semaphore; + P_TCB p_TCB; + + if (p_SCB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_SCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 1); +#else + rt_ret_val(p_TCB, OS_R_SEM); +#endif + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + /* Store token. */ + p_SCB->tokens++; + } + return (OS_R_OK); +} + + +/*--------------------------- rt_sem_wait -----------------------------------*/ + +OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout) { + /* Obtain a token; possibly wait for it */ + P_SCB p_SCB = semaphore; + + if (p_SCB->tokens) { + p_SCB->tokens--; + return (OS_R_OK); + } + /* No token available: wait for one */ + if (timeout == 0) { + return (OS_R_TMO); + } + if (p_SCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_SCB, os_tsk.run); + } + else { + p_SCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_SCB; + } + rt_block(timeout, WAIT_SEM); + return (OS_R_TMO); +} + + +/*--------------------------- isr_sem_send ----------------------------------*/ + +void isr_sem_send (OS_ID semaphore) { + /* Same function as "os_sem"send", but to be called by ISRs */ + P_SCB p_SCB = semaphore; + + rt_psq_enq (p_SCB, 0); + rt_psh_req (); +} + + +/*--------------------------- rt_sem_psh ------------------------------------*/ + +void rt_sem_psh (P_SCB p_CB) { + /* Check if task has to be waken up */ + P_TCB p_TCB; + + if (p_CB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_CB); + rt_rmv_dly (p_TCB); + p_TCB->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 1); +#else + rt_ret_val(p_TCB, OS_R_SEM); +#endif + rt_put_prio (&os_rdy, p_TCB); + } + else { + /* Store token */ + p_CB->tokens++; + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Semaphore.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SEMAPHORE.H + * Purpose: Implements binary and counting semaphores + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_sem_init (OS_ID semaphore, U16 token_count); +extern OS_RESULT rt_sem_delete(OS_ID semaphore); +extern OS_RESULT rt_sem_send (OS_ID semaphore); +extern OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout); +extern void isr_sem_send (OS_ID semaphore); +extern void rt_sem_psh (P_SCB p_CB); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_System.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,293 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SYSTEM.C + * Purpose: System Task Manager + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_Task.h" +#include "rt_System.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Mailbox.h" +#include "rt_Semaphore.h" +#include "rt_Time.h" +#include "rt_Robin.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +int os_tick_irqn; + +/*---------------------------------------------------------------------------- + * Local Variables + *---------------------------------------------------------------------------*/ + +static volatile BIT os_lock; +static volatile BIT os_psh_flag; +static U8 pend_flags; + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +#if defined (__CC_ARM) +__asm void $$RTX$$version (void) { + /* Export a version number symbol for a version control. */ + + EXPORT __RL_RTX_VER + +__RL_RTX_VER EQU 0x450 +} +#endif + + +/*--------------------------- rt_suspend ------------------------------------*/ +U32 rt_suspend (void) { + /* Suspend OS scheduler */ + U32 delta = 0xFFFF; + + rt_tsk_lock(); + + if (os_dly.p_dlnk) { + delta = os_dly.delta_time; + } +#ifndef __CMSIS_RTOS + if (os_tmr.next) { + if (os_tmr.tcnt < delta) delta = os_tmr.tcnt; + } +#endif + + return (delta); +} + + +/*--------------------------- rt_resume -------------------------------------*/ +void rt_resume (U32 sleep_time) { + /* Resume OS scheduler after suspend */ + P_TCB next; + U32 delta; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + os_robin.task = NULL; + + /* Update delays. */ + if (os_dly.p_dlnk) { + delta = sleep_time; + if (delta >= os_dly.delta_time) { + delta -= os_dly.delta_time; + os_time += os_dly.delta_time; + os_dly.delta_time = 1; + while (os_dly.p_dlnk) { + rt_dec_dly(); + if (delta == 0) break; + delta--; + os_time++; + } + } else { + os_time += delta; + os_dly.delta_time -= delta; + } + } else { + os_time += sleep_time; + } + +#ifndef __CMSIS_RTOS + /* Check the user timers. */ + if (os_tmr.next) { + delta = sleep_time; + if (delta >= os_tmr.tcnt) { + delta -= os_tmr.tcnt; + os_tmr.tcnt = 1; + while (os_tmr.next) { + rt_tmr_tick(); + if (delta == 0) break; + delta--; + } + } else { + os_tmr.tcnt -= delta; + } + } +#endif + + /* Switch back to highest ready task */ + next = rt_get_first (&os_rdy); + rt_switch_req (next); + + rt_tsk_unlock(); +} + + +/*--------------------------- rt_tsk_lock -----------------------------------*/ + +void rt_tsk_lock (void) { + /* Prevent task switching by locking out scheduler */ + OS_X_LOCK(os_tick_irqn); + os_lock = __TRUE; + OS_X_UNPEND (&pend_flags); +} + + +/*--------------------------- rt_tsk_unlock ---------------------------------*/ + +void rt_tsk_unlock (void) { + /* Unlock scheduler and re-enable task switching */ + OS_X_UNLOCK(os_tick_irqn); + os_lock = __FALSE; + OS_X_PEND (pend_flags, os_psh_flag); + os_psh_flag = __FALSE; +} + + +/*--------------------------- rt_psh_req ------------------------------------*/ + +void rt_psh_req (void) { + /* Initiate a post service handling request if required. */ + if (os_lock == __FALSE) { + OS_PEND_IRQ (); + } + else { + os_psh_flag = __TRUE; + } +} + + +/*--------------------------- rt_pop_req ------------------------------------*/ + +void rt_pop_req (void) { + /* Process an ISR post service requests. */ + struct OS_XCB *p_CB; + P_TCB next; + U32 idx; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + idx = os_psq->last; + while (os_psq->count) { + p_CB = os_psq->q[idx].id; + if (p_CB->cb_type == TCB) { + /* Is of TCB type */ + rt_evt_psh ((P_TCB)p_CB, (U16)os_psq->q[idx].arg); + } + else if (p_CB->cb_type == MCB) { + /* Is of MCB type */ + rt_mbx_psh ((P_MCB)p_CB, (void *)os_psq->q[idx].arg); + } + else { + /* Must be of SCB type */ + rt_sem_psh ((P_SCB)p_CB); + } + if (++idx == os_psq->size) idx = 0; + rt_dec (&os_psq->count); + } + os_psq->last = idx; + + next = rt_get_first (&os_rdy); + rt_switch_req (next); +} + + +/*--------------------------- os_tick_init ----------------------------------*/ + +__weak int os_tick_init (void) { + /* Initialize SysTick timer as system tick timer. */ + rt_systick_init (); + return (SYS_TICK_IRQn); /* Return IRQ number of SysTick timer */ +} + + +/*--------------------------- os_tick_irqack --------------------------------*/ + +__weak void os_tick_irqack (void) { + /* Acknowledge timer interrupt. */ +} + + +/*--------------------------- rt_systick ------------------------------------*/ + +extern void sysTimerTick(void); + +void rt_systick (void) { + if(NVIC_Pending(SYS_TICK_IRQn)){ + rt_pop_req(); + NVIC_UnpendIRQ(SYS_TICK_IRQn); + SYS_TICK_TIMER->IR = 0xF; // clear timer interrupt + return; + } + /* Check for system clock update, suspend running task. */ + P_TCB next; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + /* Check Round Robin timeout. */ + rt_chk_robin (); + + /* Update delays. */ + os_time++; + rt_dec_dly (); + + /* Check the user timers. */ +#ifdef __CMSIS_RTOS + sysTimerTick(); +#else + rt_tmr_tick (); +#endif + + /* Switch back to highest ready task */ + next = rt_get_first (&os_rdy); + rt_switch_req (next); + SYS_TICK_TIMER->IR = 0xF; // clear timer interrupt +} + +/*--------------------------- rt_stk_check ----------------------------------*/ +__weak void rt_stk_check (void) { + /* Check for stack overflow. */ + if (os_tsk.run->task_id == 0x01) { + // TODO: For the main thread the check should be done against the main heap pointer + } else { + if ((os_tsk.run->tsk_stack < (U32)os_tsk.run->stack) || + (os_tsk.run->stack[0] != MAGIC_WORD)) { + os_error (OS_ERR_STK_OVF); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_System.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,52 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SYSTEM.H + * Purpose: System Task Manager definitions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Variables */ +#define os_psq ((P_PSQ)&os_fifo) +extern int os_tick_irqn; + +/* Functions */ +extern U32 rt_suspend (void); +extern void rt_resume (U32 sleep_time); +extern void rt_tsk_lock (void); +extern void rt_tsk_unlock (void); +extern void rt_psh_req (void); +extern void rt_pop_req (void); +extern void rt_systick (void); +extern void rt_stk_check (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Task.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,341 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TASK.C + * Purpose: Task functions and system start up. + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_System.h" +#include "rt_Task.h" +#include "rt_List.h" +#include "rt_MemBox.h" +#include "rt_Robin.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* Running and next task info. */ +struct OS_TSK os_tsk; + +/* Task Control Blocks of idle demon */ +struct OS_TCB os_idle_TCB; + + +/*---------------------------------------------------------------------------- + * Local Functions + *---------------------------------------------------------------------------*/ + +OS_TID rt_get_TID (void) { + U32 tid; + + for (tid = 1; tid <= os_maxtaskrun; tid++) { + if (os_active_TCB[tid-1] == NULL) { + return ((OS_TID)tid); + } + } + return (0); +} + +#if defined (__CC_ARM) && !defined (__MICROLIB) +/*--------------------------- __user_perthread_libspace ---------------------*/ +extern void *__libspace_start; + +void *__user_perthread_libspace (void) { + /* Provide a separate libspace for each task. */ + if (os_tsk.run == NULL) { + /* RTX not running yet. */ + return (&__libspace_start); + } + return (void *)(os_tsk.run->std_libspace); +} +#endif + +/*--------------------------- rt_init_context -------------------------------*/ + +void rt_init_context (P_TCB p_TCB, U8 priority, FUNCP task_body) { + /* Initialize general part of the Task Control Block. */ + p_TCB->cb_type = TCB; + p_TCB->state = READY; + p_TCB->prio = priority; + p_TCB->p_lnk = NULL; + p_TCB->p_rlnk = NULL; + p_TCB->p_dlnk = NULL; + p_TCB->p_blnk = NULL; + p_TCB->delta_time = 0; + p_TCB->interval_time = 0; + p_TCB->events = 0; + p_TCB->waits = 0; + p_TCB->stack_frame = 0; + + rt_init_stack (p_TCB, task_body); +} + + +/*--------------------------- rt_switch_req ---------------------------------*/ + +void rt_switch_req (P_TCB p_new) { + /* Switch to next task (identified by "p_new"). */ + os_tsk.new_tsk = p_new; + p_new->state = RUNNING; + DBG_TASK_SWITCH(p_new->task_id); +} + + +/*--------------------------- rt_dispatch -----------------------------------*/ + +void rt_dispatch (P_TCB next_TCB) { + /* Dispatch next task if any identified or dispatch highest ready task */ + /* "next_TCB" identifies a task to run or has value NULL (=no next task) */ + if (next_TCB == NULL) { + /* Running task was blocked: continue with highest ready task */ + next_TCB = rt_get_first (&os_rdy); + rt_switch_req (next_TCB); + } + else { + /* Check which task continues */ + if (next_TCB->prio > os_tsk.run->prio) { + /* preempt running task */ + rt_put_rdy_first (os_tsk.run); + os_tsk.run->state = READY; + rt_switch_req (next_TCB); + } + else { + /* put next task into ready list, no task switch takes place */ + next_TCB->state = READY; + rt_put_prio (&os_rdy, next_TCB); + } + } +} + + +/*--------------------------- rt_block --------------------------------------*/ + +void rt_block (U16 timeout, U8 block_state) { + /* Block running task and choose next ready task. */ + /* "timeout" sets a time-out value or is 0xffff (=no time-out). */ + /* "block_state" defines the appropriate task state */ + P_TCB next_TCB; + + if (timeout) { + if (timeout < 0xffff) { + rt_put_dly (os_tsk.run, timeout); + } + os_tsk.run->state = block_state; + next_TCB = rt_get_first (&os_rdy); + rt_switch_req (next_TCB); + } +} + + +/*--------------------------- rt_tsk_pass -----------------------------------*/ + +void rt_tsk_pass (void) { + /* Allow tasks of same priority level to run cooperatively.*/ + P_TCB p_new; + + p_new = rt_get_same_rdy_prio(); + if (p_new != NULL) { + rt_put_prio ((P_XCB)&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_switch_req (p_new); + } +} + + +/*--------------------------- rt_tsk_self -----------------------------------*/ + +OS_TID rt_tsk_self (void) { + /* Return own task identifier value. */ + if (os_tsk.run == NULL) { + return (0); + } + return (os_tsk.run->task_id); +} + + +/*--------------------------- rt_tsk_prio -----------------------------------*/ + +OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio) { + /* Change execution priority of a task to "new_prio". */ + P_TCB p_task; + + if (task_id == 0) { + /* Change execution priority of calling task. */ + os_tsk.run->prio = new_prio; +run:if (rt_rdy_prio() > new_prio) { + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + return (OS_R_OK); + } + + /* Find the task in the "os_active_TCB" array. */ + if (task_id > os_maxtaskrun || os_active_TCB[task_id-1] == NULL) { + /* Task with "task_id" not found or not started. */ + return (OS_R_NOK); + } + p_task = os_active_TCB[task_id-1]; + p_task->prio = new_prio; + if (p_task == os_tsk.run) { + goto run; + } + rt_resort_prio (p_task); + if (p_task->state == READY) { + /* Task enqueued in a ready list. */ + p_task = rt_get_first (&os_rdy); + rt_dispatch (p_task); + } + return (OS_R_OK); +} + +/*--------------------------- rt_tsk_delete ---------------------------------*/ + +OS_RESULT rt_tsk_delete (OS_TID task_id) { + /* Terminate the task identified with "task_id". */ + P_TCB task_context; + + if (task_id == 0 || task_id == os_tsk.run->task_id) { + /* Terminate itself. */ + os_tsk.run->state = INACTIVE; + os_tsk.run->tsk_stack = 0; + rt_stk_check (); + os_active_TCB[os_tsk.run->task_id-1] = NULL; + + os_tsk.run->stack = NULL; + DBG_TASK_NOTIFY(os_tsk.run, __FALSE); + os_tsk.run = NULL; + rt_dispatch (NULL); + /* The program should never come to this point. */ + } + else { + /* Find the task in the "os_active_TCB" array. */ + if (task_id > os_maxtaskrun || os_active_TCB[task_id-1] == NULL) { + /* Task with "task_id" not found or not started. */ + return (OS_R_NOK); + } + task_context = os_active_TCB[task_id-1]; + rt_rmv_list (task_context); + rt_rmv_dly (task_context); + os_active_TCB[task_id-1] = NULL; + + task_context->stack = NULL; + DBG_TASK_NOTIFY(task_context, __FALSE); + } + return (OS_R_OK); +} + + +/*--------------------------- rt_sys_init -----------------------------------*/ + +#ifdef __CMSIS_RTOS +void rt_sys_init (void) { +#else +void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk) { +#endif + /* Initialize system and start up task declared with "first_task". */ + U32 i; + + DBG_INIT(); + + /* Initialize dynamic memory and task TCB pointers to NULL. */ + for (i = 0; i < os_maxtaskrun; i++) { + os_active_TCB[i] = NULL; + } + + /* Set up TCB of idle demon */ + os_idle_TCB.task_id = 255; + os_idle_TCB.priv_stack = idle_task_stack_size; + os_idle_TCB.stack = idle_task_stack; + rt_init_context (&os_idle_TCB, 0, os_idle_demon); + + /* Set up ready list: initially empty */ + os_rdy.cb_type = HCB; + os_rdy.p_lnk = NULL; + /* Set up delay list: initially empty */ + os_dly.cb_type = HCB; + os_dly.p_dlnk = NULL; + os_dly.p_blnk = NULL; + os_dly.delta_time = 0; + + /* Fix SP and systemvariables to assume idle task is running */ + /* Transform main program into idle task by assuming idle TCB */ +#ifndef __CMSIS_RTOS + rt_set_PSP (os_idle_TCB.tsk_stack); +#endif + os_tsk.run = &os_idle_TCB; + os_tsk.run->state = RUNNING; + + /* Initialize ps queue */ + os_psq->first = 0; + os_psq->last = 0; + os_psq->size = os_fifo_size; + + rt_init_robin (); + + /* Intitialize SVC and PendSV */ + rt_svc_init (); + +#ifndef __CMSIS_RTOS + /* Intitialize and start system clock timer */ + os_tick_irqn = os_tick_init (); + if (os_tick_irqn >= 0) { + OS_X_INIT(os_tick_irqn); + } + + /* Start up first user task before entering the endless loop */ + rt_tsk_create (first_task, prio_stksz, stk, NULL); +#endif +} + + +/*--------------------------- rt_sys_start ----------------------------------*/ + +#ifdef __CMSIS_RTOS +void rt_sys_start (void) { + /* Start system */ + + /* Intitialize and start system clock timer */ + os_tick_irqn = os_tick_init (); + if (os_tick_irqn >= 0) { + OS_X_INIT(os_tick_irqn); + } + extern void RestoreContext(); + RestoreContext(); // Start the first task +} +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Task.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,73 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TASK.H + * Purpose: Task functions and system start up. + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Definitions */ +#define __CMSIS_RTOS 1 + +/* Values for 'state' */ +#define INACTIVE 0 +#define READY 1 +#define RUNNING 2 +#define WAIT_DLY 3 +#define WAIT_ITV 4 +#define WAIT_OR 5 +#define WAIT_AND 6 +#define WAIT_SEM 7 +#define WAIT_MBX 8 +#define WAIT_MUT 9 + +/* Return codes */ +#define OS_R_TMO 0x01 +#define OS_R_EVT 0x02 +#define OS_R_SEM 0x03 +#define OS_R_MBX 0x04 +#define OS_R_MUT 0x05 + +#define OS_R_OK 0x00 +#define OS_R_NOK 0xff + +/* Variables */ +extern struct OS_TSK os_tsk; +extern struct OS_TCB os_idle_TCB; + +/* Functions */ +extern void rt_switch_req (P_TCB p_new); +extern void rt_dispatch (P_TCB next_TCB); +extern void rt_block (U16 timeout, U8 block_state); +extern void rt_tsk_pass (void); +extern OS_TID rt_tsk_self (void); +extern OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio); +extern OS_RESULT rt_tsk_delete (OS_TID task_id); +extern void rt_sys_init (void); +extern void rt_sys_start (void);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Time.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,94 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIME.C + * Purpose: Delay and interval wait functions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Conf.h" +#include "rt_Task.h" +#include "rt_Time.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* Free running system tick counter */ +U32 os_time; + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_time_get -----------------------------------*/ + +U32 rt_time_get (void) { + /* Get system time tick */ + return (os_time); +} + + +/*--------------------------- rt_dly_wait -----------------------------------*/ + +void rt_dly_wait (U16 delay_time) { + /* Delay task by "delay_time" */ + rt_block (delay_time, WAIT_DLY); +} + + +/*--------------------------- rt_itv_set ------------------------------------*/ + +void rt_itv_set (U16 interval_time) { + /* Set interval length and define start of first interval */ + os_tsk.run->interval_time = interval_time; + os_tsk.run->delta_time = interval_time + (U16)os_time; +} + + +/*--------------------------- rt_itv_wait -----------------------------------*/ + +void rt_itv_wait (void) { + /* Wait for interval end and define start of next one */ + U16 delta; + + delta = os_tsk.run->delta_time - (U16)os_time; + os_tsk.run->delta_time += os_tsk.run->interval_time; + if ((delta & 0x8000) == 0) { + rt_block (delta, WAIT_ITV); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_Time.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,47 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIME.H + * Purpose: Delay and interval wait functions definitions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern U32 os_time; + +/* Functions */ +extern U32 rt_time_get (void); +extern void rt_dly_wait (U16 delay_time); +extern void rt_itv_set (U16 interval_time); +extern void rt_itv_wait (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_ARM7/rt_TypeDef.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,128 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TYPEDEF.H + * Purpose: Type Definitions + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ +#ifndef RT_TYPE_DEF_H +#define RT_TYPE_DEF_H + +#include "os_tcb.h" + +typedef U32 OS_TID; +typedef void *OS_ID; +typedef U32 OS_RESULT; + +#define TCB_STACKF 32 /* 'stack_frame' offset */ +#define TCB_TSTACK 40 /* 'tsk_stack' offset */ + +typedef struct OS_PSFE { /* Post Service Fifo Entry */ + void *id; /* Object Identification */ + U32 arg; /* Object Argument */ +} *P_PSFE; + +typedef struct OS_PSQ { /* Post Service Queue */ + U8 first; /* FIFO Head Index */ + U8 last; /* FIFO Tail Index */ + U8 count; /* Number of stored items in FIFO */ + U8 size; /* FIFO Size */ + struct OS_PSFE q[1]; /* FIFO Content */ +} *P_PSQ; + +typedef struct OS_TSK { + P_TCB run; /* Current running task */ + P_TCB new_tsk; /* Scheduled task to run */ +} *P_TSK; + +typedef struct OS_ROBIN { /* Round Robin Control */ + P_TCB task; /* Round Robin task */ + U16 time; /* Round Robin switch time */ + U16 tout; /* Round Robin timeout */ +} *P_ROBIN; + +typedef struct OS_XCB { + U8 cb_type; /* Control Block Type */ + struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */ + struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */ + struct OS_TCB *p_dlnk; /* Link pointer for delay list */ + struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */ + U16 delta_time; /* Time until time out */ +} *P_XCB; + +typedef struct OS_MCB { + U8 cb_type; /* Control Block Type */ + U8 state; /* State flag variable */ + U8 isr_st; /* State flag variable for isr functions */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for message */ + U16 first; /* Index of the message list begin */ + U16 last; /* Index of the message list end */ + U16 count; /* Actual number of stored messages */ + U16 size; /* Maximum number of stored messages */ + void *msg[1]; /* FIFO for Message pointers 1st element */ +} *P_MCB; + +typedef struct OS_SCB { + U8 cb_type; /* Control Block Type */ + U8 mask; /* Semaphore token mask */ + U16 tokens; /* Semaphore tokens */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for tokens */ +} *P_SCB; + +typedef struct OS_MUCB { + U8 cb_type; /* Control Block Type */ + U8 prio; /* Owner task default priority */ + U16 level; /* Call nesting level */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for mutex */ + struct OS_TCB *owner; /* Mutex owner task */ +} *P_MUCB; + +typedef struct OS_XTMR { + struct OS_TMR *next; + U16 tcnt; +} *P_XTMR; + +typedef struct OS_TMR { + struct OS_TMR *next; /* Link pointer to Next timer */ + U16 tcnt; /* Timer delay count */ + U16 info; /* User defined call info */ +} *P_TMR; + +typedef struct OS_BM { + void *free; /* Pointer to first free memory block */ + void *end; /* Pointer to memory block end */ + U32 blk_size; /* Memory block size */ +} *P_BM; + +/* Definitions */ +#define __TRUE 1 +#define __FALSE 0 +#define NULL ((void *) 0) + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/HAL_CA.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,124 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CA.C + * Purpose: Hardware Abstraction Layer for Cortex-A + * Rev.: + *---------------------------------------------------------------------------- + * + * Copyright (c) 2012 ARM Limited + * 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_HAL_CA.h" + +/*--------------------------- os_init_context -------------------------------*/ + +void rt_init_stack (P_TCB p_TCB, FUNCP task_body) { + /* Prepare TCB and saved context for a first time start of a task. */ + U32 *stk,i,size; + + /* Prepare a complete interrupt frame for first task start */ + size = p_TCB->priv_stack >> 2; + if (size == 0) { + size = (U16)os_stackinfo >> 2; + } + /* Write to the top of stack. */ + stk = &p_TCB->stack[size]; + + /* Auto correct to 8-byte ARM stack alignment. */ + if ((U32)stk & 0x04) { + stk--; + } + + stk -= 16; + + /* Initial PC and default CPSR */ + stk[14] = (U32)task_body; + /* Task run mode is inherited from the startup file. */ + /* (non-privileged USER or privileged SYSTEM mode) */ + stk[15] = (os_flags & 1) ? INIT_CPSR_SYS : INIT_CPSR_USER; + /* Set T-bit if task function in Thumb mode. */ + if ((U32)task_body & 1) { + stk[15] |= CPSR_T_BIT; + } + /* Assign a void pointer to R0. */ + stk[8] = (U32)p_TCB->msg; + /* Clear R1-R12,LR registers. */ + for (i = 0; i < 8; i++) { + stk[i] = 0; + } + for (i = 9; i < 14; i++) { + stk[i] = 0; + } + + /* Initial Task stack pointer. */ + p_TCB->tsk_stack = (U32)stk; + + /* Task entry point. */ + p_TCB->ptask = task_body; + + /* Set a magic word for checking of stack overflow. */ + p_TCB->stack[0] = MAGIC_WORD; +} + + +/*--------------------------- rt_ret_val ----------------------------------*/ + +static __inline U32 *rt_ret_regs (P_TCB p_TCB) { + /* Get pointer to task return value registers (R0..R3) in Stack */ + if (p_TCB->stack_frame & 0x4) { + /* NEON/D32 Stack Frame: D0-31,FPSCR,Reserved,R4-R11,R0-R3,R12,LR,PC,xPSR */ + return (U32 *)(p_TCB->tsk_stack + 8*4 + 2*4 + 32*8); + } else if (p_TCB->stack_frame & 0x2) { + /* VFP/D16 Stack Frame: D0-D15/S0-31,FPSCR,Reserved,R4-R11,R0-R3,R12,LR,PC,xPSR */ + return (U32 *)(p_TCB->tsk_stack + 8*4 + 2*4 + 32*4); + } else { + /* Basic Stack Frame: R4-R11,R0-R3,R12,LR,PC,xPSR */ + return (U32 *)(p_TCB->tsk_stack + 8*4); + } +} + +void rt_ret_val (P_TCB p_TCB, U32 v0) { + U32 *ret; + + ret = rt_ret_regs(p_TCB); + ret[0] = v0; +} + +void rt_ret_val2(P_TCB p_TCB, U32 v0, U32 v1) { + U32 *ret; + + ret = rt_ret_regs(p_TCB); + ret[0] = v0; + ret[1] = v1; +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/RTX_CM_lib.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,563 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RTX_CM_LIB.H + * Purpose: RTX Kernel System Configuration + * Rev.: V4.73 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#if defined (__CC_ARM) +#include <rt_misc.h> +#pragma O3 +#define __USED __attribute__((used)) +#elif defined (__GNUC__) +#pragma GCC optimize ("O3") +#define __USED __attribute__((used)) +#elif defined (__ICCARM__) +#define __USED __root +#endif + + +/*---------------------------------------------------------------------------- + * Definitions + *---------------------------------------------------------------------------*/ + +#define _declare_box(pool,size,cnt) uint32_t pool[(((size)+3)/4)*(cnt) + 3] +#define _declare_box8(pool,size,cnt) uint64_t pool[(((size)+7)/8)*(cnt) + 2] + +#define OS_TCB_SIZE 64 +#define OS_TMR_SIZE 8 + +#if defined (__CC_ARM) && !defined (__MICROLIB) + +typedef void *OS_ID; +typedef uint32_t OS_TID; +typedef uint32_t OS_MUT[4]; +typedef uint32_t OS_RESULT; + +#define runtask_id() rt_tsk_self() +#define mutex_init(m) rt_mut_init(m) +#define mutex_wait(m) os_mut_wait(m,0xFFFF) +#define mutex_rel(m) os_mut_release(m) + +extern OS_TID rt_tsk_self (void); +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, uint16_t timeout); + +#define os_mut_wait(mutex,timeout) _os_mut_wait((uint32_t)rt_mut_wait,mutex,timeout) +#define os_mut_release(mutex) _os_mut_release((uint32_t)rt_mut_release,mutex) + +OS_RESULT _os_mut_release (uint32_t p, OS_ID mutex) __svc_indirect(0); +OS_RESULT _os_mut_wait (uint32_t p, OS_ID mutex, uint16_t timeout) __svc_indirect(0); + +#elif defined (__ICCARM__) + +typedef void *OS_ID; +typedef uint32_t OS_TID; +typedef uint32_t OS_MUT[4]; +typedef uint32_t OS_RESULT; + +#define runtask_id() rt_tsk_self() +#define mutex_init(m) rt_mut_init(m) +#define mutex_del(m) os_mut_delete(m) +#define mutex_wait(m) os_mut_wait(m,0xFFFF) +#define mutex_rel(m) os_mut_release(m) + +extern OS_TID rt_tsk_self (void); +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_delete (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, uint16_t timeout); + +#pragma swi_number=0 +__swi OS_RESULT _os_mut_delete (OS_ID mutex); + +static inline OS_RESULT os_mut_delete(OS_ID mutex) +{ + __asm("mov r12,%0\n" :: "r"(&rt_mut_delete) : "r12" ); + return _os_mut_delete(mutex); +} + +#pragma swi_number=0 +__swi OS_RESULT _os_mut_release (OS_ID mutex); + +static inline OS_RESULT os_mut_release(OS_ID mutex) +{ + __asm("mov r12,%0\n" :: "r"(&rt_mut_release) : "r12" ); + return _os_mut_release(mutex); +} + +#pragma swi_number=0 +__swi OS_RESULT _os_mut_wait (OS_ID mutex, uint16_t timeout); + +static inline OS_RESULT os_mut_wait(OS_ID mutex, uint16_t timeout) +{ + __asm("mov r12,%0\n" :: "r"(&rt_mut_wait) : "r12" ); + return _os_mut_wait(mutex, timeout); +} + +#include <yvals.h> /* for include DLib_Thread.h */ + +void __iar_system_Mtxinit(__iar_Rmtx *); +void __iar_system_Mtxdst(__iar_Rmtx *); +void __iar_system_Mtxlock(__iar_Rmtx *); +void __iar_system_Mtxunlock(__iar_Rmtx *); + + + + +#endif + + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +#if (OS_TIMERS != 0) +#define OS_TASK_CNT (OS_TASKCNT + 1) +#ifndef __MBED_CMSIS_RTOS_CA9 +#define OS_PRIV_CNT (OS_PRIVCNT + 2) +#define OS_STACK_SZ (4*(OS_PRIVSTKSIZE+OS_MAINSTKSIZE+OS_TIMERSTKSZ)) +#endif +#else +#define OS_TASK_CNT OS_TASKCNT +#ifndef __MBED_CMSIS_RTOS_CA9 +#define OS_PRIV_CNT (OS_PRIVCNT + 1) +#define OS_STACK_SZ (4*(OS_PRIVSTKSIZE+OS_MAINSTKSIZE)) +#endif +#endif + +uint16_t const os_maxtaskrun = OS_TASK_CNT; +#ifdef __MBED_CMSIS_RTOS_CA9 +uint32_t const os_stackinfo = (OS_STKCHECK<<24)| (OS_IDLESTKSIZE*4); +#else +uint32_t const os_stackinfo = (OS_STKCHECK<<24)| (OS_PRIV_CNT<<16) | (OS_STKSIZE*4); +#endif +uint32_t const os_rrobin = (OS_ROBIN << 16) | OS_ROBINTOUT; +uint32_t const os_tickfreq = OS_CLOCK; +uint16_t const os_tickus_i = OS_CLOCK/1000000; +uint16_t const os_tickus_f = (((uint64_t)(OS_CLOCK-1000000*(OS_CLOCK/1000000)))<<16)/1000000; +uint32_t const os_trv = OS_TRV; +uint8_t const os_flags = OS_RUNPRIV; + +/* Export following defines to uVision debugger. */ +__USED uint32_t const CMSIS_RTOS_API_Version = osCMSIS; +__USED uint32_t const CMSIS_RTOS_RTX_Version = osCMSIS_RTX; +__USED uint32_t const os_clockrate = OS_TICK; +__USED uint32_t const os_timernum = 0; + +/* Memory pool for TCB allocation */ +_declare_box (mp_tcb, OS_TCB_SIZE, OS_TASK_CNT); +uint16_t const mp_tcb_size = sizeof(mp_tcb); + +#ifdef __MBED_CMSIS_RTOS_CA9 +/* Memory pool for os_idle_demon stack allocation. */ +_declare_box8 (mp_stk, OS_IDLESTKSIZE*4, 1); +uint32_t const mp_stk_size = sizeof(mp_stk); +#else +/* Memory pool for System stack allocation (+os_idle_demon). */ +_declare_box8 (mp_stk, OS_STKSIZE*4, OS_TASK_CNT-OS_PRIV_CNT+1); +uint32_t const mp_stk_size = sizeof(mp_stk); + +/* Memory pool for user specified stack allocation (+main, +timer) */ +uint64_t os_stack_mem[2+OS_PRIV_CNT+(OS_STACK_SZ/8)]; +uint32_t const os_stack_sz = sizeof(os_stack_mem); +#endif + +#ifndef OS_FIFOSZ + #define OS_FIFOSZ 16 +#endif + +/* Fifo Queue buffer for ISR requests.*/ +uint32_t os_fifo[OS_FIFOSZ*2+1]; +uint8_t const os_fifo_size = OS_FIFOSZ; + +/* An array of Active task pointers. */ +void *os_active_TCB[OS_TASK_CNT]; + +/* User Timers Resources */ +#if (OS_TIMERS != 0) +extern void osTimerThread (void const *argument); +#ifdef __MBED_CMSIS_RTOS_CA9 +osThreadDef(osTimerThread, (osPriority)(OS_TIMERPRIO-3), 4*OS_TIMERSTKSZ); +#else +osThreadDef(osTimerThread, (osPriority)(OS_TIMERPRIO-3), 1, 4*OS_TIMERSTKSZ); +#endif +osThreadId osThreadId_osTimerThread; +osMessageQDef(osTimerMessageQ, OS_TIMERCBQS, void *); +osMessageQId osMessageQId_osTimerMessageQ; +#else +osThreadDef_t os_thread_def_osTimerThread = { NULL }; +osThreadId osThreadId_osTimerThread; +osMessageQDef(osTimerMessageQ, 0, void *); +osMessageQId osMessageQId_osTimerMessageQ; +#endif + +/* Legacy RTX User Timers not used */ +uint32_t os_tmr = 0; +uint32_t const *m_tmr = NULL; +uint16_t const mp_tmr_size = 0; + +/* singleton mutex */ +osMutexId singleton_mutex_id; +osMutexDef(singleton_mutex); + +#if defined (__CC_ARM) && !defined (__MICROLIB) + /* A memory space for arm standard library. */ + static uint32_t std_libspace[OS_TASK_CNT][96/4]; + static OS_MUT std_libmutex[OS_MUTEXCNT]; + static uint32_t nr_mutex; + extern void *__libspace_start; +#elif defined (__ICCARM__) +typedef struct os_mut_array { + OS_MUT mutex; + uint32_t used; +} os_mut_array_t; + +static os_mut_array_t std_libmutex[OS_MUTEXCNT];/* must be Zero clear */ +static uint32_t nr_mutex = 0; +#endif + + +/*---------------------------------------------------------------------------- + * RTX Optimizations (empty functions) + *---------------------------------------------------------------------------*/ + +#if OS_ROBIN == 0 + void rt_init_robin (void) {;} + void rt_chk_robin (void) {;} +#endif + +#if OS_STKCHECK == 0 + void rt_stk_check (void) {;} +#endif + + +/*---------------------------------------------------------------------------- + * Standard Library multithreading interface + *---------------------------------------------------------------------------*/ + +#if defined (__CC_ARM) && !defined (__MICROLIB) + +/*--------------------------- __user_perthread_libspace ---------------------*/ + +void *__user_perthread_libspace (void) { + /* Provide a separate libspace for each task. */ + uint32_t idx; + + idx = runtask_id (); + if (idx == 0) { + /* RTX not running yet. */ + return (&__libspace_start); + } + return ((void *)&std_libspace[idx-1]); +} + +/*--------------------------- _mutex_initialize -----------------------------*/ + +int _mutex_initialize (OS_ID *mutex) { + /* Allocate and initialize a system mutex. */ + + if (nr_mutex >= OS_MUTEXCNT) { + /* If you are here, you need to increase the number OS_MUTEXCNT. */ + for (;;); + } + *mutex = &std_libmutex[nr_mutex++]; + mutex_init (*mutex); + return (1); +} + + +/*--------------------------- _mutex_acquire --------------------------------*/ + +__attribute__((used)) void _mutex_acquire (OS_ID *mutex) { + /* Acquire a system mutex, lock stdlib resources. */ + if (runtask_id ()) { + /* RTX running, acquire a mutex. */ + mutex_wait (*mutex); + } +} + + +/*--------------------------- _mutex_release --------------------------------*/ + +__attribute__((used)) void _mutex_release (OS_ID *mutex) { + /* Release a system mutex, unlock stdlib resources. */ + if (runtask_id ()) { + /* RTX running, release a mutex. */ + mutex_rel (*mutex); + } +} + +#elif defined (__ICCARM__) + +/*--------------------------- __iar_system_Mtxinit --------------------------*/ + +void __iar_system_Mtxinit(__iar_Rmtx *mutex) +{ + /* Allocate and initialize a system mutex. */ + int32_t idx; + + for (idx = 0; idx < OS_MUTEXCNT; idx++) + { + if (std_libmutex[idx].used == 0) + { + std_libmutex[idx].used = 1; + *mutex = &std_libmutex[idx].mutex; + nr_mutex++; + break; + } + } + if (nr_mutex >= OS_MUTEXCNT) + { + /* If you are here, you need to increase the number OS_MUTEXCNT. */ + for (;;); + } + + mutex_init (*mutex); +} + +/*--------------------------- __iar_system_Mtxdst ---------------------------*/ + +void __iar_system_Mtxdst(__iar_Rmtx *mutex) +{ + /* Free a system mutex. */ + int32_t idx; + + if (nr_mutex == 0) + { + for (;;); + } + + idx = ((((uint32_t)mutex) - ((uint32_t)&std_libmutex[0].mutex)) + / sizeof(os_mut_array_t)); + + if (idx >= OS_MUTEXCNT) + { + for (;;); + } + + mutex_del (*mutex); + std_libmutex[idx].used = 0; +} + +/*--------------------------- __iar_system_Mtxlock --------------------------*/ + +void __iar_system_Mtxlock(__iar_Rmtx *mutex) +{ + /* Acquire a system mutex, lock stdlib resources. */ + if (runtask_id ()) + { + /* RTX running, acquire a mutex. */ + mutex_wait (*mutex); + } +} + +/*--------------------------- __iar_system_Mtxunlock ------------------------*/ + +void __iar_system_Mtxunlock(__iar_Rmtx *mutex) +{ + /* Release a system mutex, unlock stdlib resources. */ + if (runtask_id ()) + { + /* RTX running, release a mutex. */ + mutex_rel (*mutex); + } +} + +#endif + + +/*---------------------------------------------------------------------------- + * RTX Startup + *---------------------------------------------------------------------------*/ + +/* Main Thread definition */ +extern void pre_main (void); +#ifdef __MBED_CMSIS_RTOS_CA9 +uint32_t os_thread_def_stack_main [(4 * OS_MAINSTKSIZE) / sizeof(uint32_t)]; +osThreadDef_t os_thread_def_main = {(os_pthread)pre_main, osPriorityNormal, 1, 4*OS_MAINSTKSIZE, os_thread_def_stack_main }; +#else +osThreadDef_t os_thread_def_main = {(os_pthread)pre_main, osPriorityNormal, 1, 4*OS_MAINSTKSIZE }; +#endif + +#if defined (__CC_ARM) + +#ifdef __MICROLIB + +int main(void); +void _main_init (void) __attribute__((section(".ARM.Collect$$$$000000FF"))); +void $Super$$__cpp_initialize__aeabi_(void); + +#if __TARGET_ARCH_ARM +#pragma push +#pragma arm +#endif +void _main_init (void) { + osKernelInitialize(); + osThreadCreate(&os_thread_def_main, NULL); + osKernelStart(); + for (;;); +} +#if __TARGET_ARCH_ARM +#pragma pop +#endif + +void $Sub$$__cpp_initialize__aeabi_(void) +{ + // this should invoke C++ initializers prior _main_init, we keep this empty and + // invoke them after _main_init (=starts RTX kernel) +} + +void pre_main() +{ + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + $Super$$__cpp_initialize__aeabi_(); + main(); +} + +#else + +void * armcc_heap_base; +void * armcc_heap_top; + +int main(void); + +void pre_main (void) +{ + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + __rt_lib_init((unsigned)armcc_heap_base, (unsigned)armcc_heap_top); + main(); +} + +__asm void __rt_entry (void) { + + IMPORT __user_setup_stackheap + IMPORT os_thread_def_main + IMPORT armcc_heap_base + IMPORT armcc_heap_top + IMPORT osKernelInitialize + IMPORT osKernelStart + IMPORT osThreadCreate + + BL __user_setup_stackheap + LDR R3,=armcc_heap_base + LDR R4,=armcc_heap_top + STR R0,[R3] + STR R2,[R4] + BL osKernelInitialize + LDR R0,=os_thread_def_main + MOVS R1,#0 + BL osThreadCreate + BL osKernelStart + /* osKernelStart should not return */ + B . + + ALIGN +} +#endif + +#elif defined (__GNUC__) +extern int atexit(void (*func)(void)); +extern void __libc_fini_array(void); +extern void __libc_init_array (void); +extern int main(int argc, char **argv); + +void pre_main(void) { + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + atexit(__libc_fini_array); + __libc_init_array(); + main(0, NULL); +} + +__attribute__((naked)) void software_init_hook_rtos (void) { + __asm ( + ".syntax unified\n" + ".arm\n" + "bl osKernelInitialize\n" + "ldr r0,=os_thread_def_main\n" + "movs r1,#0\n" + "bl osThreadCreate\n" + "bl osKernelStart\n" + /* osKernelStart should not return */ + "B .\n" + ); +} + +#elif defined (__ICCARM__) +extern void* __vector_core_a9; +extern int __low_level_init(void); +extern void __iar_data_init3(void); +extern __weak void __iar_init_core( void ); +extern __weak void __iar_init_vfp( void ); +extern void __iar_dynamic_initialization(void); +extern void mbed_sdk_init(void); +extern void mbed_main(void); +extern int main(void); +static uint8_t low_level_init_needed; + +void pre_main(void) { + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + if (low_level_init_needed) { + __iar_dynamic_initialization(); + } + mbed_main(); + main(); +} + +#pragma required=__vector_core_a9 +void __iar_program_start( void ) +{ + __iar_init_core(); + __iar_init_vfp(); + + uint8_t low_level_init_needed_local; + + low_level_init_needed_local = __low_level_init(); + if (low_level_init_needed_local) { + __iar_data_init3(); + mbed_sdk_init(); + } + /* Store in a global variable after RAM has been initialized */ + low_level_init_needed = low_level_init_needed_local; + osKernelInitialize(); + osThreadCreate(&os_thread_def_main, NULL); + osKernelStart(); + /* osKernelStart should not return */ + while (1); +} + +#endif + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/RTX_Conf_CA.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,334 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RTX_Conf_CM.C + * Purpose: Configuration of CMSIS RTX Kernel + * Rev.: V4.60 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "cmsis_os.h" + +/*---------------------------------------------------------------------------- + * RTX User configuration part BEGIN + *---------------------------------------------------------------------------*/ + +// Include per-target RTX config file +#include "mbed_rtx4.h" + +//-------- <<< Use Configuration Wizard in Context Menu >>> ----------------- +// +// <h>Thread Configuration +// ======================= +// +// <o>Number of concurrent running threads <0-250> +// <i> Defines max. number of threads that will run at the same time. +// <i> Default: 6 +#ifndef OS_TASKCNT + #define OS_TASKCNT 25 +#endif + +#ifdef __MBED_CMSIS_RTOS_CA9 +// <o>Idle stack size [bytes] <64-4096:8><#/4> +// <i> Defines default stack size for the Idle thread. +#ifndef OS_IDLESTKSIZE + #define OS_IDLESTKSIZE 128 +#endif +#else // __MBED_CMSIS_RTOS_CA9 +// <o>Default Thread stack size [bytes] <64-4096:8><#/4> +// <i> Defines default stack size for threads with osThreadDef stacksz = 0 +// <i> Default: 200 +#ifndef OS_STKSIZE + #define OS_STKSIZE 200 +#endif +#endif // __MBED_CMSIS_RTOS_CA9 + +// <o>Main Thread stack size [bytes] <64-4096:8><#/4> +// <i> Defines stack size for main thread. +// <i> Default: 4096 +#ifndef OS_MAINSTKSIZE + #define OS_MAINSTKSIZE 4096 +#endif + +#ifndef __MBED_CMSIS_RTOS_CA9 +// <o>Number of threads with user-provided stack size <0-250> +// <i> Defines the number of threads with user-provided stack size. +// <i> Default: 0 +#ifndef OS_PRIVCNT + #define OS_PRIVCNT 0 +#endif + +// <o>Total stack size [bytes] for threads with user-provided stack size <0-4096:8><#/4> +// <i> Defines the combined stack size for threads with user-provided stack size. +// <i> Default: 0 +#ifndef OS_PRIVSTKSIZE + #define OS_PRIVSTKSIZE 0 +#endif +#endif // __MBED_CMSIS_RTOS_CA9 + +// <q>Check for stack overflow +// <i> Includes the stack checking code for stack overflow. +// <i> Note that additional code reduces the Kernel performance. +#ifndef OS_STKCHECK + #define OS_STKCHECK 1 +#endif + +// <o>Processor mode for thread execution +// <0=> Unprivileged mode +// <1=> Privileged mode +// <i> Default: Privileged mode +#ifndef OS_RUNPRIV + #define OS_RUNPRIV 1 +#endif + +// </h> + +// <h>RTX Kernel Timer Tick Configuration +// ====================================== +// <q> Use Cortex-M SysTick timer as RTX Kernel Timer +// <i> Use the Cortex-M SysTick timer as a time-base for RTX. +#ifndef OS_SYSTICK + #define OS_SYSTICK 0 +#endif +// +// <o>Timer clock value [Hz] <1-1000000000> +// <i> Defines the timer clock value. +// <i> Default: 12000000 (12MHz) +#ifndef OS_CLOCK + #error "no target defined" +#endif + +// <o>Timer tick value [us] <1-1000000> +// <i> Defines the timer tick value. +// <i> Default: 1000 (1ms) +#ifndef OS_TICK + #define OS_TICK 1000 +#endif + +// </h> + +// <h>System Configuration +// ======================= +// +// <e>Round-Robin Thread switching +// =============================== +// +// <i> Enables Round-Robin Thread switching. +#ifndef OS_ROBIN + #define OS_ROBIN 1 +#endif + +// <o>Round-Robin Timeout [ticks] <1-1000> +// <i> Defines how long a thread will execute before a thread switch. +// <i> Default: 5 +#ifndef OS_ROBINTOUT + #define OS_ROBINTOUT 5 +#endif + +// </e> + +// <e>User Timers +// ============== +// <i> Enables user Timers +#ifndef OS_TIMERS + #define OS_TIMERS 1 +#endif + +// <o>Timer Thread Priority +// <1=> Low +// <2=> Below Normal <3=> Normal <4=> Above Normal +// <5=> High +// <6=> Realtime (highest) +// <i> Defines priority for Timer Thread +// <i> Default: High +#ifndef OS_TIMERPRIO + #define OS_TIMERPRIO 5 +#endif + +// <o>Timer Thread stack size [bytes] <64-4096:8><#/4> +// <i> Defines stack size for Timer thread. +// <i> Default: 200 +#ifndef OS_TIMERSTKSZ + #define OS_TIMERSTKSZ WORDS_STACK_SIZE +#endif + +// <o>Timer Callback Queue size <1-32> +// <i> Number of concurrent active timer callback functions. +// <i> Default: 4 +#ifndef OS_TIMERCBQS + #define OS_TIMERCBQS 4 +#endif + +// </e> + +// <o>ISR FIFO Queue size<4=> 4 entries <8=> 8 entries +// <12=> 12 entries <16=> 16 entries +// <24=> 24 entries <32=> 32 entries +// <48=> 48 entries <64=> 64 entries +// <96=> 96 entries +// <i> ISR functions store requests to this buffer, +// <i> when they are called from the interrupt handler. +// <i> Default: 16 entries +#ifndef OS_FIFOSZ + #define OS_FIFOSZ 16 +#endif + +// </h> + +//------------- <<< end of configuration section >>> ----------------------- + +// Standard library system mutexes +// =============================== +// Define max. number system mutexes that are used to protect +// the arm standard runtime library. For microlib they are not used. +#ifndef OS_MUTEXCNT + #define OS_MUTEXCNT 12 +#endif + +/*---------------------------------------------------------------------------- + * RTX User configuration part END + *---------------------------------------------------------------------------*/ + +#define OS_TRV ((uint32_t)(((double)OS_CLOCK*(double)OS_TICK)/1E6)-1) + + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +/*--------------------------- os_idle_demon ---------------------------------*/ +extern void rtos_idle_loop(void); + +void os_idle_demon (void) { + /* The idle demon is a system thread, running when no other thread is */ + /* ready to run. */ + rtos_idle_loop(); +} + +#if (OS_SYSTICK == 0) // Functions for alternative timer as RTX kernel timer + +/*--------------------------- os_tick_init ----------------------------------*/ +#if defined(TARGET_RZ_A1H) || defined(TARGET_VK_RZ_A1H) +#define OSTM0 (0xFCFEC000uL) /* OSTM0 */ +#define OSTM1 (0xFCFEC400uL) /* OSTM1 */ +#define CPG (0xFCFE0410uL) /* CPG */ + +#define CPGSTBCR5 (*((volatile unsigned char*)(CPG + 0x00000018uL))) + +#define OSTM0CMP (*((volatile unsigned long*)(OSTM0 + 0x00000000uL))) +#define OSTM0CNT (*((volatile unsigned long*)(OSTM0 + 0x00000004uL))) +#define OSTM0TE (*((volatile unsigned char*)(OSTM0 + 0x00000010uL))) +#define OSTM0TS (*((volatile unsigned char*)(OSTM0 + 0x00000014uL))) +#define OSTM0TT (*((volatile unsigned char*)(OSTM0 + 0x00000018uL))) +#define OSTM0CTL (*((volatile unsigned char*)(OSTM0 + 0x00000020uL))) + +#define OSTM1CMP (*((volatile unsigned long*)(OSTM1 + 0x00000000uL))) +#define OSTM1CNT (*((volatile unsigned long*)(OSTM1 + 0x00000004uL))) +#define OSTM1TE (*((volatile unsigned char*)(OSTM1 + 0x00000010uL))) +#define OSTM1TS (*((volatile unsigned char*)(OSTM1 + 0x00000014uL))) +#define OSTM1TT (*((volatile unsigned char*)(OSTM1 + 0x00000018uL))) +#define OSTM1CTL (*((volatile unsigned char*)(OSTM1 + 0x00000020uL))) + +#define CPG_STBCR5_BIT_MSTP51 (0x02u) /* OSTM0 */ +#define CM1_RENESAS_RZ_A1_P0_CLK ( 32000000u) +#define CM0_RENESAS_RZ_A1_P0_CLK ( 33333333u) + +typedef enum +{ + IRQ_SGI0 = 0, + IRQ_OSTMI0TINT = 134 +} IRQn_Type; + +typedef void(*IRQHandler)(); + +extern void PendSV_Handler(uint32_t); +extern void OS_Tick_Handler(uint32_t); +extern uint32_t InterruptHandlerRegister (IRQn_Type irq, IRQHandler handler); +#endif + +// Initialize alternative hardware timer as RTX kernel timer +// Return: IRQ number of the alternative hardware timer +int os_tick_init (void) { +#if defined(TARGET_RZ_A1H) || defined(TARGET_VK_RZ_A1H) + CPGSTBCR5 &= ~(CPG_STBCR5_BIT_MSTP51); /* enable OSTM0 clock */ + + OSTM0TT = 0x1; /* Stop the counter and clears the OSTM0TE bit. */ + OSTM0CTL = 0x1; /* Interval timer mode. Interrupt enabled */ + + OSTM0CMP = (uint32_t)(((double)CM0_RENESAS_RZ_A1_P0_CLK*(double)OS_TICK)/1E6); + + OSTM0TS = 0x1; /* Start the counter and sets the OSTM0TE bit. */ + + InterruptHandlerRegister(IRQ_SGI0 , (IRQHandler)PendSV_Handler); + InterruptHandlerRegister(IRQ_OSTMI0TINT, (IRQHandler)OS_Tick_Handler); + + + return IRQ_OSTMI0TINT; /* Return IRQ number of timer (0..239) */ + /* RTX will set and configure the interrupt */ +#endif +} + +/*--------------------------- os_tick_irqack --------------------------------*/ + +// Acknowledge alternative hardware timer interrupt +void os_tick_irqack (void) { + /* ... */ +} + +#endif // (OS_SYSTICK == 0) + +/*--------------------------- os_error --------------------------------------*/ +extern void mbed_die(void); + +void os_error (uint32_t err_code) { + /* This function is called when a runtime error is detected. Parameter */ + /* 'err_code' holds the runtime error code (defined in RTL.H). */ + mbed_die(); + + /* HERE: include optional code to be executed on runtime error. */ + for (;;); +} + +/*---------------------------------------------------------------------------- + * RTX Hooks + *---------------------------------------------------------------------------*/ +extern void thread_terminate_hook(osThreadId id); + +void sysThreadTerminate(osThreadId id) { + thread_terminate_hook(id); +} + +/*---------------------------------------------------------------------------- + * RTX Configuration Functions + *---------------------------------------------------------------------------*/ + +#include "RTX_CM_lib.h" + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/RTX_Config.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,78 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RTX_CONFIG.H + * Purpose: Exported functions of RTX_Config.c + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + + +/* Error Codes */ +#define OS_ERR_STK_OVF 1 +#define OS_ERR_FIFO_OVF 2 +#define OS_ERR_MBX_OVF 3 + +/* Definitions */ +#define BOX_ALIGN_8 0x80000000 +#define _declare_box(pool,size,cnt) U32 pool[(((size)+3)/4)*(cnt) + 3] +#define _declare_box8(pool,size,cnt) U64 pool[(((size)+7)/8)*(cnt) + 2] +#define _init_box8(pool,size,bsize) _init_box (pool,size,(bsize) | BOX_ALIGN_8) + +/* Variables */ +extern U32 mp_tcb[]; +extern U64 mp_stk[]; +extern U32 os_fifo[]; +extern void *os_active_TCB[]; + +/* Constants */ +extern U16 const os_maxtaskrun; +extern U32 const os_trv; +extern U8 const os_flags; +extern U32 const os_stackinfo; +extern U32 const os_rrobin; +extern U32 const os_clockrate; +extern U32 const os_timernum; +extern U16 const mp_tcb_size; +extern U32 const mp_stk_size; +extern U32 const *m_tmr; +extern U16 const mp_tmr_size; +extern U8 const os_fifo_size; + +/* Functions */ +extern void os_idle_demon (void); +extern int os_tick_init (void); +extern U32 os_tick_val (void); +extern U32 os_tick_ovf (void); +extern void os_tick_irqack (void); +extern void os_tmr_call (U16 info); +extern void os_error (U32 err_code); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_ARM/HAL_CA9.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,437 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CA9.c + * Purpose: Hardware Abstraction Layer for Cortex-A9 + * Rev.: 8 April 2015 + *---------------------------------------------------------------------------- + * + * Copyright (c) 2012 - 2015 ARM Limited + * 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_Task.h" +#include "rt_List.h" +#include "rt_MemBox.h" +#include "rt_HAL_CA.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + +//For A-class, set USR/SYS stack +__asm void rt_set_PSP (U32 stack) { + ARM + + MRS R1, CPSR + CPS #MODE_SYS ;no effect in USR mode + ISB + MOV SP, R0 + MSR CPSR_c, R1 ;no effect in USR mode + ISB + BX LR + +} + +//For A-class, get USR/SYS stack +__asm U32 rt_get_PSP (void) { + ARM + + MRS R1, CPSR + CPS #MODE_SYS ;no effect in USR mode + ISB + MOV R0, SP + MSR CPSR_c, R1 ;no effect in USR mode + ISB + BX LR +} + +/*--------------------------- _alloc_box ------------------------------------*/ +__asm void *_alloc_box (void *box_mem) { + /* Function wrapper for Unprivileged/Privileged mode. */ + ARM + + LDR R12,=__cpp(rt_alloc_box) + MRS R2, CPSR + LSLS R2, #28 + BXNE R12 + SVC 0 + BX LR +} + + +/*--------------------------- _free_box -------------------------------------*/ +__asm int _free_box (void *box_mem, void *box) { + /* Function wrapper for Unprivileged/Privileged mode. */ + ARM + + LDR R12,=__cpp(rt_free_box) + MRS R2, CPSR + LSLS R2, #28 + BXNE R12 + SVC 0 + BX LR + +} + +/*-------------------------- SVC_Handler -----------------------------------*/ + +#pragma push +#pragma arm +__asm void SVC_Handler (void) { + PRESERVE8 + ARM + + IMPORT rt_tsk_lock + IMPORT rt_tsk_unlock + IMPORT SVC_Count + IMPORT SVC_Table + IMPORT rt_stk_check + IMPORT FPUEnable + IMPORT scheduler_suspended ; flag set by rt_suspend, cleared by rt_resume, read by SVC_Handler + +Mode_SVC EQU 0x13 + + SRSFD SP!, #Mode_SVC ; Push LR_SVC and SPRS_SVC onto SVC mode stack + PUSH {R4} ; Push R4 so we can use it as a temp + + MRS R4,SPSR ; Get SPSR + TST R4,#CPSR_T_BIT ; Check Thumb Bit + LDRNEH R4,[LR,#-2] ; Thumb: Load Halfword + BICNE R4,R4,#0xFF00 ; Extract SVC Number + LDREQ R4,[LR,#-4] ; ARM: Load Word + BICEQ R4,R4,#0xFF000000 ; Extract SVC Number + + /* Lock out systick and re-enable interrupts */ + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + PUSH {R12, LR} ; Store stack adjustment and dummy LR to SVC stack + + BLX rt_tsk_lock + CPSIE i + + POP {R12, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + POP {R0-R3,R12,LR} + + CMP R4,#0 + BNE SVC_User + + MRS R4,SPSR + PUSH {R4} ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + PUSH {R4, LR} ; Store stack adjustment and dummy LR + BLX R12 + POP {R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + POP {R4} ; Restore R4 + MSR SPSR_CXSF,R4 + + /* Here we will be in SVC mode (even if coming in from PendSV_Handler or OS_Tick_Handler) */ +Sys_Switch + LDR LR,=__cpp(&os_tsk) + LDM LR,{R4,LR} ; os_tsk.run, os_tsk.new_tsk + CMP R4,LR + BNE switching + + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + PUSH {R12, LR} ; Store stack adjustment and dummy LR to SVC stack + + CPSID i + ; Do not unlock scheduler if it has just been suspended by rt_suspend() + LDR R1,=scheduler_suspended + LDRB R0, [R1] + CMP R0, #1 + BEQ dont_unlock + BLX rt_tsk_unlock +dont_unlock + + POP {R12, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + POP {R0-R3,R12,LR} + POP {R4} + RFEFD SP! ; Return from exception, no task switch + +switching + CLREX + CMP R4,#0 + ADDEQ SP,SP,#12 ; Original R4, LR & SPSR do not need to be popped when we are paging in a different task + BEQ SVC_Next ; Runtask deleted? + + + PUSH {R8-R11} //R4 and LR already stacked + MOV R10,R4 ; Preserve os_tsk.run + MOV R11,LR ; Preserve os_tsk.new_tsk + + ADD R8,SP,#16 ; Unstack R4,LR + LDMIA R8,{R4,LR} + + SUB SP,SP,#4 ; Make space on the stack for the next instn + STMIA SP,{SP}^ ; Put User SP onto stack + POP {R8} ; Pop User SP into R8 + + MRS R9,SPSR + STMDB R8!,{R9} ; User CPSR + STMDB R8!,{LR} ; User PC + STMDB R8,{LR}^ ; User LR + SUB R8,R8,#4 ; No writeback for store of User LR + STMDB R8!,{R0-R3,R12} ; User R0-R3,R12 + MOV R3,R10 ; os_tsk.run + MOV LR,R11 ; os_tsk.new_tsk + POP {R9-R12} + ADD SP,SP,#12 ; Fix up SP for unstack of R4, LR & SPSR + STMDB R8!,{R4-R7,R9-R12} ; User R4-R11 + + //If applicable, stack VFP/NEON state + MRC p15,0,R1,c1,c0,2 ; VFP/NEON access enabled? (CPACR) + AND R2,R1,#0x00F00000 + CMP R2,#0x00F00000 + BNE no_outgoing_vfp + VMRS R2,FPSCR + STMDB R8!,{R2,R4} ; Push FPSCR, maintain 8-byte alignment + VSTMDB R8!,{D0-D15} + VSTMDB R8!,{D16-D31} + LDRB R2,[R3,#TCB_STACKF] ; Record in TCB that NEON/D32 state is stacked + ORR R2,#4 + STRB R2,[R3,#TCB_STACKF] + +no_outgoing_vfp + STR R8,[R3,#TCB_TSTACK] + MOV R4,LR + + PUSH {R4} ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + PUSH {R4, LR} ; Store stack adjustment and dummy LR to SVC stack + + BLX rt_stk_check + + POP {R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + POP {R4} ; Restore R4 + + MOV LR,R4 + +SVC_Next //R4 == os_tsk.run, LR == os_tsk.new_tsk, R0-R3, R5-R12 corruptible + LDR R1,=__cpp(&os_tsk) ; os_tsk.run = os_tsk.new_tsk + STR LR,[R1] + LDRB R1,[LR,#TCB_TID] ; os_tsk.run->task_id + LSL R1,#8 ; Store PROCID + MCR p15,0,R1,c13,c0,1 ; Write CONTEXTIDR + + LDR R0,[LR,#TCB_TSTACK] ; os_tsk.run->tsk_stack + + //Does incoming task have VFP/NEON state in stack? + LDRB R3,[LR,#TCB_STACKF] + ANDS R3, R3, #0x6 + MRC p15,0,R1,c1,c0,2 ; Read CPACR + ANDEQ R1,R1,#0xFF0FFFFF ; Disable VFP/NEON access if incoming task does not have stacked VFP/NEON state + ORRNE R1,R1,#0x00F00000 ; Enable VFP/NEON access if incoming task does have stacked VFP/NEON state + MCR p15,0,R1,c1,c0,2 ; Write CPACR + BEQ no_incoming_vfp + ISB ; We only need the sync if we enabled, otherwise we will context switch before next VFP/NEON instruction anyway + VLDMIA R0!,{D16-D31} + VLDMIA R0!,{D0-D15} + LDR R2,[R0] + VMSR FPSCR,R2 + ADD R0,R0,#8 + +no_incoming_vfp + LDR R1,[R0,#60] ; Restore User CPSR + MSR SPSR_CXSF,R1 + LDMIA R0!,{R4-R11} ; Restore User R4-R11 + ADD R0,R0,#4 ; Restore User R1-R3,R12 + LDMIA R0!,{R1-R3,R12} + LDMIA R0,{LR}^ ; Restore User LR + ADD R0,R0,#4 ; No writeback for load to user LR + LDMIA R0!,{LR} ; Restore User PC + ADD R0,R0,#4 ; Correct User SP for unstacked user CPSR + + PUSH {R0} ; Push R0 onto stack + LDMIA SP,{SP}^ ; Get R0 off stack into User SP + ADD SP,SP,#4 ; Put SP back + + LDR R0,[R0,#-32] ; Restore R0 + + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + PUSH {R12, LR} ; Store stack adjustment and dummy LR to SVC stack + + CPSID i + BLX rt_tsk_unlock + + POP {R12, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + POP {R0-R3,R12,LR} + + MOVS PC,LR ; Return from exception + + + /*------------------- User SVC -------------------------------*/ + +SVC_User + LDR R12,=SVC_Count + LDR R12,[R12] + CMP R4,R12 ; Check for overflow + BHI SVC_Done + + LDR R12,=SVC_Table-4 + LDR R12,[R12,R4,LSL #2] ; Load SVC Function Address + MRS R4,SPSR ; Save SPSR + PUSH {R4} ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + PUSH {R4, LR} ; Store stack adjustment and dummy LR + BLX R12 ; Call SVC Function + POP {R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + POP {R4} ; Restore R4 + MSR SPSR_CXSF,R4 ; Restore SPSR + +SVC_Done + PUSH {R0-R3,R12,LR} + + PUSH {R4} ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + PUSH {R4, LR} ; Store stack adjustment and dummy LR + + CPSID i + BLX rt_tsk_unlock + + POP {R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + POP {R4} ; Restore R4 + + POP {R0-R3,R12,LR} + POP {R4} + RFEFD SP! ; Return from exception +} +#pragma pop + +#pragma push +#pragma arm +__asm void PendSV_Handler (U32 IRQn) { + ARM + + IMPORT rt_tsk_lock + IMPORT IRQNestLevel ; Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + IMPORT seen_id0_active ; Flag used to workaround GIC 390 errata 733075 - set in startup_Renesas_RZ_A1.s + + ADD SP,SP,#8 //fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + //Disable systick interrupts, then write EOIR. We want interrupts disabled before we enter the context switcher. + PUSH {R0, R1} + BLX rt_tsk_lock + POP {R0, R1} + LDR R1, =__cpp(&GICInterface_BASE) + LDR R1, [R1, #0] + STR R0, [R1, #0x10] + + ; If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STRBEQ R0, [R1] ; Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel ; Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 ; Decrement nesting counter + STR R1, [R0] + + BLX __cpp(rt_pop_req) + + POP {R1, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R1 ; Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_CXSF,R0 + POP {R0-R3,R12} ; Leave SPSR & LR on the stack + PUSH {R4} + B Sys_Switch +} +#pragma pop + + +#pragma push +#pragma arm +__asm void OS_Tick_Handler (U32 IRQn) { + ARM + + IMPORT rt_tsk_lock + IMPORT IRQNestLevel ; Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + IMPORT seen_id0_active ; Flag used to workaround GIC 390 errata 733075 - set in startup_Renesas_RZ_A1.s + + ADD SP,SP,#8 //fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + PUSH {R0, R1} + BLX rt_tsk_lock + POP {R0, R1} + LDR R1, =__cpp(&GICInterface_BASE) + LDR R1, [R1, #0] + STR R0, [R1, #0x10] + + ; If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STRBEQ R0, [R1] ; Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel ; Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 ; Decrement nesting counter + STR R1, [R0] + + BLX __cpp(os_tick_irqack) + BLX __cpp(rt_systick) + + POP {R1, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R1 ; Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_CXSF,R0 + POP {R0-R3,R12} ; Leave SPSR & LR on the stack + PUSH {R4} + B Sys_Switch +} +#pragma pop + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_ARM/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,57 @@ +;/*---------------------------------------------------------------------------- +; * RL-ARM - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + AREA SVC_TABLE, CODE, READONLY + + EXPORT SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + EXPORT SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTL Kernel. +; DCD __SVC_1 ; InitMemorySubsystem + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_GCC/HAL_CA9.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,472 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CA9.c + * Purpose: Hardware Abstraction Layer for Cortex-A9 + * Rev.: 8 April 2015 + *---------------------------------------------------------------------------- + * + * Copyright (c) 2012 - 2015 ARM Limited + * 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. + *---------------------------------------------------------------------------*/ + + .global rt_set_PSP + .global rt_get_PSP + .global _alloc_box + .global _free_box + .global SVC_Handler + .global PendSV_Handler + .global OS_Tick_Handler + +/* macro defines form rt_HAL_CA.h */ + .EQU CPSR_T_BIT, 0x20 + .EQU CPSR_I_BIT, 0x80 + .EQU CPSR_F_BIT, 0x40 + + .EQU MODE_USR, 0x10 + .EQU MODE_FIQ, 0x11 + .EQU MODE_IRQ, 0x12 + .EQU MODE_SVC, 0x13 + .EQU MODE_ABT, 0x17 + .EQU MODE_UND, 0x1B + .EQU MODE_SYS, 0x1F + +/* macro defines form rt_TypeDef.h */ + .EQU TCB_TID, 3 /* 'task id' offset */ + .EQU TCB_STACKF, 37 /* 'stack_frame' offset */ + .EQU TCB_TSTACK, 44 /* 'tsk_stack' offset for LARGE_STACK */ + + + .extern rt_alloc_box + .extern os_tsk + .extern GICInterface_BASE + .extern rt_pop_req + .extern os_tick_irqack + .extern rt_systick + + .text + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + +@ For A-class, set USR/SYS stack +@ __asm void rt_set_PSP (U32 stack) { +rt_set_PSP: + .ARM + + MRS R1, CPSR + CPS #MODE_SYS @no effect in USR mode + ISB + MOV SP, R0 + MSR CPSR_c, R1 @no effect in USR mode + ISB + BX LR + +@ } + +@ For A-class, get USR/SYS stack +@ __asm U32 rt_get_PSP (void) { +rt_get_PSP: + .ARM + + MRS R1, CPSR + CPS #MODE_SYS @no effect in USR mode + ISB + MOV R0, SP + MSR CPSR_c, R1 @no effect in USR mode + ISB + BX LR +@ } + +/*--------------------------- _alloc_box ------------------------------------*/ +@ __asm void *_alloc_box (void *box_mem) { +_alloc_box: + /* Function wrapper for Unprivileged/Privileged mode. */ + .ARM + + LDR R12,=rt_alloc_box + MRS R2, CPSR + LSLS R2, #28 + BXNE R12 + SVC 0 + BX LR +@ } + + +/*--------------------------- _free_box -------------------------------------*/ +@ __asm int _free_box (void *box_mem, void *box) { +_free_box: + /* Function wrapper for Unprivileged/Privileged mode. */ + .ARM + + LDR R12,=rt_free_box + MRS R2, CPSR + LSLS R2, #28 + BXNE R12 + SVC 0 + BX LR + +@ } + +/*-------------------------- SVC_Handler -----------------------------------*/ + +@ #pragma push +@ #pragma arm +@ __asm void SVC_Handler (void) { +SVC_Handler: + .eabi_attribute Tag_ABI_align8_preserved,1 + .ARM + + .extern rt_tsk_lock + .extern rt_tsk_unlock + .extern SVC_Count + .extern SVC_Table + .extern rt_stk_check + .extern FPUEnable + .extern scheduler_suspended @ flag set by rt_suspend, cleared by rt_resume, read by SVC_Handler + + .EQU Mode_SVC, 0x13 + + SRSDB SP!, #Mode_SVC @ Push LR_SVC and SPRS_SVC onto SVC mode stack @ Use SRSDB because SRSFD isn't supported by GCC-ARM. + PUSH {R4} @ Push R4 so we can use it as a temp + + MRS R4,SPSR @ Get SPSR + TST R4,#CPSR_T_BIT @ Check Thumb Bit + LDRNEH R4,[LR,#-2] @ Thumb: Load Halfword + BICNE R4,R4,#0xFF00 @ Extract SVC Number + LDREQ R4,[LR,#-4] @ ARM: Load Word + BICEQ R4,R4,#0xFF000000 @ Extract SVC Number + + /* Lock out systick and re-enable interrupts */ + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R12 @ Adjust stack + PUSH {R12, LR} @ Store stack adjustment and dummy LR to SVC stack + + BLX rt_tsk_lock + CPSIE i + + POP {R12, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R12 @ Unadjust stack + + POP {R0-R3,R12,LR} + + CMP R4,#0 + BNE SVC_User + + MRS R4,SPSR + PUSH {R4} @ Push R4 so we can use it as a temp + AND R4, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R4 @ Adjust stack + PUSH {R4, LR} @ Store stack adjustment and dummy LR + BLX R12 + POP {R4, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R4 @ Unadjust stack + POP {R4} @ Restore R4 + MSR SPSR_cxsf,R4 + + /* Here we will be in SVC mode (even if coming in from PendSV_Handler or OS_Tick_Handler) */ +Sys_Switch: + LDR LR,=os_tsk + LDM LR,{R4,LR} @ os_tsk.run, os_tsk.new_tsk + CMP R4,LR + BNE switching + + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R12 @ Adjust stack + PUSH {R12, LR} @ Store stack adjustment and dummy LR to SVC stack + + CPSID i + @ Do not unlock scheduler if it has just been suspended by rt_suspend() + LDR R1,=scheduler_suspended + LDRB R0, [R1] + CMP R0, #1 + BEQ dont_unlock + BLX rt_tsk_unlock +dont_unlock: + + POP {R12, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R12 @ Unadjust stack + + POP {R0-R3,R12,LR} + POP {R4} + RFEFD SP! @ Return from exception, no task switch + +switching: + CLREX + CMP R4,#0 + ADDEQ SP,SP,#12 @ Original R4, LR & SPSR do not need to be popped when we are paging in a different task + BEQ SVC_Next @ Runtask deleted? + + + PUSH {R8-R11} @ R4 and LR already stacked + MOV R10,R4 @ Preserve os_tsk.run + MOV R11,LR @ Preserve os_tsk.new_tsk + + ADD R8,SP,#16 @ Unstack R4,LR + LDMIA R8,{R4,LR} + + SUB SP,SP,#4 @ Make space on the stack for the next instn + STMIA SP,{SP}^ @ Put User SP onto stack + POP {R8} @ Pop User SP into R8 + + MRS R9,SPSR + STMDB R8!,{R9} @ User CPSR + STMDB R8!,{LR} @ User PC + STMDB R8,{LR}^ @ User LR + SUB R8,R8,#4 @ No writeback for store of User LR + STMDB R8!,{R0-R3,R12} @ User R0-R3,R12 + MOV R3,R10 @ os_tsk.run + MOV LR,R11 @ os_tsk.new_tsk + POP {R9-R12} + ADD SP,SP,#12 @ Fix up SP for unstack of R4, LR & SPSR + STMDB R8!,{R4-R7,R9-R12} @ User R4-R11 + + @ If applicable, stack VFP/NEON state + MRC p15,0,R1,c1,c0,2 @ VFP/NEON access enabled? (CPACR) + AND R2,R1,#0x00F00000 + CMP R2,#0x00F00000 + BNE no_outgoing_vfp + VMRS R2,FPSCR + STMDB R8!,{R2,R4} @ Push FPSCR, maintain 8-byte alignment + VSTMDB R8!,{D0-D15} + VSTMDB R8!,{D16-D31} + LDRB R2,[R3,#TCB_STACKF] @ Record in TCB that NEON/D32 state is stacked + ORR R2,#4 + STRB R2,[R3,#TCB_STACKF] + +no_outgoing_vfp: + STR R8,[R3,#TCB_TSTACK] + MOV R4,LR + + PUSH {R4} @ Push R4 so we can use it as a temp + AND R4, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R4 @ Adjust stack + PUSH {R4, LR} @ Store stack adjustment and dummy LR to SVC stack + + BLX rt_stk_check + + POP {R4, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R4 @ Unadjust stack + POP {R4} @ Restore R4 + + MOV LR,R4 + +SVC_Next: @ R4 == os_tsk.run, LR == os_tsk.new_tsk, R0-R3, R5-R12 corruptible + LDR R1,=os_tsk @ os_tsk.run = os_tsk.new_tsk + STR LR,[R1] + LDRB R1,[LR,#TCB_TID] @ os_tsk.run->task_id + LSL R1,#8 @ Store PROCID + MCR p15,0,R1,c13,c0,1 @ Write CONTEXTIDR + + LDR R0,[LR,#TCB_TSTACK] @ os_tsk.run->tsk_stack + + @ Does incoming task have VFP/NEON state in stack? + LDRB R3,[LR,#TCB_STACKF] + ANDS R3, R3, #0x6 + MRC p15,0,R1,c1,c0,2 @ Read CPACR + ANDEQ R1,R1,#0xFF0FFFFF @ Disable VFP/NEON access if incoming task does not have stacked VFP/NEON state + ORRNE R1,R1,#0x00F00000 @ Enable VFP/NEON access if incoming task does have stacked VFP/NEON state + MCR p15,0,R1,c1,c0,2 @ Write CPACR + BEQ no_incoming_vfp + ISB @ We only need the sync if we enabled, otherwise we will context switch before next VFP/NEON instruction anyway + VLDMIA R0!,{D16-D31} + VLDMIA R0!,{D0-D15} + LDR R2,[R0] + VMSR FPSCR,R2 + ADD R0,R0,#8 + +no_incoming_vfp: + LDR R1,[R0,#60] @ Restore User CPSR + MSR SPSR_cxsf,R1 + LDMIA R0!,{R4-R11} @ Restore User R4-R11 + ADD R0,R0,#4 @ Restore User R1-R3,R12 + LDMIA R0!,{R1-R3,R12} + LDMIA R0,{LR}^ @ Restore User LR + ADD R0,R0,#4 @ No writeback for load to user LR + LDMIA R0!,{LR} @ Restore User PC + ADD R0,R0,#4 @ Correct User SP for unstacked user CPSR + + PUSH {R0} @ Push R0 onto stack + LDMIA SP,{SP}^ @ Get R0 off stack into User SP + ADD SP,SP,#4 @ Put SP back + + LDR R0,[R0,#-32] @ Restore R0 + + PUSH {R0-R3,R12,LR} + + AND R12, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R12 @ Adjust stack + PUSH {R12, LR} @ Store stack adjustment and dummy LR to SVC stack + + CPSID i + BLX rt_tsk_unlock + + POP {R12, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R12 @ Unadjust stack + + POP {R0-R3,R12,LR} + + MOVS PC,LR @ Return from exception + + + /*------------------- User SVC -------------------------------*/ + +SVC_User: + LDR R12,=SVC_Count + LDR R12,[R12] + CMP R4,R12 @ Check for overflow + BHI SVC_Done + + LDR R12,=SVC_Table-4 + LDR R12,[R12,R4,LSL #2] @ Load SVC Function Address + MRS R4,SPSR @ Save SPSR + PUSH {R4} @ Push R4 so we can use it as a temp + AND R4, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R4 @ Adjust stack + PUSH {R4, LR} @ Store stack adjustment and dummy LR + BLX R12 @ Call SVC Function + POP {R4, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R4 @ Unadjust stack + POP {R4} @ Restore R4 + MSR SPSR_cxsf,R4 @ Restore SPSR + +SVC_Done: + PUSH {R0-R3,R12,LR} + + PUSH {R4} @ Push R4 so we can use it as a temp + AND R4, SP, #4 @ Ensure stack is 8-byte aligned + SUB SP, SP, R4 @ Adjust stack + PUSH {R4, LR} @ Store stack adjustment and dummy LR + + CPSID i + BLX rt_tsk_unlock + + POP {R4, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R4 @ Unadjust stack + POP {R4} @ Restore R4 + + POP {R0-R3,R12,LR} + POP {R4} + RFEFD SP! @ Return from exception +@ } +@ #pragma pop + +@ #pragma push +@ #pragma arm +@ __asm void PendSV_Handler (U32 IRQn) { +PendSV_Handler: + .ARM + + .extern rt_tsk_lock + .extern IRQNestLevel @ Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + .extern seen_id0_active @ Flag used to workaround GIC 390 errata 733075 - set in startup_Renesas_RZ_A1.s + + ADD SP,SP,#8 @ fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + @ Disable systick interrupts, then write EOIR. We want interrupts disabled before we enter the context switcher. + PUSH {R0, R1} + BLX rt_tsk_lock + POP {R0, R1} + LDR R1, =GICInterface_BASE + LDR R1, [R1, #0] + STR R0, [R1, #0x10] + + @ If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STREQB R0, [R1] @ Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel @ Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 @ Decrement nesting counter + STR R1, [R0] + + BLX rt_pop_req + + POP {R1, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R1 @ Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_cxsf,R0 + POP {R0-R3,R12} @ Leave SPSR & LR on the stack + PUSH {R4} + B Sys_Switch +@ } +@ #pragma pop + + +@ #pragma push +@ #pragma arm +@ __asm void OS_Tick_Handler (U32 IRQn) { +OS_Tick_Handler: + .ARM + + .extern rt_tsk_lock + .extern IRQNestLevel @ Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + .extern seen_id0_active @ Flag used to workaround GIC 390 errata 733075 - set in startup_Renesas_RZ_A1.s + + ADD SP,SP,#8 @ fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + PUSH {R0, R1} + BLX rt_tsk_lock + POP {R0, R1} + LDR R1, =GICInterface_BASE + LDR R1, [R1, #0] + STR R0, [R1, #0x10] + + @ If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STREQB R0, [R1] @ Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel @ Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 @ Decrement nesting counter + STR R1, [R0] + + BLX os_tick_irqack + BLX rt_systick + + POP {R1, LR} @ Get stack adjustment & discard dummy LR + ADD SP, SP, R1 @ Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_cxsf,R0 + POP {R0-R3,R12} @ Leave SPSR & LR on the stack + PUSH {R4} + B Sys_Switch +@ } +@ #pragma pop + + + .END +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_GCC/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,57 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: SVC_TABLE.S + * Purpose: Pre-defined SVC Table for Cortex-M + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + + + .section SVC_TABLE @, CODE, READONLY + + .global SVC_Count + +.EQU SVC_Cnt, (SVC_End-SVC_Table)/4 +SVC_Count: .word SVC_Cnt + +@ Import user SVC functions here. +@ .extern __SVC_1 + + .global SVC_Table +SVC_Table: +@ Insert user SVC functions here. SVC 0 used by RTL Kernel. +@ .word __SVC_1 @ InitMemorySubsystem + +SVC_End: + + .END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/HAL_CA9.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CA9.c + * Purpose: Hardware Abstraction Layer for Cortex-A9 + * Rev.: 23 March 2015 + *---------------------------------------------------------------------------- + * + * Copyright (c) 2012 - 2015 ARM Limited + * 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. + *---------------------------------------------------------------------------*/ + +//unsigned char seen_id0_active = 0; // single byte to hold a flag used in the workaround for GIC errata 733075 + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + +/* Functions move to HAL_CA9_asm.S */ + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/HAL_CA9_asm.s Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,480 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CA9.c + * Purpose: Hardware Abstraction Layer for Cortex-A9 + * Rev.: 8 April 2015 + *---------------------------------------------------------------------------- + * + * Copyright (c) 2012 - 2015 ARM Limited + * 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. + *---------------------------------------------------------------------------*/ + + PUBLIC rt_set_PSP + PUBLIC rt_get_PSP + PUBLIC _alloc_box + PUBLIC _free_box + PUBLIC SWI_Handler + PUBLIC PendSV_Handler + PUBLIC OS_Tick_Handler + +/* macro defines form rt_HAL_CA.h */ +#define CPSR_T_BIT 0x20 +#define CPSR_I_BIT 0x80 +#define CPSR_F_BIT 0x40 + +#define MODE_USR 0x10 +#define MODE_FIQ 0x11 +#define MODE_IRQ 0x12 +#define MODE_SVC 0x13 +#define MODE_ABT 0x17 +#define MODE_UND 0x1B +#define MODE_SYS 0x1F + +/* macro defines form rt_TypeDef.h */ +#define TCB_TID 3 /* 'task id' offset */ +#define TCB_STACKF 37 /* 'stack_frame' offset */ +#ifndef __LARGE_PRIV_STACK +#define TCB_TSTACK 40 /* 'tsk_stack' offset */ +#else +#define TCB_TSTACK 44 /* 'tsk_stack' offset for LARGE_STACK */ +#endif + + + IMPORT rt_alloc_box + IMPORT rt_free_box + IMPORT os_tsk + IMPORT GICInterface_BASE + IMPORT rt_pop_req + IMPORT os_tick_irqack + IMPORT rt_systick + + SECTION `.text`:CODE:ROOT(2) + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + +//For A-class, set USR/SYS stack +//__asm void rt_set_PSP (U32 stack) { +rt_set_PSP: + ARM + + MRS R1, CPSR + CPS #MODE_SYS ;no effect in USR mode + ISB + MOV SP, R0 + MSR CPSR_c, R1 ;no effect in USR mode + ISB + BX LR + +//} + +//For A-class, get USR/SYS stack +//__asm U32 rt_get_PSP (void) { +rt_get_PSP: + ARM + + MRS R1, CPSR + CPS #MODE_SYS ;no effect in USR mode + ISB + MOV R0, SP + MSR CPSR_c, R1 ;no effect in USR mode + ISB + BX LR +//} + +/*--------------------------- _alloc_box ------------------------------------*/ +//__asm void *_alloc_box (void *box_mem) { +_alloc_box: + /* Function wrapper for Unprivileged/Privileged mode. */ + ARM + + LDR R12,=(rt_alloc_box) + MRS R2, CPSR + LSLS R2, R2,#28 + BXNE R12 + SVC 0 + BX LR +//} + + +/*--------------------------- _free_box -------------------------------------*/ +//__asm int _free_box (void *box_mem, void *box) { +_free_box: + /* Function wrapper for Unprivileged/Privileged mode. */ + + LDR R12,=(rt_free_box) + MRS R2, CPSR + LSLS R2, R2,#28 + BXNE R12 + SVC 0 + BX LR + +//} + +/*-------------------------- SWI_Handler -----------------------------------*/ + +//#pragma push +//#pragma arm +//__asm void SWI_Handler (void) { +SWI_Handler: + PRESERVE8 + ARM + + IMPORT rt_tsk_lock + IMPORT rt_tsk_unlock + IMPORT SVC_Count + IMPORT SVC_Table + IMPORT rt_stk_check + IMPORT FPUEnable + IMPORT scheduler_suspended ; flag set by rt_suspend, cleared by rt_resume, read by SWI_Handler + +Mode_SVC EQU 0x13 + + SRSDB #Mode_SVC! ; Push LR_SVC and SPRS_SVC onto SVC mode stack + STR R4,[SP,#-0x4]! ; Push R4 so we can use it as a temp + + MRS R4,SPSR ; Get SPSR + TST R4,#CPSR_T_BIT ; Check Thumb Bit + LDRNEH R4,[LR,#-2] ; Thumb: Load Halfword + BICNE R4,R4,#0xFF00 ; Extract SVC Number + LDREQ R4,[LR,#-4] ; ARM: Load Word + BICEQ R4,R4,#0xFF000000 ; Extract SVC Number + + /* Lock out systick and re-enable interrupts */ + STMDB SP!,{R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + STMDB SP!,{R12, LR} ; Store stack adjustment and dummy LR to SVC stack + + BLX rt_tsk_lock + CPSIE i + + LDMIA SP!,{R12,LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + LDMIA SP!,{R0-R3,R12,LR} + + CMP R4,#0 + BNE SVC_User + + MRS R4,SPSR + STR R4,[SP,#-0x4]! ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + STMDB SP!,{R4, LR} ; Store stack adjustment and dummy LR + BLX R12 + LDMIA SP!,{R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + LDR R4,[SP],#0x4 ; Restore R4 + MSR SPSR_CXSF,R4 + + /* Here we will be in SVC mode (even if coming in from PendSV_Handler or OS_Tick_Handler) */ +Sys_Switch: + LDR LR,=(os_tsk) + LDMIA LR,{R4,LR} ; os_tsk.run, os_tsk.new + CMP R4,LR + BNE switching + + STMDB SP!,{R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + STMDB SP!,{R12,LR} ; Store stack adjustment and dummy LR to SVC stack + + CPSID i + ; Do not unlock scheduler if it has just been suspended by rt_suspend() + LDR R1,=scheduler_suspended + LDRB R0, [R1] + CMP R0, #1 + BEQ dont_unlock + BLX rt_tsk_unlock +dont_unlock: + + LDMIA SP!,{R12,LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + LDMIA SP!,{R0-R3,R12,LR} + LDR R4,[SP],#0x4 + RFEFD SP! ; Return from exception, no task switch + +switching: + CLREX + CMP R4,#0 + ADDEQ SP,SP,#12 ; Original R4, LR & SPSR do not need to be popped when we are paging in a different task + BEQ SVC_Next ; Runtask deleted? + + + STMDB SP!,{R8-R11} //R4 and LR already stacked + MOV R10,R4 ; Preserve os_tsk.run + MOV R11,LR ; Preserve os_tsk.new + + ADD R8,SP,#16 ; Unstack R4,LR + LDMIA R8,{R4,LR} + + SUB SP,SP,#4 ; Make space on the stack for the next instn + STMIA SP,{SP}^ ; Put User SP onto stack + LDR R8,[SP],#0x4 ; Pop User SP into R8 + + MRS R9,SPSR + STMDB R8!,{R9} ; User CPSR + STMDB R8!,{LR} ; User PC + STMDB R8,{LR}^ ; User LR + SUB R8,R8,#4 ; No writeback for store of User LR + STMDB R8!,{R0-R3,R12} ; User R0-R3,R12 + MOV R3,R10 ; os_tsk.run + MOV LR,R11 ; os_tsk.new + LDMIA SP!,{R9-R12} + ADD SP,SP,#12 ; Fix up SP for unstack of R4, LR & SPSR + STMDB R8!,{R4-R7,R9-R12} ; User R4-R11 + + //If applicable, stack VFP/NEON state + MRC p15,0,R1,c1,c0,2 ; VFP/NEON access enabled? (CPACR) + AND R2,R1,#0x00F00000 + CMP R2,#0x00F00000 + BNE no_outgoing_vfp + VMRS R2,FPSCR + STMDB R8!,{R2,R4} ; Push FPSCR, maintain 8-byte alignment + //IF {TARGET_FEATURE_EXTENSION_REGISTER_COUNT} == 32 + VSTMDB R8!,{D0-D15} + VSTMDB R8!,{D16-D31} + LDRB R2,[R3,#TCB_STACKF] ; Record in TCB that NEON/D32 state is stacked + ORR R2,R2,#4 + STRB R2,[R3,#TCB_STACKF] + //ENDIF + +no_outgoing_vfp: + STR R8,[R3,#TCB_TSTACK] + MOV R4,LR + + STR R4,[SP,#-0x4]! ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + STMDB SP!,{R4, LR} ; Store stack adjustment and dummy LR to SVC stack + + BLX rt_stk_check + + LDMIA SP!,{R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + LDR R4,[SP],#0x4 ; Restore R4 + + MOV LR,R4 + +SVC_Next: //R4 == os_tsk.run, LR == os_tsk.new, R0-R3, R5-R12 corruptible + LDR R1,=(os_tsk) ; os_tsk.run = os_tsk.new + STR LR,[R1] + LDRB R1,[LR,#TCB_TID] ; os_tsk.run->task_id + LSL R1,R1,#8 ; Store PROCID + MCR p15,0,R1,c13,c0,1 ; Write CONTEXTIDR + + LDR R0,[LR,#TCB_TSTACK] ; os_tsk.run->tsk_stack + + //Does incoming task have VFP/NEON state in stack? + LDRB R3,[LR,#TCB_STACKF] + ANDS R3, R3, #0x6 + MRC p15,0,R1,c1,c0,2 ; Read CPACR + BICEQ R1,R1,#0x00F00000 ; Disable VFP/NEON access if incoming task does not have stacked VFP/NEON state + ORRNE R1,R1,#0x00F00000 ; Enable VFP/NEON access if incoming task does have stacked VFP/NEON state + MCR p15,0,R1,c1,c0,2 ; Write CPACR + BEQ no_incoming_vfp + ISB ; We only need the sync if we enabled, otherwise we will context switch before next VFP/NEON instruction anyway + //IF {TARGET_FEATURE_EXTENSION_REGISTER_COUNT} == 32 + VLDMIA R0!,{D16-D31} + //ENDIF + VLDMIA R0!,{D0-D15} + LDR R2,[R0] + VMSR FPSCR,R2 + ADD R0,R0,#8 + +no_incoming_vfp: + LDR R1,[R0,#60] ; Restore User CPSR + MSR SPSR_CXSF,R1 + LDMIA R0!,{R4-R11} ; Restore User R4-R11 + ADD R0,R0,#4 ; Restore User R1-R3,R12 + LDMIA R0!,{R1-R3,R12} + LDMIA R0,{LR}^ ; Restore User LR + ADD R0,R0,#4 ; No writeback for load to user LR + LDMIA R0!,{LR} ; Restore User PC + ADD R0,R0,#4 ; Correct User SP for unstacked user CPSR + + STR R0,[SP,#-0x4]! ; Push R0 onto stack + LDMIA SP,{SP}^ ; Get R0 off stack into User SP + ADD SP,SP,#4 ; Put SP back + + LDR R0,[R0,#-32] ; Restore R0 + + STMDB SP!,{R0-R3,R12,LR} + + AND R12, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R12 ; Adjust stack + STMDB sp!,{R12, LR} ; Store stack adjustment and dummy LR to SVC stack + + CPSID i + BLX rt_tsk_unlock + + LDMIA sp!,{R12, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R12 ; Unadjust stack + + LDMIA SP!,{R0-R3,R12,LR} + + MOVS PC,LR ; Return from exception + + + /*------------------- User SVC -------------------------------*/ + +SVC_User: + LDR R12,=SVC_Count + LDR R12,[R12] + CMP R4,R12 ; Check for overflow + BHI SVC_Done + + LDR R12,=SVC_Table-4 + LDR R12,[R12,R4,LSL #2] ; Load SVC Function Address + MRS R4,SPSR ; Save SPSR + STR R4,[SP,#-0x4]! ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + STMDB SP!,{R4, LR} ; Store stack adjustment and dummy LR + BLX R12 ; Call SVC Function + LDMIA SP!,{R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + LDR R4,[SP],#0x4 ; Restore R4 + MSR SPSR_CXSF,R4 ; Restore SPSR + +SVC_Done: + STMDB sp!,{R0-R3,R12,LR} + + STR R4,[sp,#-0x4]! ; Push R4 so we can use it as a temp + AND R4, SP, #4 ; Ensure stack is 8-byte aligned + SUB SP, SP, R4 ; Adjust stack + STMDB SP!,{R4, LR} ; Store stack adjustment and dummy LR + + CPSID i + BLX rt_tsk_unlock + + LDMIA SP!,{R4, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R4 ; Unadjust stack + LDR R4,[SP],#0x4 ; Restore R4 + + LDMIA SP!,{R0-R3,R12,LR} + LDR R4,[SP],#0x4 + RFEFD SP! ; Return from exception +//} +//#pragma pop + +//#pragma push +//#pragma arm +//__asm void PendSV_Handler (U32 IRQn) { +PendSV_Handler: + ARM + + IMPORT rt_tsk_lock + IMPORT IRQNestLevel ; Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + IMPORT seen_id0_active ; Flag used to workaround GIC 390 errata 733075 - set in startup_Renesas_RZ_A1.s + + ADD SP,SP,#8 //fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + //Disable systick interrupts, then write EOIR. We want interrupts disabled before we enter the context switcher. + STMDB SP!,{R0, R1} + BLX rt_tsk_lock + LDMIA SP!,{R0, R1} + LDR R1,=(GICInterface_BASE) + LDR R1, [R1, #0] + STR R0, [R1, #0x10] + + ; If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STRBEQ R0, [R1] ; Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel ; Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 ; Decrement nesting counter + STR R1, [R0] + + BLX (rt_pop_req) + + LDMIA SP!,{R1, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R1 ; Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_CXSF,R0 + LDMIA SP!,{R0-R3,R12} ; Leave SPSR & LR on the stack + STR R4,[SP,#-0x4]! + B Sys_Switch +//} +//#pragma pop + + +//#pragma push +//#pragma arm +//__asm void OS_Tick_Handler (U32 IRQn) { +OS_Tick_Handler: + ARM + + IMPORT rt_tsk_lock + IMPORT IRQNestLevel ; Flag indicates whether inside an ISR, and the depth of nesting. 0 = not in ISR. + IMPORT seen_id0_active ; Flag used to workaround GIC 390 errata 733075 - set in startup_Renesas_RZ_A1.s + + ADD SP,SP,#8 //fix up stack pointer (R0 has been pushed and will never be popped, R1 was pushed for stack alignment) + + STMDB SP!,{R0, R1} + BLX rt_tsk_lock + LDMIA SP!,{R0, R1} + LDR R1, =(GICInterface_BASE) + LDR R1, [R1, #0] + STR R0, [R1, #0x10] + + ; If it was interrupt ID0, clear the seen flag, otherwise return as normal + CMP R0, #0 + LDREQ R1, =seen_id0_active + STRBEQ R0, [R1] ; Clear the seen flag, using R0 (which is 0), to save loading another register + + LDR R0, =IRQNestLevel ; Get address of nesting counter + LDR R1, [R0] + SUB R1, R1, #1 ; Decrement nesting counter + STR R1, [R0] + + BLX (os_tick_irqack) + BLX (rt_systick) + + LDMIA SP!,{R1, LR} ; Get stack adjustment & discard dummy LR + ADD SP, SP, R1 ; Unadjust stack + + LDR R0,[SP,#24] + MSR SPSR_CXSF,R0 + LDMIA SP!,{R0-R3,R12} ; Leave SPSR & LR on the stack + STR R4,[SP,#-0x4]! + B Sys_Switch +//} +//#pragma pop + + + END +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/TOOLCHAIN_IAR/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,57 @@ +;/*---------------------------------------------------------------------------- +; * RL-ARM - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + SECTION SVC_TABLE:CODE:ROOT(2) + + EXPORT SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + EXPORT SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTL Kernel. +; DCD __SVC_1 ; InitMemorySubsystem + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/cmsis_os.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,879 @@ +/* ---------------------------------------------------------------------- + * $Date: 5. February 2013 + * $Revision: V1.02 + * + * Project: CMSIS-RTOS API + * Title: cmsis_os.h RTX header file + * + * Version 0.02 + * Initial Proposal Phase + * Version 0.03 + * osKernelStart added, optional feature: main started as thread + * osSemaphores have standard behavior + * osTimerCreate does not start the timer, added osTimerStart + * osThreadPass is renamed to osThreadYield + * Version 1.01 + * Support for C++ interface + * - const attribute removed from the osXxxxDef_t typedef's + * - const attribute added to the osXxxxDef macros + * Added: osTimerDelete, osMutexDelete, osSemaphoreDelete + * Added: osKernelInitialize + * Version 1.02 + * Control functions for short timeouts in microsecond resolution: + * Added: osKernelSysTick, osKernelSysTickFrequency, osKernelSysTickMicroSec + * Removed: osSignalGet + *---------------------------------------------------------------------------- + * + * Copyright (c) 2013 ARM LIMITED + * 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. + *---------------------------------------------------------------------------*/ + +/** +\page cmsis_os_h Header File Template: cmsis_os.h + +The file \b cmsis_os.h is a template header file for a CMSIS-RTOS compliant Real-Time Operating System (RTOS). +Each RTOS that is compliant with CMSIS-RTOS shall provide a specific \b cmsis_os.h header file that represents +its implementation. + +The file cmsis_os.h contains: + - CMSIS-RTOS API function definitions + - struct definitions for parameters and return types + - status and priority values used by CMSIS-RTOS API functions + - macros for defining threads and other kernel objects + + +<b>Name conventions and header file modifications</b> + +All definitions are prefixed with \b os to give an unique name space for CMSIS-RTOS functions. +Definitions that are prefixed \b os_ are not used in the application code but local to this header file. +All definitions and functions that belong to a module are grouped and have a common prefix, i.e. \b osThread. + +Definitions that are marked with <b>CAN BE CHANGED</b> can be adapted towards the needs of the actual CMSIS-RTOS implementation. +These definitions can be specific to the underlying RTOS kernel. + +Definitions that are marked with <b>MUST REMAIN UNCHANGED</b> cannot be altered. Otherwise the CMSIS-RTOS implementation is no longer +compliant to the standard. Note that some functions are optional and need not to be provided by every CMSIS-RTOS implementation. + + +<b>Function calls from interrupt service routines</b> + +The following CMSIS-RTOS functions can be called from threads and interrupt service routines (ISR): + - \ref osSignalSet + - \ref osSemaphoreRelease + - \ref osPoolAlloc, \ref osPoolCAlloc, \ref osPoolFree + - \ref osMessagePut, \ref osMessageGet + - \ref osMailAlloc, \ref osMailCAlloc, \ref osMailGet, \ref osMailPut, \ref osMailFree + +Functions that cannot be called from an ISR are verifying the interrupt status and return in case that they are called +from an ISR context the status code \b osErrorISR. In some implementations this condition might be caught using the HARD FAULT vector. + +Some CMSIS-RTOS implementations support CMSIS-RTOS function calls from multiple ISR at the same time. +If this is impossible, the CMSIS-RTOS rejects calls by nested ISR functions with the status code \b osErrorISRRecursive. + + +<b>Define and reference object definitions</b> + +With <b>\#define osObjectsExternal</b> objects are defined as external symbols. This allows to create a consistent header file +that is used throughout a project as shown below: + +<i>Header File</i> +\code +#include <cmsis_os.h> // CMSIS RTOS header file + +// Thread definition +extern void thread_sample (void const *argument); // function prototype +osThreadDef (thread_sample, osPriorityBelowNormal, 1, 100); + +// Pool definition +osPoolDef(MyPool, 10, long); +\endcode + + +This header file defines all objects when included in a C/C++ source file. When <b>\#define osObjectsExternal</b> is +present before the header file, the objects are defined as external symbols. A single consistent header file can therefore be +used throughout the whole project. + +<i>Example</i> +\code +#include "osObjects.h" // Definition of the CMSIS-RTOS objects +\endcode + +\code +#define osObjectExternal // Objects will be defined as external symbols +#include "osObjects.h" // Reference to the CMSIS-RTOS objects +\endcode + +*/ + +#ifndef _CMSIS_OS_H +#define _CMSIS_OS_H + +/// \note MUST REMAIN UNCHANGED: \b osCMSIS identifies the CMSIS-RTOS API version. +#define osCMSIS 0x10002 ///< API version (main [31:16] .sub [15:0]) + +/// \note CAN BE CHANGED: \b osCMSIS_KERNEL identifies the underlying RTOS kernel and version number. +#define osCMSIS_RTX ((4<<16)|74) ///< RTOS identification and version (main [31:16] .sub [15:0]) + +/// \note MUST REMAIN UNCHANGED: \b osKernelSystemId shall be consistent in every CMSIS-RTOS. +#define osKernelSystemId "RTX V4.74" ///< RTOS identification string + +#define CMSIS_OS_RTX +#define CMSIS_OS_RTX_CA /* new define for Coretex-A */ + +// The stack space occupied is mainly dependent on the underling C standard library +#if defined(TOOLCHAIN_GCC) || defined(TOOLCHAIN_ARM_STD) || defined(TOOLCHAIN_IAR) +# define WORDS_STACK_SIZE 512 +#elif defined(TOOLCHAIN_ARM_MICRO) +# define WORDS_STACK_SIZE 128 +#endif + +#define DEFAULT_STACK_SIZE (WORDS_STACK_SIZE*4) + +/// \note MUST REMAIN UNCHANGED: \b osFeature_xxx shall be consistent in every CMSIS-RTOS. +#define osFeature_MainThread 1 ///< main thread 1=main can be thread, 0=not available +#define osFeature_Pool 1 ///< Memory Pools: 1=available, 0=not available +#define osFeature_MailQ 1 ///< Mail Queues: 1=available, 0=not available +#define osFeature_MessageQ 1 ///< Message Queues: 1=available, 0=not available +#define osFeature_Signals 16 ///< maximum number of Signal Flags available per thread +#define osFeature_Semaphore 65535 ///< maximum count for \ref osSemaphoreCreate function +#define osFeature_Wait 0 ///< osWait function: 1=available, 0=not available +#define osFeature_SysTick 1 ///< osKernelSysTick functions: 1=available, 0=not available +#define osFeature_ThreadEnum 1 ///< Thread enumeration available + +#if defined (__CC_ARM) +#define os_InRegs __value_in_regs // Compiler specific: force struct in registers +#else +#define os_InRegs +#endif + +#include <stdint.h> +#include <stddef.h> + +#ifdef __cplusplus +extern "C" +{ +#endif + + +// ==== Enumeration, structures, defines ==== + +/// Priority used for thread control. +/// \note MUST REMAIN UNCHANGED: \b osPriority shall be consistent in every CMSIS-RTOS. +typedef enum { + osPriorityIdle = -3, ///< priority: idle (lowest) + osPriorityLow = -2, ///< priority: low + osPriorityBelowNormal = -1, ///< priority: below normal + osPriorityNormal = 0, ///< priority: normal (default) + osPriorityAboveNormal = +1, ///< priority: above normal + osPriorityHigh = +2, ///< priority: high + osPriorityRealtime = +3, ///< priority: realtime (highest) + osPriorityError = 0x84 ///< system cannot determine priority or thread has illegal priority +} osPriority; + +/// Timeout value. +/// \note MUST REMAIN UNCHANGED: \b osWaitForever shall be consistent in every CMSIS-RTOS. +#define osWaitForever 0xFFFFFFFF ///< wait forever timeout value + +/// Status code values returned by CMSIS-RTOS functions. +/// \note MUST REMAIN UNCHANGED: \b osStatus shall be consistent in every CMSIS-RTOS. +typedef enum { + osOK = 0, ///< function completed; no error or event occurred. + osEventSignal = 0x08, ///< function completed; signal event occurred. + osEventMessage = 0x10, ///< function completed; message event occurred. + osEventMail = 0x20, ///< function completed; mail event occurred. + osEventTimeout = 0x40, ///< function completed; timeout occurred. + osErrorParameter = 0x80, ///< parameter error: a mandatory parameter was missing or specified an incorrect object. + osErrorResource = 0x81, ///< resource not available: a specified resource was not available. + osErrorTimeoutResource = 0xC1, ///< resource not available within given time: a specified resource was not available within the timeout period. + osErrorISR = 0x82, ///< not allowed in ISR context: the function cannot be called from interrupt service routines. + osErrorISRRecursive = 0x83, ///< function called multiple times from ISR with same object. + osErrorPriority = 0x84, ///< system cannot determine priority or thread has illegal priority. + osErrorNoMemory = 0x85, ///< system is out of memory: it was impossible to allocate or reserve memory for the operation. + osErrorValue = 0x86, ///< value of a parameter is out of range. + osErrorOS = 0xFF, ///< unspecified RTOS error: run-time error but no other error message fits. + os_status_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization. +} osStatus; + + +/// Timer type value for the timer definition. +/// \note MUST REMAIN UNCHANGED: \b os_timer_type shall be consistent in every CMSIS-RTOS. +typedef enum { + osTimerOnce = 0, ///< one-shot timer + osTimerPeriodic = 1 ///< repeating timer +} os_timer_type; + +typedef enum { + osThreadInfoState, + osThreadInfoStackSize, + osThreadInfoStackMax, + osThreadInfoEntry, + osThreadInfoArg, + + osThreadInfo_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization. +} osThreadInfo; + +/// Entry point of a thread. +/// \note MUST REMAIN UNCHANGED: \b os_pthread shall be consistent in every CMSIS-RTOS. +typedef void (*os_pthread) (void const *argument); + +/// Entry point of a timer call back function. +/// \note MUST REMAIN UNCHANGED: \b os_ptimer shall be consistent in every CMSIS-RTOS. +typedef void (*os_ptimer) (void const *argument); + +// >>> the following data type definitions may shall adapted towards a specific RTOS + +/// Thread ID identifies the thread (pointer to a thread control block). +/// \note CAN BE CHANGED: \b os_thread_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_thread_cb *osThreadId; + +/// Timer ID identifies the timer (pointer to a timer control block). +/// \note CAN BE CHANGED: \b os_timer_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_timer_cb *osTimerId; + +/// Mutex ID identifies the mutex (pointer to a mutex control block). +/// \note CAN BE CHANGED: \b os_mutex_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_mutex_cb *osMutexId; + +/// Semaphore ID identifies the semaphore (pointer to a semaphore control block). +/// \note CAN BE CHANGED: \b os_semaphore_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_semaphore_cb *osSemaphoreId; + +/// Pool ID identifies the memory pool (pointer to a memory pool control block). +/// \note CAN BE CHANGED: \b os_pool_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_pool_cb *osPoolId; + +/// Message ID identifies the message queue (pointer to a message queue control block). +/// \note CAN BE CHANGED: \b os_messageQ_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_messageQ_cb *osMessageQId; + +/// Mail ID identifies the mail queue (pointer to a mail queue control block). +/// \note CAN BE CHANGED: \b os_mailQ_cb is implementation specific in every CMSIS-RTOS. +typedef struct os_mailQ_cb *osMailQId; + +/// Thread enumeration ID identifies the enumeration (pointer to a thread enumeration control block). +typedef uint32_t *osThreadEnumId; + +/// Thread Definition structure contains startup information of a thread. +/// \note CAN BE CHANGED: \b os_thread_def is implementation specific in every CMSIS-RTOS. +typedef struct os_thread_def { + os_pthread pthread; ///< start address of thread function + osPriority tpriority; ///< initial thread priority + uint32_t instances; ///< maximum number of instances of that thread function + uint32_t stacksize; ///< stack size requirements in bytes; 0 is default stack size +#ifdef __MBED_CMSIS_RTOS_CA9 + uint32_t *stack_pointer; ///< pointer to the stack memory block +#endif +} osThreadDef_t; + +/// Timer Definition structure contains timer parameters. +/// \note CAN BE CHANGED: \b os_timer_def is implementation specific in every CMSIS-RTOS. +typedef struct os_timer_def { + os_ptimer ptimer; ///< start address of a timer function + void *timer; ///< pointer to internal data +} osTimerDef_t; + +/// Mutex Definition structure contains setup information for a mutex. +/// \note CAN BE CHANGED: \b os_mutex_def is implementation specific in every CMSIS-RTOS. +typedef struct os_mutex_def { + void *mutex; ///< pointer to internal data +} osMutexDef_t; + +/// Semaphore Definition structure contains setup information for a semaphore. +/// \note CAN BE CHANGED: \b os_semaphore_def is implementation specific in every CMSIS-RTOS. +typedef struct os_semaphore_def { + void *semaphore; ///< pointer to internal data +} osSemaphoreDef_t; + +/// Definition structure for memory block allocation. +/// \note CAN BE CHANGED: \b os_pool_def is implementation specific in every CMSIS-RTOS. +typedef struct os_pool_def { + uint32_t pool_sz; ///< number of items (elements) in the pool + uint32_t item_sz; ///< size of an item + void *pool; ///< pointer to memory for pool +} osPoolDef_t; + +/// Definition structure for message queue. +/// \note CAN BE CHANGED: \b os_messageQ_def is implementation specific in every CMSIS-RTOS. +typedef struct os_messageQ_def { + uint32_t queue_sz; ///< number of elements in the queue + void *pool; ///< memory array for messages +} osMessageQDef_t; + +/// Definition structure for mail queue. +/// \note CAN BE CHANGED: \b os_mailQ_def is implementation specific in every CMSIS-RTOS. +typedef struct os_mailQ_def { + uint32_t queue_sz; ///< number of elements in the queue + uint32_t item_sz; ///< size of an item + void *pool; ///< memory array for mail +} osMailQDef_t; + +/// Event structure contains detailed information about an event. +/// \note MUST REMAIN UNCHANGED: \b os_event shall be consistent in every CMSIS-RTOS. +/// However the struct may be extended at the end. +typedef struct { + osStatus status; ///< status code: event or error information + union { + uint32_t v; ///< message as 32-bit value + void *p; ///< message or mail as void pointer + int32_t signals; ///< signal flags + } value; ///< event value + union { + osMailQId mail_id; ///< mail id obtained by \ref osMailCreate + osMessageQId message_id; ///< message id obtained by \ref osMessageCreate + } def; ///< event definition +} osEvent; + + +// ==== Kernel Control Functions ==== + +/// Initialize the RTOS Kernel for creating objects. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osKernelInitialize shall be consistent in every CMSIS-RTOS. +osStatus osKernelInitialize (void); + +/// Start the RTOS Kernel. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osKernelStart shall be consistent in every CMSIS-RTOS. +osStatus osKernelStart (void); + +/// Check if the RTOS kernel is already started. +/// \note MUST REMAIN UNCHANGED: \b osKernelRunning shall be consistent in every CMSIS-RTOS. +/// \return 0 RTOS is not started, 1 RTOS is started. +int32_t osKernelRunning(void); + +#if (defined (osFeature_SysTick) && (osFeature_SysTick != 0)) // System Timer available + +extern uint32_t const os_tickfreq; +extern uint16_t const os_tickus_i; +extern uint16_t const os_tickus_f; + +/// Get the RTOS kernel system timer counter. +/// \note MUST REMAIN UNCHANGED: \b osKernelSysTick shall be consistent in every CMSIS-RTOS. +/// \return RTOS kernel system timer as 32-bit value +uint32_t osKernelSysTick (void); + +/// The RTOS kernel system timer frequency in Hz. +/// \note Reflects the system timer setting and is typically defined in a configuration file. +#define osKernelSysTickFrequency os_tickfreq + +/// Convert a microseconds value to a RTOS kernel system timer value. +/// \param microsec time value in microseconds. +/// \return time value normalized to the \ref osKernelSysTickFrequency +/* +#define osKernelSysTickMicroSec(microsec) (((uint64_t)microsec * (osKernelSysTickFrequency)) / 1000000) +*/ +#define osKernelSysTickMicroSec(microsec) ((microsec * os_tickus_i) + ((microsec * os_tickus_f) >> 16)) + +#endif // System Timer available + +// ==== Thread Management ==== + +/// Create a Thread Definition with function, priority, and stack requirements. +/// \param name name of the thread function. +/// \param priority initial priority of the thread function. +/// \param instances number of possible thread instances. +/// \param stacksz stack size (in bytes) requirements for the thread function. +/// \note CAN BE CHANGED: The parameters to \b osThreadDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osThreadDef(name, priority, instances, stacksz) \ +extern const osThreadDef_t os_thread_def_##name +#else // define the object +#ifdef __MBED_CMSIS_RTOS_CA9 +#define osThreadDef(name, priority, stacksz) \ +uint32_t os_thread_def_stack_##name [stacksz / sizeof(uint32_t)]; \ +const osThreadDef_t os_thread_def_##name = \ +{ (name), (priority), 1, (stacksz), (os_thread_def_stack_##name) } +#else +#define osThreadDef(name, priority, instances, stacksz) \ +const osThreadDef_t os_thread_def_##name = \ +{ (name), (priority), (instances), (stacksz) } +#endif +#endif + +/// Access a Thread definition. +/// \param name name of the thread definition object. +/// \note CAN BE CHANGED: The parameter to \b osThread shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osThread(name) \ +&os_thread_def_##name + +/// Create a thread and add it to Active Threads and set it to state READY. +/// \param[in] thread_def thread definition referenced with \ref osThread. +/// \param[in] argument pointer that is passed to the thread function as start argument. +/// \return thread ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osThreadCreate shall be consistent in every CMSIS-RTOS. +osThreadId osThreadCreate (const osThreadDef_t *thread_def, void *argument); + +/// Return the thread ID of the current running thread. +/// \return thread ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osThreadGetId shall be consistent in every CMSIS-RTOS. +osThreadId osThreadGetId (void); + +/// Terminate execution of a thread and remove it from Active Threads. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osThreadTerminate shall be consistent in every CMSIS-RTOS. +osStatus osThreadTerminate (osThreadId thread_id); + +/// Pass control to next thread that is in state \b READY. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osThreadYield shall be consistent in every CMSIS-RTOS. +osStatus osThreadYield (void); + +/// Change priority of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] priority new priority value for the thread function. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osThreadSetPriority shall be consistent in every CMSIS-RTOS. +osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority); + +/// Get current priority of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return current priority value of the thread function. +/// \note MUST REMAIN UNCHANGED: \b osThreadGetPriority shall be consistent in every CMSIS-RTOS. +osPriority osThreadGetPriority (osThreadId thread_id); + +#ifdef __MBED_CMSIS_RTOS_CA9 +/// Get current thread state. +uint8_t osThreadGetState (osThreadId thread_id); +#endif + +/// Get into from an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] info information to read. +/// \return current state of the thread function. +/// \return requested info that includes the status code. +os_InRegs osEvent _osThreadGetInfo(osThreadId thread_id, osThreadInfo info); + +// ==== Generic Wait Functions ==== + +/// Wait for Timeout (Time Delay). +/// \param[in] millisec time delay value +/// \return status code that indicates the execution status of the function. +osStatus osDelay (uint32_t millisec); + +#if (defined (osFeature_Wait) && (osFeature_Wait != 0)) // Generic Wait available + +/// Wait for Signal, Message, Mail, or Timeout. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return event that contains signal, message, or mail information or error code. +/// \note MUST REMAIN UNCHANGED: \b osWait shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osWait (uint32_t millisec); + +#endif // Generic Wait available + + +// ==== Timer Management Functions ==== +/// Define a Timer object. +/// \param name name of the timer object. +/// \param function name of the timer call back function. +/// \note CAN BE CHANGED: The parameter to \b osTimerDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osTimerDef(name, function) \ +extern const osTimerDef_t os_timer_def_##name +#else // define the object +#define osTimerDef(name, function) \ +uint32_t os_timer_cb_##name[5]; \ +const osTimerDef_t os_timer_def_##name = \ +{ (function), (os_timer_cb_##name) } +#endif + +/// Access a Timer definition. +/// \param name name of the timer object. +/// \note CAN BE CHANGED: The parameter to \b osTimer shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osTimer(name) \ +&os_timer_def_##name + +/// Create a timer. +/// \param[in] timer_def timer object referenced with \ref osTimer. +/// \param[in] type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior. +/// \param[in] argument argument to the timer call back function. +/// \return timer ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osTimerCreate shall be consistent in every CMSIS-RTOS. +osTimerId osTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument); + +/// Start or restart a timer. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \param[in] millisec time delay value of the timer. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osTimerStart shall be consistent in every CMSIS-RTOS. +osStatus osTimerStart (osTimerId timer_id, uint32_t millisec); + +/// Stop the timer. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osTimerStop shall be consistent in every CMSIS-RTOS. +osStatus osTimerStop (osTimerId timer_id); + +/// Delete a timer that was created by \ref osTimerCreate. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osTimerDelete shall be consistent in every CMSIS-RTOS. +osStatus osTimerDelete (osTimerId timer_id); + + +// ==== Signal Management ==== + +/// Set the specified Signal Flags of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] signals specifies the signal flags of the thread that should be set. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. +/// \note MUST REMAIN UNCHANGED: \b osSignalSet shall be consistent in every CMSIS-RTOS. +int32_t osSignalSet (osThreadId thread_id, int32_t signals); + +/// Clear the specified Signal Flags of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] signals specifies the signal flags of the thread that shall be cleared. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. +/// \note MUST REMAIN UNCHANGED: \b osSignalClear shall be consistent in every CMSIS-RTOS. +int32_t osSignalClear (osThreadId thread_id, int32_t signals); + +/// Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread. +/// \param[in] signals wait until all specified signal flags set or 0 for any single signal flag. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return event flag information or error code. +/// \note MUST REMAIN UNCHANGED: \b osSignalWait shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec); + + +// ==== Mutex Management ==== + +/// Define a Mutex. +/// \param name name of the mutex object. +/// \note CAN BE CHANGED: The parameter to \b osMutexDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osMutexDef(name) \ +extern const osMutexDef_t os_mutex_def_##name +#else // define the object +#define osMutexDef(name) \ +uint32_t os_mutex_cb_##name[4] = { 0 }; \ +const osMutexDef_t os_mutex_def_##name = { (os_mutex_cb_##name) } +#endif + +/// Access a Mutex definition. +/// \param name name of the mutex object. +/// \note CAN BE CHANGED: The parameter to \b osMutex shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osMutex(name) \ +&os_mutex_def_##name + +/// Create and Initialize a Mutex object. +/// \param[in] mutex_def mutex definition referenced with \ref osMutex. +/// \return mutex ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMutexCreate shall be consistent in every CMSIS-RTOS. +osMutexId osMutexCreate (const osMutexDef_t *mutex_def); + +/// Wait until a Mutex becomes available. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMutexWait shall be consistent in every CMSIS-RTOS. +osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec); + +/// Release a Mutex that was obtained by \ref osMutexWait. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMutexRelease shall be consistent in every CMSIS-RTOS. +osStatus osMutexRelease (osMutexId mutex_id); + +/// Delete a Mutex that was created by \ref osMutexCreate. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMutexDelete shall be consistent in every CMSIS-RTOS. +osStatus osMutexDelete (osMutexId mutex_id); + + +// ==== Semaphore Management Functions ==== + +#if (defined (osFeature_Semaphore) && (osFeature_Semaphore != 0)) // Semaphore available + +/// Define a Semaphore object. +/// \param name name of the semaphore object. +/// \note CAN BE CHANGED: The parameter to \b osSemaphoreDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osSemaphoreDef(name) \ +extern const osSemaphoreDef_t os_semaphore_def_##name +#else // define the object +#define osSemaphoreDef(name) \ +uint32_t os_semaphore_cb_##name[2] = { 0 }; \ +const osSemaphoreDef_t os_semaphore_def_##name = { (os_semaphore_cb_##name) } +#endif + +/// Access a Semaphore definition. +/// \param name name of the semaphore object. +/// \note CAN BE CHANGED: The parameter to \b osSemaphore shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osSemaphore(name) \ +&os_semaphore_def_##name + +/// Create and Initialize a Semaphore object used for managing resources. +/// \param[in] semaphore_def semaphore definition referenced with \ref osSemaphore. +/// \param[in] count number of available resources. +/// \return semaphore ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreCreate shall be consistent in every CMSIS-RTOS. +osSemaphoreId osSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count); + +/// Wait until a Semaphore token becomes available. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return number of available tokens, or -1 in case of incorrect parameters. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreWait shall be consistent in every CMSIS-RTOS. +int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec); + +/// Release a Semaphore token. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreRelease shall be consistent in every CMSIS-RTOS. +osStatus osSemaphoreRelease (osSemaphoreId semaphore_id); + +/// Delete a Semaphore that was created by \ref osSemaphoreCreate. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osSemaphoreDelete shall be consistent in every CMSIS-RTOS. +osStatus osSemaphoreDelete (osSemaphoreId semaphore_id); + +#endif // Semaphore available + + +// ==== Memory Pool Management Functions ==== + +#if (defined (osFeature_Pool) && (osFeature_Pool != 0)) // Memory Pool Management available + +/// \brief Define a Memory Pool. +/// \param name name of the memory pool. +/// \param no maximum number of blocks (objects) in the memory pool. +/// \param type data type of a single block (object). +/// \note CAN BE CHANGED: The parameter to \b osPoolDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osPoolDef(name, no, type) \ +extern const osPoolDef_t os_pool_def_##name +#else // define the object +#define osPoolDef(name, no, type) \ +uint32_t os_pool_m_##name[3+((sizeof(type)+3)/4)*(no)]; \ +const osPoolDef_t os_pool_def_##name = \ +{ (no), sizeof(type), (os_pool_m_##name) } +#endif + +/// \brief Access a Memory Pool definition. +/// \param name name of the memory pool +/// \note CAN BE CHANGED: The parameter to \b osPool shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osPool(name) \ +&os_pool_def_##name + +/// Create and Initialize a memory pool. +/// \param[in] pool_def memory pool definition referenced with \ref osPool. +/// \return memory pool ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osPoolCreate shall be consistent in every CMSIS-RTOS. +osPoolId osPoolCreate (const osPoolDef_t *pool_def); + +/// Allocate a memory block from a memory pool. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \return address of the allocated memory block or NULL in case of no memory available. +/// \note MUST REMAIN UNCHANGED: \b osPoolAlloc shall be consistent in every CMSIS-RTOS. +void *osPoolAlloc (osPoolId pool_id); + +/// Allocate a memory block from a memory pool and set memory block to zero. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \return address of the allocated memory block or NULL in case of no memory available. +/// \note MUST REMAIN UNCHANGED: \b osPoolCAlloc shall be consistent in every CMSIS-RTOS. +void *osPoolCAlloc (osPoolId pool_id); + +/// Return an allocated memory block back to a specific memory pool. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \param[in] block address of the allocated memory block that is returned to the memory pool. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osPoolFree shall be consistent in every CMSIS-RTOS. +osStatus osPoolFree (osPoolId pool_id, void *block); + +#endif // Memory Pool Management available + + +// ==== Message Queue Management Functions ==== + +#if (defined (osFeature_MessageQ) && (osFeature_MessageQ != 0)) // Message Queues available + +/// \brief Create a Message Queue Definition. +/// \param name name of the queue. +/// \param queue_sz maximum number of messages in the queue. +/// \param type data type of a single message element (for debugger). +/// \note CAN BE CHANGED: The parameter to \b osMessageQDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osMessageQDef(name, queue_sz, type) \ +extern const osMessageQDef_t os_messageQ_def_##name +#else // define the object +#define osMessageQDef(name, queue_sz, type) \ +uint32_t os_messageQ_q_##name[4+(queue_sz)] = { 0 }; \ +const osMessageQDef_t os_messageQ_def_##name = \ +{ (queue_sz), (os_messageQ_q_##name) } +#endif + +/// \brief Access a Message Queue Definition. +/// \param name name of the queue +/// \note CAN BE CHANGED: The parameter to \b osMessageQ shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osMessageQ(name) \ +&os_messageQ_def_##name + +/// Create and Initialize a Message Queue. +/// \param[in] queue_def queue definition referenced with \ref osMessageQ. +/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. +/// \return message queue ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMessageCreate shall be consistent in every CMSIS-RTOS. +osMessageQId osMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id); + +/// Put a Message to a Queue. +/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. +/// \param[in] info message information. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMessagePut shall be consistent in every CMSIS-RTOS. +osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec); + +/// Get a Message or Wait for a Message from a Queue. +/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out. +/// \return event information that includes status code. +/// \note MUST REMAIN UNCHANGED: \b osMessageGet shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec); + +#endif // Message Queues available + + +// ==== Mail Queue Management Functions ==== + +#if (defined (osFeature_MailQ) && (osFeature_MailQ != 0)) // Mail Queues available + +/// \brief Create a Mail Queue Definition. +/// \param name name of the queue +/// \param queue_sz maximum number of messages in queue +/// \param type data type of a single message element +/// \note CAN BE CHANGED: The parameter to \b osMailQDef shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osMailQDef(name, queue_sz, type) \ +extern const osMailQDef_t os_mailQ_def_##name +#else // define the object +#define osMailQDef(name, queue_sz, type) \ +uint32_t os_mailQ_q_##name[4+(queue_sz)] = { 0 }; \ +uint32_t os_mailQ_m_##name[3+((sizeof(type)+3)/4)*(queue_sz)]; \ +void * os_mailQ_p_##name[2] = { (os_mailQ_q_##name), os_mailQ_m_##name }; \ +const osMailQDef_t os_mailQ_def_##name = \ +{ (queue_sz), sizeof(type), (os_mailQ_p_##name) } +#endif + +/// \brief Access a Mail Queue Definition. +/// \param name name of the queue +/// \note CAN BE CHANGED: The parameter to \b osMailQ shall be consistent but the +/// macro body is implementation specific in every CMSIS-RTOS. +#define osMailQ(name) \ +&os_mailQ_def_##name + +/// Create and Initialize mail queue. +/// \param[in] queue_def reference to the mail queue definition obtain with \ref osMailQ +/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. +/// \return mail queue ID for reference by other functions or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMailCreate shall be consistent in every CMSIS-RTOS. +osMailQId osMailCreate (const osMailQDef_t *queue_def, osThreadId thread_id); + +/// Allocate a memory block from a mail. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return pointer to memory block that can be filled with mail or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMailAlloc shall be consistent in every CMSIS-RTOS. +void *osMailAlloc (osMailQId queue_id, uint32_t millisec); + +/// Allocate a memory block from a mail and set memory block to zero. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return pointer to memory block that can be filled with mail or NULL in case of error. +/// \note MUST REMAIN UNCHANGED: \b osMailCAlloc shall be consistent in every CMSIS-RTOS. +void *osMailCAlloc (osMailQId queue_id, uint32_t millisec); + +/// Put a mail to a queue. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMailPut shall be consistent in every CMSIS-RTOS. +osStatus osMailPut (osMailQId queue_id, void *mail); + +/// Get a mail from a queue. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec timeout value or 0 in case of no time-out +/// \return event that contains mail information or error code. +/// \note MUST REMAIN UNCHANGED: \b osMailGet shall be consistent in every CMSIS-RTOS. +os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec); + +/// Free a memory block from a mail. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] mail pointer to the memory block that was obtained with \ref osMailGet. +/// \return status code that indicates the execution status of the function. +/// \note MUST REMAIN UNCHANGED: \b osMailFree shall be consistent in every CMSIS-RTOS. +osStatus osMailFree (osMailQId queue_id, void *mail); + +#endif // Mail Queues available + + +// ==== Thread Enumeration Functions ==== + +#if (defined (osFeature_ThreadEnum) && (osFeature_ThreadEnum != 0)) // Thread enumeration available + +/// Start a thread enumeration. +/// \return an enumeration ID or NULL on error. +osThreadEnumId _osThreadsEnumStart(void); + +/// Get the next task ID in the enumeration. +/// \return a thread ID or NULL on if the end of the enumeration has been reached. +osThreadId _osThreadEnumNext(osThreadEnumId enum_id); + +/// Free the enumeration structure. +/// \param[in] enum_id pointer to the enumeration ID that was obtained with \ref _osThreadsEnumStart. +/// \return status code that indicates the execution status of the function. +osStatus _osThreadEnumFree(osThreadEnumId enum_id); + +#endif // Thread Enumeration available + + +// ==== RTX Extensions ==== + +/// os_suspend: http://www.keil.com/support/man/docs/rlarm/rlarm_os_suspend.htm +uint32_t os_suspend (void); + +/// os_resume: http://www.keil.com/support/man/docs/rlarm/rlarm_os_resume.htm +void os_resume (uint32_t sleep_time); + + +#ifdef __cplusplus +} +#endif + +#endif // _CMSIS_OS_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_CMSIS.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,2332 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: rt_CMSIS.c + * Purpose: CMSIS RTOS API + * Rev.: V4.74 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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_0(f,t,t1,...) \ +__svc_indirect(0) t _##f (t(*)(t1),t1); \ + t f (t1 a1); \ +__attribute__((always_inline)) \ +static __inline t __##f (t1 a1) { \ + _##f(f,a1); \ +} + +#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_0(f,t,t1) \ +__attribute__((always_inline)) \ +static inline t __##f (t1 a1) { \ + SVC_Arg1(t1); \ + SVC_Call(f); \ +} + +#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_0(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); \ + _##f(a1); \ +} + +#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 + +#ifndef __MBED_CMSIS_RTOS_CA9 +// OS Stack Memory for Threads definitions +extern uint64_t os_stack_mem[]; +extern const uint32_t os_stack_sz; +#endif + +// 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. */ + +// Thread creation and destruction +osMutexDef(osThreadMutex); +osMutexId osMutexId_osThreadMutex; +void sysThreadTerminate(osThreadId id); + +// ==== 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) { + // Interrupts disabled + if (__get_CPSR() & 0x80) { + return 1; + } + + 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) +SVC_0_1(svcKernelSysTick, uint32_t, RET_uint32_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) { +#ifdef __MBED_CMSIS_RTOS_CA9 + if (!os_initialized) { + rt_sys_init(); // RTX System Initialization + } +#else + 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 + } +#endif + + 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); + // Initialize thread mutex + osMutexId_osThreadMutex = osMutexCreate(osMutex(osThreadMutex)); + } + + sysThreadError(osOK); + + os_initialized = 1; + os_running = 0; + + return osOK; +} + +/// Start the RTOS Kernel +osStatus svcKernelStart (void) { + + if (os_running) return osOK; + + rt_tsk_prio(0, os_tsk.run->prio_base); // Restore priority + if (os_tsk.run->task_id == 0xFF) { // Idle Thread + __set_PSP(os_tsk.run->tsk_stack + 8*4); // Setup PSP + } + 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; +} + +/// Get the RTOS kernel system timer counter +uint32_t svcKernelSysTick (void) { + uint32_t tick, tick0; + + tick = os_tick_val(); + if (os_tick_ovf()) { + tick0 = os_tick_val(); + if (tick0 < tick) tick = tick0; + tick += (os_trv + 1) * (os_time + 1); + } else { + tick += (os_trv + 1) * os_time; + } + + return tick; +} + +// 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(); + } +} + +/// Get the RTOS kernel system timer counter +uint32_t osKernelSysTick (void) { + if (__exceptional_mode()) return 0; // Not allowed in ISR + return __svcKernelSysTick(); +} + + +// ==== 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) +SVC_2_3(svcThreadGetInfo, os_InRegs osEvent, osThreadId, osThreadInfo, RET_osEvent) + +// 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; + } + +#ifdef __MBED_CMSIS_RTOS_CA9 + if (thread_def->stacksize != 0) { // Custom stack size + stk = (void *)thread_def->stack_pointer; + } else { // Default stack size + stk = NULL; + } +#else + 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; + } +#endif + + 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 +#ifndef __MBED_CMSIS_RTOS_CA9 + if (stk != NULL) { + rt_free_mem(os_stack_mem, stk); // Free allocated stack + } +#endif + 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; +#ifndef __MBED_CMSIS_RTOS_CA9 + void *stk; +#endif + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) return osErrorParameter; + +#ifndef __MBED_CMSIS_RTOS_CA9 + stk = ptcb->priv_stack ? ptcb->stack : NULL; // Private stack +#endif + + res = rt_tsk_delete(ptcb->task_id); // Delete task + + if (res == OS_R_NOK) return osErrorResource; // Delete task failed + +#ifndef __MBED_CMSIS_RTOS_CA9 + if (stk != NULL) { + rt_free_mem(os_stack_mem, stk); // Free private stack + } +#endif + + 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); +} + +/// Get info from an active thread +os_InRegs osEvent_type svcThreadGetInfo (osThreadId thread_id, osThreadInfo info) { + P_TCB ptcb; + osEvent ret; + ret.status = osOK; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) { + ret.status = osErrorValue; +#if defined (__GNUC__) && defined (__ARM_PCS_VFP) + osEvent_ret_status; + return; +#else + return osEvent_ret_status; +#endif + } + + if (osThreadInfoStackSize == info) { + uint32_t size; + size = ptcb->priv_stack; + if (0 == size) { + // This is an OS task - always a fixed size + size = os_stackinfo & 0x3FFFF; + } + ret.value.v = size; +#if defined (__GNUC__) && defined (__ARM_PCS_VFP) + osEvent_ret_value; + return; +#else + return osEvent_ret_value; +#endif + } + + if (osThreadInfoStackMax == info) { + // Cortex-A RTX does not have stack init so + // the maximum stack usage cannot be obtained. + ret.status = osErrorResource; +#if defined (__GNUC__) && defined (__ARM_PCS_VFP) + osEvent_ret_status; + return; +#else + return osEvent_ret_status; +#endif + } + + if (osThreadInfoEntry == info) { + ret.value.p = (void*)ptcb->ptask; +#if defined (__GNUC__) && defined (__ARM_PCS_VFP) + osEvent_ret_value; + return; +#else + return osEvent_ret_value; +#endif + } + + if (osThreadInfoArg == info) { + ret.value.p = (void*)ptcb->argv; +#if defined (__GNUC__) && defined (__ARM_PCS_VFP) + osEvent_ret_value; + return; +#else + return osEvent_ret_value; +#endif + } + + // Unsupported option so return error + ret.status = osErrorParameter; +#if defined (__GNUC__) && defined (__ARM_PCS_VFP) + osEvent_ret_status; + return; +#else + return osEvent_ret_status; +#endif +} + +// 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 { + osThreadId id; + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + // Thread mutex must be held when a thread is created or terminated + id = __svcThreadCreate(thread_def, argument); + osMutexRelease(osMutexId_osThreadMutex); + return id; + } +} + +/// 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) { + osStatus status; + if (__exceptional_mode()) return osErrorISR; // Not allowed in ISR + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + sysThreadTerminate(thread_id); + // Thread mutex must be held when a thread is created or terminated + status = __svcThreadTerminate(thread_id); + osMutexRelease(osMutexId_osThreadMutex); + return status; +} + +/// 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) { + osThreadId id; + // Thread mutex must be held when a thread is created or terminated + // Note - the mutex will be released automatically by the os when + // the thread is terminated + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + id = __svcThreadGetId(); + sysThreadTerminate(id); + __svcThreadTerminate(id); + 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 INACTIVE; + + return ptcb->state; +} +#endif + +/// Get the requested info from the specified active thread +os_InRegs osEvent _osThreadGetInfo(osThreadId thread_id, osThreadInfo info) { + osEvent ret; + if (__exceptional_mode()) { + ret.status = osErrorISR; + return ret; // Not allowed in ISR + } + return __svcThreadGetInfo(thread_id, info); +} + +osThreadEnumId _osThreadsEnumStart() { + static uint32_t thread_enum_index; + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + thread_enum_index = 0; + return &thread_enum_index; +} + +osThreadId _osThreadEnumNext(osThreadEnumId enum_id) { + uint32_t i; + osThreadId id = NULL; + uint32_t *index = (uint32_t*)enum_id; + for (i = *index; i < os_maxtaskrun; i++) { + if (os_active_TCB[i] != NULL) { + id = (osThreadId)os_active_TCB[i]; + break; + } + } + if (i == os_maxtaskrun) { + // Include the idle task at the end of the enumeration + id = &os_idle_TCB; + } + *index = i + 1; + return id; +} + +osStatus _osThreadEnumFree(osThreadEnumId enum_id) { + uint32_t *index = (uint32_t*)enum_id; + *index = 0; + osMutexRelease(osMutexId_osThreadMutex); + return osOK; +} + +// ==== 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->next = 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; + } + } +} + +/// Get user timers wake-up time +uint32_t sysUserTimerWakeupTime (void) { + + if (os_timer_head) { + return os_timer_head->tcnt; + } + return 0xFFFF; +} + +/// Update user timers on resume +void sysUserTimerUpdate (uint32_t sleep_time) { + + while (os_timer_head && sleep_time) { + if (sleep_time >= os_timer_head->tcnt) { + sleep_time -= os_timer_head->tcnt; + os_timer_head->tcnt = 1; + sysTimerTick(); + } else { + os_timer_head->tcnt -= sleep_time; + break; + } + } +} + + +// 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_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; +} + +/// 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); +} + +/// 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->p_lnk != NULL) && (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); + 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__ + + +// ==== RTX Extensions ==== + +// Service Calls declarations +SVC_0_1(rt_suspend, uint32_t, RET_uint32_t) +SVC_1_0(rt_resume, void, uint32_t) + + +// Public API + +/// Suspends the OS task scheduler +uint32_t os_suspend (void) { + return __rt_suspend(); +} + +/// Resumes the OS task scheduler +void os_resume (uint32_t sleep_time) { + __rt_resume(sleep_time); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Event.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,194 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_EVENT.C + * Purpose: Implements waits and wake-ups for event flags + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Task.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_evt_wait -----------------------------------*/ + +OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait) { + /* Wait for one or more event flags with optional time-out. */ + /* "wait_flags" identifies the flags to wait for. */ + /* "timeout" is the time-out limit in system ticks (0xffff if no time-out) */ + /* "and_wait" specifies the AND-ing of "wait_flags" as condition to be met */ + /* to complete the wait. (OR-ing if set to 0). */ + U32 block_state; + + if (and_wait) { + /* Check for AND-connected events */ + if ((os_tsk.run->events & wait_flags) == wait_flags) { + os_tsk.run->events &= ~wait_flags; + return (OS_R_EVT); + } + block_state = WAIT_AND; + } + else { + /* Check for OR-connected events */ + if (os_tsk.run->events & wait_flags) { + os_tsk.run->waits = os_tsk.run->events & wait_flags; + os_tsk.run->events &= ~wait_flags; + return (OS_R_EVT); + } + block_state = WAIT_OR; + } + /* Task has to wait */ + os_tsk.run->waits = wait_flags; + rt_block (timeout, (U8)block_state); + return (OS_R_TMO); +} + + +/*--------------------------- rt_evt_set ------------------------------------*/ + +void rt_evt_set (U16 event_flags, OS_TID task_id) { + /* Set one or more event flags of a selectable task. */ + P_TCB p_tcb; + + p_tcb = os_active_TCB[task_id-1]; + if (p_tcb == NULL) { + return; + } + p_tcb->events |= event_flags; + event_flags = p_tcb->waits; + /* If the task is not waiting for an event, it should not be put */ + /* to ready state. */ + if (p_tcb->state == WAIT_AND) { + /* Check for AND-connected events */ + if ((p_tcb->events & event_flags) == event_flags) { + goto wkup; + } + } + if (p_tcb->state == WAIT_OR) { + /* Check for OR-connected events */ + if (p_tcb->events & event_flags) { + p_tcb->waits &= p_tcb->events; +wkup: p_tcb->events &= ~event_flags; + rt_rmv_dly (p_tcb); + p_tcb->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val2(p_tcb, 0x08/*osEventSignal*/, p_tcb->waits); +#else + rt_ret_val (p_tcb, OS_R_EVT); +#endif + rt_dispatch (p_tcb); + } + } +} + + +/*--------------------------- rt_evt_clr ------------------------------------*/ + +void rt_evt_clr (U16 clear_flags, OS_TID task_id) { + /* Clear one or more event flags (identified by "clear_flags") of a */ + /* selectable task (identified by "task"). */ + P_TCB task = os_active_TCB[task_id-1]; + + if (task == NULL) { + return; + } + task->events &= ~clear_flags; +} + + +/*--------------------------- isr_evt_set -----------------------------------*/ + +void isr_evt_set (U16 event_flags, OS_TID task_id) { + /* Same function as "os_evt_set", but to be called by ISRs. */ + P_TCB p_tcb = os_active_TCB[task_id-1]; + + if (p_tcb == NULL) { + return; + } + rt_psq_enq (p_tcb, event_flags); + rt_psh_req (); +} + + +/*--------------------------- rt_evt_get ------------------------------------*/ + +U16 rt_evt_get (void) { + /* Get events of a running task after waiting for OR connected events. */ + return (os_tsk.run->waits); +} + + +/*--------------------------- rt_evt_psh ------------------------------------*/ + +void rt_evt_psh (P_TCB p_CB, U16 set_flags) { + /* Check if task has to be waken up */ + U16 event_flags; + + p_CB->events |= set_flags; + event_flags = p_CB->waits; + if (p_CB->state == WAIT_AND) { + /* Check for AND-connected events */ + if ((p_CB->events & event_flags) == event_flags) { + goto rdy; + } + } + if (p_CB->state == WAIT_OR) { + /* Check for OR-connected events */ + if (p_CB->events & event_flags) { + p_CB->waits &= p_CB->events; +rdy: p_CB->events &= ~event_flags; + rt_rmv_dly (p_CB); + p_CB->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val2(p_CB, 0x08/*osEventSignal*/, p_CB->waits); +#else + rt_ret_val (p_CB, OS_R_EVT); +#endif + rt_put_prio (&os_rdy, p_CB); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Event.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_EVENT.H + * Purpose: Implements waits and wake-ups for event flags + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait); +extern void rt_evt_set (U16 event_flags, OS_TID task_id); +extern void rt_evt_clr (U16 clear_flags, OS_TID task_id); +extern void isr_evt_set (U16 event_flags, OS_TID task_id); +extern U16 rt_evt_get (void); +extern void rt_evt_psh (P_TCB p_CB, U16 set_flags); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_HAL_CA.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,242 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_HAL_CA.H + * Purpose: Hardware Abstraction Layer for Cortex-A definitions + * Rev.: 14th Jan 2014 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Definitions */ +#define INIT_CPSR_SYS 0x4000001F +#define INIT_CPSR_USER 0x40000010 + +#define CPSR_T_BIT 0x20 +#define CPSR_I_BIT 0x80 +#define CPSR_F_BIT 0x40 + +#define MODE_USR 0x10 +#define MODE_FIQ 0x11 +#define MODE_IRQ 0x12 +#define MODE_SVC 0x13 +#define MODE_ABT 0x17 +#define MODE_UND 0x1B +#define MODE_SYS 0x1F + +#define MAGIC_WORD 0xE25A2EA5 + +#include "core_ca9.h" + +#if defined (__CC_ARM) /* ARM Compiler */ + +#if ((__TARGET_ARCH_7_M || __TARGET_ARCH_7E_M || __TARGET_ARCH_7_A) && !defined(NO_EXCLUSIVE_ACCESS)) + #define __USE_EXCLUSIVE_ACCESS +#else + #undef __USE_EXCLUSIVE_ACCESS +#endif + +/* Supress __ldrex and __strex deprecated warnings - "#3731-D: intrinsic is deprecated" */ +#ifdef __USE_EXCLUSIVE_ACCESS +#pragma diag_suppress 3731 +#endif + +#elif defined (__GNUC__) /* GNU Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if defined (__VFP_FP__) && !defined(__SOFTFP__) +#define __TARGET_FPU_VFP 1 +#else +#define __TARGET_FPU_VFP 0 +#endif + +#define __inline inline +#define __weak __attribute__((weak)) + +#elif defined (__ICCARM__) /* IAR Compiler */ + +#endif + +static U8 priority = 0xff; + +extern const U32 GICDistributor_BASE; +extern const U32 GICInterface_BASE; + +/* GIC registers - Distributor */ +#define GICD_ICDICER0 (*((volatile U32 *)(GICDistributor_BASE + 0x180))) /* - RW - Interrupt Clear-Enable Registers */ +#define GICD_ICDISER0 (*((volatile U32 *)(GICDistributor_BASE + 0x100))) /* - RW - Interrupt Set-Enable Registers */ +#define GICD_ICDIPR0 (*((volatile U32 *)(GICDistributor_BASE + 0x400))) /* - RW - Interrupt Priority Registers */ +#define GICD_ICDSGIR (*((volatile U32 *)(GICDistributor_BASE + 0xf00))) /* - RW - Interrupt Software Interrupt Register */ +#define GICD_ICDICERx(irq) *(volatile U32 *)(&GICD_ICDICER0 + irq/32) +#define GICD_ICDISERx(irq) *(volatile U32 *)(&GICD_ICDISER0 + irq/32) + +/* GIC register - CPU Interface */ +#define GICI_ICCPMR (*((volatile U32 *)(GICInterface_BASE + 0x004))) /* - RW - Interrupt Priority Mask Register */ + +#define SGI_PENDSV 0 /* SGI0 */ +#define SGI_PENDSV_BIT ((U32)(1 << (SGI_PENDSV & 0xf))) + +//Increase priority filter to prevent timer and PendSV interrupts signaling. Guarantees that interrupts will not be forwarded. +#if defined (__ICCARM__) +#define OS_LOCK() int irq_dis = __disable_irq_iar();\ + priority = GICI_ICCPMR; \ + GICI_ICCPMR = 0xff; \ + GICI_ICCPMR = GICI_ICCPMR - 1; \ + __DSB();\ + if(!irq_dis) __enable_irq(); \ + +#else +#define OS_LOCK() int irq_dis = __disable_irq();\ + priority = GICI_ICCPMR; \ + GICI_ICCPMR = 0xff; \ + GICI_ICCPMR = GICI_ICCPMR - 1; \ + __DSB();\ + if(!irq_dis) __enable_irq(); \ + +#endif + +//Restore priority filter. Re-enable timer and PendSV signaling +#define OS_UNLOCK() __DSB(); \ + GICI_ICCPMR = priority; \ + +#define OS_PEND_IRQ() GICD_ICDSGIR = 0x0010000 | SGI_PENDSV +#define OS_PEND(fl,p) if(p) OS_PEND_IRQ(); +#define OS_UNPEND(fl) + +/* HW initialization needs to be done in os_tick_init (void) -RTX_Conf_CM.c- + * OS_X_INIT enables the IRQ n in the GIC */ +#define OS_X_INIT(n) volatile char *reg; \ + reg = (char *)(&GICD_ICDIPR0 + n / 4); \ + reg += n % 4; \ + *reg = (char)0xff; \ + *reg = *reg - 1; \ + GICD_ICDISERx(n) = (U32)(1 << n % 32); +#define OS_X_LOCK(n) OS_LOCK() +#define OS_X_UNLOCK(n) OS_UNLOCK() +#define OS_X_PEND_IRQ() OS_PEND_IRQ() +#define OS_X_PEND(fl,p) if(p) OS_X_PEND_IRQ(); +#define OS_X_UNPEND(fl) + + +/* Functions */ +#ifdef __USE_EXCLUSIVE_ACCESS + #define rt_inc(p) while(__strex((__ldrex(p)+1),p)) + #define rt_dec(p) while(__strex((__ldrex(p)-1),p)) +#else +#if defined (__ICCARM__) + #define rt_inc(p) { int irq_dis = __disable_irq_iar();(*p)++;if(!irq_dis) __enable_irq(); } + #define rt_dec(p) { int irq_dis = __disable_irq_iar();(*p)--;if(!irq_dis) __enable_irq(); } +#else + #define rt_inc(p) { int irq_dis = __disable_irq();(*p)++;if(!irq_dis) __enable_irq(); } + #define rt_dec(p) { int irq_dis = __disable_irq();(*p)--;if(!irq_dis) __enable_irq(); } +#endif /* __ICCARM__ */ +#endif /* __USE_EXCLUSIVE_ACCESS */ + +__inline static U32 rt_inc_qi (U32 size, U8 *count, U8 *first) { + U32 cnt,c2; +#ifdef __USE_EXCLUSIVE_ACCESS + do { + if ((cnt = __ldrex(count)) == size) { + __clrex(); + return (cnt); } + } while (__strex(cnt+1, count)); + do { + c2 = (cnt = __ldrex(first)) + 1; + if (c2 == size) c2 = 0; + } while (__strex(c2, first)); +#else + int irq_dis; + #if defined (__ICCARM__) + irq_dis = __disable_irq_iar(); + #else + irq_dis = __disable_irq(); + #endif /* __ICCARM__ */ + if ((cnt = *count) < size) { + *count = cnt+1; + c2 = (cnt = *first) + 1; + if (c2 == size) c2 = 0; + *first = c2; + } + if(!irq_dis) __enable_irq (); +#endif + return (cnt); +} + +__inline static void rt_systick_init (void) { + /* Cortex-A doesn't have a Systick. User needs to provide an alternative timer using RTX_Conf_CM configuration */ + /* HW initialization needs to be done in os_tick_init (void) -RTX_Conf_CM.c- */ +} + +__inline static U32 rt_systick_val (void) { + /* Cortex-A doesn't have a Systick. User needs to provide an alternative timer using RTX_Conf_CM configuration */ + /* HW initialization needs to be done in os_tick_init (void) -RTX_Conf_CM.c- */ + return 0; +} + +__inline static U32 rt_systick_ovf (void) { + /* Cortex-A doesn't have a Systick. User needs to provide an alternative timer using RTX_Conf_CM configuration */ + /* HW initialization needs to be done in os_tick_init (void) -RTX_Conf_CM.c- */ + return 0; +} + +__inline static void rt_svc_init (void) { + /* Register pendSV - through SGI */ + volatile char *reg; + + reg = (char *)(&GICD_ICDIPR0 + SGI_PENDSV/4); + reg += SGI_PENDSV % 4; + /* Write 0xff to read priority level */ + *reg = (char)0xff; + /* Read priority level and set the lowest possible*/ + *reg = *reg - 1; + + GICD_ICDISERx(SGI_PENDSV) = (U32)SGI_PENDSV_BIT; +} + +extern void rt_set_PSP (U32 stack); +extern U32 rt_get_PSP (void); +extern void os_set_env (P_TCB p_TCB); +extern void *_alloc_box (void *box_mem); +extern int _free_box (void *box_mem, void *box); + +extern void rt_init_stack (P_TCB p_TCB, FUNCP task_body); +extern void rt_ret_val (P_TCB p_TCB, U32 v0); +extern void rt_ret_val2 (P_TCB p_TCB, U32 v0, U32 v1); + +extern void dbg_init (void); +extern void dbg_task_notify (P_TCB p_tcb, BOOL create); +extern void dbg_task_switch (U32 task_id); + +#define DBG_INIT() +#define DBG_TASK_NOTIFY(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_HAL_CM.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,289 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_HAL_CM.H + * Purpose: Hardware Abstraction Layer for Cortex-M definitions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Definitions */ +#define INITIAL_xPSR 0x01000000 +#define DEMCR_TRCENA 0x01000000 +#define ITM_ITMENA 0x00000001 +#define MAGIC_WORD 0xE25A2EA5 + +#if defined (__CC_ARM) /* ARM Compiler */ + +#if ((__TARGET_ARCH_7_M || __TARGET_ARCH_7E_M) && !defined(NO_EXCLUSIVE_ACCESS)) + #define __USE_EXCLUSIVE_ACCESS +#else + #undef __USE_EXCLUSIVE_ACCESS +#endif + +/* Supress __ldrex and __strex deprecated warnings - "#3731-D: intrinsic is deprecated" */ +#ifdef __USE_EXCLUSIVE_ACCESS +#pragma diag_suppress 3731 +#endif + +#elif defined (__GNUC__) /* GNU Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if defined (__CORTEX_M0) +#define __TARGET_ARCH_6S_M 1 +#else +#define __TARGET_ARCH_6S_M 0 +#endif + +#if defined (__VFP_FP__) && !defined(__SOFTFP__) +#define __TARGET_FPU_VFP 1 +#else +#define __TARGET_FPU_VFP 0 +#endif + +#define __inline inline +#define __weak __attribute__((weak)) + +#ifndef __CMSIS_GENERIC + +__attribute__((always_inline)) static inline void __enable_irq(void) +{ + __asm volatile ("cpsie i"); +} + +__attribute__((always_inline)) static inline U32 __disable_irq(void) +{ + U32 result; + + __asm volatile ("mrs %0, primask" : "=r" (result)); + __asm volatile ("cpsid i"); + return(result & 1); +} + +#endif + +__attribute__(( always_inline)) static inline U8 __clz(U32 value) +{ + U8 result; + + __asm volatile ("clz %0, %1" : "=r" (result) : "r" (value)); + return(result); +} + +#elif defined (__ICCARM__) /* IAR Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if (__CORE__ == __ARM6M__) +#define __TARGET_ARCH_6S_M 1 +#else +#define __TARGET_ARCH_6S_M 0 +#endif + +#if defined __ARMVFP__ +#define __TARGET_FPU_VFP 1 +#else +#define __TARGET_FPU_VFP 0 +#endif + +#define __inline inline + +#ifndef __CMSIS_GENERIC + +static inline void __enable_irq(void) +{ + __asm volatile ("cpsie i"); +} + +static inline U32 __disable_irq(void) +{ + U32 result; + + __asm volatile ("mrs %0, primask" : "=r" (result)); + __asm volatile ("cpsid i"); + return(result & 1); +} + +#endif + +static inline U8 __clz(U32 value) +{ + U8 result; + + __asm volatile ("clz %0, %1" : "=r" (result) : "r" (value)); + return(result); +} + +#endif + +/* NVIC registers */ +#define NVIC_ST_CTRL (*((volatile U32 *)0xE000E010)) +#define NVIC_ST_RELOAD (*((volatile U32 *)0xE000E014)) +#define NVIC_ST_CURRENT (*((volatile U32 *)0xE000E018)) +#define NVIC_ISER ((volatile U32 *)0xE000E100) +#define NVIC_ICER ((volatile U32 *)0xE000E180) +#if (__TARGET_ARCH_6S_M) +#define NVIC_IP ((volatile U32 *)0xE000E400) +#else +#define NVIC_IP ((volatile U8 *)0xE000E400) +#endif +#define NVIC_INT_CTRL (*((volatile U32 *)0xE000ED04)) +#define NVIC_AIR_CTRL (*((volatile U32 *)0xE000ED0C)) +#define NVIC_SYS_PRI2 (*((volatile U32 *)0xE000ED1C)) +#define NVIC_SYS_PRI3 (*((volatile U32 *)0xE000ED20)) + +#define OS_PEND_IRQ() NVIC_INT_CTRL = (1<<28) +#define OS_PENDING ((NVIC_INT_CTRL >> 26) & (1<<2 | 1)) +#define OS_UNPEND(fl) NVIC_INT_CTRL = (*fl = OS_PENDING) << 25 +#define OS_PEND(fl,p) NVIC_INT_CTRL = (fl | p<<2) << 26 +#define OS_LOCK() NVIC_ST_CTRL = 0x0005 +#define OS_UNLOCK() NVIC_ST_CTRL = 0x0007 + +#define OS_X_PENDING ((NVIC_INT_CTRL >> 28) & 1) +#define OS_X_UNPEND(fl) NVIC_INT_CTRL = (*fl = OS_X_PENDING) << 27 +#define OS_X_PEND(fl,p) NVIC_INT_CTRL = (fl | p) << 28 +#if (__TARGET_ARCH_6S_M) +#define OS_X_INIT(n) NVIC_IP[n>>2] |= 0xFF << (8*(n & 0x03)); \ + NVIC_ISER[n>>5] = 1 << (n & 0x1F) +#else +#define OS_X_INIT(n) NVIC_IP[n] = 0xFF; \ + NVIC_ISER[n>>5] = 1 << (n & 0x1F) +#endif +#define OS_X_LOCK(n) NVIC_ICER[n>>5] = 1 << (n & 0x1F) +#define OS_X_UNLOCK(n) NVIC_ISER[n>>5] = 1 << (n & 0x1F) + +/* Core Debug registers */ +#define DEMCR (*((volatile U32 *)0xE000EDFC)) + +/* ITM registers */ +#define ITM_CONTROL (*((volatile U32 *)0xE0000E80)) +#define ITM_ENABLE (*((volatile U32 *)0xE0000E00)) +#define ITM_PORT30_U32 (*((volatile U32 *)0xE0000078)) +#define ITM_PORT31_U32 (*((volatile U32 *)0xE000007C)) +#define ITM_PORT31_U16 (*((volatile U16 *)0xE000007C)) +#define ITM_PORT31_U8 (*((volatile U8 *)0xE000007C)) + +/* Variables */ +extern BIT dbg_msg; + +/* Functions */ +#ifdef __USE_EXCLUSIVE_ACCESS + #define rt_inc(p) while(__strex((__ldrex(p)+1),p)) + #define rt_dec(p) while(__strex((__ldrex(p)-1),p)) +#else + #define rt_inc(p) __disable_irq();(*p)++;__enable_irq(); + #define rt_dec(p) __disable_irq();(*p)--;__enable_irq(); +#endif + +__inline static U32 rt_inc_qi (U32 size, U8 *count, U8 *first) { + U32 cnt,c2; +#ifdef __USE_EXCLUSIVE_ACCESS + do { + if ((cnt = __ldrex(count)) == size) { + __clrex(); + return (cnt); } + } while (__strex(cnt+1, count)); + do { + c2 = (cnt = __ldrex(first)) + 1; + if (c2 == size) c2 = 0; + } while (__strex(c2, first)); +#else + __disable_irq(); + if ((cnt = *count) < size) { + *count = cnt+1; + c2 = (cnt = *first) + 1; + if (c2 == size) c2 = 0; + *first = c2; + } + __enable_irq (); +#endif + return (cnt); +} + +__inline static void rt_systick_init (void) { + NVIC_ST_RELOAD = os_trv; + NVIC_ST_CURRENT = 0; + NVIC_ST_CTRL = 0x0007; + NVIC_SYS_PRI3 |= 0xFF000000; +} + +__inline static U32 rt_systick_val (void) { + return (os_trv - NVIC_ST_CURRENT); +} + +__inline static U32 rt_systick_ovf (void) { + return ((NVIC_INT_CTRL >> 26) & 1); +} + +__inline static void rt_svc_init (void) { +#if !(__TARGET_ARCH_6S_M) + int sh,prigroup; +#endif + NVIC_SYS_PRI3 |= 0x00FF0000; +#if (__TARGET_ARCH_6S_M) + NVIC_SYS_PRI2 |= (NVIC_SYS_PRI3<<(8+1)) & 0xFC000000; +#else + sh = 8 - __clz (~((NVIC_SYS_PRI3 << 8) & 0xFF000000)); + prigroup = ((NVIC_AIR_CTRL >> 8) & 0x07); + if (prigroup >= sh) { + sh = prigroup + 1; + } + NVIC_SYS_PRI2 = ((0xFEFFFFFF << sh) & 0xFF000000) | (NVIC_SYS_PRI2 & 0x00FFFFFF); +#endif +} + +extern void rt_set_PSP (U32 stack); +extern U32 rt_get_PSP (void); +extern void os_set_env (void); +extern void *_alloc_box (void *box_mem); +extern int _free_box (void *box_mem, void *box); + +extern void rt_init_stack (P_TCB p_TCB, FUNCP task_body); +extern void rt_ret_val (P_TCB p_TCB, U32 v0); +extern void rt_ret_val2 (P_TCB p_TCB, U32 v0, U32 v1); + +extern void dbg_init (void); +extern void dbg_task_notify (P_TCB p_tcb, BOOL create); +extern void dbg_task_switch (U32 task_id); + +#ifdef DBG_MSG +#define DBG_INIT() dbg_init() +#define DBG_TASK_NOTIFY(p_tcb,create) if (dbg_msg) dbg_task_notify(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) if (dbg_msg && (os_tsk.new_tsk!=os_tsk.run)) \ + dbg_task_switch(task_id) +#else +#define DBG_INIT() +#define DBG_TASK_NOTIFY(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_List.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,324 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_LIST.C + * Purpose: Functions for the management of different lists + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Time.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* List head of chained ready tasks */ +struct OS_XCB os_rdy; +/* List head of chained delay tasks */ +struct OS_XCB os_dly; + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_put_prio -----------------------------------*/ + +void rt_put_prio (P_XCB p_CB, P_TCB p_task) { + /* Put task identified with "p_task" into list ordered by priority. */ + /* "p_CB" points to head of list; list has always an element at end with */ + /* a priority less than "p_task->prio". */ + P_TCB p_CB2; + U32 prio; + BOOL sem_mbx = __FALSE; + + if (p_CB->cb_type == SCB || p_CB->cb_type == MCB || p_CB->cb_type == MUCB) { + sem_mbx = __TRUE; + } + prio = p_task->prio; + p_CB2 = p_CB->p_lnk; + /* Search for an entry in the list */ + while (p_CB2 != NULL && prio <= p_CB2->prio) { + p_CB = (P_XCB)p_CB2; + p_CB2 = p_CB2->p_lnk; + } + /* Entry found, insert the task into the list */ + p_task->p_lnk = p_CB2; + p_CB->p_lnk = p_task; + if (sem_mbx) { + if (p_CB2 != NULL) { + p_CB2->p_rlnk = p_task; + } + p_task->p_rlnk = (P_TCB)p_CB; + } + else { + p_task->p_rlnk = NULL; + } +} + + +/*--------------------------- rt_get_first ----------------------------------*/ + +P_TCB rt_get_first (P_XCB p_CB) { + /* Get task at head of list: it is the task with highest priority. */ + /* "p_CB" points to head of list. */ + P_TCB p_first; + + p_first = p_CB->p_lnk; + p_CB->p_lnk = p_first->p_lnk; + if (p_CB->cb_type == SCB || p_CB->cb_type == MCB || p_CB->cb_type == MUCB) { + if (p_first->p_lnk != NULL) { + p_first->p_lnk->p_rlnk = (P_TCB)p_CB; + p_first->p_lnk = NULL; + } + p_first->p_rlnk = NULL; + } + else { + p_first->p_lnk = NULL; + } + return (p_first); +} + + +/*--------------------------- rt_put_rdy_first ------------------------------*/ + +void rt_put_rdy_first (P_TCB p_task) { + /* Put task identified with "p_task" at the head of the ready list. The */ + /* task must have at least a priority equal to highest priority in list. */ + p_task->p_lnk = os_rdy.p_lnk; + p_task->p_rlnk = NULL; + os_rdy.p_lnk = p_task; +} + + +/*--------------------------- rt_get_same_rdy_prio --------------------------*/ + +P_TCB rt_get_same_rdy_prio (void) { + /* Remove a task of same priority from ready list if any exists. Other- */ + /* wise return NULL. */ + P_TCB p_first; + + p_first = os_rdy.p_lnk; + if (p_first->prio == os_tsk.run->prio) { + os_rdy.p_lnk = os_rdy.p_lnk->p_lnk; + return (p_first); + } + return (NULL); +} + + +/*--------------------------- rt_resort_prio --------------------------------*/ + +void rt_resort_prio (P_TCB p_task) { + /* Re-sort ordered lists after the priority of 'p_task' has changed. */ + P_TCB p_CB; + + if (p_task->p_rlnk == NULL) { + if (p_task->state == READY) { + /* Task is chained into READY list. */ + p_CB = (P_TCB)&os_rdy; + goto res; + } + } + else { + p_CB = p_task->p_rlnk; + while (p_CB->cb_type == TCB) { + /* Find a header of this task chain list. */ + p_CB = p_CB->p_rlnk; + } +res:rt_rmv_list (p_task); + rt_put_prio ((P_XCB)p_CB, p_task); + } +} + + +/*--------------------------- rt_put_dly ------------------------------------*/ + +void rt_put_dly (P_TCB p_task, U16 delay) { + /* Put a task identified with "p_task" into chained delay wait list using */ + /* a delay value of "delay". */ + P_TCB p; + U32 delta,idelay = delay; + + p = (P_TCB)&os_dly; + if (p->p_dlnk == NULL) { + /* Delay list empty */ + delta = 0; + goto last; + } + delta = os_dly.delta_time; + while (delta < idelay) { + if (p->p_dlnk == NULL) { + /* End of list found */ +last: p_task->p_dlnk = NULL; + p->p_dlnk = p_task; + p_task->p_blnk = p; + p->delta_time = (U16)(idelay - delta); + p_task->delta_time = 0; + return; + } + p = p->p_dlnk; + delta += p->delta_time; + } + /* Right place found */ + p_task->p_dlnk = p->p_dlnk; + p->p_dlnk = p_task; + p_task->p_blnk = p; + if (p_task->p_dlnk != NULL) { + p_task->p_dlnk->p_blnk = p_task; + } + p_task->delta_time = (U16)(delta - idelay); + p->delta_time -= p_task->delta_time; +} + + +/*--------------------------- rt_dec_dly ------------------------------------*/ + +void rt_dec_dly (void) { + /* Decrement delta time of list head: remove tasks having a value of zero.*/ + P_TCB p_rdy; + + if (os_dly.p_dlnk == NULL) { + return; + } + os_dly.delta_time--; + while ((os_dly.delta_time == 0) && (os_dly.p_dlnk != NULL)) { + p_rdy = os_dly.p_dlnk; + if (p_rdy->p_rlnk != NULL) { + /* Task is really enqueued, remove task from semaphore/mailbox */ + /* timeout waiting list. */ + p_rdy->p_rlnk->p_lnk = p_rdy->p_lnk; + if (p_rdy->p_lnk != NULL) { + p_rdy->p_lnk->p_rlnk = p_rdy->p_rlnk; + p_rdy->p_lnk = NULL; + } + p_rdy->p_rlnk = NULL; + } + rt_put_prio (&os_rdy, p_rdy); + os_dly.delta_time = p_rdy->delta_time; + if (p_rdy->state == WAIT_ITV) { + /* Calculate the next time for interval wait. */ + p_rdy->delta_time = p_rdy->interval_time + (U16)os_time; + } + p_rdy->state = READY; + os_dly.p_dlnk = p_rdy->p_dlnk; + if (p_rdy->p_dlnk != NULL) { + p_rdy->p_dlnk->p_blnk = (P_TCB)&os_dly; + p_rdy->p_dlnk = NULL; + } + p_rdy->p_blnk = NULL; + } +} + + +/*--------------------------- rt_rmv_list -----------------------------------*/ + +void rt_rmv_list (P_TCB p_task) { + /* Remove task identified with "p_task" from ready, semaphore or mailbox */ + /* waiting list if enqueued. */ + P_TCB p_b; + + if (p_task->p_rlnk != NULL) { + /* A task is enqueued in semaphore / mailbox waiting list. */ + p_task->p_rlnk->p_lnk = p_task->p_lnk; + if (p_task->p_lnk != NULL) { + p_task->p_lnk->p_rlnk = p_task->p_rlnk; + } + return; + } + + p_b = (P_TCB)&os_rdy; + while (p_b != NULL) { + /* Search the ready list for task "p_task" */ + if (p_b->p_lnk == p_task) { + p_b->p_lnk = p_task->p_lnk; + return; + } + p_b = p_b->p_lnk; + } +} + + +/*--------------------------- rt_rmv_dly ------------------------------------*/ + +void rt_rmv_dly (P_TCB p_task) { + /* Remove task identified with "p_task" from delay list if enqueued. */ + P_TCB p_b; + + p_b = p_task->p_blnk; + if (p_b != NULL) { + /* Task is really enqueued */ + p_b->p_dlnk = p_task->p_dlnk; + if (p_task->p_dlnk != NULL) { + /* 'p_task' is in the middle of list */ + p_b->delta_time += p_task->delta_time; + p_task->p_dlnk->p_blnk = p_b; + p_task->p_dlnk = NULL; + } + else { + /* 'p_task' is at the end of list */ + p_b->delta_time = 0; + } + p_task->p_blnk = NULL; + } +} + + +/*--------------------------- rt_psq_enq ------------------------------------*/ + +void rt_psq_enq (OS_ID entry, U32 arg) { + /* Insert post service request "entry" into ps-queue. */ + U32 idx; + + idx = rt_inc_qi (os_psq->size, &os_psq->count, &os_psq->first); + if (idx < os_psq->size) { + os_psq->q[idx].id = entry; + os_psq->q[idx].arg = arg; + } + else { + os_error (OS_ERR_FIFO_OVF); + } +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_List.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,67 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_LIST.H + * Purpose: Functions for the management of different lists + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Definitions */ + +/* Values for 'cb_type' */ +#define TCB 0 +#define MCB 1 +#define SCB 2 +#define MUCB 3 +#define HCB 4 + +/* Variables */ +extern struct OS_XCB os_rdy; +extern struct OS_XCB os_dly; + +/* Functions */ +extern void rt_put_prio (P_XCB p_CB, P_TCB p_task); +extern P_TCB rt_get_first (P_XCB p_CB); +extern void rt_put_rdy_first (P_TCB p_task); +extern P_TCB rt_get_same_rdy_prio (void); +extern void rt_resort_prio (P_TCB p_task); +extern void rt_put_dly (P_TCB p_task, U16 delay); +extern void rt_dec_dly (void); +extern void rt_rmv_list (P_TCB p_task); +extern void rt_rmv_dly (P_TCB p_task); +extern void rt_psq_enq (OS_ID entry, U32 arg); + +/* This is a fast macro generating in-line code */ +#define rt_rdy_prio(void) (os_rdy.p_lnk->prio) + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Mailbox.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,296 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MAILBOX.C + * Purpose: Implements waits and wake-ups for mailbox messages + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Mailbox.h" +#include "rt_MemBox.h" +#include "rt_Task.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_mbx_init -----------------------------------*/ + +void rt_mbx_init (OS_ID mailbox, U16 mbx_size) { + /* Initialize a mailbox */ + P_MCB p_MCB = mailbox; + + p_MCB->cb_type = MCB; + p_MCB->state = 0; + p_MCB->isr_st = 0; + p_MCB->p_lnk = NULL; + p_MCB->first = 0; + p_MCB->last = 0; + p_MCB->count = 0; + p_MCB->size = (mbx_size + sizeof(void *) - sizeof(struct OS_MCB)) / + (U32)sizeof (void *); +} + + +/*--------------------------- rt_mbx_send -----------------------------------*/ + +OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout) { + /* Send message to a mailbox */ + P_MCB p_MCB = mailbox; + P_TCB p_TCB; + + if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 1)) { + /* A task is waiting for message */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val2(p_TCB, 0x10/*osEventMessage*/, (U32)p_msg); +#else + *p_TCB->msg = p_msg; + rt_ret_val (p_TCB, OS_R_MBX); +#endif + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + /* Store message in mailbox queue */ + if (p_MCB->count == p_MCB->size) { + /* No free message entry, wait for one. If message queue is full, */ + /* then no task is waiting for message. The 'p_MCB->p_lnk' list */ + /* pointer can now be reused for send message waits task list. */ + if (timeout == 0) { + return (OS_R_TMO); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + /* Task is waiting to send a message */ + p_MCB->state = 2; + } + os_tsk.run->msg = p_msg; + rt_block (timeout, WAIT_MBX); + return (OS_R_TMO); + } + /* Yes, there is a free entry in a mailbox. */ + p_MCB->msg[p_MCB->first] = p_msg; + rt_inc (&p_MCB->count); + if (++p_MCB->first == p_MCB->size) { + p_MCB->first = 0; + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mbx_wait -----------------------------------*/ + +OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout) { + /* Receive a message; possibly wait for it */ + P_MCB p_MCB = mailbox; + P_TCB p_TCB; + + /* If a message is available in the fifo buffer */ + /* remove it from the fifo buffer and return. */ + if (p_MCB->count) { + *message = p_MCB->msg[p_MCB->last]; + if (++p_MCB->last == p_MCB->size) { + p_MCB->last = 0; + } + if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 2)) { + /* A task is waiting to send message */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_OK); +#endif + p_MCB->msg[p_MCB->first] = p_TCB->msg; + if (++p_MCB->first == p_MCB->size) { + p_MCB->first = 0; + } + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + rt_dec (&p_MCB->count); + } + return (OS_R_OK); + } + /* No message available: wait for one */ + if (timeout == 0) { + return (OS_R_TMO); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + /* Task is waiting to receive a message */ + p_MCB->state = 1; + } + rt_block(timeout, WAIT_MBX); +#ifndef __CMSIS_RTOS + os_tsk.run->msg = message; +#endif + return (OS_R_TMO); +} + + +/*--------------------------- rt_mbx_check ----------------------------------*/ + +OS_RESULT rt_mbx_check (OS_ID mailbox) { + /* Check for free space in a mailbox. Returns the number of messages */ + /* that can be stored to a mailbox. It returns 0 when mailbox is full. */ + P_MCB p_MCB = mailbox; + + return (p_MCB->size - p_MCB->count); +} + + +/*--------------------------- isr_mbx_send ----------------------------------*/ + +void isr_mbx_send (OS_ID mailbox, void *p_msg) { + /* Same function as "os_mbx_send", but to be called by ISRs. */ + P_MCB p_MCB = mailbox; + + rt_psq_enq (p_MCB, (U32)p_msg); + rt_psh_req (); +} + + +/*--------------------------- isr_mbx_receive -------------------------------*/ + +OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message) { + /* Receive a message in the interrupt function. The interrupt function */ + /* should not wait for a message since this would block the rtx os. */ + P_MCB p_MCB = mailbox; + + if (p_MCB->count) { + /* A message is available in the fifo buffer. */ + *message = p_MCB->msg[p_MCB->last]; + if (p_MCB->state == 2) { + /* A task is locked waiting to send message */ + rt_psq_enq (p_MCB, 0); + rt_psh_req (); + } + rt_dec (&p_MCB->count); + if (++p_MCB->last == p_MCB->size) { + p_MCB->last = 0; + } + return (OS_R_MBX); + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mbx_psh ------------------------------------*/ + +void rt_mbx_psh (P_MCB p_CB, void *p_msg) { + /* Store the message to the mailbox queue or pass it to task directly. */ + P_TCB p_TCB; + void *mem; + + if (p_CB->p_lnk != NULL) switch (p_CB->state) { +#ifdef __CMSIS_RTOS + case 3: + /* Task is waiting to allocate memory, remove it from the waiting list */ + mem = rt_alloc_box(p_msg); + if (mem == NULL) break; + p_TCB = rt_get_first ((P_XCB)p_CB); + rt_ret_val(p_TCB, (U32)mem); + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; +#endif + case 2: + /* Task is waiting to send a message, remove it from the waiting list */ + p_TCB = rt_get_first ((P_XCB)p_CB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_OK); +#endif + p_CB->msg[p_CB->first] = p_TCB->msg; + rt_inc (&p_CB->count); + if (++p_CB->first == p_CB->size) { + p_CB->first = 0; + } + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; + case 1: + /* Task is waiting for a message, pass the message to the task directly */ + p_TCB = rt_get_first ((P_XCB)p_CB); +#ifdef __CMSIS_RTOS + rt_ret_val2(p_TCB, 0x10/*osEventMessage*/, (U32)p_msg); +#else + *p_TCB->msg = p_msg; + rt_ret_val (p_TCB, OS_R_MBX); +#endif + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; + } else { + /* No task is waiting for a message, store it to the mailbox queue */ + if (p_CB->count < p_CB->size) { + p_CB->msg[p_CB->first] = p_msg; + rt_inc (&p_CB->count); + if (++p_CB->first == p_CB->size) { + p_CB->first = 0; + } + } + else { + os_error (OS_ERR_MBX_OVF); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Mailbox.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,48 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MAILBOX.H + * Purpose: Implements waits and wake-ups for mailbox messages + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_mbx_init (OS_ID mailbox, U16 mbx_size); +extern OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout); +extern OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout); +extern OS_RESULT rt_mbx_check (OS_ID mailbox); +extern void isr_mbx_send (OS_ID mailbox, void *p_msg); +extern OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message); +extern void rt_mbx_psh (P_MCB p_CB, void *p_msg); + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_MemBox.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,179 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMBOX.C + * Purpose: Interface functions for fixed memory block management system + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_MemBox.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- _init_box -------------------------------------*/ + +int _init_box (void *box_mem, U32 box_size, U32 blk_size) { + /* Initialize memory block system, returns 0 if OK, 1 if fails. */ + void *end; + void *blk; + void *next; + U32 sizeof_bm; + + /* Create memory structure. */ + if (blk_size & BOX_ALIGN_8) { + /* Memory blocks 8-byte aligned. */ + blk_size = ((blk_size & ~BOX_ALIGN_8) + 7) & ~7; + sizeof_bm = (sizeof (struct OS_BM) + 7) & ~7; + } + else { + /* Memory blocks 4-byte aligned. */ + blk_size = (blk_size + 3) & ~3; + sizeof_bm = sizeof (struct OS_BM); + } + if (blk_size == 0) { + return (1); + } + if ((blk_size + sizeof_bm) > box_size) { + return (1); + } + /* Create a Memory structure. */ + blk = ((U8 *) box_mem) + sizeof_bm; + ((P_BM) box_mem)->free = blk; + end = ((U8 *) box_mem) + box_size; + ((P_BM) box_mem)->end = end; + ((P_BM) box_mem)->blk_size = blk_size; + + /* Link all free blocks using offsets. */ + end = ((U8 *) end) - blk_size; + while (1) { + next = ((U8 *) blk) + blk_size; + if (next > end) break; + *((void **)blk) = next; + blk = next; + } + /* end marker */ + *((void **)blk) = 0; + return (0); +} + +/*--------------------------- rt_alloc_box ----------------------------------*/ + +void *rt_alloc_box (void *box_mem) { + /* Allocate a memory block and return start address. */ + void **free; +#ifndef __USE_EXCLUSIVE_ACCESS + int irq_dis; + + +#if defined (__ICCARM__) + irq_dis = __disable_irq_iar(); +#else + irq_dis = __disable_irq (); +#endif /* __ICCARM__ */ + free = ((P_BM) box_mem)->free; + if (free) { + ((P_BM) box_mem)->free = *free; + } + if (!irq_dis) __enable_irq (); +#else + do { + if ((free = (void **)__ldrex(&((P_BM) box_mem)->free)) == 0) { + __clrex(); + break; + } + } while (__strex((U32)*free, &((P_BM) box_mem)->free)); +#endif + return (free); +} + + +/*--------------------------- _calloc_box -----------------------------------*/ + +void *_calloc_box (void *box_mem) { + /* Allocate a 0-initialized memory block and return start address. */ + void *free; + U32 *p; + U32 i; + + free = _alloc_box (box_mem); + if (free) { + p = free; + for (i = ((P_BM) box_mem)->blk_size; i; i -= 4) { + *p = 0; + p++; + } + } + return (free); +} + + +/*--------------------------- rt_free_box -----------------------------------*/ + +int rt_free_box (void *box_mem, void *box) { + /* Free a memory block, returns 0 if OK, 1 if box does not belong to box_mem */ +#ifndef __USE_EXCLUSIVE_ACCESS + int irq_dis; +#endif + + if (box < box_mem || box >= ((P_BM) box_mem)->end) { + return (1); + } + +#ifndef __USE_EXCLUSIVE_ACCESS +#if defined (__ICCARM__) + irq_dis = __disable_irq_iar(); +#else + irq_dis = __disable_irq (); +#endif /* __ICCARM__ */ + *((void **)box) = ((P_BM) box_mem)->free; + ((P_BM) box_mem)->free = box; + if (!irq_dis) __enable_irq (); +#else + do { + *((void **)box) = (void *)__ldrex(&((P_BM) box_mem)->free); + } while (__strex ((U32)box, &((P_BM) box_mem)->free)); +#endif + return (0); +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_MemBox.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMBOX.H + * Purpose: Interface functions for fixed memory block management system + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +#define rt_init_box _init_box +#define rt_calloc_box _calloc_box +extern int _init_box (void *box_mem, U32 box_size, U32 blk_size); +extern void *rt_alloc_box (void *box_mem); +extern void * _calloc_box (void *box_mem); +extern int rt_free_box (void *box_mem, void *box); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Memory.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,140 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMORY.C + * Purpose: Interface functions for Dynamic Memory Management System + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "rt_Memory.h" + + +/* Functions */ + +// Initialize Dynamic Memory pool +// Parameters: +// pool: Pointer to memory pool +// size: Size of memory pool in bytes +// Return: 0 - OK, 1 - Error + +int rt_init_mem (void *pool, U32 size) { + MEMP *ptr; + + if ((pool == NULL) || (size < sizeof(MEMP))) return (1); + + ptr = (MEMP *)pool; + ptr->next = (MEMP *)((U32)pool + size - sizeof(MEMP *)); + ptr->next->next = NULL; + ptr->len = 0; + + return (0); +} + +// Allocate Memory from Memory pool +// Parameters: +// pool: Pointer to memory pool +// size: Size of memory in bytes to allocate +// Return: Pointer to allocated memory + +void *rt_alloc_mem (void *pool, U32 size) { + MEMP *p, *p_search, *p_new; + U32 hole_size; + + if ((pool == NULL) || (size == 0)) return NULL; + + /* Add header offset to 'size' */ + size += sizeof(MEMP); + /* Make sure that block is 4-byte aligned */ + size = (size + 3) & ~3; + + p_search = (MEMP *)pool; + while (1) { + hole_size = (U32)p_search->next - (U32)p_search; + hole_size -= p_search->len; + /* Check if hole size is big enough */ + if (hole_size >= size) break; + p_search = p_search->next; + if (p_search->next == NULL) { + /* Failed, we are at the end of the list */ + return NULL; + } + } + + if (p_search->len == 0) { + /* No block is allocated, set the Length of the first element */ + p_search->len = size; + p = (MEMP *)(((U32)p_search) + sizeof(MEMP)); + } else { + /* Insert new list element into the memory list */ + p_new = (MEMP *)((U32)p_search + p_search->len); + p_new->next = p_search->next; + p_new->len = size; + p_search->next = p_new; + p = (MEMP *)(((U32)p_new) + sizeof(MEMP)); + } + + return (p); +} + +// Free Memory and return it to Memory pool +// Parameters: +// pool: Pointer to memory pool +// mem: Pointer to memory to free +// Return: 0 - OK, 1 - Error + +int rt_free_mem (void *pool, void *mem) { + MEMP *p_search, *p_prev, *p_return; + + if ((pool == NULL) || (mem == NULL)) return (1); + + p_return = (MEMP *)((U32)mem - sizeof(MEMP)); + + /* Set list header */ + p_prev = NULL; + p_search = (MEMP *)pool; + while (p_search != p_return) { + p_prev = p_search; + p_search = p_search->next; + if (p_search == NULL) { + /* Valid Memory block not found */ + return (1); + } + } + + if (p_prev == NULL) { + /* First block to be released, only set length to 0 */ + p_search->len = 0; + } else { + /* Discard block from chain list */ + p_prev->next = p_search->next; + } + + return (0); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Memory.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,44 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMORY.H + * Purpose: Interface functions for Dynamic Memory Management System + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Types */ +typedef struct mem { /* << Memory Pool management struct >> */ + struct mem *next; /* Next Memory Block in the list */ + U32 len; /* Length of data block */ +} MEMP; + +/* Functions */ +extern int rt_init_mem (void *pool, U32 size); +extern void *rt_alloc_mem (void *pool, U32 size); +extern int rt_free_mem (void *pool, void *mem);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Mutex.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,267 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MUTEX.C + * Purpose: Implements mutex synchronization objects + * Rev.: V4.73 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Mutex.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_mut_init -----------------------------------*/ + +void rt_mut_init (OS_ID mutex) { + /* Initialize a mutex object */ + P_MUCB p_MCB = mutex; + + p_MCB->cb_type = MUCB; + p_MCB->level = 0; + p_MCB->p_lnk = NULL; + p_MCB->owner = NULL; + p_MCB->p_mlnk = NULL; +} + + +/*--------------------------- rt_mut_delete ---------------------------------*/ + +#ifdef __CMSIS_RTOS +OS_RESULT rt_mut_delete (OS_ID mutex) { + /* Delete a mutex object */ + P_MUCB p_MCB = mutex; + P_TCB p_TCB; + P_MUCB p_mlnk; + U8 prio; + + __DMB(); + /* Restore owner task's priority. */ + if (p_MCB->level != 0) { + + p_TCB = p_MCB->owner; + + /* Remove mutex from task mutex owner list. */ + p_mlnk = p_TCB->p_mlnk; + if (p_mlnk == p_MCB) { + p_TCB->p_mlnk = p_MCB->p_mlnk; + } + else { + while (p_mlnk) { + if (p_mlnk->p_mlnk == p_MCB) { + p_mlnk->p_mlnk = p_MCB->p_mlnk; + break; + } + p_mlnk = p_mlnk->p_mlnk; + } + } + + /* Restore owner task's priority. */ + prio = p_TCB->prio_base; + p_mlnk = p_TCB->p_mlnk; + while (p_mlnk) { + if (p_mlnk->p_lnk && (p_mlnk->p_lnk->prio > prio)) { + /* A task with higher priority is waiting for mutex. */ + prio = p_mlnk->p_lnk->prio; + } + p_mlnk = p_mlnk->p_mlnk; + } + if (p_TCB->prio != prio) { + p_TCB->prio = prio; + if (p_TCB != os_tsk.run) { + rt_resort_prio (p_TCB); + } + } + + } + + while (p_MCB->p_lnk != NULL) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); + rt_ret_val(p_TCB, 0/*osOK*/); + rt_rmv_dly(p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + } + + if (os_rdy.p_lnk && (os_rdy.p_lnk->prio > os_tsk.run->prio)) { + /* preempt running task */ + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + + p_MCB->cb_type = 0; + + return (OS_R_OK); +} +#endif + + +/*--------------------------- rt_mut_release --------------------------------*/ + +OS_RESULT rt_mut_release (OS_ID mutex) { + /* Release a mutex object */ + P_MUCB p_MCB = mutex; + P_TCB p_TCB; + P_MUCB p_mlnk; + U8 prio; + + if (p_MCB->level == 0 || p_MCB->owner != os_tsk.run) { + /* Unbalanced mutex release or task is not the owner */ + return (OS_R_NOK); + } + __DMB(); + if (--p_MCB->level != 0) { + return (OS_R_OK); + } + + /* Remove mutex from task mutex owner list. */ + p_mlnk = os_tsk.run->p_mlnk; + if (p_mlnk == p_MCB) { + os_tsk.run->p_mlnk = p_MCB->p_mlnk; + } + else { + while (p_mlnk) { + if (p_mlnk->p_mlnk == p_MCB) { + p_mlnk->p_mlnk = p_MCB->p_mlnk; + break; + } + p_mlnk = p_mlnk->p_mlnk; + } + } + + /* Restore owner task's priority. */ + prio = os_tsk.run->prio_base; + p_mlnk = os_tsk.run->p_mlnk; + while (p_mlnk) { + if (p_mlnk->p_lnk && (p_mlnk->p_lnk->prio > prio)) { + /* A task with higher priority is waiting for mutex. */ + prio = p_mlnk->p_lnk->prio; + } + p_mlnk = p_mlnk->p_mlnk; + } + os_tsk.run->prio = prio; + + if (p_MCB->p_lnk != NULL) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_MUT); +#endif + rt_rmv_dly (p_TCB); + /* A waiting task becomes the owner of this mutex. */ + p_MCB->level = 1; + p_MCB->owner = p_TCB; + p_MCB->p_mlnk = p_TCB->p_mlnk; + p_TCB->p_mlnk = p_MCB; + /* Priority inversion, check which task continues. */ + if (os_tsk.run->prio >= rt_rdy_prio()) { + rt_dispatch (p_TCB); + } + else { + /* Ready task has higher priority than running task. */ + rt_put_prio (&os_rdy, os_tsk.run); + rt_put_prio (&os_rdy, p_TCB); + os_tsk.run->state = READY; + p_TCB->state = READY; + rt_dispatch (NULL); + } + } + else { + /* Check if own priority lowered by priority inversion. */ + if (rt_rdy_prio() > os_tsk.run->prio) { + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mut_wait -----------------------------------*/ + +OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout) { + /* Wait for a mutex, continue when mutex is free. */ + P_MUCB p_MCB = mutex; + + if (p_MCB->level == 0) { + p_MCB->owner = os_tsk.run; + p_MCB->p_mlnk = os_tsk.run->p_mlnk; + os_tsk.run->p_mlnk = p_MCB; + goto inc; + } + if (p_MCB->owner == os_tsk.run) { + /* OK, running task is the owner of this mutex. */ +inc:p_MCB->level++; + __DMB(); + return (OS_R_OK); + } + /* Mutex owned by another task, wait until released. */ + if (timeout == 0) { + return (OS_R_TMO); + } + /* Raise the owner task priority if lower than current priority. */ + /* This priority inversion is called priority inheritance. */ + if (p_MCB->owner->prio < os_tsk.run->prio) { + p_MCB->owner->prio = os_tsk.run->prio; + rt_resort_prio (p_MCB->owner); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + } + rt_block(timeout, WAIT_MUT); + return (OS_R_TMO); +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Mutex.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,44 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_MUTEX.H + * Purpose: Implements mutex synchronization objects + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_delete (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Robin.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,88 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_ROBIN.C + * Purpose: Round Robin Task switching + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Time.h" +#include "rt_Robin.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +struct OS_ROBIN os_robin; + + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +/*--------------------------- rt_init_robin ---------------------------------*/ + +__weak void rt_init_robin (void) { + /* Initialize Round Robin variables. */ + os_robin.task = NULL; + os_robin.tout = (U16)os_rrobin; +} + +/*--------------------------- rt_chk_robin ----------------------------------*/ + +__weak void rt_chk_robin (void) { + /* Check if Round Robin timeout expired and switch to the next ready task.*/ + P_TCB p_new; + + if (os_robin.task != os_rdy.p_lnk) { + /* New task was suspended, reset Round Robin timeout. */ + os_robin.task = os_rdy.p_lnk; + os_robin.time = (U16)os_time + os_robin.tout - 1; + } + if (os_robin.time == (U16)os_time) { + /* Round Robin timeout has expired, swap Robin tasks. */ + os_robin.task = NULL; + p_new = rt_get_first (&os_rdy); + rt_put_prio ((P_XCB)&os_rdy, p_new); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Robin.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,45 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_ROBIN.H + * Purpose: Round Robin Task switching definitions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern struct OS_ROBIN os_robin; + +/* Functions */ +extern void rt_init_robin (void); +extern void rt_chk_robin (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Semaphore.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,191 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SEMAPHORE.C + * Purpose: Implements binary and counting semaphores + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Semaphore.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_sem_init -----------------------------------*/ + +void rt_sem_init (OS_ID semaphore, U16 token_count) { + /* Initialize a semaphore */ + P_SCB p_SCB = semaphore; + + p_SCB->cb_type = SCB; + p_SCB->p_lnk = NULL; + p_SCB->tokens = token_count; +} + + +/*--------------------------- rt_sem_delete ---------------------------------*/ + +#ifdef __CMSIS_RTOS +OS_RESULT rt_sem_delete (OS_ID semaphore) { + /* Delete semaphore */ + P_SCB p_SCB = semaphore; + P_TCB p_TCB; + + __DMB(); + while (p_SCB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_SCB); + rt_ret_val(p_TCB, 0); + rt_rmv_dly(p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + } + + if (os_rdy.p_lnk && (os_rdy.p_lnk->prio > os_tsk.run->prio)) { + /* preempt running task */ + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + + p_SCB->cb_type = 0; + + return (OS_R_OK); +} +#endif + + +/*--------------------------- rt_sem_send -----------------------------------*/ + +OS_RESULT rt_sem_send (OS_ID semaphore) { + /* Return a token to semaphore */ + P_SCB p_SCB = semaphore; + P_TCB p_TCB; + + __DMB(); + if (p_SCB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_SCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 1); +#else + rt_ret_val(p_TCB, OS_R_SEM); +#endif + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + /* Store token. */ + p_SCB->tokens++; + } + return (OS_R_OK); +} + + +/*--------------------------- rt_sem_wait -----------------------------------*/ + +OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout) { + /* Obtain a token; possibly wait for it */ + P_SCB p_SCB = semaphore; + + if (p_SCB->tokens) { + p_SCB->tokens--; + __DMB(); + return (OS_R_OK); + } + /* No token available: wait for one */ + if (timeout == 0) { + return (OS_R_TMO); + } + if (p_SCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_SCB, os_tsk.run); + } + else { + p_SCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_SCB; + } + rt_block(timeout, WAIT_SEM); + return (OS_R_TMO); +} + + +/*--------------------------- isr_sem_send ----------------------------------*/ + +void isr_sem_send (OS_ID semaphore) { + /* Same function as "os_sem_send", but to be called by ISRs */ + P_SCB p_SCB = semaphore; + + rt_psq_enq (p_SCB, 0); + rt_psh_req (); +} + + +/*--------------------------- rt_sem_psh ------------------------------------*/ + +void rt_sem_psh (P_SCB p_CB) { + /* Check if task has to be waken up */ + P_TCB p_TCB; + + __DMB(); + if (p_CB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_CB); + rt_rmv_dly (p_TCB); + p_TCB->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 1); +#else + rt_ret_val(p_TCB, OS_R_SEM); +#endif + rt_put_prio (&os_rdy, p_TCB); + } + else { + /* Store token */ + p_CB->tokens++; + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Semaphore.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SEMAPHORE.H + * Purpose: Implements binary and counting semaphores + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_sem_init (OS_ID semaphore, U16 token_count); +extern OS_RESULT rt_sem_delete(OS_ID semaphore); +extern OS_RESULT rt_sem_send (OS_ID semaphore); +extern OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout); +extern void isr_sem_send (OS_ID semaphore); +extern void rt_sem_psh (P_SCB p_CB); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_System.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,337 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SYSTEM.C + * Purpose: System Task Manager + * Rev.: 8 April 2015 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_Task.h" +#include "rt_System.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Mailbox.h" +#include "rt_Semaphore.h" +#include "rt_Time.h" +#include "rt_Timer.h" +#include "rt_Robin.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +int os_tick_irqn; +U8 scheduler_suspended = 0; // flag set by rt_suspend, cleared by rt_resume, read by SVC_Handler + +/*---------------------------------------------------------------------------- + * Local Variables + *---------------------------------------------------------------------------*/ + +static volatile BIT os_lock; +static volatile BIT os_psh_flag; +#ifndef __CORTEX_A9 +static U8 pend_flags; +#endif +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +#define RL_RTX_VER 0x473 + +#if defined (__CC_ARM) +__asm void $$RTX$$version (void) { + /* Export a version number symbol for a version control. */ + + EXPORT __RL_RTX_VER + +__RL_RTX_VER EQU RL_RTX_VER +} +#endif + + +/*--------------------------- rt_suspend ------------------------------------*/ + +extern U32 sysUserTimerWakeupTime(void); + +U32 rt_suspend (void) { + /* Suspend OS scheduler */ + U32 delta = 0xFFFF; +#ifdef __CMSIS_RTOS + U32 sleep; +#endif + + rt_tsk_lock(); + scheduler_suspended = 1; + + if (os_dly.p_dlnk) { + delta = os_dly.delta_time; + } +#ifdef __CMSIS_RTOS + sleep = sysUserTimerWakeupTime(); + if (sleep < delta) delta = sleep; +#else + if (os_tmr.next) { + if (os_tmr.tcnt < delta) delta = os_tmr.tcnt; + } +#endif + + return (delta); +} + + +/*--------------------------- rt_resume -------------------------------------*/ + +extern void sysUserTimerUpdate (U32 sleep_time); + +void rt_resume (U32 sleep_time) { + /* Resume OS scheduler after suspend */ + P_TCB next; + U32 delta; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + os_robin.task = NULL; + + /* Update delays. */ + if (os_dly.p_dlnk) { + delta = sleep_time; + if (delta >= os_dly.delta_time) { + delta -= os_dly.delta_time; + os_time += os_dly.delta_time; + os_dly.delta_time = 1; + while (os_dly.p_dlnk) { + rt_dec_dly(); + if (delta == 0) break; + delta--; + os_time++; + } + } else { + os_time += delta; + os_dly.delta_time -= delta; + } + } else { + os_time += sleep_time; + } + + /* Check the user timers. */ +#ifdef __CMSIS_RTOS + sysUserTimerUpdate(sleep_time); +#else + if (os_tmr.next) { + delta = sleep_time; + if (delta >= os_tmr.tcnt) { + delta -= os_tmr.tcnt; + os_tmr.tcnt = 1; + while (os_tmr.next) { + rt_tmr_tick(); + if (delta == 0) break; + delta--; + } + } else { + os_tmr.tcnt -= delta; + } + } +#endif + + /* Switch back to highest ready task */ + next = rt_get_first (&os_rdy); + rt_switch_req (next); + + scheduler_suspended = 0; + rt_tsk_unlock(); +} + + +/*--------------------------- rt_tsk_lock -----------------------------------*/ + +void rt_tsk_lock (void) { + /* Prevent task switching by locking out scheduler */ + if (os_lock == __TRUE) // don't lock again if already locked + return; + + if (os_tick_irqn < 0) { + OS_LOCK(); + os_lock = __TRUE; + OS_UNPEND (&pend_flags); + } else { + OS_X_LOCK(os_tick_irqn); + os_lock = __TRUE; + OS_X_UNPEND (&pend_flags); + } +} + + +/*--------------------------- rt_tsk_unlock ---------------------------------*/ + +void rt_tsk_unlock (void) { + /* Unlock scheduler and re-enable task switching */ + if (os_tick_irqn < 0) { + OS_UNLOCK(); + os_lock = __FALSE; + OS_PEND (pend_flags, os_psh_flag); + os_psh_flag = __FALSE; + } else { + OS_X_UNLOCK(os_tick_irqn); + os_lock = __FALSE; + OS_X_PEND (pend_flags, os_psh_flag); + os_psh_flag = __FALSE; + } +} + + +/*--------------------------- rt_psh_req ------------------------------------*/ + +void rt_psh_req (void) { + /* Initiate a post service handling request if required. */ + if (os_lock == __FALSE) { + OS_PEND_IRQ (); + } + else { + os_psh_flag = __TRUE; + } +} + + +/*--------------------------- rt_pop_req ------------------------------------*/ + +void rt_pop_req (void) { + /* Process an ISR post service requests. */ + struct OS_XCB *p_CB; + P_TCB next; + U32 idx; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + idx = os_psq->last; + while (os_psq->count) { + p_CB = os_psq->q[idx].id; + if (p_CB->cb_type == TCB) { + /* Is of TCB type */ + rt_evt_psh ((P_TCB)p_CB, (U16)os_psq->q[idx].arg); + } + else if (p_CB->cb_type == MCB) { + /* Is of MCB type */ + rt_mbx_psh ((P_MCB)p_CB, (void *)os_psq->q[idx].arg); + } + else { + /* Must be of SCB type */ + rt_sem_psh ((P_SCB)p_CB); + } + if (++idx == os_psq->size) idx = 0; + rt_dec (&os_psq->count); + } + os_psq->last = idx; + + next = rt_get_first (&os_rdy); + rt_switch_req (next); +} + + +/*--------------------------- os_tick_init ----------------------------------*/ + +__weak int os_tick_init (void) { + /* Initialize SysTick timer as system tick timer. */ + rt_systick_init (); + return (-1); /* Return IRQ number of SysTick timer */ +} + +/*--------------------------- os_tick_val -----------------------------------*/ + +__weak U32 os_tick_val (void) { + /* Get SysTick timer current value (0 .. OS_TRV). */ + return rt_systick_val(); +} + +/*--------------------------- os_tick_ovf -----------------------------------*/ + +__weak U32 os_tick_ovf (void) { + /* Get SysTick timer overflow flag */ + return rt_systick_ovf(); +} + +/*--------------------------- os_tick_irqack --------------------------------*/ + +__weak void os_tick_irqack (void) { + /* Acknowledge timer interrupt. */ +} + + +/*--------------------------- rt_systick ------------------------------------*/ + +extern void sysTimerTick(void); + +void rt_systick (void) { + /* Check for system clock update, suspend running task. */ + P_TCB next; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + /* Check Round Robin timeout. */ + rt_chk_robin (); + + /* Update delays. */ + os_time++; + rt_dec_dly (); + + /* Check the user timers. */ +#ifdef __CMSIS_RTOS + sysTimerTick(); +#else + rt_tmr_tick (); +#endif + + /* Switch back to highest ready task */ + next = rt_get_first (&os_rdy); + rt_switch_req (next); +} + +/*--------------------------- rt_stk_check ----------------------------------*/ + +__weak void rt_stk_check (void) { + /* Check for stack overflow. */ + if ((os_tsk.run->tsk_stack < (U32)os_tsk.run->stack) || + (os_tsk.run->stack[0] != MAGIC_WORD)) { + os_error (OS_ERR_STK_OVF); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_System.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,52 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_SYSTEM.H + * Purpose: System Task Manager definitions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Variables */ +#define os_psq ((P_PSQ)&os_fifo) +extern int os_tick_irqn; + +/* Functions */ +extern U32 rt_suspend (void); +extern void rt_resume (U32 sleep_time); +extern void rt_tsk_lock (void); +extern void rt_tsk_unlock (void); +extern void rt_psh_req (void); +extern void rt_pop_req (void); +extern void rt_systick (void); +extern void rt_stk_check (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Task.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,436 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TASK.C + * Purpose: Task functions and system start up. + * Rev.: V4.73 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_Task.h" +#include "rt_List.h" +#include "rt_MemBox.h" +#include "rt_Robin.h" +#ifdef __CORTEX_A9 +#include "rt_HAL_CA.h" +#else +#include "rt_HAL_CM.h" +#endif + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* Running and next task info. */ +struct OS_TSK os_tsk; + +/* Task Control Blocks of idle demon */ +struct OS_TCB os_idle_TCB; + + +/*---------------------------------------------------------------------------- + * Local Functions + *---------------------------------------------------------------------------*/ + +static OS_TID rt_get_TID (void) { + U32 tid; + + for (tid = 1; tid <= os_maxtaskrun; tid++) { + if (os_active_TCB[tid-1] == NULL) { + return ((OS_TID)tid); + } + } + return (0); +} + + +/*--------------------------- rt_init_context -------------------------------*/ + +static void rt_init_context (P_TCB p_TCB, U8 priority, FUNCP task_body) { + /* Initialize general part of the Task Control Block. */ + p_TCB->cb_type = TCB; + p_TCB->state = READY; + p_TCB->prio = priority; + p_TCB->prio_base = priority; + p_TCB->p_lnk = NULL; + p_TCB->p_rlnk = NULL; + p_TCB->p_dlnk = NULL; + p_TCB->p_blnk = NULL; + p_TCB->p_mlnk = NULL; + p_TCB->delta_time = 0; + p_TCB->interval_time = 0; + p_TCB->events = 0; + p_TCB->waits = 0; + p_TCB->stack_frame = 0; + + if (p_TCB->priv_stack == 0) { + /* Allocate the memory space for the stack. */ + p_TCB->stack = rt_alloc_box (mp_stk); + } + rt_init_stack (p_TCB, task_body); +} + + +/*--------------------------- rt_switch_req ---------------------------------*/ + +void rt_switch_req (P_TCB p_new) { + /* Switch to next task (identified by "p_new"). */ + os_tsk.new_tsk = p_new; + p_new->state = RUNNING; + DBG_TASK_SWITCH(p_new->task_id); +} + + +/*--------------------------- rt_dispatch -----------------------------------*/ + +void rt_dispatch (P_TCB next_TCB) { + /* Dispatch next task if any identified or dispatch highest ready task */ + /* "next_TCB" identifies a task to run or has value NULL (=no next task) */ + if (next_TCB == NULL) { + /* Running task was blocked: continue with highest ready task */ + next_TCB = rt_get_first (&os_rdy); + rt_switch_req (next_TCB); + } + else { + /* Check which task continues */ + if (next_TCB->prio > os_tsk.run->prio) { + /* preempt running task */ + rt_put_rdy_first (os_tsk.run); + os_tsk.run->state = READY; + rt_switch_req (next_TCB); + } + else { + /* put next task into ready list, no task switch takes place */ + next_TCB->state = READY; + rt_put_prio (&os_rdy, next_TCB); + } + } +} + + +/*--------------------------- rt_block --------------------------------------*/ + +void rt_block (U16 timeout, U8 block_state) { + /* Block running task and choose next ready task. */ + /* "timeout" sets a time-out value or is 0xffff (=no time-out). */ + /* "block_state" defines the appropriate task state */ + P_TCB next_TCB; + + if (timeout) { + if (timeout < 0xffff) { + rt_put_dly (os_tsk.run, timeout); + } + os_tsk.run->state = block_state; + next_TCB = rt_get_first (&os_rdy); + rt_switch_req (next_TCB); + } +} + + +/*--------------------------- rt_tsk_pass -----------------------------------*/ + +void rt_tsk_pass (void) { + /* Allow tasks of same priority level to run cooperatively.*/ + P_TCB p_new; + + p_new = rt_get_same_rdy_prio(); + if (p_new != NULL) { + rt_put_prio ((P_XCB)&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_switch_req (p_new); + } +} + + +/*--------------------------- rt_tsk_self -----------------------------------*/ + +OS_TID rt_tsk_self (void) { + /* Return own task identifier value. */ + if (os_tsk.run == NULL) { + return (0); + } + return (os_tsk.run->task_id); +} + + +/*--------------------------- rt_tsk_prio -----------------------------------*/ + +OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio) { + /* Change execution priority of a task to "new_prio". */ + P_TCB p_task; + + if (task_id == 0) { + /* Change execution priority of calling task. */ + os_tsk.run->prio = new_prio; + os_tsk.run->prio_base = new_prio; +run:if (rt_rdy_prio() > new_prio) { + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + return (OS_R_OK); + } + + /* Find the task in the "os_active_TCB" array. */ + if (task_id > os_maxtaskrun || os_active_TCB[task_id-1] == NULL) { + /* Task with "task_id" not found or not started. */ + return (OS_R_NOK); + } + p_task = os_active_TCB[task_id-1]; + p_task->prio = new_prio; + p_task->prio_base = new_prio; + if (p_task == os_tsk.run) { + goto run; + } + rt_resort_prio (p_task); + if (p_task->state == READY) { + /* Task enqueued in a ready list. */ + p_task = rt_get_first (&os_rdy); + rt_dispatch (p_task); + } + return (OS_R_OK); +} + + +/*--------------------------- rt_tsk_create ---------------------------------*/ + +OS_TID rt_tsk_create (FUNCP task, U32 prio_stksz, void *stk, void *argv) { + /* Start a new task declared with "task". */ + P_TCB task_context; + U32 i; + + /* Priority 0 is reserved for idle task! */ + if ((prio_stksz & 0xFF) == 0) { + prio_stksz += 1; + } + task_context = rt_alloc_box (mp_tcb); + if (task_context == NULL) { + return (0); + } + /* If "size != 0" use a private user provided stack. */ + task_context->stack = stk; + task_context->priv_stack = prio_stksz >> 8; + /* Pass parameter 'argv' to 'rt_init_context' */ + task_context->msg = argv; + /* For 'size == 0' system allocates the user stack from the memory pool. */ + rt_init_context (task_context, prio_stksz & 0xFF, task); + + /* Find a free entry in 'os_active_TCB' table. */ + i = rt_get_TID (); + os_active_TCB[i-1] = task_context; + task_context->task_id = i; + DBG_TASK_NOTIFY(task_context, __TRUE); + rt_dispatch (task_context); + return ((OS_TID)i); +} + + +/*--------------------------- rt_tsk_delete ---------------------------------*/ + +OS_RESULT rt_tsk_delete (OS_TID task_id) { + /* Terminate the task identified with "task_id". */ + P_TCB task_context; + P_TCB p_TCB; + P_MUCB p_MCB, p_MCB0; + + if (task_id == 0 || task_id == os_tsk.run->task_id) { + /* Terminate itself. */ + os_tsk.run->state = INACTIVE; + os_tsk.run->tsk_stack = rt_get_PSP (); + rt_stk_check (); + p_MCB = os_tsk.run->p_mlnk; + while (p_MCB) { + /* Release mutexes owned by this task */ + if (p_MCB->p_lnk) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_MUT); +#endif + rt_rmv_dly (p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + /* A waiting task becomes the owner of this mutex. */ + p_MCB0 = p_MCB; + p_MCB->level = 1; + p_MCB->owner = p_TCB; + p_MCB->p_mlnk = p_TCB->p_mlnk; + p_TCB->p_mlnk = p_MCB; + p_MCB = p_MCB0->p_mlnk; + } + else { + p_MCB = p_MCB->p_mlnk; + } + } + os_active_TCB[os_tsk.run->task_id-1] = NULL; + rt_free_box (mp_stk, os_tsk.run->stack); + os_tsk.run->stack = NULL; + DBG_TASK_NOTIFY(os_tsk.run, __FALSE); + rt_free_box (mp_tcb, os_tsk.run); + os_tsk.run = NULL; + rt_dispatch (NULL); + /* The program should never come to this point. */ + } + else { + /* Find the task in the "os_active_TCB" array. */ + if (task_id > os_maxtaskrun || os_active_TCB[task_id-1] == NULL) { + /* Task with "task_id" not found or not started. */ + return (OS_R_NOK); + } + task_context = os_active_TCB[task_id-1]; + rt_rmv_list (task_context); + rt_rmv_dly (task_context); + p_MCB = task_context->p_mlnk; + while (p_MCB) { + /* Release mutexes owned by this task */ + if (p_MCB->p_lnk) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_MUT); +#endif + rt_rmv_dly (p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + /* A waiting task becomes the owner of this mutex. */ + p_MCB0 = p_MCB; + p_MCB->level = 1; + p_MCB->owner = p_TCB; + p_MCB->p_mlnk = p_TCB->p_mlnk; + p_TCB->p_mlnk = p_MCB; + p_MCB = p_MCB0->p_mlnk; + } + else { + p_MCB = p_MCB->p_mlnk; + } + } + os_active_TCB[task_id-1] = NULL; + rt_free_box (mp_stk, task_context->stack); + task_context->stack = NULL; + DBG_TASK_NOTIFY(task_context, __FALSE); + rt_free_box (mp_tcb, task_context); + if (rt_rdy_prio() > os_tsk.run->prio) { + /* Ready task has higher priority than running task. */ + os_tsk.run->state = READY; + rt_put_prio (&os_rdy, os_tsk.run); + rt_dispatch (NULL); + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_sys_init -----------------------------------*/ + +#ifdef __CMSIS_RTOS +void rt_sys_init (void) { +#else +void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk) { +#endif + /* Initialize system and start up task declared with "first_task". */ + U32 i; + + DBG_INIT(); + + /* Initialize dynamic memory and task TCB pointers to NULL. */ + for (i = 0; i < os_maxtaskrun; i++) { + os_active_TCB[i] = NULL; + } + rt_init_box (&mp_tcb, mp_tcb_size, sizeof(struct OS_TCB)); + rt_init_box (&mp_stk, mp_stk_size, BOX_ALIGN_8 | (U16)(os_stackinfo)); + rt_init_box ((U32 *)m_tmr, mp_tmr_size, sizeof(struct OS_TMR)); + + /* Set up TCB of idle demon */ + os_idle_TCB.task_id = 255; + os_idle_TCB.priv_stack = 0; + rt_init_context (&os_idle_TCB, 0, os_idle_demon); + + /* Set up ready list: initially empty */ + os_rdy.cb_type = HCB; + os_rdy.p_lnk = NULL; + /* Set up delay list: initially empty */ + os_dly.cb_type = HCB; + os_dly.p_dlnk = NULL; + os_dly.p_blnk = NULL; + os_dly.delta_time = 0; + + /* Fix SP and system variables to assume idle task is running */ + /* Transform main program into idle task by assuming idle TCB */ +#ifndef __CMSIS_RTOS + rt_set_PSP (os_idle_TCB.tsk_stack+32); +#endif + os_tsk.run = &os_idle_TCB; + os_tsk.run->state = RUNNING; + + /* Initialize ps queue */ + os_psq->first = 0; + os_psq->last = 0; + os_psq->size = os_fifo_size; + + rt_init_robin (); + + /* Initialize SVC and PendSV */ + rt_svc_init (); + +#ifndef __CMSIS_RTOS + /* Initialize and start system clock timer */ + os_tick_irqn = os_tick_init (); + if (os_tick_irqn >= 0) { + OS_X_INIT(os_tick_irqn); + } + + /* Start up first user task before entering the endless loop */ + rt_tsk_create (first_task, prio_stksz, stk, NULL); +#endif +} + + +/*--------------------------- rt_sys_start ----------------------------------*/ + +#ifdef __CMSIS_RTOS +void rt_sys_start (void) { + /* Start system */ + + /* Initialize and start system clock timer */ + os_tick_irqn = os_tick_init (); + if (os_tick_irqn >= 0) { + OS_X_INIT(os_tick_irqn); + } +} +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Task.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,87 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TASK.H + * Purpose: Task functions and system start up. + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Definitions */ + +/* Values for 'state' */ +#define INACTIVE 0 +#define READY 1 +#define RUNNING 2 +#define WAIT_DLY 3 +#define WAIT_ITV 4 +#define WAIT_OR 5 +#define WAIT_AND 6 +#define WAIT_SEM 7 +#define WAIT_MBX 8 +#define WAIT_MUT 9 + +/* Return codes */ +#define OS_R_TMO 0x01 +#define OS_R_EVT 0x02 +#define OS_R_SEM 0x03 +#define OS_R_MBX 0x04 +#define OS_R_MUT 0x05 + +#define OS_R_OK 0x00 +#define OS_R_NOK 0xff + +/* Variables */ +extern struct OS_TSK os_tsk; +extern struct OS_TCB os_idle_TCB; + +/* Functions */ +extern void rt_switch_req (P_TCB p_new); +extern void rt_dispatch (P_TCB next_TCB); +extern void rt_block (U16 timeout, U8 block_state); +extern void rt_tsk_pass (void); +extern OS_TID rt_tsk_self (void); +extern OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio); +extern OS_TID rt_tsk_create (FUNCP task, U32 prio_stksz, void *stk, void *argv); +extern OS_RESULT rt_tsk_delete (OS_TID task_id); +#ifdef __CMSIS_RTOS +extern void rt_sys_init (void); +extern void rt_sys_start (void); +#else +extern void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk); +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + + + + + +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Time.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,94 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIME.C + * Purpose: Delay and interval wait functions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_Task.h" +#include "rt_Time.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* Free running system tick counter */ +U32 os_time; + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_time_get -----------------------------------*/ + +U32 rt_time_get (void) { + /* Get system time tick */ + return (os_time); +} + + +/*--------------------------- rt_dly_wait -----------------------------------*/ + +void rt_dly_wait (U16 delay_time) { + /* Delay task by "delay_time" */ + rt_block (delay_time, WAIT_DLY); +} + + +/*--------------------------- rt_itv_set ------------------------------------*/ + +void rt_itv_set (U16 interval_time) { + /* Set interval length and define start of first interval */ + os_tsk.run->interval_time = interval_time; + os_tsk.run->delta_time = interval_time + (U16)os_time; +} + + +/*--------------------------- rt_itv_wait -----------------------------------*/ + +void rt_itv_wait (void) { + /* Wait for interval end and define start of next one */ + U16 delta; + + delta = os_tsk.run->delta_time - (U16)os_time; + os_tsk.run->delta_time += os_tsk.run->interval_time; + if ((delta & 0x8000) == 0) { + rt_block (delta, WAIT_ITV); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Time.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,47 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIME.H + * Purpose: Delay and interval wait functions definitions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern U32 os_time; + +/* Functions */ +extern U32 rt_time_get (void); +extern void rt_dly_wait (U16 delay_time); +extern void rt_itv_set (U16 interval_time); +extern void rt_itv_wait (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_Timer.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIMER.H + * Purpose: User timer functions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern struct OS_XTMR os_tmr; + +/* Functions */ +extern void rt_tmr_tick (void); +extern OS_ID rt_tmr_create (U16 tcnt, U16 info); +extern OS_ID rt_tmr_kill (OS_ID timer); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_A/rt_TypeDef.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,187 @@ +/*---------------------------------------------------------------------------- + * RL-ARM - RTX + *---------------------------------------------------------------------------- + * Name: RT_TYPEDEF.H + * Purpose: Type Definitions + * Rev.: V4.73 (plus large stack) + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Types */ +typedef char S8; +typedef unsigned char U8; +typedef short S16; +typedef unsigned short U16; +typedef int S32; +typedef unsigned int U32; +typedef long long S64; +typedef unsigned long long U64; +typedef unsigned char BIT; +typedef unsigned int BOOL; +typedef void (*FUNCP)(void); + +typedef U32 OS_TID; +typedef void *OS_ID; +typedef U32 OS_RESULT; + +typedef struct OS_TCB { + /* General part: identical for all implementations. */ + U8 cb_type; /* Control Block Type */ + U8 state; /* Task state */ + U8 prio; /* Execution priority */ + U8 task_id; /* Task ID value for optimized TCB access */ + struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */ + struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */ + struct OS_TCB *p_dlnk; /* Link pointer for delay list */ + struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */ + U16 delta_time; /* Time until time out */ + U16 interval_time; /* Time interval for periodic waits */ + U16 events; /* Event flags */ + U16 waits; /* Wait flags */ + void **msg; /* Direct message passing when task waits */ + struct OS_MUCB *p_mlnk; /* Link pointer for mutex owner list */ + U8 prio_base; /* Base priority */ + + /* Hardware dependant part: specific for Cortex processor */ + U8 stack_frame; /* Stack frame: 0x0 Basic, 0x1 Extended, 0x2 VFP/D16 stacked, 0x4 NEON/D32 stacked */ +#if defined (__ICCARM__) +#ifndef __LARGE_PRIV_STACK + U16 priv_stack; /* Private stack size, 0= system assigned */ +#else + U16 reserved; /* Reserved (padding) */ + U32 priv_stack; /* Private stack size for LARGE_STACK, 0= system assigned */ +#endif /* __LARGE_PRIV_STACK */ +#else + U16 reserved; /* Reserved (padding) */ + U32 priv_stack; /* Private stack size for LARGE_STACK, 0= system assigned */ +#endif + U32 tsk_stack; /* Current task Stack pointer (R13) */ + U32 *stack; /* Pointer to Task Stack memory block */ + + /* Task entry point used for uVision debugger */ + FUNCP ptask; /* Task entry address */ + void *argv; /* Task argument */ +} *P_TCB; +#define TCB_TID 3 /* 'task id' offset */ +#define TCB_STACKF 37 /* 'stack_frame' offset */ +#if defined (__ICCARM__) +#ifndef __LARGE_PRIV_STACK +#define TCB_TSTACK 40 /* 'tsk_stack' offset */ +#else +#define TCB_TSTACK 44 /* 'tsk_stack' offset for LARGE_STACK */ +#endif /* __LARGE_PRIV_STACK */ +#else +#define TCB_TSTACK 44 /* 'tsk_stack' offset for LARGE_STACK */ +#endif + +typedef struct OS_PSFE { /* Post Service Fifo Entry */ + void *id; /* Object Identification */ + U32 arg; /* Object Argument */ +} *P_PSFE; + +typedef struct OS_PSQ { /* Post Service Queue */ + U8 first; /* FIFO Head Index */ + U8 last; /* FIFO Tail Index */ + U8 count; /* Number of stored items in FIFO */ + U8 size; /* FIFO Size */ + struct OS_PSFE q[1]; /* FIFO Content */ +} *P_PSQ; + +typedef struct OS_TSK { + P_TCB run; /* Current running task */ + P_TCB new_tsk; /* Scheduled task to run */ +} *P_TSK; + +typedef struct OS_ROBIN { /* Round Robin Control */ + P_TCB task; /* Round Robin task */ + U16 time; /* Round Robin switch time */ + U16 tout; /* Round Robin timeout */ +} *P_ROBIN; + +typedef struct OS_XCB { + U8 cb_type; /* Control Block Type */ + struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */ + struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */ + struct OS_TCB *p_dlnk; /* Link pointer for delay list */ + struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */ + U16 delta_time; /* Time until time out */ +} *P_XCB; + +typedef struct OS_MCB { + U8 cb_type; /* Control Block Type */ + U8 state; /* State flag variable */ + U8 isr_st; /* State flag variable for isr functions */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for message */ + U16 first; /* Index of the message list begin */ + U16 last; /* Index of the message list end */ + U16 count; /* Actual number of stored messages */ + U16 size; /* Maximum number of stored messages */ + void *msg[1]; /* FIFO for Message pointers 1st element */ +} *P_MCB; + +typedef struct OS_SCB { + U8 cb_type; /* Control Block Type */ + U8 mask; /* Semaphore token mask */ + U16 tokens; /* Semaphore tokens */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for tokens */ +} *P_SCB; + +typedef struct OS_MUCB { + U8 cb_type; /* Control Block Type */ + U16 level; /* Call nesting level */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for mutex */ + struct OS_TCB *owner; /* Mutex owner task */ + struct OS_MUCB *p_mlnk; /* Chain of mutexes by owner task */ +} *P_MUCB; + +typedef struct OS_XTMR { + struct OS_TMR *next; + U16 tcnt; +} *P_XTMR; + +typedef struct OS_TMR { + struct OS_TMR *next; /* Link pointer to Next timer */ + U16 tcnt; /* Timer delay count */ + U16 info; /* User defined call info */ +} *P_TMR; + +typedef struct OS_BM { + void *free; /* Pointer to first free memory block */ + void *end; /* Pointer to memory block end */ + U32 blk_size; /* Memory block size */ +} *P_BM; + +/* Definitions */ +#define __TRUE 1 +#define __FALSE 0 +#define NULL ((void *) 0) + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/HAL_CM.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,207 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM.C + * Purpose: Hardware Abstraction Layer for Cortex-M + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_HAL_CM.h" +#include "cmsis_os.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +#ifdef DBG_MSG +BIT dbg_msg; +#endif + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_init_stack ---------------------------------*/ + +void rt_init_stack (P_TCB p_TCB, FUNCP task_body) { + /* Prepare TCB and saved context for a first time start of a task. */ + U32 *stk,i,size; + + /* Prepare a complete interrupt frame for first task start */ + size = p_TCB->priv_stack >> 2; + if (size == 0U) { + size = (U16)os_stackinfo >> 2; + } + + /* Write to the top of stack. */ + stk = &p_TCB->stack[size]; + + /* Auto correct to 8-byte ARM stack alignment. */ + if ((U32)stk & 0x04U) { + stk--; + } + + stk -= 16; + + /* Default xPSR and initial PC */ + stk[15] = INITIAL_xPSR; + stk[14] = (U32)task_body; + + /* Clear R4-R11,R0-R3,R12,LR registers. */ + for (i = 0U; i < 14U; i++) { + stk[i] = 0U; + } + + /* Assign a void pointer to R0. */ + stk[8] = (U32)p_TCB->msg; + + /* Initial Task stack pointer. */ + p_TCB->tsk_stack = (U32)stk; + + /* Task entry point. */ + p_TCB->ptask = task_body; + + +#ifdef __MBED_CMSIS_RTOS_CM + /* Set a magic word for checking of stack overflow. + For the main thread (ID: MAIN_THREAD_ID) the stack is in a memory area shared with the + heap, therefore the last word of the stack is a moving target. + We want to do stack/heap collision detection instead. + Similar applies to stack filling for the magic pattern. + */ + if (p_TCB->task_id != MAIN_THREAD_ID) { + p_TCB->stack[0] = MAGIC_WORD; + + /* Initialize stack with magic pattern. */ + if (os_stackinfo & 0x10000000U) { + if (size > (16U+1U)) { + for (i = ((size - 16U)/2U) - 1U; i; i--) { + stk -= 2U; + stk[1] = MAGIC_PATTERN; + stk[0] = MAGIC_PATTERN; + } + if (--stk > p_TCB->stack) { + *stk = MAGIC_PATTERN; + } + } + } + } +#else + /* Initialize stack with magic pattern. */ + if (os_stackinfo & 0x10000000U) { + if (size > (16U+1U)) { + for (i = ((size - 16U)/2U) - 1U; i; i--) { + stk -= 2U; + stk[1] = MAGIC_PATTERN; + stk[0] = MAGIC_PATTERN; + } + if (--stk > p_TCB->stack) { + *stk = MAGIC_PATTERN; + } + } + } + + /* Set a magic word for checking of stack overflow. */ + p_TCB->stack[0] = MAGIC_WORD; +#endif +} + + +/*--------------------------- rt_ret_val ----------------------------------*/ + +static __inline U32 *rt_ret_regs (P_TCB p_TCB) { + /* Get pointer to task return value registers (R0..R3) in Stack */ +#if defined(__TARGET_FPU_VFP) + if (p_TCB->stack_frame) { + /* Extended Stack Frame: R4-R11,S16-S31,R0-R3,R12,LR,PC,xPSR,S0-S15,FPSCR */ + return (U32 *)(p_TCB->tsk_stack + (8U*4U) + (16U*4U)); + } else { + /* Basic Stack Frame: R4-R11,R0-R3,R12,LR,PC,xPSR */ + return (U32 *)(p_TCB->tsk_stack + (8U*4U)); + } +#else + /* Stack Frame: R4-R11,R0-R3,R12,LR,PC,xPSR */ + return (U32 *)(p_TCB->tsk_stack + (8U*4U)); +#endif +} + +void rt_ret_val (P_TCB p_TCB, U32 v0) { + U32 *ret; + + ret = rt_ret_regs(p_TCB); + ret[0] = v0; +} + +void rt_ret_val2(P_TCB p_TCB, U32 v0, U32 v1) { + U32 *ret; + + ret = rt_ret_regs(p_TCB); + ret[0] = v0; + ret[1] = v1; +} + + +/*--------------------------- dbg_init --------------------------------------*/ + +#ifdef DBG_MSG +void dbg_init (void) { + if (((DEMCR & DEMCR_TRCENA) != 0U) && + ((ITM_CONTROL & ITM_ITMENA) != 0U) && + ((ITM_ENABLE & (1UL << 31)) != 0U)) { + dbg_msg = __TRUE; + } +} +#endif + +/*--------------------------- dbg_task_notify -------------------------------*/ + +#ifdef DBG_MSG +void dbg_task_notify (P_TCB p_tcb, BOOL create) { + while (ITM_PORT31_U32 == 0U); + ITM_PORT31_U32 = (U32)p_tcb->ptask; + while (ITM_PORT31_U32 == 0U); + ITM_PORT31_U16 = (U16)((create << 8) | p_tcb->task_id); +} +#endif + +/*--------------------------- dbg_task_switch -------------------------------*/ + +#ifdef DBG_MSG +void dbg_task_switch (U32 task_id) { + while (ITM_PORT31_U32 == 0U); + ITM_PORT31_U8 = (U8)task_id; +} +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/RTX_CM_lib.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,608 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RTX_CM_LIB.H + * Purpose: RTX Kernel System Configuration + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ +#include "mbed_error.h" + +#if defined (__CC_ARM) +#include <rt_misc.h> +#pragma O3 +#define __USED __attribute__((used)) +#elif defined (__GNUC__) +#pragma GCC optimize ("O3") +#define __USED __attribute__((used)) +#elif defined (__ICCARM__) +#define __USED __root +#endif + + +/*---------------------------------------------------------------------------- + * Definitions + *---------------------------------------------------------------------------*/ + +#define _declare_box(pool,size,cnt) uint32_t pool[(((size)+3)/4)*(cnt) + 3] +#define _declare_box8(pool,size,cnt) uint64_t pool[(((size)+7)/8)*(cnt) + 2] + +#define OS_TCB_SIZE 64 +#define OS_TMR_SIZE 8 + +typedef void *OS_ID; +typedef uint32_t OS_TID; +typedef uint32_t OS_MUT[4]; +typedef uint32_t OS_RESULT; + +#if defined (__CC_ARM) && !defined (__MICROLIB) + +#define runtask_id() rt_tsk_self() +#define mutex_init(m) rt_mut_init(m) +#define mutex_wait(m) os_mut_wait(m,0xFFFFU) +#define mutex_rel(m) os_mut_release(m) + +extern uint8_t os_running; +extern OS_TID rt_tsk_self (void); +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, uint16_t timeout); + +#define os_mut_wait(mutex,timeout) _os_mut_wait((uint32_t)rt_mut_wait,mutex,timeout) +#define os_mut_release(mutex) _os_mut_release((uint32_t)rt_mut_release,mutex) + +OS_RESULT _os_mut_release (uint32_t p, OS_ID mutex) __svc_indirect(0); +OS_RESULT _os_mut_wait (uint32_t p, OS_ID mutex, uint16_t timeout) __svc_indirect(0); + +#endif + + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +#if (OS_TASKCNT == 0) +#error "Invalid number of concurrent running threads!" +#endif + +#if (OS_PRIVCNT >= OS_TASKCNT) +#error "Too many threads with user-provided stack size!" +#endif + +#if (OS_TIMERS != 0) +#define OS_TASK_CNT (OS_TASKCNT + 1) +#ifndef __MBED_CMSIS_RTOS_CM +#define OS_PRIV_CNT (OS_PRIVCNT + 2) +#define OS_STACK_SZ (4*(OS_PRIVSTKSIZE+OS_MAINSTKSIZE+OS_TIMERSTKSZ)) +#endif +#else +#define OS_TASK_CNT OS_TASKCNT +#ifndef __MBED_CMSIS_RTOS_CM +#define OS_PRIV_CNT (OS_PRIVCNT + 1) +#define OS_STACK_SZ (4*(OS_PRIVSTKSIZE+OS_MAINSTKSIZE)) +#endif +#endif + +#ifndef OS_STKINIT +#define OS_STKINIT 0 +#endif + +uint16_t const os_maxtaskrun = OS_TASK_CNT; +#ifdef __MBED_CMSIS_RTOS_CM +uint32_t const os_stackinfo = (OS_STKINIT<<28) | (OS_STKCHECK<<24) | (OS_IDLESTKSIZE*4); +#else +uint32_t const os_stackinfo = (OS_STKINIT<<28) | (OS_STKCHECK<<24) | (OS_PRIV_CNT<<16) | (OS_STKSIZE*4); +#endif +uint32_t const os_rrobin = (OS_ROBIN << 16) | OS_ROBINTOUT; +uint32_t const os_tickfreq = OS_CLOCK; +uint16_t const os_tickus_i = OS_CLOCK/1000000; +uint16_t const os_tickus_f = (((uint64_t)(OS_CLOCK-1000000*(OS_CLOCK/1000000)))<<16)/1000000; +uint32_t const os_trv = OS_TRV; +#if defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED) +uint8_t const os_flags = 0; +#else /* defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED) */ +uint8_t const os_flags = OS_RUNPRIV; +#endif /* defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED) */ + +/* Export following defines to uVision debugger. */ +__USED uint32_t const CMSIS_RTOS_API_Version = osCMSIS; +__USED uint32_t const CMSIS_RTOS_RTX_Version = osCMSIS_RTX; +__USED uint32_t const os_clockrate = OS_TICK; +__USED uint32_t const os_timernum = 0U; + +/* Memory pool for TCB allocation */ +_declare_box (mp_tcb, OS_TCB_SIZE, OS_TASK_CNT); +uint16_t const mp_tcb_size = sizeof(mp_tcb); + +#ifdef __MBED_CMSIS_RTOS_CM +/* Memory pool for os_idle_demon stack allocation. */ +_declare_box8 (mp_stk, OS_IDLESTKSIZE*4, 1); +uint32_t const mp_stk_size = sizeof(mp_stk); +#else +/* Memory pool for System stack allocation (+os_idle_demon). */ +_declare_box8 (mp_stk, OS_STKSIZE*4, OS_TASK_CNT-OS_PRIV_CNT+1); +uint32_t const mp_stk_size = sizeof(mp_stk); + +/* Memory pool for user specified stack allocation (+main, +timer) */ +uint64_t os_stack_mem[2+OS_PRIV_CNT+(OS_STACK_SZ/8)]; +uint32_t const os_stack_sz = sizeof(os_stack_mem); +#endif + +#ifndef OS_FIFOSZ + #define OS_FIFOSZ 16 +#endif + +/* Fifo Queue buffer for ISR requests.*/ +uint32_t os_fifo[OS_FIFOSZ*2+1]; +uint8_t const os_fifo_size = OS_FIFOSZ; + +/* An array of Active task pointers. */ +void *os_active_TCB[OS_TASK_CNT]; + +/* User Timers Resources */ +#if (OS_TIMERS != 0) +extern void osTimerThread (void const *argument); +#ifdef __MBED_CMSIS_RTOS_CM +osThreadDef(osTimerThread, (osPriority)(OS_TIMERPRIO-3), 4*OS_TIMERSTKSZ); +#else +osThreadDef(osTimerThread, (osPriority)(OS_TIMERPRIO-3), 1, 4*OS_TIMERSTKSZ); +#endif +osThreadId osThreadId_osTimerThread; +osMessageQDef(osTimerMessageQ, OS_TIMERCBQS, void *); +osMessageQId osMessageQId_osTimerMessageQ; +#else +osThreadDef_t os_thread_def_osTimerThread = { NULL }; +osThreadId osThreadId_osTimerThread; +osMessageQDef(osTimerMessageQ, 0U, void *); +osMessageQId osMessageQId_osTimerMessageQ; +#endif + +/* Legacy RTX User Timers not used */ +uint32_t os_tmr = 0U; +uint32_t const *m_tmr = NULL; +uint16_t const mp_tmr_size = 0U; + +/* singleton mutex */ +osMutexId singleton_mutex_id; +osMutexDef(singleton_mutex); + +#if defined (__CC_ARM) && !defined (__MICROLIB) + /* A memory space for arm standard library. */ + static uint32_t std_libspace[OS_TASK_CNT][96/4]; + static OS_MUT std_libmutex[OS_MUTEXCNT]; + static uint32_t nr_mutex; + extern void *__libspace_start; +#endif + +#if defined (__ICCARM__) +static osMutexId std_mutex_id_sys[_MAX_LOCK] = {0}; +static OS_MUT std_mutex_sys[_MAX_LOCK] = {0}; +#define _FOPEN_MAX 10 +static osMutexId std_mutex_id_file[_FOPEN_MAX] = {0}; +static OS_MUT std_mutex_file[_FOPEN_MAX] = {0}; +void __iar_system_Mtxinit(__iar_Rmtx *mutex) /* Initialize a system lock */ +{ + osMutexDef_t def; + uint32_t index; + for (index = 0; index < _MAX_LOCK; index++) { + if (0 == std_mutex_id_sys[index]) { + def.mutex = &std_mutex_sys[index]; + std_mutex_id_sys[index] = osMutexCreate(&def); + *mutex = (__iar_Rmtx*)&std_mutex_id_sys[index]; + return; + } + } + // This should never happen + error("Not enough mutexes\n"); +} + +void __iar_system_Mtxdst(__iar_Rmtx *mutex)/*Destroy a system lock */ +{ + osMutexDelete(*(osMutexId*)*mutex); + *mutex = 0; +} + +void __iar_system_Mtxlock(__iar_Rmtx *mutex) /* Lock a system lock */ +{ + osMutexWait(*(osMutexId*)*mutex, osWaitForever); +} + +void __iar_system_Mtxunlock(__iar_Rmtx *mutex) /* Unlock a system lock */ +{ + osMutexRelease(*(osMutexId*)*mutex); +} + +void __iar_file_Mtxinit(__iar_Rmtx *mutex)/*Initialize a file lock */ +{ + osMutexDef_t def; + uint32_t index; + for (index = 0; index < _FOPEN_MAX; index++) { + if (0 == std_mutex_id_file[index]) { + def.mutex = &std_mutex_file[index]; + std_mutex_id_file[index] = osMutexCreate(&def); + *mutex = (__iar_Rmtx*)&std_mutex_id_file[index]; + return; + } + } + // The variable _FOPEN_MAX needs to be increased + error("Not enough mutexes\n"); +} + +void __iar_file_Mtxdst(__iar_Rmtx *mutex) /* Destroy a file lock */ +{ + osMutexDelete(*(osMutexId*)*mutex); + *mutex = 0; +} + +void __iar_file_Mtxlock(__iar_Rmtx *mutex) /* Lock a file lock */ +{ + osMutexWait(*(osMutexId*)*mutex, osWaitForever); +} + +void __iar_file_Mtxunlock(__iar_Rmtx *mutex) /* Unlock a file lock */ +{ + osMutexRelease(*(osMutexId*)*mutex); +} + +#endif + +/*---------------------------------------------------------------------------- + * RTX Optimizations (empty functions) + *---------------------------------------------------------------------------*/ + +#if OS_ROBIN == 0 + void rt_init_robin (void) {;} + void rt_chk_robin (void) {;} +#endif + +#if OS_STKCHECK == 0 + void rt_stk_check (void) {;} +#endif + + +/*---------------------------------------------------------------------------- + * Standard Library multithreading interface + *---------------------------------------------------------------------------*/ + +#if defined (__CC_ARM) && !defined (__MICROLIB) + +/*--------------------------- __user_perthread_libspace ---------------------*/ + +void *__user_perthread_libspace (void) { + /* Provide a separate libspace for each task. */ + uint32_t idx; + + idx = (os_running != 0U) ? runtask_id () : 0U; + if (idx == 0U) { + /* RTX not running yet. */ + return (&__libspace_start); + } + return ((void *)&std_libspace[idx-1]); +} + +/*--------------------------- _mutex_initialize -----------------------------*/ + +int _mutex_initialize (OS_ID *mutex) { + /* Allocate and initialize a system mutex. */ + + if (nr_mutex >= OS_MUTEXCNT) { + /* If you are here, you need to increase the number OS_MUTEXCNT. */ + error("Not enough stdlib mutexes\n"); + } + *mutex = &std_libmutex[nr_mutex++]; + mutex_init (*mutex); + return (1); +} + + +/*--------------------------- _mutex_acquire --------------------------------*/ + +__attribute__((used)) void _mutex_acquire (OS_ID *mutex) { + /* Acquire a system mutex, lock stdlib resources. */ + if (os_running) { + /* RTX running, acquire a mutex. */ + mutex_wait (*mutex); + } +} + + +/*--------------------------- _mutex_release --------------------------------*/ + +__attribute__((used)) void _mutex_release (OS_ID *mutex) { + /* Release a system mutex, unlock stdlib resources. */ + if (os_running) { + /* RTX running, release a mutex. */ + mutex_rel (*mutex); + } +} + +#endif + + +/*---------------------------------------------------------------------------- + * RTX Startup + *---------------------------------------------------------------------------*/ + +/* Main Thread definition */ +extern void pre_main (void); +osThreadDef_t os_thread_def_main = {(os_pthread)pre_main, osPriorityNormal, 1U, 0U, NULL}; + +#ifdef __CC_ARM +#if defined(TARGET_NUMAKER_PFM_NUC472) +extern uint32_t Image$$ARM_LIB_HEAP$$Base[]; +#define HEAP_START ((uint32_t) Image$$ARM_LIB_HEAP$$Base) +#else +extern uint32_t Image$$RW_IRAM1$$ZI$$Limit[]; +#define HEAP_START (Image$$RW_IRAM1$$ZI$$Limit) +#endif +#elif defined(__GNUC__) +extern uint32_t __end__[]; +#define HEAP_START (__end__) +#elif defined(__ICCARM__) +#pragma section="HEAP" +#define HEAP_END (void *)__section_end("HEAP") +#endif + +void set_main_stack(void) { +#if defined(TARGET_NUMAKER_PFM_NUC472) + // Scheduler stack: OS_MAINSTKSIZE words + // Main thread stack: Reserved stack size - OS_MAINSTKSIZE words + os_thread_def_main.stack_pointer = (uint32_t *) FINAL_SP; + os_thread_def_main.stacksize = (uint32_t) INITIAL_SP - (uint32_t) FINAL_SP - OS_MAINSTKSIZE * 4; +#else +#if defined(__ICCARM__) + /* For IAR heap is defined .icf file */ + uint32_t main_stack_size = ((uint32_t)INITIAL_SP - (uint32_t)HEAP_END) - interrupt_stack_size; +#else + /* For ARM , uARM, or GCC_ARM , heap can grow and reach main stack */ +#endif + // That is the bottom of the main stack block: no collision detection + os_thread_def_main.stack_pointer = HEAP_START; + + // Leave OS_MAINSTKSIZE words for the scheduler and interrupts + os_thread_def_main.stacksize = (INITIAL_SP - (unsigned int)HEAP_START) - (OS_MAINSTKSIZE * 4); +#endif +} + +#if defined (__CC_ARM) + +#ifdef __MICROLIB + +int main(void); +void _main_init (void) __attribute__((section(".ARM.Collect$$$$000000FF"))); +void $Super$$__cpp_initialize__aeabi_(void); + +void _main_init (void) { + osKernelInitialize(); +#ifdef __MBED_CMSIS_RTOS_CM + set_main_stack(); +#endif + osThreadCreate(&os_thread_def_main, NULL); + osKernelStart(); + for (;;); +} + +void $Sub$$__cpp_initialize__aeabi_(void) +{ + // this should invoke C++ initializers prior _main_init, we keep this empty and + // invoke them after _main_init (=starts RTX kernel) +} + +void pre_main() +{ + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + $Super$$__cpp_initialize__aeabi_(); + main(); +} + +#else + +void * armcc_heap_base; +void * armcc_heap_top; + +int main(void); + +void pre_main (void) +{ + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + __rt_lib_init((unsigned)armcc_heap_base, (unsigned)armcc_heap_top); + main(); +} + +/* The single memory model is checking for stack collision at run time, verifing + that the heap pointer is underneath the stack pointer. + + With the RTOS there is not only one stack above the heap, there are multiple + stacks and some of them are underneath the heap pointer. +*/ +#pragma import(__use_two_region_memory) + +__asm void __rt_entry (void) { + + IMPORT __user_setup_stackheap + IMPORT armcc_heap_base + IMPORT armcc_heap_top + IMPORT _platform_post_stackheap_init + IMPORT os_thread_def_main + IMPORT osKernelInitialize +#ifdef __MBED_CMSIS_RTOS_CM + IMPORT set_main_stack +#endif + IMPORT osKernelStart + IMPORT osThreadCreate + + /* __user_setup_stackheap returns: + * - Heap base in r0 (if the program uses the heap). + * - Stack base in sp. + * - Heap limit in r2 (if the program uses the heap and uses two-region memory). + * + * More info can be found in: + * ARM Compiler ARM C and C++ Libraries and Floating-Point Support User Guide + */ + BL __user_setup_stackheap + LDR R3,=armcc_heap_base + LDR R4,=armcc_heap_top + STR R0,[R3] + STR R2,[R4] + BL _platform_post_stackheap_init + BL osKernelInitialize +#ifdef __MBED_CMSIS_RTOS_CM + BL set_main_stack +#endif + LDR R0,=os_thread_def_main + MOVS R1,#0 + BL osThreadCreate + BL osKernelStart + /* osKernelStart should not return */ + B . + + ALIGN +} + +#endif + +#elif defined (__GNUC__) + +osMutexDef(malloc_mutex); +static osMutexId malloc_mutex_id; +osMutexDef(env_mutex); +static osMutexId env_mutex_id; + +extern int atexit(void (*func)(void)); +extern void __libc_fini_array(void); +extern void __libc_init_array (void); +extern int main(int argc, char **argv); + +void pre_main(void) { + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + malloc_mutex_id = osMutexCreate(osMutex(malloc_mutex)); + env_mutex_id = osMutexCreate(osMutex(env_mutex)); + __libc_init_array(); + main(0, NULL); +} + +__attribute__((naked)) void software_init_hook_rtos (void) { + __asm ( + "bl osKernelInitialize\n" +#ifdef __MBED_CMSIS_RTOS_CM + "bl set_main_stack\n" +#endif + "ldr r0,=os_thread_def_main\n" + "movs r1,#0\n" + "bl osThreadCreate\n" + "bl osKernelStart\n" + /* osKernelStart should not return */ + "B .\n" + ); +} + +// Opaque declaration of _reent structure +struct _reent; + +void __rtos_malloc_lock( struct _reent *_r ) +{ + osMutexWait(malloc_mutex_id, osWaitForever); +} + +void __rtos_malloc_unlock( struct _reent *_r ) +{ + osMutexRelease(malloc_mutex_id); +} + +void __rtos_env_lock( struct _reent *_r ) +{ + osMutexWait(env_mutex_id, osWaitForever); +} + +void __rtos_env_unlock( struct _reent *_r ) +{ + osMutexRelease(env_mutex_id); +} + +#elif defined (__ICCARM__) + +extern void* __vector_table; +extern int __low_level_init(void); +extern void __iar_data_init3(void); +extern __weak void __iar_init_core( void ); +extern __weak void __iar_init_vfp( void ); +extern void __iar_dynamic_initialization(void); +extern void mbed_sdk_init(void); +extern void mbed_main(void); +extern int main(void); +extern void exit(int arg); + +static uint8_t low_level_init_needed; + +void pre_main(void) { + singleton_mutex_id = osMutexCreate(osMutex(singleton_mutex)); + if (low_level_init_needed) { + __iar_dynamic_initialization(); + } + mbed_main(); + main(); +} + +#pragma required=__vector_table +void __iar_program_start( void ) +{ +#ifdef __MBED_CMSIS_RTOS_CM + __iar_init_core(); + __iar_init_vfp(); + + uint8_t low_level_init_needed_local; + + low_level_init_needed_local = __low_level_init(); + if (low_level_init_needed_local) { + __iar_data_init3(); + mbed_sdk_init(); + } + /* Store in a global variable after RAM has been initialized */ + low_level_init_needed = low_level_init_needed_local; +#endif + osKernelInitialize(); +#ifdef __MBED_CMSIS_RTOS_CM + set_main_stack(); +#endif + osThreadCreate(&os_thread_def_main, NULL); + osKernelStart(); + /* osKernelStart should not return */ + while (1); +} + +#endif + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/RTX_Conf_CM.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,281 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RTX_Conf_CM.C + * Purpose: Configuration of CMSIS RTX Kernel for Cortex-M + * Rev.: V4.70.1 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "cmsis_os.h" + + +/*---------------------------------------------------------------------------- + * RTX User configuration part BEGIN + *---------------------------------------------------------------------------*/ + +// Include per-target RTX config file +#include "mbed_rtx4.h" + +//-------- <<< Use Configuration Wizard in Context Menu >>> ----------------- +// +// <h>Thread Configuration +// ======================= +// +// <o>Number of concurrent running user threads <1-250> +// <i> Defines max. number of user threads that will run at the same time. +// <i> Default: 6 +#ifndef OS_TASKCNT + #error "no target defined" +#endif + +#ifdef __MBED_CMSIS_RTOS_CM +// <o>Idle stack size [bytes] <64-4096:8><#/4> +// <i> Defines default stack size for the Idle thread. +#ifndef OS_IDLESTKSIZE + #define OS_IDLESTKSIZE 128 +#endif +#else // __MBED_CMSIS_RTOS_CM +// <o>Default Thread stack size [bytes] <64-4096:8><#/4> +// <i> Defines default stack size for threads with osThreadDef stacksz = 0 +// <i> Default: 200 +#ifndef OS_STKSIZE + #define OS_STKSIZE 200 +#endif +#endif // __MBED_CMSIS_RTOS_CM + +// <o>Main Thread stack size [bytes] <64-32768:8><#/4> +#ifndef OS_MAINSTKSIZE + #error "no target defined" +#endif + +#ifndef __MBED_CMSIS_RTOS_CM +// <o>Number of threads with user-provided stack size <0-250> +// <i> Defines the number of threads with user-provided stack size. +// <i> Default: 0 +#ifndef OS_PRIVCNT + #define OS_PRIVCNT 0 +#endif + +// <o>Total stack size [bytes] for threads with user-provided stack size <0-1048576:8><#/4> +// <i> Defines the combined stack size for threads with user-provided stack size. +// <i> Default: 0 +#ifndef OS_PRIVSTKSIZE + #define OS_PRIVSTKSIZE 0 // this stack size value is in words +#endif +#endif // __MBED_CMSIS_RTOS_CM + +// <q>Stack overflow checking +// <i> Enable stack overflow checks at thread switch. +// <i> Enabling this option increases slightly the execution time of a thread switch. +#ifndef OS_STKCHECK + #define OS_STKCHECK 1 +#endif + +// <q>Stack usage watermark +// <i> Initialize thread stack with watermark pattern for analyzing stack usage (current/maximum) in System and Thread Viewer. +// <i> Enabling this option increases significantly the execution time of osThreadCreate. +#ifndef OS_STKINIT + #if (defined(MBED_STACK_STATS_ENABLED) && MBED_STACK_STATS_ENABLED) + #define OS_STKINIT 1 + #else + #define OS_STKINIT 0 + #endif +#endif + +// <o>Processor mode for thread execution +// <0=> Unprivileged mode +// <1=> Privileged mode +// <i> Default: Privileged mode +#ifndef OS_RUNPRIV + #define OS_RUNPRIV 1 +#endif + +// </h> + +// <h>RTX Kernel Timer Tick Configuration +// ====================================== +// <q> Use Cortex-M SysTick timer as RTX Kernel Timer +// <i> Cortex-M processors provide in most cases a SysTick timer that can be used as +// <i> as time-base for RTX. +#ifndef OS_SYSTICK + #define OS_SYSTICK 1 +#endif +// +// <o>RTOS Kernel Timer input clock frequency [Hz] <1-1000000000> +// <i> Defines the input frequency of the RTOS Kernel Timer. +// <i> When the Cortex-M SysTick timer is used, the input clock +// <i> is on most systems identical with the core clock. +#ifndef OS_CLOCK + #error "no target defined" +#endif + +// <o>RTX Timer tick interval value [us] <1-1000000> +// <i> The RTX Timer tick interval value is used to calculate timeout values. +// <i> When the Cortex-M SysTick timer is enabled, the value also configures the SysTick timer. +// <i> Default: 1000 (1ms) +#ifndef OS_TICK + #define OS_TICK 1000 +#endif + +// </h> + +// <h>System Configuration +// ======================= +// +// <e>Round-Robin Thread switching +// =============================== +// +// <i> Enables Round-Robin Thread switching. +#ifndef OS_ROBIN + #define OS_ROBIN 1 +#endif + +// <o>Round-Robin Timeout [ticks] <1-1000> +// <i> Defines how long a thread will execute before a thread switch. +// <i> Default: 5 +#ifndef OS_ROBINTOUT + #define OS_ROBINTOUT 5 +#endif + +// </e> + +// <e>User Timers +// ============== +// <i> Enables user Timers +#ifndef OS_TIMERS + #define OS_TIMERS 1 +#endif + +// <o>Timer Thread Priority +// <1=> Low +// <2=> Below Normal <3=> Normal <4=> Above Normal +// <5=> High +// <6=> Realtime (highest) +// <i> Defines priority for Timer Thread +// <i> Default: High +#ifndef OS_TIMERPRIO + #define OS_TIMERPRIO 5 +#endif + +// <o>Timer Thread stack size [bytes] <64-4096:8><#/4> +// <i> Defines stack size for Timer thread. +// <i> Default: 200 +#ifndef OS_TIMERSTKSZ + #define OS_TIMERSTKSZ 200 +#endif + +// <o>Timer Callback Queue size <1-32> +// <i> Number of concurrent active timer callback functions. +// <i> Default: 4 +#ifndef OS_TIMERCBQS + #define OS_TIMERCBQS 4 +#endif + +// </e> + +// <o>ISR FIFO Queue size<4=> 4 entries <8=> 8 entries +// <12=> 12 entries <16=> 16 entries +// <24=> 24 entries <32=> 32 entries +// <48=> 48 entries <64=> 64 entries +// <96=> 96 entries +// <i> ISR functions store requests to this buffer, +// <i> when they are called from the interrupt handler. +// <i> Default: 16 entries +#ifndef OS_FIFOSZ + #define OS_FIFOSZ 16 +#endif + +// </h> + +//------------- <<< end of configuration section >>> ----------------------- + +// Standard library system mutexes +// =============================== +// Define max. number system mutexes that are used to protect +// the arm standard runtime library. For microlib they are not used. +#ifndef OS_MUTEXCNT + #define OS_MUTEXCNT 12 +#endif + +/*---------------------------------------------------------------------------- + * RTX User configuration part END + *---------------------------------------------------------------------------*/ + +#define OS_TRV ((uint32_t)(((double)OS_CLOCK*(double)OS_TICK)/1E6)-1) + + +/*---------------------------------------------------------------------------- + * OS Idle daemon + *---------------------------------------------------------------------------*/ +extern void rtos_idle_loop(void); + +void os_idle_demon (void) { + /* The idle demon is a system thread, running when no other thread is */ + /* ready to run. */ + rtos_idle_loop(); +} + +/*---------------------------------------------------------------------------- + * RTX Errors + *---------------------------------------------------------------------------*/ +extern void error(const char* format, ...); +extern osThreadId svcThreadGetId (void); + +void os_error (uint32_t err_code) { + /* This function is called when a runtime error is detected. Parameter */ + /* 'err_code' holds the runtime error code (defined in RTX_Config.h). */ + osThreadId err_task = svcThreadGetId(); + error("RTX error code: 0x%08X, task ID: 0x%08X\n", err_code, err_task); +} + +void sysThreadError(osStatus status) { + if (status != osOK) { + osThreadId err_task = svcThreadGetId(); + error("CMSIS-RTOS error status: 0x%08X, task ID: 0x%08X\n", status, err_task); + } +} + +/*---------------------------------------------------------------------------- + * RTX Hooks + *---------------------------------------------------------------------------*/ +extern void thread_terminate_hook(osThreadId id); + +void sysThreadTerminate(osThreadId id) { + thread_terminate_hook(id); +} + +/*---------------------------------------------------------------------------- + * RTX Configuration Functions + *---------------------------------------------------------------------------*/ + +#include "RTX_CM_lib.h" + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/RTX_Config.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,84 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RTX_CONFIG.H + * Purpose: Exported functions of RTX_Config.c + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + + +/* Error Codes */ +#define OS_ERR_STK_OVF 1U +#define OS_ERR_FIFO_OVF 2U +#define OS_ERR_MBX_OVF 3U +#define OS_ERR_TIMER_OVF 4U + +/* Definitions */ +#define BOX_ALIGN_8 0x80000000U +#define _declare_box(pool,size,cnt) U32 pool[(((size)+3)/4)*(cnt) + 3] +#define _declare_box8(pool,size,cnt) U64 pool[(((size)+7)/8)*(cnt) + 2] +#define _init_box8(pool,size,bsize) _init_box (pool,size,(bsize) | BOX_ALIGN_8) + +/* Variables */ +extern U32 mp_tcb[]; +extern U64 mp_stk[]; +extern U32 os_fifo[]; +extern void *os_active_TCB[]; + +/* Constants */ +extern U16 const os_maxtaskrun; +extern U32 const os_trv; +extern U8 const os_flags; +extern U32 const os_stackinfo; +extern U32 const os_rrobin; +extern U32 const os_clockrate; +extern U32 const os_timernum; +extern U16 const mp_tcb_size; +extern U32 const mp_stk_size; +extern U32 const *m_tmr; +extern U16 const mp_tmr_size; +extern U8 const os_fifo_size; + +/* Functions */ +extern void os_idle_demon (void); +extern S32 os_tick_init (void); +extern U32 os_tick_val (void); +extern U32 os_tick_ovf (void); +extern void os_tick_irqack (void); +extern void os_tmr_call (U16 info); +extern void os_error (U32 err_code); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0/TOOLCHAIN_ARM/HAL_CM0.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,301 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM0.C + * Purpose: Hardware Abstraction Layer for Cortex-M0 + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_HAL_CM.h" +#include "rt_Task.h" +#include "rt_MemBox.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +__asm void rt_set_PSP (U32 stack) { + MSR PSP,R0 + BX LR +} + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +__asm U32 rt_get_PSP (void) { + MRS R0,PSP + BX LR +} + + +/*--------------------------- os_set_env ------------------------------------*/ + +__asm void os_set_env (void) { + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + MOV R0,SP ; PSP = MSP + MSR PSP,R0 + LDR R0,=__cpp(&os_flags) + LDRB R0,[R0] + LSLS R0,#31 + BNE PrivilegedE + MOVS R0,#0x03 ; Unprivileged Thread mode, use PSP + MSR CONTROL,R0 + BX LR +PrivilegedE + MOVS R0,#0x02 ; Privileged Thread mode, use PSP + MSR CONTROL,R0 + BX LR + + ALIGN +} + + +/*--------------------------- _alloc_box ------------------------------------*/ + +__asm void *_alloc_box (void *box_mem) { + /* Function wrapper for Unprivileged/Privileged mode. */ + LDR R3,=__cpp(rt_alloc_box) + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedA + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedA + SVC 0 + BX LR +PrivilegedA + BX R12 + + ALIGN +} + + +/*--------------------------- _free_box -------------------------------------*/ + +__asm U32 _free_box (void *box_mem, void *box) { + /* Function wrapper for Unprivileged/Privileged mode. */ + LDR R3,=__cpp(rt_free_box) + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedF + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedF + SVC 0 + BX LR +PrivilegedF + BX R12 + + ALIGN +} + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +__asm void SVC_Handler (void) { + PRESERVE8 + + IMPORT SVC_Count + IMPORT SVC_Table + IMPORT rt_stk_check + + MRS R0,PSP ; Read PSP + LDR R1,[R0,#24] ; Read Saved PC from Stack + SUBS R1,R1,#2 ; Point to SVC Instruction + LDRB R1,[R1] ; Load SVC Number + CMP R1,#0 + BNE SVC_User ; User SVC Number > 0 + + MOV LR,R4 + LDMIA R0,{R0-R3,R4} ; Read R0-R3,R12 from stack + MOV R12,R4 + MOV R4,LR + BLX R12 ; Call SVC Function + + MRS R3,PSP ; Read PSP + STMIA R3!,{R0-R2} ; Store return values + + LDR R3,=__cpp(&os_tsk) + LDMIA R3!,{R1,R2} ; os_tsk.run, os_tsk.new + CMP R1,R2 + BEQ SVC_Exit ; no task switch + + SUBS R3,#8 + CMP R1,#0 ; Runtask deleted? + BEQ SVC_Next + + MRS R0,PSP ; Read PSP + SUBS R0,R0,#32 ; Adjust Start Address + STR R0,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack + STMIA R0!,{R4-R7} ; Save old context (R4-R7) + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} ; Save old context (R8-R11) + + PUSH {R2,R3} + BL rt_stk_check ; Check for Stack overflow + POP {R2,R3} + +SVC_Next + STR R2,[R3] ; os_tsk.run = os_tsk.new + + LDR R0,[R2,#TCB_TSTACK] ; os_tsk.new->tsk_stack + ADDS R0,R0,#16 ; Adjust Start Address + LDMIA R0!,{R4-R7} ; Restore new Context (R8-R11) + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 ; Write PSP + SUBS R0,R0,#32 ; Adjust Start Address + LDMIA R0!,{R4-R7} ; Restore new Context (R4-R7) + +SVC_Exit + MOVS R0,#:NOT:0xFFFFFFFD ; Set EXC_RETURN value + MVNS R0,R0 + BX R0 ; RETI to Thread Mode, use PSP + + /*------------------- User SVC ------------------------------*/ + +SVC_User + PUSH {R4,LR} ; Save Registers + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done ; Overflow + + LDR R4,=SVC_Table-4 + LSLS R1,R1,#2 + LDR R4,[R4,R1] ; Load SVC Function Address + MOV LR,R4 + + LDMIA R0,{R0-R3,R4} ; Read R0-R3,R12 from stack + MOV R12,R4 + BLX LR ; Call SVC Function + + MRS R4,PSP ; Read PSP + STMIA R4!,{R0-R3} ; Function return values +SVC_Done + POP {R4,PC} ; RETI + + ALIGN +} + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +__asm void PendSV_Handler (void) { + PRESERVE8 + + BL __cpp(rt_pop_req) + +Sys_Switch + LDR R3,=__cpp(&os_tsk) + LDMIA R3!,{R1,R2} ; os_tsk.run, os_tsk.new + CMP R1,R2 + BEQ Sys_Exit ; no task switch + + SUBS R3,#8 + + MRS R0,PSP ; Read PSP + SUBS R0,R0,#32 ; Adjust Start Address + STR R0,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack + STMIA R0!,{R4-R7} ; Save old context (R4-R7) + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} ; Save old context (R8-R11) + + PUSH {R2,R3} + BL rt_stk_check ; Check for Stack overflow + POP {R2,R3} + + STR R2,[R3] ; os_tsk.run = os_tsk.new + + LDR R0,[R2,#TCB_TSTACK] ; os_tsk.new->tsk_stack + ADDS R0,R0,#16 ; Adjust Start Address + LDMIA R0!,{R4-R7} ; Restore new Context (R8-R11) + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 ; Write PSP + SUBS R0,R0,#32 ; Adjust Start Address + LDMIA R0!,{R4-R7} ; Restore new Context (R4-R7) + +Sys_Exit + MOVS R0,#:NOT:0xFFFFFFFD ; Set EXC_RETURN value + MVNS R0,R0 + BX R0 ; RETI to Thread Mode, use PSP + + ALIGN +} + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +__asm void SysTick_Handler (void) { + PRESERVE8 + + BL __cpp(rt_systick) + B Sys_Switch + + ALIGN +} + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +__asm void OS_Tick_Handler (void) { + PRESERVE8 + + BL __cpp(os_tick_irqack) + BL __cpp(rt_systick) + B Sys_Switch + + ALIGN +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0/TOOLCHAIN_ARM/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,57 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * 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. +; *---------------------------------------------------------------------------*/ + + + AREA SVC_TABLE, CODE, READONLY + + EXPORT SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + EXPORT SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTL Kernel. +; DCD __SVC_1 ; user SVC function + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0/TOOLCHAIN_GCC/HAL_CM0.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,370 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM0.S + * Purpose: Hardware Abstraction Layer for Cortex-M0 + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + + .file "HAL_CM0.S" + .syntax unified + + .equ TCB_TSTACK, 44 + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + .thumb + + .section ".text" + .align 2 + + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +# void rt_set_PSP (U32 stack); + + .thumb_func + .type rt_set_PSP, %function + .global rt_set_PSP +rt_set_PSP: + .fnstart + .cantunwind + + MSR PSP,R0 + BX LR + + .fnend + .size rt_set_PSP, .-rt_set_PSP + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +# U32 rt_get_PSP (void); + + .thumb_func + .type rt_get_PSP, %function + .global rt_get_PSP +rt_get_PSP: + .fnstart + .cantunwind + + MRS R0,PSP + BX LR + + .fnend + .size rt_get_PSP, .-rt_get_PSP + + +/*--------------------------- os_set_env ------------------------------------*/ + +# void os_set_env (void); + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + + .thumb_func + .type os_set_env, %function + .global os_set_env +os_set_env: + .fnstart + .cantunwind + + MOV R0,SP /* PSP = MSP */ + MSR PSP,R0 + LDR R0,=os_flags + LDRB R0,[R0] + LSLS R0,#31 + BNE PrivilegedE + MOVS R0,#0x03 /* Unprivileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR +PrivilegedE: + MOVS R0,#0x02 /* Privileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR + + .fnend + .size os_set_env, .-os_set_env + + +/*--------------------------- _alloc_box ------------------------------------*/ + +# void *_alloc_box (void *box_mem); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .thumb_func + .type _alloc_box, %function + .global _alloc_box +_alloc_box: + .fnstart + .cantunwind + + LDR R3,=rt_alloc_box + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedA + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedA + SVC 0 + BX LR +PrivilegedA: + BX R12 + + .fnend + .size _alloc_box, .-_alloc_box + + +/*--------------------------- _free_box -------------------------------------*/ + +# U32 _free_box (void *box_mem, void *box); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .thumb_func + .type _free_box, %function + .global _free_box +_free_box: + .fnstart + .cantunwind + + LDR R3,=rt_free_box + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedF + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedF + SVC 0 + BX LR +PrivilegedF: + BX R12 + + .fnend + .size _free_box, .-_free_box + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +# void SVC_Handler (void); + + .thumb_func + .type SVC_Handler, %function + .global SVC_Handler +SVC_Handler: + .fnstart + .cantunwind + + MRS R0,PSP /* Read PSP */ + LDR R1,[R0,#24] /* Read Saved PC from Stack */ + SUBS R1,R1,#2 /* Point to SVC Instruction */ + LDRB R1,[R1] /* Load SVC Number */ + CMP R1,#0 + BNE SVC_User /* User SVC Number > 0 */ + + MOV LR,R4 + LDMIA R0,{R0-R3,R4} /* Read R0-R3,R12 from stack */ + MOV R12,R4 + MOV R4,LR + BLX R12 /* Call SVC Function */ + + MRS R3,PSP /* Read PSP */ + STMIA R3!,{R0-R2} /* Store return values */ + + LDR R3,=os_tsk + LDMIA R3!,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ SVC_Exit /* no task switch */ + + SUBS R3,#8 + CMP R1,#0 /* Runtask deleted? */ + BEQ SVC_Next + + MRS R0,PSP /* Read PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + STR R0,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + STMIA R0!,{R4-R7} /* Save old context (R4-R7) */ + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} /* Save old context (R8-R11) */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + +SVC_Next: + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R0,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + ADDS R0,R0,#16 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R8-R11) */ + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 /* Write PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R4-R7) */ + +SVC_Exit: + MOVS R0,#~0xFFFFFFFD /* Set EXC_RETURN value */ + MVNS R0,R0 + BX R0 /* RETI to Thread Mode, use PSP */ + + /*------------------- User SVC ------------------------------*/ + +SVC_User: + PUSH {R4,LR} /* Save Registers */ + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done /* Overflow */ + + LDR R4,=SVC_Table-4 + LSLS R1,R1,#2 + LDR R4,[R4,R1] /* Load SVC Function Address */ + MOV LR,R4 + + LDMIA R0,{R0-R3,R4} /* Read R0-R3,R12 from stack */ + MOV R12,R4 + BLX LR /* Call SVC Function */ + + MRS R4,PSP /* Read PSP */ + STMIA R4!,{R0-R3} /* Function return values */ +SVC_Done: + POP {R4,PC} /* RETI */ + + .fnend + .size SVC_Handler, .-SVC_Handler + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +# void PendSV_Handler (void); + + .thumb_func + .type PendSV_Handler, %function + .global PendSV_Handler + .global Sys_Switch +PendSV_Handler: + .fnstart + .cantunwind + + BL rt_pop_req + +Sys_Switch: + LDR R3,=os_tsk + LDMIA R3!,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ Sys_Exit /* no task switch */ + + SUBS R3,#8 + + MRS R0,PSP /* Read PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + STR R0,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + STMIA R0!,{R4-R7} /* Save old context (R4-R7) */ + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} /* Save old context (R8-R11) */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R0,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + ADDS R0,R0,#16 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R8-R11) */ + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 /* Write PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R4-R7) */ + +Sys_Exit: + MOVS R0,#~0xFFFFFFFD /* Set EXC_RETURN value */ + MVNS R0,R0 + BX R0 /* RETI to Thread Mode, use PSP */ + + .fnend + .size PendSV_Handler, .-PendSV_Handler + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +# void SysTick_Handler (void); + + .thumb_func + .type SysTick_Handler, %function + .global SysTick_Handler +SysTick_Handler: + .fnstart + .cantunwind + + BL rt_systick + B Sys_Switch + + .fnend + .size SysTick_Handler, .-SysTick_Handler + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +# void OS_Tick_Handler (void); + + .thumb_func + .type OS_Tick_Handler, %function + .global OS_Tick_Handler +OS_Tick_Handler: + .fnstart + .cantunwind + + BL os_tick_irqack + BL rt_systick + B Sys_Switch + + .fnend + .size OS_Tick_Handler, .-OS_Tick_Handler + + + .end + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0/TOOLCHAIN_GCC/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,56 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + .file "SVC_Table.S" + + + .section ".svc_table" + + .global SVC_Table +SVC_Table: +/* Insert user SVC functions here. SVC 0 used by RTL Kernel. */ +# .long __SVC_1 /* user SVC function */ +SVC_End: + + .global SVC_Count +SVC_Count: + .long (SVC_End-SVC_Table)/4 + + + .end + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0/TOOLCHAIN_IAR/HAL_CM0.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,312 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM0.S + * Purpose: Hardware Abstraction Layer for Cortex-M0 + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + + NAME HAL_CM0.S + + #define TCB_TSTACK 44 + + EXTERN os_flags + EXTERN os_tsk + EXTERN rt_alloc_box + EXTERN rt_free_box + EXTERN rt_stk_check + EXTERN rt_pop_req + EXTERN rt_systick + EXTERN os_tick_irqack + EXTERN SVC_Table + EXTERN SVC_Count + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + SECTION .text:CODE:NOROOT(2) + THUMB + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +; void rt_set_PSP (U32 stack); + + PUBLIC rt_set_PSP +rt_set_PSP: + + MSR PSP,R0 + BX LR + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +; U32 rt_get_PSP (void); + + PUBLIC rt_get_PSP +rt_get_PSP: + + MRS R0,PSP + BX LR + + +/*--------------------------- os_set_env ------------------------------------*/ + +; void os_set_env (void); + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + + PUBLIC os_set_env +os_set_env: + + MOV R0,SP /* PSP = MSP */ + MSR PSP,R0 + LDR R0,=os_flags + LDRB R0,[R0] + LSLS R0,#31 + BNE PrivilegedE + MOVS R0,#0x03 /* Unprivileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR +PrivilegedE: + MOVS R0,#0x02 /* Privileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR + + +/*--------------------------- _alloc_box ------------------------------------*/ + +; void *_alloc_box (void *box_mem); + /* Function wrapper for Unprivileged/Privileged mode. */ + + PUBLIC _alloc_box +_alloc_box: + + LDR R3,=rt_alloc_box + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedA + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedA + SVC 0 + BX LR +PrivilegedA: + BX R12 + + +/*--------------------------- _free_box -------------------------------------*/ + +; U32 _free_box (void *box_mem, void *box); + /* Function wrapper for Unprivileged/Privileged mode. */ + + PUBLIC _free_box +_free_box: + + LDR R3,=rt_free_box + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedF + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedF + SVC 0 + BX LR +PrivilegedF: + BX R12 + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +; void SVC_Handler (void); + + PUBLIC SVC_Handler +SVC_Handler: + + MRS R0,PSP /* Read PSP */ + LDR R1,[R0,#24] /* Read Saved PC from Stack */ + SUBS R1,R1,#2 /* Point to SVC Instruction */ + LDRB R1,[R1] /* Load SVC Number */ + CMP R1,#0 + BNE SVC_User /* User SVC Number > 0 */ + + MOV LR,R4 + LDMIA R0,{R0-R3,R4} /* Read R0-R3,R12 from stack */ + MOV R12,R4 + MOV R4,LR + BLX R12 /* Call SVC Function */ + + MRS R3,PSP /* Read PSP */ + STMIA R3!,{R0-R2} /* Store return values */ + + LDR R3,=os_tsk + LDMIA R3!,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ SVC_Exit /* no task switch */ + + SUBS R3,#8 + CMP R1,#0 /* Runtask deleted? */ + BEQ SVC_Next + + MRS R0,PSP /* Read PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + STR R0,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + STMIA R0!,{R4-R7} /* Save old context (R4-R7) */ + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} /* Save old context (R8-R11) */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + +SVC_Next: + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R0,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + ADDS R0,R0,#16 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R8-R11) */ + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 /* Write PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R4-R7) */ + +SVC_Exit: + MOVS R0,#~0xFFFFFFFD /* Set EXC_RETURN value */ + MVNS R0,R0 + BX R0 /* RETI to Thread Mode, use PSP */ + + /*------------------- User SVC ------------------------------*/ + +SVC_User: + PUSH {R4,LR} /* Save Registers */ + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done /* Overflow */ + + LDR R4,=SVC_Table-4 + LSLS R1,R1,#2 + LDR R4,[R4,R1] /* Load SVC Function Address */ + MOV LR,R4 + + LDMIA R0,{R0-R3,R4} /* Read R0-R3,R12 from stack */ + MOV R12,R4 + BLX LR /* Call SVC Function */ + + MRS R4,PSP /* Read PSP */ + STMIA R4!,{R0-R3} /* Function return values */ +SVC_Done: + POP {R4,PC} /* RETI */ + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +; void PendSV_Handler (void); + + PUBLIC PendSV_Handler +PendSV_Handler: + + BL rt_pop_req + +Sys_Switch: + LDR R3,=os_tsk + LDMIA R3!,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ Sys_Exit /* no task switch */ + + SUBS R3,#8 + + MRS R0,PSP /* Read PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + STR R0,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + STMIA R0!,{R4-R7} /* Save old context (R4-R7) */ + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} /* Save old context (R8-R11) */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R0,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + ADDS R0,R0,#16 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R8-R11) */ + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 /* Write PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R4-R7) */ + +Sys_Exit: + MOVS R0,#~0xFFFFFFFD /* Set EXC_RETURN value */ + MVNS R0,R0 + BX R0 /* RETI to Thread Mode, use PSP */ + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +; void SysTick_Handler (void); + + PUBLIC SysTick_Handler +SysTick_Handler: + + BL rt_systick + B Sys_Switch + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +; void OS_Tick_Handler (void); + + PUBLIC OS_Tick_Handler +OS_Tick_Handler: + + BL os_tick_irqack + BL rt_systick + B Sys_Switch + + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0/TOOLCHAIN_IAR/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,58 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + NAME SVC_TABLE + SECTION .text:CONST (2) + + PUBLIC SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + PUBLIC SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTL Kernel. +; DCD __SVC_1 ; user SVC function + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0P/TOOLCHAIN_ARM/HAL_CM0.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,301 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM0.C + * Purpose: Hardware Abstraction Layer for Cortex-M0 + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_HAL_CM.h" +#include "rt_Task.h" +#include "rt_MemBox.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +__asm void rt_set_PSP (U32 stack) { + MSR PSP,R0 + BX LR +} + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +__asm U32 rt_get_PSP (void) { + MRS R0,PSP + BX LR +} + + +/*--------------------------- os_set_env ------------------------------------*/ + +__asm void os_set_env (void) { + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + MOV R0,SP ; PSP = MSP + MSR PSP,R0 + LDR R0,=__cpp(&os_flags) + LDRB R0,[R0] + LSLS R0,#31 + BNE PrivilegedE + MOVS R0,#0x03 ; Unprivileged Thread mode, use PSP + MSR CONTROL,R0 + BX LR +PrivilegedE + MOVS R0,#0x02 ; Privileged Thread mode, use PSP + MSR CONTROL,R0 + BX LR + + ALIGN +} + + +/*--------------------------- _alloc_box ------------------------------------*/ + +__asm void *_alloc_box (void *box_mem) { + /* Function wrapper for Unprivileged/Privileged mode. */ + LDR R3,=__cpp(rt_alloc_box) + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedA + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedA + SVC 0 + BX LR +PrivilegedA + BX R12 + + ALIGN +} + + +/*--------------------------- _free_box -------------------------------------*/ + +__asm U32 _free_box (void *box_mem, void *box) { + /* Function wrapper for Unprivileged/Privileged mode. */ + LDR R3,=__cpp(rt_free_box) + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedF + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedF + SVC 0 + BX LR +PrivilegedF + BX R12 + + ALIGN +} + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +__asm void SVC_Handler (void) { + PRESERVE8 + + IMPORT SVC_Count + IMPORT SVC_Table + IMPORT rt_stk_check + + MRS R0,PSP ; Read PSP + LDR R1,[R0,#24] ; Read Saved PC from Stack + SUBS R1,R1,#2 ; Point to SVC Instruction + LDRB R1,[R1] ; Load SVC Number + CMP R1,#0 + BNE SVC_User ; User SVC Number > 0 + + MOV LR,R4 + LDMIA R0,{R0-R3,R4} ; Read R0-R3,R12 from stack + MOV R12,R4 + MOV R4,LR + BLX R12 ; Call SVC Function + + MRS R3,PSP ; Read PSP + STMIA R3!,{R0-R2} ; Store return values + + LDR R3,=__cpp(&os_tsk) + LDMIA R3!,{R1,R2} ; os_tsk.run, os_tsk.new + CMP R1,R2 + BEQ SVC_Exit ; no task switch + + SUBS R3,#8 + CMP R1,#0 ; Runtask deleted? + BEQ SVC_Next + + MRS R0,PSP ; Read PSP + SUBS R0,R0,#32 ; Adjust Start Address + STR R0,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack + STMIA R0!,{R4-R7} ; Save old context (R4-R7) + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} ; Save old context (R8-R11) + + PUSH {R2,R3} + BL rt_stk_check ; Check for Stack overflow + POP {R2,R3} + +SVC_Next + STR R2,[R3] ; os_tsk.run = os_tsk.new + + LDR R0,[R2,#TCB_TSTACK] ; os_tsk.new->tsk_stack + ADDS R0,R0,#16 ; Adjust Start Address + LDMIA R0!,{R4-R7} ; Restore new Context (R8-R11) + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 ; Write PSP + SUBS R0,R0,#32 ; Adjust Start Address + LDMIA R0!,{R4-R7} ; Restore new Context (R4-R7) + +SVC_Exit + MOVS R0,#:NOT:0xFFFFFFFD ; Set EXC_RETURN value + MVNS R0,R0 + BX R0 ; RETI to Thread Mode, use PSP + + /*------------------- User SVC ------------------------------*/ + +SVC_User + PUSH {R4,LR} ; Save Registers + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done ; Overflow + + LDR R4,=SVC_Table-4 + LSLS R1,R1,#2 + LDR R4,[R4,R1] ; Load SVC Function Address + MOV LR,R4 + + LDMIA R0,{R0-R3,R4} ; Read R0-R3,R12 from stack + MOV R12,R4 + BLX LR ; Call SVC Function + + MRS R4,PSP ; Read PSP + STMIA R4!,{R0-R3} ; Function return values +SVC_Done + POP {R4,PC} ; RETI + + ALIGN +} + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +__asm void PendSV_Handler (void) { + PRESERVE8 + + BL __cpp(rt_pop_req) + +Sys_Switch + LDR R3,=__cpp(&os_tsk) + LDMIA R3!,{R1,R2} ; os_tsk.run, os_tsk.new + CMP R1,R2 + BEQ Sys_Exit ; no task switch + + SUBS R3,#8 + + MRS R0,PSP ; Read PSP + SUBS R0,R0,#32 ; Adjust Start Address + STR R0,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack + STMIA R0!,{R4-R7} ; Save old context (R4-R7) + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} ; Save old context (R8-R11) + + PUSH {R2,R3} + BL rt_stk_check ; Check for Stack overflow + POP {R2,R3} + + STR R2,[R3] ; os_tsk.run = os_tsk.new + + LDR R0,[R2,#TCB_TSTACK] ; os_tsk.new->tsk_stack + ADDS R0,R0,#16 ; Adjust Start Address + LDMIA R0!,{R4-R7} ; Restore new Context (R8-R11) + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 ; Write PSP + SUBS R0,R0,#32 ; Adjust Start Address + LDMIA R0!,{R4-R7} ; Restore new Context (R4-R7) + +Sys_Exit + MOVS R0,#:NOT:0xFFFFFFFD ; Set EXC_RETURN value + MVNS R0,R0 + BX R0 ; RETI to Thread Mode, use PSP + + ALIGN +} + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +__asm void SysTick_Handler (void) { + PRESERVE8 + + BL __cpp(rt_systick) + B Sys_Switch + + ALIGN +} + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +__asm void OS_Tick_Handler (void) { + PRESERVE8 + + BL __cpp(os_tick_irqack) + BL __cpp(rt_systick) + B Sys_Switch + + ALIGN +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0P/TOOLCHAIN_ARM/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,57 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * 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. +; *---------------------------------------------------------------------------*/ + + + AREA SVC_TABLE, CODE, READONLY + + EXPORT SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + EXPORT SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTL Kernel. +; DCD __SVC_1 ; user SVC function + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0P/TOOLCHAIN_GCC/HAL_CM0.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,370 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM0.S + * Purpose: Hardware Abstraction Layer for Cortex-M0 + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + + .file "HAL_CM0.S" + .syntax unified + + .equ TCB_TSTACK, 44 + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + .thumb + + .section ".text" + .align 2 + + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +# void rt_set_PSP (U32 stack); + + .thumb_func + .type rt_set_PSP, %function + .global rt_set_PSP +rt_set_PSP: + .fnstart + .cantunwind + + MSR PSP,R0 + BX LR + + .fnend + .size rt_set_PSP, .-rt_set_PSP + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +# U32 rt_get_PSP (void); + + .thumb_func + .type rt_get_PSP, %function + .global rt_get_PSP +rt_get_PSP: + .fnstart + .cantunwind + + MRS R0,PSP + BX LR + + .fnend + .size rt_get_PSP, .-rt_get_PSP + + +/*--------------------------- os_set_env ------------------------------------*/ + +# void os_set_env (void); + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + + .thumb_func + .type os_set_env, %function + .global os_set_env +os_set_env: + .fnstart + .cantunwind + + MOV R0,SP /* PSP = MSP */ + MSR PSP,R0 + LDR R0,=os_flags + LDRB R0,[R0] + LSLS R0,#31 + BNE PrivilegedE + MOVS R0,#0x03 /* Unprivileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR +PrivilegedE: + MOVS R0,#0x02 /* Privileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR + + .fnend + .size os_set_env, .-os_set_env + + +/*--------------------------- _alloc_box ------------------------------------*/ + +# void *_alloc_box (void *box_mem); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .thumb_func + .type _alloc_box, %function + .global _alloc_box +_alloc_box: + .fnstart + .cantunwind + + LDR R3,=rt_alloc_box + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedA + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedA + SVC 0 + BX LR +PrivilegedA: + BX R12 + + .fnend + .size _alloc_box, .-_alloc_box + + +/*--------------------------- _free_box -------------------------------------*/ + +# U32 _free_box (void *box_mem, void *box); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .thumb_func + .type _free_box, %function + .global _free_box +_free_box: + .fnstart + .cantunwind + + LDR R3,=rt_free_box + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedF + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedF + SVC 0 + BX LR +PrivilegedF: + BX R12 + + .fnend + .size _free_box, .-_free_box + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +# void SVC_Handler (void); + + .thumb_func + .type SVC_Handler, %function + .global SVC_Handler +SVC_Handler: + .fnstart + .cantunwind + + MRS R0,PSP /* Read PSP */ + LDR R1,[R0,#24] /* Read Saved PC from Stack */ + SUBS R1,R1,#2 /* Point to SVC Instruction */ + LDRB R1,[R1] /* Load SVC Number */ + CMP R1,#0 + BNE SVC_User /* User SVC Number > 0 */ + + MOV LR,R4 + LDMIA R0,{R0-R3,R4} /* Read R0-R3,R12 from stack */ + MOV R12,R4 + MOV R4,LR + BLX R12 /* Call SVC Function */ + + MRS R3,PSP /* Read PSP */ + STMIA R3!,{R0-R2} /* Store return values */ + + LDR R3,=os_tsk + LDMIA R3!,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ SVC_Exit /* no task switch */ + + SUBS R3,#8 + CMP R1,#0 /* Runtask deleted? */ + BEQ SVC_Next + + MRS R0,PSP /* Read PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + STR R0,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + STMIA R0!,{R4-R7} /* Save old context (R4-R7) */ + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} /* Save old context (R8-R11) */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + +SVC_Next: + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R0,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + ADDS R0,R0,#16 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R8-R11) */ + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 /* Write PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R4-R7) */ + +SVC_Exit: + MOVS R0,#~0xFFFFFFFD /* Set EXC_RETURN value */ + MVNS R0,R0 + BX R0 /* RETI to Thread Mode, use PSP */ + + /*------------------- User SVC ------------------------------*/ + +SVC_User: + PUSH {R4,LR} /* Save Registers */ + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done /* Overflow */ + + LDR R4,=SVC_Table-4 + LSLS R1,R1,#2 + LDR R4,[R4,R1] /* Load SVC Function Address */ + MOV LR,R4 + + LDMIA R0,{R0-R3,R4} /* Read R0-R3,R12 from stack */ + MOV R12,R4 + BLX LR /* Call SVC Function */ + + MRS R4,PSP /* Read PSP */ + STMIA R4!,{R0-R3} /* Function return values */ +SVC_Done: + POP {R4,PC} /* RETI */ + + .fnend + .size SVC_Handler, .-SVC_Handler + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +# void PendSV_Handler (void); + + .thumb_func + .type PendSV_Handler, %function + .global PendSV_Handler + .global Sys_Switch +PendSV_Handler: + .fnstart + .cantunwind + + BL rt_pop_req + +Sys_Switch: + LDR R3,=os_tsk + LDMIA R3!,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ Sys_Exit /* no task switch */ + + SUBS R3,#8 + + MRS R0,PSP /* Read PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + STR R0,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + STMIA R0!,{R4-R7} /* Save old context (R4-R7) */ + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} /* Save old context (R8-R11) */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R0,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + ADDS R0,R0,#16 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R8-R11) */ + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 /* Write PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R4-R7) */ + +Sys_Exit: + MOVS R0,#~0xFFFFFFFD /* Set EXC_RETURN value */ + MVNS R0,R0 + BX R0 /* RETI to Thread Mode, use PSP */ + + .fnend + .size PendSV_Handler, .-PendSV_Handler + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +# void SysTick_Handler (void); + + .thumb_func + .type SysTick_Handler, %function + .global SysTick_Handler +SysTick_Handler: + .fnstart + .cantunwind + + BL rt_systick + B Sys_Switch + + .fnend + .size SysTick_Handler, .-SysTick_Handler + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +# void OS_Tick_Handler (void); + + .thumb_func + .type OS_Tick_Handler, %function + .global OS_Tick_Handler +OS_Tick_Handler: + .fnstart + .cantunwind + + BL os_tick_irqack + BL rt_systick + B Sys_Switch + + .fnend + .size OS_Tick_Handler, .-OS_Tick_Handler + + + .end + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0P/TOOLCHAIN_GCC/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,56 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + .file "SVC_Table.S" + + + .section ".svc_table" + + .global SVC_Table +SVC_Table: +/* Insert user SVC functions here. SVC 0 used by RTL Kernel. */ +# .long __SVC_1 /* user SVC function */ +SVC_End: + + .global SVC_Count +SVC_Count: + .long (SVC_End-SVC_Table)/4 + + + .end + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0P/TOOLCHAIN_IAR/HAL_CM0.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,312 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM0.S + * Purpose: Hardware Abstraction Layer for Cortex-M0 + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + + NAME HAL_CM0.S + + #define TCB_TSTACK 44 + + EXTERN os_flags + EXTERN os_tsk + EXTERN rt_alloc_box + EXTERN rt_free_box + EXTERN rt_stk_check + EXTERN rt_pop_req + EXTERN rt_systick + EXTERN os_tick_irqack + EXTERN SVC_Table + EXTERN SVC_Count + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + SECTION .text:CODE:NOROOT(2) + THUMB + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +; void rt_set_PSP (U32 stack); + + PUBLIC rt_set_PSP +rt_set_PSP: + + MSR PSP,R0 + BX LR + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +; U32 rt_get_PSP (void); + + PUBLIC rt_get_PSP +rt_get_PSP: + + MRS R0,PSP + BX LR + + +/*--------------------------- os_set_env ------------------------------------*/ + +; void os_set_env (void); + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + + PUBLIC os_set_env +os_set_env: + + MOV R0,SP /* PSP = MSP */ + MSR PSP,R0 + LDR R0,=os_flags + LDRB R0,[R0] + LSLS R0,#31 + BNE PrivilegedE + MOVS R0,#0x03 /* Unprivileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR +PrivilegedE: + MOVS R0,#0x02 /* Privileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR + + +/*--------------------------- _alloc_box ------------------------------------*/ + +; void *_alloc_box (void *box_mem); + /* Function wrapper for Unprivileged/Privileged mode. */ + + PUBLIC _alloc_box +_alloc_box: + + LDR R3,=rt_alloc_box + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedA + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedA + SVC 0 + BX LR +PrivilegedA: + BX R12 + + +/*--------------------------- _free_box -------------------------------------*/ + +; U32 _free_box (void *box_mem, void *box); + /* Function wrapper for Unprivileged/Privileged mode. */ + + PUBLIC _free_box +_free_box: + + LDR R3,=rt_free_box + MOV R12,R3 + MRS R3,IPSR + LSLS R3,#24 + BNE PrivilegedF + MRS R3,CONTROL + LSLS R3,#31 + BEQ PrivilegedF + SVC 0 + BX LR +PrivilegedF: + BX R12 + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +; void SVC_Handler (void); + + PUBLIC SVC_Handler +SVC_Handler: + + MRS R0,PSP /* Read PSP */ + LDR R1,[R0,#24] /* Read Saved PC from Stack */ + SUBS R1,R1,#2 /* Point to SVC Instruction */ + LDRB R1,[R1] /* Load SVC Number */ + CMP R1,#0 + BNE SVC_User /* User SVC Number > 0 */ + + MOV LR,R4 + LDMIA R0,{R0-R3,R4} /* Read R0-R3,R12 from stack */ + MOV R12,R4 + MOV R4,LR + BLX R12 /* Call SVC Function */ + + MRS R3,PSP /* Read PSP */ + STMIA R3!,{R0-R2} /* Store return values */ + + LDR R3,=os_tsk + LDMIA R3!,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ SVC_Exit /* no task switch */ + + SUBS R3,#8 + CMP R1,#0 /* Runtask deleted? */ + BEQ SVC_Next + + MRS R0,PSP /* Read PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + STR R0,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + STMIA R0!,{R4-R7} /* Save old context (R4-R7) */ + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} /* Save old context (R8-R11) */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + +SVC_Next: + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R0,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + ADDS R0,R0,#16 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R8-R11) */ + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 /* Write PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R4-R7) */ + +SVC_Exit: + MOVS R0,#~0xFFFFFFFD /* Set EXC_RETURN value */ + MVNS R0,R0 + BX R0 /* RETI to Thread Mode, use PSP */ + + /*------------------- User SVC ------------------------------*/ + +SVC_User: + PUSH {R4,LR} /* Save Registers */ + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done /* Overflow */ + + LDR R4,=SVC_Table-4 + LSLS R1,R1,#2 + LDR R4,[R4,R1] /* Load SVC Function Address */ + MOV LR,R4 + + LDMIA R0,{R0-R3,R4} /* Read R0-R3,R12 from stack */ + MOV R12,R4 + BLX LR /* Call SVC Function */ + + MRS R4,PSP /* Read PSP */ + STMIA R4!,{R0-R3} /* Function return values */ +SVC_Done: + POP {R4,PC} /* RETI */ + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +; void PendSV_Handler (void); + + PUBLIC PendSV_Handler +PendSV_Handler: + + BL rt_pop_req + +Sys_Switch: + LDR R3,=os_tsk + LDMIA R3!,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ Sys_Exit /* no task switch */ + + SUBS R3,#8 + + MRS R0,PSP /* Read PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + STR R0,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + STMIA R0!,{R4-R7} /* Save old context (R4-R7) */ + MOV R4,R8 + MOV R5,R9 + MOV R6,R10 + MOV R7,R11 + STMIA R0!,{R4-R7} /* Save old context (R8-R11) */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R0,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + ADDS R0,R0,#16 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R8-R11) */ + MOV R8,R4 + MOV R9,R5 + MOV R10,R6 + MOV R11,R7 + MSR PSP,R0 /* Write PSP */ + SUBS R0,R0,#32 /* Adjust Start Address */ + LDMIA R0!,{R4-R7} /* Restore new Context (R4-R7) */ + +Sys_Exit: + MOVS R0,#~0xFFFFFFFD /* Set EXC_RETURN value */ + MVNS R0,R0 + BX R0 /* RETI to Thread Mode, use PSP */ + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +; void SysTick_Handler (void); + + PUBLIC SysTick_Handler +SysTick_Handler: + + BL rt_systick + B Sys_Switch + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +; void OS_Tick_Handler (void); + + PUBLIC OS_Tick_Handler +OS_Tick_Handler: + + BL os_tick_irqack + BL rt_systick + B Sys_Switch + + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M0P/TOOLCHAIN_IAR/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,58 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + NAME SVC_TABLE + SECTION .text:CONST (2) + + PUBLIC SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + PUBLIC SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTL Kernel. +; DCD __SVC_1 ; user SVC function + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M3/TOOLCHAIN_ARM/HAL_CM3.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,274 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM3.C + * Purpose: Hardware Abstraction Layer for Cortex-M3 + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_HAL_CM.h" +#include "rt_Task.h" +#include "rt_MemBox.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +__asm void rt_set_PSP (U32 stack) { + MSR PSP,R0 + BX LR +} + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +__asm U32 rt_get_PSP (void) { + MRS R0,PSP + BX LR +} + + +/*--------------------------- os_set_env ------------------------------------*/ + +__asm void os_set_env (void) { + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + MOV R0,SP ; PSP = MSP + MSR PSP,R0 + LDR R0,=__cpp(&os_flags) + LDRB R0,[R0] + LSLS R0,#31 + MOVNE R0,#0x02 ; Privileged Thread mode, use PSP + MOVEQ R0,#0x03 ; Unprivileged Thread mode, use PSP + MSR CONTROL,R0 + BX LR + + ALIGN +} + + +/*--------------------------- _alloc_box ------------------------------------*/ + +__asm void *_alloc_box (void *box_mem) { + /* Function wrapper for Unprivileged/Privileged mode. */ + LDR R12,=__cpp(rt_alloc_box) + MRS R3,IPSR + LSLS R3,#24 + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + BXEQ R12 + SVC 0 + BX LR + + ALIGN +} + + +/*--------------------------- _free_box -------------------------------------*/ + +__asm U32 _free_box (void *box_mem, void *box) { + /* Function wrapper for Unprivileged/Privileged mode. */ + LDR R12,=__cpp(rt_free_box) + MRS R3,IPSR + LSLS R3,#24 + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + BXEQ R12 + SVC 0 + BX LR + + ALIGN +} + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +__asm void SVC_Handler (void) { + PRESERVE8 + + IMPORT SVC_Count + IMPORT SVC_Table + IMPORT rt_stk_check + +#ifdef IFX_XMC4XXX + EXPORT SVC_Handler_Veneer +SVC_Handler_Veneer +#endif + + MRS R0,PSP ; Read PSP + LDR R1,[R0,#24] ; Read Saved PC from Stack + LDRB R1,[R1,#-2] ; Load SVC Number + CBNZ R1,SVC_User + + LDM R0,{R0-R3,R12} ; Read R0-R3,R12 from stack + BLX R12 ; Call SVC Function + + MRS R12,PSP ; Read PSP + STM R12,{R0-R2} ; Store return values + + LDR R3,=__cpp(&os_tsk) + LDM R3,{R1,R2} ; os_tsk.run, os_tsk.new + CMP R1,R2 + BEQ SVC_Exit ; no task switch + + CBZ R1,SVC_Next ; Runtask deleted? + STMDB R12!,{R4-R11} ; Save Old context + STR R12,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack + + PUSH {R2,R3} + BL rt_stk_check ; Check for Stack overflow + POP {R2,R3} + +SVC_Next + STR R2,[R3] ; os_tsk.run = os_tsk.new + + LDR R12,[R2,#TCB_TSTACK] ; os_tsk.new->tsk_stack + LDMIA R12!,{R4-R11} ; Restore New Context + MSR PSP,R12 ; Write PSP + +SVC_Exit + MVN LR,#:NOT:0xFFFFFFFD ; set EXC_RETURN value +#ifdef IFX_XMC4XXX + PUSH {LR} + POP {PC} +#else + BX LR +#endif + + /*------------------- User SVC ------------------------------*/ + +SVC_User + PUSH {R4,LR} ; Save Registers + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done ; Overflow + + LDR R4,=SVC_Table-4 + LDR R4,[R4,R1,LSL #2] ; Load SVC Function Address + + LDM R0,{R0-R3,R12} ; Read R0-R3,R12 from stack + BLX R4 ; Call SVC Function + + MRS R12,PSP + STM R12,{R0-R3} ; Function return values +SVC_Done + POP {R4,PC} ; RETI + + ALIGN +} + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +__asm void PendSV_Handler (void) { + PRESERVE8 + +#ifdef IFX_XMC4XXX + EXPORT PendSV_Handler_Veneer +PendSV_Handler_Veneer +#endif + + BL __cpp(rt_pop_req) + +Sys_Switch + LDR R3,=__cpp(&os_tsk) + LDM R3,{R1,R2} ; os_tsk.run, os_tsk.new + CMP R1,R2 + BEQ Sys_Exit + + MRS R12,PSP ; Read PSP + STMDB R12!,{R4-R11} ; Save Old context + STR R12,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack + + PUSH {R2,R3} + BL rt_stk_check ; Check for Stack overflow + POP {R2,R3} + + STR R2,[R3] ; os_tsk.run = os_tsk.new + + LDR R12,[R2,#TCB_TSTACK] ; os_tsk.new->tsk_stack + LDMIA R12!,{R4-R11} ; Restore New Context + MSR PSP,R12 ; Write PSP + +Sys_Exit + MVN LR,#:NOT:0xFFFFFFFD ; set EXC_RETURN value +#ifdef IFX_XMC4XXX + PUSH {LR} + POP {PC} +#else + BX LR ; Return to Thread Mode +#endif + + ALIGN +} + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +__asm void SysTick_Handler (void) { + PRESERVE8 + +#ifdef IFX_XMC4XXX + EXPORT SysTick_Handler_Veneer +SysTick_Handler_Veneer +#endif + + BL __cpp(rt_systick) + B Sys_Switch + + ALIGN +} + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +__asm void OS_Tick_Handler (void) { + PRESERVE8 + + BL __cpp(os_tick_irqack) + BL __cpp(rt_systick) + B Sys_Switch + + ALIGN +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M3/TOOLCHAIN_ARM/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,57 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + AREA SVC_TABLE, CODE, READONLY + + EXPORT SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + EXPORT SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTL Kernel. +; DCD __SVC_1 ; user SVC function + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M3/TOOLCHAIN_GCC/HAL_CM3.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,345 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM3.S + * Purpose: Hardware Abstraction Layer for Cortex-M3 + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + + .file "HAL_CM3.S" + .syntax unified + + .equ TCB_TSTACK, 44 + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + .thumb + + .section ".text" + .align 2 + + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +# void rt_set_PSP (U32 stack); + + .thumb_func + .type rt_set_PSP, %function + .global rt_set_PSP +rt_set_PSP: + .fnstart + .cantunwind + + MSR PSP,R0 + BX LR + + .fnend + .size rt_set_PSP, .-rt_set_PSP + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +# U32 rt_get_PSP (void); + + .thumb_func + .type rt_get_PSP, %function + .global rt_get_PSP +rt_get_PSP: + .fnstart + .cantunwind + + MRS R0,PSP + BX LR + + .fnend + .size rt_get_PSP, .-rt_get_PSP + + +/*--------------------------- os_set_env ------------------------------------*/ + +# void os_set_env (void); + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + + .thumb_func + .type os_set_env, %function + .global os_set_env +os_set_env: + .fnstart + .cantunwind + + MOV R0,SP /* PSP = MSP */ + MSR PSP,R0 + LDR R0,=os_flags + LDRB R0,[R0] + LSLS R0,#31 + ITE NE + MOVNE R0,#0x02 /* Privileged Thread mode, use PSP */ + MOVEQ R0,#0x03 /* Unprivileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR + + .fnend + .size os_set_env, .-os_set_env + + +/*--------------------------- _alloc_box ------------------------------------*/ + +# void *_alloc_box (void *box_mem); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .thumb_func + .type _alloc_box, %function + .global _alloc_box +_alloc_box: + .fnstart + .cantunwind + + LDR R12,=rt_alloc_box + MRS R3,IPSR + LSLS R3,#24 + IT NE + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + IT EQ + BXEQ R12 + SVC 0 + BX LR + + .fnend + .size _alloc_box, .-_alloc_box + + +/*--------------------------- _free_box -------------------------------------*/ + +# U32 _free_box (void *box_mem, void *box); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .thumb_func + .type _free_box, %function + .global _free_box +_free_box: + .fnstart + .cantunwind + + LDR R12,=rt_free_box + MRS R3,IPSR + LSLS R3,#24 + IT NE + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + IT EQ + BXEQ R12 + SVC 0 + BX LR + + .fnend + .size _free_box, .-_free_box + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +# void SVC_Handler (void); + + .thumb_func + .type SVC_Handler, %function + .global SVC_Handler +SVC_Handler: + .ifdef IFX_XMC4XXX + .global SVC_Handler_Veneer +SVC_Handler_Veneer: + .endif + .fnstart + .cantunwind + + MRS R0,PSP /* Read PSP */ + LDR R1,[R0,#24] /* Read Saved PC from Stack */ + LDRB R1,[R1,#-2] /* Load SVC Number */ + CBNZ R1,SVC_User + + LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */ + BLX R12 /* Call SVC Function */ + + MRS R12,PSP /* Read PSP */ + STM R12,{R0-R2} /* Store return values */ + + LDR R3,=os_tsk + LDM R3,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ SVC_Exit /* no task switch */ + + CBZ R1,SVC_Next /* Runtask deleted? */ + STMDB R12!,{R4-R11} /* Save Old context */ + STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + +SVC_Next: + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R12,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + LDMIA R12!,{R4-R11} /* Restore New Context */ + MSR PSP,R12 /* Write PSP */ + +SVC_Exit: + MVN LR,#~0xFFFFFFFD /* set EXC_RETURN value */ + .ifdef IFX_XMC4XXX + PUSH {LR} + POP {PC} + .else + BX LR + .endif + + /*------------------- User SVC ------------------------------*/ + +SVC_User: + PUSH {R4,LR} /* Save Registers */ + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done /* Overflow */ + + LDR R4,=SVC_Table-4 + LDR R4,[R4,R1,LSL #2] /* Load SVC Function Address */ + + LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */ + BLX R4 /* Call SVC Function */ + + MRS R12,PSP + STM R12,{R0-R3} /* Function return values */ +SVC_Done: + POP {R4,PC} /* RETI */ + + .fnend + .size SVC_Handler, .-SVC_Handler + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +# void PendSV_Handler (void); + + .thumb_func + .type PendSV_Handler, %function + .global PendSV_Handler + .global Sys_Switch +PendSV_Handler: + .ifdef IFX_XMC4XXX + .global PendSV_Handler_Veneer +PendSV_Handler_Veneer: + .endif + .fnstart + .cantunwind + + BL rt_pop_req + +Sys_Switch: + LDR R3,=os_tsk + LDM R3,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ Sys_Exit + + MRS R12,PSP /* Read PSP */ + STMDB R12!,{R4-R11} /* Save Old context */ + STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R12,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + LDMIA R12!,{R4-R11} /* Restore New Context */ + MSR PSP,R12 /* Write PSP */ + +Sys_Exit: + MVN LR,#~0xFFFFFFFD /* set EXC_RETURN value */ + .ifdef IFX_XMC4XXX + PUSH {LR} + POP {PC} + .else + BX LR /* Return to Thread Mode */ + .endif + + .fnend + .size PendSV_Handler, .-PendSV_Handler + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +# void SysTick_Handler (void); + + .thumb_func + .type SysTick_Handler, %function + .global SysTick_Handler +SysTick_Handler: + .ifdef IFX_XMC4XXX + .global SysTick_Handler_Veneer +SysTick_Handler_Veneer: + .endif + .fnstart + .cantunwind + + BL rt_systick + B Sys_Switch + + .fnend + .size SysTick_Handler, .-SysTick_Handler + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +# void OS_Tick_Handler (void); + + .thumb_func + .type OS_Tick_Handler, %function + .global OS_Tick_Handler +OS_Tick_Handler: + .fnstart + .cantunwind + + BL os_tick_irqack + BL rt_systick + B Sys_Switch + + .fnend + .size OS_Tick_Handler, .-OS_Tick_Handler + + + .end + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M3/TOOLCHAIN_GCC/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,56 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + .file "SVC_Table.S" + + + .section ".svc_table" + + .global SVC_Table +SVC_Table: +/* Insert user SVC functions here. SVC 0 used by RTL Kernel. */ +# .long __SVC_1 /* user SVC function */ +SVC_End: + + .global SVC_Count +SVC_Count: + .long (SVC_End-SVC_Table)/4 + + + .end + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M3/TOOLCHAIN_IAR/HAL_CM3.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,265 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM3.S + * Purpose: Hardware Abstraction Layer for Cortex-M3 + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + + NAME HAL_CM3.S + + #define TCB_TSTACK 44 + + EXTERN os_flags + EXTERN os_tsk + EXTERN rt_alloc_box + EXTERN rt_free_box + EXTERN rt_stk_check + EXTERN rt_pop_req + EXTERN rt_systick + EXTERN os_tick_irqack + EXTERN SVC_Table + EXTERN SVC_Count + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + SECTION .text:CODE:NOROOT(2) + THUMB + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +; void rt_set_PSP (U32 stack); + + PUBLIC rt_set_PSP +rt_set_PSP: + + MSR PSP,R0 + BX LR + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +; U32 rt_get_PSP (void); + + PUBLIC rt_get_PSP +rt_get_PSP: + + MRS R0,PSP + BX LR + + +/*--------------------------- os_set_env ------------------------------------*/ + +; void os_set_env (void); + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + + PUBLIC os_set_env +os_set_env: + + MOV R0,SP /* PSP = MSP */ + MSR PSP,R0 + LDR R0,=os_flags + LDRB R0,[R0] + LSLS R0,#31 + ITE NE + MOVNE R0,#0x02 /* Privileged Thread mode, use PSP */ + MOVEQ R0,#0x03 /* Unprivileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR + + +/*--------------------------- _alloc_box ------------------------------------*/ + +; void *_alloc_box (void *box_mem); + /* Function wrapper for Unprivileged/Privileged mode. */ + + PUBLIC _alloc_box +_alloc_box: + + LDR R12,=rt_alloc_box + MRS R3,IPSR + LSLS R3,#24 + IT NE + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + IT EQ + BXEQ R12 + SVC 0 + BX LR + + +/*--------------------------- _free_box -------------------------------------*/ + +; U32 _free_box (void *box_mem, void *box); + /* Function wrapper for Unprivileged/Privileged mode. */ + + PUBLIC _free_box +_free_box: + + LDR R12,=rt_free_box + MRS R3,IPSR + LSLS R3,#24 + IT NE + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + IT EQ + BXEQ R12 + SVC 0 + BX LR + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +; void SVC_Handler (void); + + PUBLIC SVC_Handler +SVC_Handler: + + MRS R0,PSP /* Read PSP */ + LDR R1,[R0,#24] /* Read Saved PC from Stack */ + LDRB R1,[R1,#-2] /* Load SVC Number */ + CBNZ R1,SVC_User + + LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */ + BLX R12 /* Call SVC Function */ + + MRS R12,PSP /* Read PSP */ + STM R12,{R0-R2} /* Store return values */ + + LDR R3,=os_tsk + LDM R3,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ SVC_Exit /* no task switch */ + + CBZ R1,SVC_Next /* Runtask deleted? */ + STMDB R12!,{R4-R11} /* Save Old context */ + STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + +SVC_Next: + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R12,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + LDMIA R12!,{R4-R11} /* Restore New Context */ + MSR PSP,R12 /* Write PSP */ + +SVC_Exit: + MVN LR,#~0xFFFFFFFD /* set EXC_RETURN value */ + BX LR + + /*------------------- User SVC ------------------------------*/ + +SVC_User: + PUSH {R4,LR} /* Save Registers */ + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done /* Overflow */ + + LDR R4,=SVC_Table-4 + LDR R4,[R4,R1,LSL #2] /* Load SVC Function Address */ + + LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */ + BLX R4 /* Call SVC Function */ + + MRS R12,PSP + STM R12,{R0-R3} /* Function return values */ +SVC_Done: + POP {R4,PC} /* RETI */ + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +; void PendSV_Handler (void); + + PUBLIC PendSV_Handler +PendSV_Handler: + + BL rt_pop_req + +Sys_Switch: + LDR R3,=os_tsk + LDM R3,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + BEQ Sys_Exit + + MRS R12,PSP /* Read PSP */ + STMDB R12!,{R4-R11} /* Save Old context */ + STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R12,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + LDMIA R12!,{R4-R11} /* Restore New Context */ + MSR PSP,R12 /* Write PSP */ + +Sys_Exit: + MVN LR,#~0xFFFFFFFD /* set EXC_RETURN value */ + BX LR /* Return to Thread Mode */ + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +; void SysTick_Handler (void); + + PUBLIC SysTick_Handler +SysTick_Handler: + + BL rt_systick + B Sys_Switch + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +; void OS_Tick_Handler (void); + + PUBLIC OS_Tick_Handler +OS_Tick_Handler: + + BL os_tick_irqack + BL rt_systick + B Sys_Switch + + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_M3/TOOLCHAIN_IAR/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,58 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + NAME SVC_TABLE + SECTION .text:CONST (2) + + PUBLIC SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + PUBLIC SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTL Kernel. +; DCD __SVC_1 ; user SVC function + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_RTOS_M4_M7/TOOLCHAIN_ARM/HAL_CM4.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,327 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM4.C + * Purpose: Hardware Abstraction Layer for Cortex-M4 + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_HAL_CM.h" +#include "rt_Task.h" +#include "rt_MemBox.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +__asm void rt_set_PSP (U32 stack) { + MSR PSP,R0 + BX LR +} + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +__asm U32 rt_get_PSP (void) { + MRS R0,PSP + BX LR +} + + +/*--------------------------- os_set_env ------------------------------------*/ + +__asm void os_set_env (void) { + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + MOV R0,SP ; PSP = MSP + MSR PSP,R0 + LDR R0,=__cpp(&os_flags) + LDRB R0,[R0] + LSLS R0,#31 + MOVNE R0,#0x02 ; Privileged Thread mode, use PSP + MOVEQ R0,#0x03 ; Unprivileged Thread mode, use PSP + MSR CONTROL,R0 + BX LR + + ALIGN +} + + +/*--------------------------- _alloc_box ------------------------------------*/ + +__asm void *_alloc_box (void *box_mem) { + /* Function wrapper for Unprivileged/Privileged mode. */ + LDR R12,=__cpp(rt_alloc_box) + MRS R3,IPSR + LSLS R3,#24 + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + BXEQ R12 + SVC 0 + BX LR + + ALIGN +} + + +/*--------------------------- _free_box -------------------------------------*/ + +__asm U32 _free_box (void *box_mem, void *box) { + /* Function wrapper for Unprivileged/Privileged mode. */ + LDR R12,=__cpp(rt_free_box) + MRS R3,IPSR + LSLS R3,#24 + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + BXEQ R12 + SVC 0 + BX LR + + ALIGN +} + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +__asm void SVC_Handler (void) { + PRESERVE8 + + IMPORT SVC_Count + IMPORT SVC_Table + IMPORT rt_stk_check + +#ifdef IFX_XMC4XXX + EXPORT SVC_Handler_Veneer +SVC_Handler_Veneer +#endif + + MRS R0,PSP ; Read PSP + LDR R1,[R0,#24] ; Read Saved PC from Stack + LDRB R1,[R1,#-2] ; Load SVC Number + CBNZ R1,SVC_User + + LDM R0,{R0-R3,R12} ; Read R0-R3,R12 from stack + PUSH {R4,LR} ; Save EXC_RETURN + BLX R12 ; Call SVC Function + POP {R4,LR} ; Restore EXC_RETURN + + MRS R12,PSP ; Read PSP + STM R12,{R0-R2} ; Store return values + + LDR R3,=__cpp(&os_tsk) + LDM R3,{R1,R2} ; os_tsk.run, os_tsk.new + CMP R1,R2 +#ifdef IFX_XMC4XXX + PUSHEQ {LR} + POPEQ {PC} +#else + BXEQ LR ; RETI, no task switch +#endif + + CBNZ R1,SVC_ContextSave ; Runtask not deleted? + + TST LR,#0x10 ; is it extended frame? + BNE SVC_ContextRestore + LDR R1,=0xE000EF34 + LDR R0,[R1] ; Load FPCCR + BIC R0,#1 ; Clear LSPACT (Lazy state) + STR R0,[R1] ; Store FPCCR + B SVC_ContextRestore + +SVC_ContextSave + TST LR,#0x10 ; is it extended frame? +#if (__FPU_PRESENT == 1) + VSTMDBEQ R12!,{S16-S31} ; yes, stack also VFP hi-regs +#endif + MOVEQ R0,#0x01 ; os_tsk->stack_frame val + MOVNE R0,#0x00 + STRB R0,[R1,#TCB_STACKF] ; os_tsk.run->stack_frame = val + STMDB R12!,{R4-R11} ; Save Old context + STR R12,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack + + PUSH {R2,R3} + BL rt_stk_check ; Check for Stack overflow + POP {R2,R3} + +SVC_ContextRestore + STR R2,[R3] ; os_tsk.run = os_tsk.new + + LDR R12,[R2,#TCB_TSTACK] ; os_tsk.new->tsk_stack + LDMIA R12!,{R4-R11} ; Restore New Context + LDRB R0,[R2,#TCB_STACKF] ; Stack Frame + CMP R0,#0 ; Basic/Extended Stack Frame + MVNEQ LR,#:NOT:0xFFFFFFFD ; set EXC_RETURN value + MVNNE LR,#:NOT:0xFFFFFFED +#if (__FPU_PRESENT == 1) + VLDMIANE R12!,{S16-S31} ; restore VFP hi-registers +#endif + MSR PSP,R12 ; Write PSP + +SVC_Exit +#ifdef IFX_XMC4XXX + PUSH {LR} + POP {PC} +#else + BX LR +#endif + + /*------------------- User SVC ------------------------------*/ + +SVC_User + PUSH {R4,LR} ; Save Registers + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done ; Overflow + + LDR R4,=SVC_Table-4 + LDR R4,[R4,R1,LSL #2] ; Load SVC Function Address + + LDM R0,{R0-R3,R12} ; Read R0-R3,R12 from stack + BLX R4 ; Call SVC Function + + MRS R12,PSP + STM R12,{R0-R3} ; Function return values +SVC_Done + POP {R4,PC} ; RETI + + ALIGN +} + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +__asm void PendSV_Handler (void) { + PRESERVE8 + +#ifdef IFX_XMC4XXX + EXPORT PendSV_Handler_Veneer +PendSV_Handler_Veneer +#endif + + PUSH {R4,LR} ; Save EXC_RETURN + BL __cpp(rt_pop_req) + +Sys_Switch + POP {R4,LR} ; Restore EXC_RETURN + + LDR R3,=__cpp(&os_tsk) + LDM R3,{R1,R2} ; os_tsk.run, os_tsk.new + CMP R1,R2 +#ifdef IFX_XMC4XXX + PUSHEQ {LR} + POPEQ {PC} +#else + BXEQ LR ; RETI, no task switch +#endif + + MRS R12,PSP ; Read PSP + TST LR,#0x10 ; is it extended frame? +#if (__FPU_PRESENT == 1) + VSTMDBEQ R12!,{S16-S31} ; yes, stack also VFP hi-regs +#endif + MOVEQ R0,#0x01 ; os_tsk->stack_frame val + MOVNE R0,#0x00 + STRB R0,[R1,#TCB_STACKF] ; os_tsk.run->stack_frame = val + STMDB R12!,{R4-R11} ; Save Old context + STR R12,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack + + PUSH {R2,R3} + BL rt_stk_check ; Check for Stack overflow + POP {R2,R3} + + STR R2,[R3] ; os_tsk.run = os_tsk.new + + LDR R12,[R2,#TCB_TSTACK] ; os_tsk.new->tsk_stack + LDMIA R12!,{R4-R11} ; Restore New Context + LDRB R0,[R2,#TCB_STACKF] ; Stack Frame + CMP R0,#0 ; Basic/Extended Stack Frame + MVNEQ LR,#:NOT:0xFFFFFFFD ; set EXC_RETURN value + MVNNE LR,#:NOT:0xFFFFFFED +#if (__FPU_PRESENT == 1) + VLDMIANE R12!,{S16-S31} ; restore VFP hi-regs +#endif + MSR PSP,R12 ; Write PSP + +Sys_Exit +#ifdef IFX_XMC4XXX + PUSH {LR} + POP {PC} +#else + BX LR ; Return to Thread Mode +#endif + + ALIGN +} + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +__asm void SysTick_Handler (void) { + PRESERVE8 + +#ifdef IFX_XMC4XXX + EXPORT SysTick_Handler_Veneer +SysTick_Handler_Veneer +#endif + + PUSH {R4,LR} ; Save EXC_RETURN + BL __cpp(rt_systick) + B Sys_Switch + + ALIGN +} + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +__asm void OS_Tick_Handler (void) { + PRESERVE8 + + PUSH {R4,LR} ; Save EXC_RETURN + BL __cpp(os_tick_irqack) + BL __cpp(rt_systick) + B Sys_Switch + + ALIGN +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_RTOS_M4_M7/TOOLCHAIN_ARM/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,57 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + AREA SVC_TABLE, CODE, READONLY + + EXPORT SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + EXPORT SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTL Kernel. +; DCD __SVC_1 ; user SVC function + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_RTOS_M4_M7/TOOLCHAIN_GCC/HAL_CM4.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,419 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM4.S + * Purpose: Hardware Abstraction Layer for Cortex-M4 + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + + .file "HAL_CM4.S" + .syntax unified + + .equ TCB_STACKF, 37 + .equ TCB_TSTACK, 44 + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + .thumb + + .section ".text" + .align 2 + + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +# void rt_set_PSP (U32 stack); + + .thumb_func + .type rt_set_PSP, %function + .global rt_set_PSP +rt_set_PSP: + .fnstart + .cantunwind + + MSR PSP,R0 + BX LR + + .fnend + .size rt_set_PSP, .-rt_set_PSP + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +# U32 rt_get_PSP (void); + + .thumb_func + .type rt_get_PSP, %function + .global rt_get_PSP +rt_get_PSP: + .fnstart + .cantunwind + + MRS R0,PSP + BX LR + + .fnend + .size rt_get_PSP, .-rt_get_PSP + + +/*--------------------------- os_set_env ------------------------------------*/ + +# void os_set_env (void); + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + + .thumb_func + .type os_set_env, %function + .global os_set_env +os_set_env: + .fnstart + .cantunwind + + MOV R0,SP /* PSP = MSP */ + MSR PSP,R0 + LDR R0,=os_flags + LDRB R0,[R0] + LSLS R0,#31 + ITE NE + MOVNE R0,#0x02 /* Privileged Thread mode, use PSP */ + MOVEQ R0,#0x03 /* Unprivileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR + + .fnend + .size os_set_env, .-os_set_env + + +/*--------------------------- _alloc_box ------------------------------------*/ + +# void *_alloc_box (void *box_mem); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .thumb_func + .type _alloc_box, %function + .global _alloc_box +_alloc_box: + .fnstart + .cantunwind + + LDR R12,=rt_alloc_box + MRS R3,IPSR + LSLS R3,#24 + IT NE + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + IT EQ + BXEQ R12 + SVC 0 + BX LR + + .fnend + .size _alloc_box, .-_alloc_box + + +/*--------------------------- _free_box -------------------------------------*/ + +# U32 _free_box (void *box_mem, void *box); + /* Function wrapper for Unprivileged/Privileged mode. */ + + .thumb_func + .type _free_box, %function + .global _free_box +_free_box: + .fnstart + .cantunwind + + LDR R12,=rt_free_box + MRS R3,IPSR + LSLS R3,#24 + IT NE + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + IT EQ + BXEQ R12 + SVC 0 + BX LR + + .fnend + .size _free_box, .-_free_box + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +# void SVC_Handler (void); + + .thumb_func + .type SVC_Handler, %function + .global SVC_Handler +SVC_Handler: + .ifdef IFX_XMC4XXX + .global SVC_Handler_Veneer +SVC_Handler_Veneer: + .endif + .fnstart + .cantunwind + + MRS R0,PSP /* Read PSP */ + LDR R1,[R0,#24] /* Read Saved PC from Stack */ + LDRB R1,[R1,#-2] /* Load SVC Number */ + CBNZ R1,SVC_User + + LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */ + PUSH {R4,LR} /* Save EXC_RETURN */ + BLX R12 /* Call SVC Function */ + POP {R4,LR} /* Restore EXC_RETURN */ + + MRS R12,PSP /* Read PSP */ + STM R12,{R0-R2} /* Store return values */ + + LDR R3,=os_tsk + LDM R3,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + .ifdef IFX_XMC4XXX + ITT EQ + PUSHEQ {LR} + POPEQ {PC} + .else + IT EQ + BXEQ LR /* RETI, no task switch */ + .endif + + CBNZ R1,SVC_ContextSave /* Runtask not deleted? */ + + TST LR,#0x10 /* is it extended frame? */ + BNE SVC_ContextRestore + LDR R1,=0xE000EF34 + LDR R0,[R1] /* Load FPCCR */ + BIC R0,#1 /* Clear LSPACT (Lazy state) */ + STR R0,[R1] /* Store FPCCR */ + B SVC_ContextRestore + +SVC_ContextSave: + TST LR,#0x10 /* is it extended frame? */ +#ifdef __FPU_PRESENT + ITTE EQ + VSTMDBEQ R12!,{S16-S31} /* yes, stack also VFP hi-regs */ +#else + ITE EQ +#endif + MOVEQ R0,#0x01 /* os_tsk->stack_frame val */ + MOVNE R0,#0x00 + STRB R0,[R1,#TCB_STACKF] /* os_tsk.run->stack_frame = val */ + STMDB R12!,{R4-R11} /* Save Old context */ + STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + +SVC_ContextRestore: + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R12,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + LDMIA R12!,{R4-R11} /* Restore New Context */ + LDRB R0,[R2,#TCB_STACKF] /* Stack Frame */ + CMP R0,#0 /* Basic/Extended Stack Frame */ +#ifdef __FPU_PRESENT + ITEE EQ +#else + ITE EQ +#endif + MVNEQ LR,#~0xFFFFFFFD /* set EXC_RETURN value */ + MVNNE LR,#~0xFFFFFFED +#ifdef __FPU_PRESENT + VLDMIANE R12!,{S16-S31} /* restore VFP hi-registers */ +#endif + MSR PSP,R12 /* Write PSP */ + +SVC_Exit: + .ifdef IFX_XMC4XXX + PUSH {LR} + POP {PC} + .else + BX LR + .endif + + /*------------------- User SVC ------------------------------*/ + +SVC_User: + PUSH {R4,LR} /* Save Registers */ + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done /* Overflow */ + + LDR R4,=SVC_Table-4 + LDR R4,[R4,R1,LSL #2] /* Load SVC Function Address */ + + LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */ + BLX R4 /* Call SVC Function */ + + MRS R12,PSP + STM R12,{R0-R3} /* Function return values */ +SVC_Done: + POP {R4,PC} /* RETI */ + + .fnend + .size SVC_Handler, .-SVC_Handler + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +# void PendSV_Handler (void); + + .thumb_func + .type PendSV_Handler, %function + .global PendSV_Handler + .global Sys_Switch +PendSV_Handler: + .ifdef IFX_XMC4XXX + .global PendSV_Handler_Veneer +PendSV_Handler_Veneer: + .endif + .fnstart + .cantunwind + + PUSH {R4,LR} /* Save EXC_RETURN */ + BL rt_pop_req + +Sys_Switch: + POP {R4,LR} /* Restore EXC_RETURN */ + + LDR R3,=os_tsk + LDM R3,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 + .ifdef IFX_XMC4XXX + ITT EQ + PUSHEQ {LR} + POPEQ {PC} + .else + IT EQ + BXEQ LR /* RETI, no task switch */ + .endif + + MRS R12,PSP /* Read PSP */ + TST LR,#0x10 /* is it extended frame? */ +#ifdef __FPU_PRESENT + ITTE EQ + VSTMDBEQ R12!,{S16-S31} /* yes, stack also VFP hi-regs */ +#else + ITE EQ +#endif + MOVEQ R0,#0x01 /* os_tsk->stack_frame val */ + MOVNE R0,#0x00 + STRB R0,[R1,#TCB_STACKF] /* os_tsk.run->stack_frame = val */ + STMDB R12!,{R4-R11} /* Save Old context */ + STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R12,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + LDMIA R12!,{R4-R11} /* Restore New Context */ + LDRB R0,[R2,#TCB_STACKF] /* Stack Frame */ + CMP R0,#0 /* Basic/Extended Stack Frame */ +#ifdef __FPU_PRESENT + ITEE EQ +#else + ITE EQ +#endif + MVNEQ LR,#~0xFFFFFFFD /* set EXC_RETURN value */ + MVNNE LR,#~0xFFFFFFED +#ifdef __FPU_PRESENT + VLDMIANE R12!,{S16-S31} /* restore VFP hi-registers */ +#endif + MSR PSP,R12 /* Write PSP */ + +Sys_Exit: + .ifdef IFX_XMC4XXX + PUSH {LR} + POP {PC} + .else + BX LR /* Return to Thread Mode */ + .endif + + .fnend + .size PendSV_Handler, .-PendSV_Handler + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +# void SysTick_Handler (void); + + .thumb_func + .type SysTick_Handler, %function + .global SysTick_Handler +SysTick_Handler: + .ifdef IFX_XMC4XXX + .global SysTick_Handler_Veneer +SysTick_Handler_Veneer: + .endif + .fnstart + .cantunwind + + PUSH {R4,LR} /* Save EXC_RETURN */ + BL rt_systick + B Sys_Switch + + .fnend + .size SysTick_Handler, .-SysTick_Handler + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +# void OS_Tick_Handler (void); + + .thumb_func + .type OS_Tick_Handler, %function + .global OS_Tick_Handler +OS_Tick_Handler: + .fnstart + .cantunwind + + PUSH {R4,LR} /* Save EXC_RETURN */ + BL os_tick_irqack + BL rt_systick + B Sys_Switch + + .fnend + .size OS_Tick_Handler, .-OS_Tick_Handler + + + .end + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_RTOS_M4_M7/TOOLCHAIN_GCC/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,56 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + .file "SVC_Table.S" + + + .section ".svc_table" + + .global SVC_Table +SVC_Table: +/* Insert user SVC functions here. SVC 0 used by RTL Kernel. */ +# .long __SVC_1 /* user SVC function */ +SVC_End: + + .global SVC_Count +SVC_Count: + .long (SVC_End-SVC_Table)/4 + + + .end + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_RTOS_M4_M7/TOOLCHAIN_IAR/HAL_CM4.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,363 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: HAL_CM4.S + * Purpose: Hardware Abstraction Layer for Cortex-M4 + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + + NAME HAL_CM4.S + + #define TCB_STACKF 37 + #define TCB_TSTACK 44 + + EXTERN os_flags + EXTERN os_tsk + EXTERN rt_alloc_box + EXTERN rt_free_box + EXTERN rt_stk_check + EXTERN rt_pop_req + EXTERN rt_systick + EXTERN os_tick_irqack + EXTERN SVC_Table + EXTERN SVC_Count + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + SECTION .text:CODE:NOROOT(2) + THUMB + +/*--------------------------- rt_set_PSP ------------------------------------*/ + +; void rt_set_PSP (U32 stack); + + PUBLIC rt_set_PSP +rt_set_PSP: + + MSR PSP,R0 + BX LR + + +/*--------------------------- rt_get_PSP ------------------------------------*/ + +; U32 rt_get_PSP (void); + + PUBLIC rt_get_PSP +rt_get_PSP: + + MRS R0,PSP + BX LR + + +/*--------------------------- os_set_env ------------------------------------*/ + +; void os_set_env (void); + /* Switch to Unprivileged/Privileged Thread mode, use PSP. */ + + PUBLIC os_set_env +os_set_env: + + MOV R0,SP /* PSP = MSP */ + MSR PSP,R0 + LDR R0,=os_flags + LDRB R0,[R0] + LSLS R0,#31 + ITE NE + MOVNE R0,#0x02 /* Privileged Thread mode, use PSP */ + MOVEQ R0,#0x03 /* Unprivileged Thread mode, use PSP */ + MSR CONTROL,R0 + BX LR + + +/*--------------------------- _alloc_box ------------------------------------*/ + +; void *_alloc_box (void *box_mem); + /* Function wrapper for Unprivileged/Privileged mode. */ + + PUBLIC _alloc_box +_alloc_box: + + LDR R12,=rt_alloc_box + MRS R3,IPSR + LSLS R3,#24 + IT NE + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + IT EQ + BXEQ R12 + SVC 0 + BX LR + + +/*--------------------------- _free_box -------------------------------------*/ + +; U32 _free_box (void *box_mem, void *box); + /* Function wrapper for Unprivileged/Privileged mode. */ + + PUBLIC _free_box +_free_box: + + LDR R12,=rt_free_box + MRS R3,IPSR + LSLS R3,#24 + IT NE + BXNE R12 + MRS R3,CONTROL + LSLS R3,#31 + IT EQ + BXEQ R12 + SVC 0 + BX LR + + +/*-------------------------- SVC_Handler ------------------------------------*/ + +; void SVC_Handler (void); + + PUBLIC SVC_Handler +SVC_Handler: + +#ifdef IFX_XMC4XXX + PUBLIC SVC_Handler_Veneer +SVC_Handler_Veneer: +#endif + + MRS R0,PSP /* Read PSP */ + LDR R1,[R0,#24] /* Read Saved PC from Stack */ + LDRB R1,[R1,#-2] /* Load SVC Number */ + CBNZ R1,SVC_User + + LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */ + PUSH {R4,LR} /* Save EXC_RETURN */ + BLX R12 /* Call SVC Function */ + POP {R4,LR} /* Restore EXC_RETURN */ + + MRS R12,PSP /* Read PSP */ + STM R12,{R0-R2} /* Store return values */ + + LDR R3,=os_tsk + LDM R3,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 +#ifdef IFX_XMC4XXX + ITT EQ + PUSHEQ {LR} + POPEQ {PC} +#else + IT EQ + BXEQ LR /* RETI, no task switch */ +#endif + + CBNZ R1,SVC_ContextSave /* Runtask not deleted? */ + + TST LR,#0x10 /* is it extended frame? */ + BNE SVC_ContextRestore + LDR R1,=0xE000EF34 + LDR R0,[R1] /* Load FPCCR */ + BIC R0,R0,#1 /* Clear LSPACT (Lazy state) */ + STR R0,[R1] /* Store FPCCR */ + B SVC_ContextRestore + +SVC_ContextSave: + TST LR,#0x10 /* is it extended frame? */ +#if (__FPU_PRESENT == 1) + ITTE EQ + VSTMDBEQ R12!,{S16-S31} /* yes, stack also VFP hi-regs */ +#else + ITE EQ +#endif + MOVEQ R0,#0x01 /* os_tsk->stack_frame val */ + MOVNE R0,#0x00 + STRB R0,[R1,#TCB_STACKF] /* os_tsk.run->stack_frame = val */ + STMDB R12!,{R4-R11} /* Save Old context */ + STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + +SVC_ContextRestore: + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R12,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + LDMIA R12!,{R4-R11} /* Restore New Context */ + LDRB R0,[R2,#TCB_STACKF] /* Stack Frame */ + CMP R0,#0 /* Basic/Extended Stack Frame */ +#if (__FPU_PRESENT == 1) + ITEE EQ +#else + ITE EQ +#endif + MVNEQ LR,#~0xFFFFFFFD /* set EXC_RETURN value */ + MVNNE LR,#~0xFFFFFFED +#if (__FPU_PRESENT == 1) + VLDMIANE R12!,{S16-S31} /* restore VFP hi-registers */ +#endif + MSR PSP,R12 /* Write PSP */ + +SVC_Exit: +#ifdef IFX_XMC4XXX + PUSH {LR} + POP {PC} +#else + BX LR +#endif + + /*------------------- User SVC ------------------------------*/ + +SVC_User: + PUSH {R4,LR} /* Save Registers */ + LDR R2,=SVC_Count + LDR R2,[R2] + CMP R1,R2 + BHI SVC_Done /* Overflow */ + + LDR R4,=SVC_Table-4 + LDR R4,[R4,R1,LSL #2] /* Load SVC Function Address */ + + LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */ + BLX R4 /* Call SVC Function */ + + MRS R12,PSP + STM R12,{R0-R3} /* Function return values */ +SVC_Done: + POP {R4,PC} /* RETI */ + + +/*-------------------------- PendSV_Handler ---------------------------------*/ + +; void PendSV_Handler (void); + + PUBLIC PendSV_Handler +PendSV_Handler: + +#ifdef IFX_XMC4XXX + PUBLIC PendSV_Handler_Veneer +PendSV_Handler_Veneer: +#endif + + PUSH {R4,LR} /* Save EXC_RETURN */ + BL rt_pop_req + +Sys_Switch: + POP {R4,LR} /* Restore EXC_RETURN */ + + LDR R3,=os_tsk + LDM R3,{R1,R2} /* os_tsk.run, os_tsk.new */ + CMP R1,R2 +#ifdef IFX_XMC4XXX + ITT EQ + PUSHEQ {LR} + POPEQ {PC} +#else + IT EQ + BXEQ LR /* RETI, no task switch */ +#endif + + MRS R12,PSP /* Read PSP */ + TST LR,#0x10 /* is it extended frame? */ +#if (__FPU_PRESENT == 1) + ITTE EQ + VSTMDBEQ R12!,{S16-S31} /* yes, stack also VFP hi-regs */ +#else + ITE EQ +#endif + MOVEQ R0,#0x01 /* os_tsk->stack_frame val */ + MOVNE R0,#0x00 + STRB R0,[R1,#TCB_STACKF] /* os_tsk.run->stack_frame = val */ + STMDB R12!,{R4-R11} /* Save Old context */ + STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */ + + PUSH {R2,R3} + BL rt_stk_check /* Check for Stack overflow */ + POP {R2,R3} + + STR R2,[R3] /* os_tsk.run = os_tsk.new */ + + LDR R12,[R2,#TCB_TSTACK] /* os_tsk.new->tsk_stack */ + LDMIA R12!,{R4-R11} /* Restore New Context */ + LDRB R0,[R2,#TCB_STACKF] /* Stack Frame */ + CMP R0,#0 /* Basic/Extended Stack Frame */ +#if (__FPU_PRESENT == 1) + ITEE EQ +#else + ITE EQ +#endif + MVNEQ LR,#~0xFFFFFFFD /* set EXC_RETURN value */ + MVNNE LR,#~0xFFFFFFED +#if (__FPU_PRESENT == 1) + VLDMIANE R12!,{S16-S31} /* restore VFP hi-registers */ +#endif + MSR PSP,R12 /* Write PSP */ + +Sys_Exit: +#ifdef IFX_XMC4XXX + PUSH {LR} + POP {PC} +#else + BX LR /* Return to Thread Mode */ +#endif + + +/*-------------------------- SysTick_Handler --------------------------------*/ + +; void SysTick_Handler (void); + + PUBLIC SysTick_Handler +SysTick_Handler: +#ifdef IFX_XMC4XXX + PUBLIC SysTick_Handler_Veneer +SysTick_Handler_Veneer: +#endif + + PUSH {R4,LR} /* Save EXC_RETURN */ + BL rt_systick + B Sys_Switch + + +/*-------------------------- OS_Tick_Handler --------------------------------*/ + +; void OS_Tick_Handler (void); + + PUBLIC OS_Tick_Handler +OS_Tick_Handler: + + PUSH {R4,LR} /* Save EXC_RETURN */ + BL os_tick_irqack + BL rt_systick + B Sys_Switch + + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/TARGET_RTOS_M4_M7/TOOLCHAIN_IAR/SVC_Table.S Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,58 @@ +;/*---------------------------------------------------------------------------- +; * CMSIS-RTOS - RTX +; *---------------------------------------------------------------------------- +; * Name: SVC_TABLE.S +; * Purpose: Pre-defined SVC Table for Cortex-M +; * Rev.: V4.70 +; *---------------------------------------------------------------------------- +; * +; * Copyright (c) 1999-2009 KEIL, 2009-2013 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. +; *---------------------------------------------------------------------------*/ + + + NAME SVC_TABLE + SECTION .text:CONST (2) + + PUBLIC SVC_Count + +SVC_Cnt EQU (SVC_End-SVC_Table)/4 +SVC_Count DCD SVC_Cnt + +; Import user SVC functions here. +; IMPORT __SVC_1 + + PUBLIC SVC_Table +SVC_Table +; Insert user SVC functions here. SVC 0 used by RTL Kernel. +; DCD __SVC_1 ; user SVC function + +SVC_End + + END + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/cmsis_os.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,749 @@ + +/** \addtogroup rtos */ +/** @{*/ +/* ---------------------------------------------------------------------- + * $Date: 5. February 2013 + * $Revision: V1.02 + * + * Project: CMSIS-RTOS API + * Title: cmsis_os.h RTX header file + * + * Version 0.02 + * Initial Proposal Phase + * Version 0.03 + * osKernelStart added, optional feature: main started as thread + * osSemaphores have standard behavior + * osTimerCreate does not start the timer, added osTimerStart + * osThreadPass is renamed to osThreadYield + * Version 1.01 + * Support for C++ interface + * - const attribute removed from the osXxxxDef_t typedef's + * - const attribute added to the osXxxxDef macros + * Added: osTimerDelete, osMutexDelete, osSemaphoreDelete + * Added: osKernelInitialize + * Version 1.02 + * Control functions for short timeouts in microsecond resolution: + * Added: osKernelSysTick, osKernelSysTickFrequency, osKernelSysTickMicroSec + * Removed: osSignalGet + *---------------------------------------------------------------------------- + * + * Copyright (c) 2013 ARM LIMITED + * 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. + *---------------------------------------------------------------------------*/ + + +#ifndef _CMSIS_OS_H +#define _CMSIS_OS_H + +#define CMSIS_OS_RTX + +// __MBED_CMSIS_RTOS_CM captures our changes to the RTX kernel +#ifndef __MBED_CMSIS_RTOS_CM +#define __MBED_CMSIS_RTOS_CM +#endif +// we use __CMSIS_RTOS version, which changes some API in the kernel +#ifndef __CMSIS_RTOS +#define __CMSIS_RTOS +#endif + +// The stack space occupied is mainly dependent on the underling C standard library +#if defined(TOOLCHAIN_GCC) || defined(TOOLCHAIN_ARM_STD) || defined(TOOLCHAIN_IAR) +# define WORDS_STACK_SIZE 512 +#elif defined(TOOLCHAIN_ARM_MICRO) +# define WORDS_STACK_SIZE 128 +#endif + +#ifdef __MBED_CMSIS_RTOS_CM + +/* If os timers macro is set to 0, there's no timer thread created, therefore + * main thread has tid 0x01 + */ +#if defined(OS_TIMERS) && (OS_TIMERS == 0) +#define MAIN_THREAD_ID 0x01 +#else +#define MAIN_THREAD_ID 0x02 +#endif +#endif + +#if defined(TARGET_XDOT_L151CC) +#define DEFAULT_STACK_SIZE (WORDS_STACK_SIZE/2) +#else +#define DEFAULT_STACK_SIZE (WORDS_STACK_SIZE*4) +#endif + +#define osCMSIS 0x10002U ///< CMSIS-RTOS API version (main [31:16] .sub [15:0]) + +#define osCMSIS_RTX ((4<<16)|80) ///< RTOS identification and version (main [31:16] .sub [15:0]) + +#define osKernelSystemId "RTX V4.80" ///< RTOS identification string + + +#define osFeature_MainThread 1 ///< main can be thread +#define osFeature_Pool 1 ///< Memory Pools available +#define osFeature_MailQ 1 ///< Mail Queues available +#define osFeature_MessageQ 1 ///< Message Queues available +#define osFeature_Signals 16 ///< 16 Signal Flags available per thread +#define osFeature_Semaphore 65535 ///< Maximum count for \ref osSemaphoreCreate function +#define osFeature_Wait 0 ///< osWait not available +#define osFeature_SysTick 1 ///< osKernelSysTick functions available +#define osFeature_ThreadEnum 1 ///< Thread enumeration available + +#if defined (__CC_ARM) +#define os_InRegs __value_in_regs // Compiler specific: force struct in registers +#elif defined (__ICCARM__) +#define os_InRegs __value_in_regs // Compiler specific: force struct in registers +#else +#define os_InRegs +#endif + +#include <stdint.h> +#include <stddef.h> + +#ifdef __cplusplus +extern "C" +{ +#endif + +// ==== Enumeration, structures, defines ==== + +/// Priority used for thread control. +typedef enum { + osPriorityIdle = -3, ///< priority: idle (lowest) + osPriorityLow = -2, ///< priority: low + osPriorityBelowNormal = -1, ///< priority: below normal + osPriorityNormal = 0, ///< priority: normal (default) + osPriorityAboveNormal = +1, ///< priority: above normal + osPriorityHigh = +2, ///< priority: high + osPriorityRealtime = +3, ///< priority: realtime (highest) + osPriorityError = 0x84 ///< system cannot determine priority or thread has illegal priority +} osPriority; + +/// Timeout value. +#define osWaitForever 0xFFFFFFFFU ///< wait forever timeout value + +/// Status code values returned by CMSIS-RTOS functions. +typedef enum { + osOK = 0, ///< function completed; no error or event occurred. + osEventSignal = 0x08, ///< function completed; signal event occurred. + osEventMessage = 0x10, ///< function completed; message event occurred. + osEventMail = 0x20, ///< function completed; mail event occurred. + osEventTimeout = 0x40, ///< function completed; timeout occurred. + osErrorParameter = 0x80, ///< parameter error: a mandatory parameter was missing or specified an incorrect object. + osErrorResource = 0x81, ///< resource not available: a specified resource was not available. + osErrorTimeoutResource = 0xC1, ///< resource not available within given time: a specified resource was not available within the timeout period. + osErrorISR = 0x82, ///< not allowed in ISR context: the function cannot be called from interrupt service routines. + osErrorISRRecursive = 0x83, ///< function called multiple times from ISR with same object. + osErrorPriority = 0x84, ///< system cannot determine priority or thread has illegal priority. + osErrorNoMemory = 0x85, ///< system is out of memory: it was impossible to allocate or reserve memory for the operation. + osErrorValue = 0x86, ///< value of a parameter is out of range. + osErrorOS = 0xFF, ///< unspecified RTOS error: run-time error but no other error message fits. + os_status_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization. +} osStatus; + + +/// Timer type value for the timer definition. +typedef enum { + osTimerOnce = 0, ///< one-shot timer + osTimerPeriodic = 1 ///< repeating timer +} os_timer_type; + +typedef enum { + osThreadInfoState, + osThreadInfoStackSize, + osThreadInfoStackMax, + osThreadInfoEntry, + osThreadInfoArg, + + osThreadInfo_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization. +} osThreadInfo; + +/// Entry point of a thread. +typedef void (*os_pthread) (void const *argument); + +/// Entry point of a timer call back function. +typedef void (*os_ptimer) (void const *argument); + +// >>> the following data type definitions may shall adapted towards a specific RTOS + +/// Thread ID identifies the thread (pointer to a thread control block). +typedef struct os_thread_cb *osThreadId; + +/// Timer ID identifies the timer (pointer to a timer control block). +typedef struct os_timer_cb *osTimerId; + +/// Mutex ID identifies the mutex (pointer to a mutex control block). +typedef struct os_mutex_cb *osMutexId; + +/// Semaphore ID identifies the semaphore (pointer to a semaphore control block). +typedef struct os_semaphore_cb *osSemaphoreId; + +/// Pool ID identifies the memory pool (pointer to a memory pool control block). +typedef struct os_pool_cb *osPoolId; + +/// Message ID identifies the message queue (pointer to a message queue control block). +typedef struct os_messageQ_cb *osMessageQId; + +/// Mail ID identifies the mail queue (pointer to a mail queue control block). +typedef struct os_mailQ_cb *osMailQId; + +/// Thread enumeration ID identifies the enumeration (pointer to a thread enumeration control block). +typedef uint32_t *osThreadEnumId; + +/// Thread Definition structure contains startup information of a thread. +typedef struct os_thread_def { + os_pthread pthread; ///< start address of thread function + osPriority tpriority; ///< initial thread priority + uint32_t instances; ///< maximum number of instances of that thread function + uint32_t stacksize; ///< stack size requirements in bytes; 0 is default stack size +#ifdef __MBED_CMSIS_RTOS_CM + uint32_t *stack_pointer; ///< pointer to the stack memory block +#endif +} osThreadDef_t; + +/// Timer Definition structure contains timer parameters. +typedef struct os_timer_def { + os_ptimer ptimer; ///< start address of a timer function + void *timer; ///< pointer to internal data +} osTimerDef_t; + +/// Mutex Definition structure contains setup information for a mutex. +typedef struct os_mutex_def { + void *mutex; ///< pointer to internal data +} osMutexDef_t; + +/// Semaphore Definition structure contains setup information for a semaphore. +typedef struct os_semaphore_def { + void *semaphore; ///< pointer to internal data +} osSemaphoreDef_t; + +/// Definition structure for memory block allocation. +typedef struct os_pool_def { + uint32_t pool_sz; ///< number of items (elements) in the pool + uint32_t item_sz; ///< size of an item + void *pool; ///< pointer to memory for pool +} osPoolDef_t; + +/// Definition structure for message queue. +typedef struct os_messageQ_def { + uint32_t queue_sz; ///< number of elements in the queue + void *pool; ///< memory array for messages +} osMessageQDef_t; + +/// Definition structure for mail queue. +typedef struct os_mailQ_def { + uint32_t queue_sz; ///< number of elements in the queue + uint32_t item_sz; ///< size of an item + void *pool; ///< memory array for mail +} osMailQDef_t; + +/// Event structure contains detailed information about an event. +typedef struct { + osStatus status; ///< status code: event or error information + union { + uint32_t v; ///< message as 32-bit value + void *p; ///< message or mail as void pointer + int32_t signals; ///< signal flags + } value; ///< event value + union { + osMailQId mail_id; ///< mail id obtained by \ref osMailCreate + osMessageQId message_id; ///< message id obtained by \ref osMessageCreate + } def; ///< event definition +} osEvent; + + +// ==== Kernel Control Functions ==== + +/// Initialize the RTOS Kernel for creating objects. +/// \return status code that indicates the execution status of the function. +osStatus osKernelInitialize (void); + +/// Start the RTOS Kernel. +/// \return status code that indicates the execution status of the function. +osStatus osKernelStart (void); + +/// Check if the RTOS kernel is already started. +/// \return 0 RTOS is not started, 1 RTOS is started. +int32_t osKernelRunning(void); + +#if (defined (osFeature_SysTick) && (osFeature_SysTick != 0)) // System Timer available + +/// \cond INTERNAL_VARIABLES +extern uint32_t const os_tickfreq; +extern uint16_t const os_tickus_i; +extern uint16_t const os_tickus_f; +/// \endcond + +/// Get the RTOS kernel system timer counter. +/// \return RTOS kernel system timer as 32-bit value +uint32_t osKernelSysTick (void); + +/// The RTOS kernel system timer frequency in Hz. +/// \note Reflects the system timer setting and is typically defined in a configuration file. +#define osKernelSysTickFrequency os_tickfreq + +/// Convert a microseconds value to a RTOS kernel system timer value. +/// \param microsec time value in microseconds. +/// \return time value normalized to the \ref osKernelSysTickFrequency +/* +#define osKernelSysTickMicroSec(microsec) (((uint64_t)microsec * (osKernelSysTickFrequency)) / 1000000) +*/ +#define osKernelSysTickMicroSec(microsec) ((microsec * os_tickus_i) + ((microsec * os_tickus_f) >> 16)) + +#endif // System Timer available + +// ==== Thread Management ==== + +/// Create a Thread Definition with function, priority, and stack requirements. +/// \param name name of the thread function. +/// \param priority initial priority of the thread function. +/// \param instances number of possible thread instances. +/// \param stacksz stack size (in bytes) requirements for the thread function. +/// macro body is implementation specific in every CMSIS-RTOS. +#if defined (osObjectsExternal) // object is external +#define osThreadDef(name, priority, instances, stacksz) \ +extern const osThreadDef_t os_thread_def_##name +#else // define the object +#ifdef __MBED_CMSIS_RTOS_CM +#define osThreadDef(name, priority, stacksz) \ +uint32_t os_thread_def_stack_##name [stacksz / sizeof(uint32_t)]; \ +const osThreadDef_t os_thread_def_##name = \ +{ (name), (priority), 1, (stacksz), (os_thread_def_stack_##name) } +#else +#define osThreadDef(name, priority, instances, stacksz) \ +const osThreadDef_t os_thread_def_##name = \ +{ (name), (priority), (instances), (stacksz) } +#endif +#endif + +/// Access a Thread definition. +/// \param name name of the thread definition object. +/// macro body is implementation specific in every CMSIS-RTOS. +#define osThread(name) \ +&os_thread_def_##name + +/// Create a thread and add it to Active Threads and set it to state READY. +/// \param[in] thread_def thread definition referenced with \ref osThread. +/// \param[in] argument pointer that is passed to the thread function as start argument. +/// \return thread ID for reference by other functions or NULL in case of error. +osThreadId osThreadCreate (const osThreadDef_t *thread_def, void *argument); + +osThreadId osThreadContextCreate (const osThreadDef_t *thread_def, void *argument, void *context); + +/// Return the thread ID of the current running thread. +/// \return thread ID for reference by other functions or NULL in case of error. +osThreadId osThreadGetId (void); + +/// Terminate execution of a thread and remove it from Active Threads. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return status code that indicates the execution status of the function. +osStatus osThreadTerminate (osThreadId thread_id); + +/// Pass control to next thread that is in state \b READY. +/// \return status code that indicates the execution status of the function. +osStatus osThreadYield (void); + +/// Change priority of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] priority new priority value for the thread function. +/// \return status code that indicates the execution status of the function. +osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority); + +/// Get current priority of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \return current priority value of the thread function. +osPriority osThreadGetPriority (osThreadId thread_id); + +#ifdef __MBED_CMSIS_RTOS_CM +/// Get current thread state. +uint8_t osThreadGetState (osThreadId thread_id); +#endif + +/// Get into from an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] info information to read. +/// \return current state of the thread function. +/// \return requested info that includes the status code. +os_InRegs osEvent _osThreadGetInfo(osThreadId thread_id, osThreadInfo info); + +// ==== Generic Wait Functions ==== + +/// Wait for Timeout (Time Delay). +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue "Time delay" value +/// \return status code that indicates the execution status of the function. +osStatus osDelay (uint32_t millisec); + +#if (defined (osFeature_Wait) && (osFeature_Wait != 0)) // Generic Wait available + +/// Wait for Signal, Message, Mail, or Timeout. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out +/// \return event that contains signal, message, or mail information or error code. +os_InRegs osEvent osWait (uint32_t millisec); + +#endif // Generic Wait available + + +// ==== Timer Management Functions ==== +/// Define a Timer object. +/// \param name name of the timer object. +/// \param function name of the timer call back function. +#if defined (osObjectsExternal) // object is external +#define osTimerDef(name, function) \ +extern const osTimerDef_t os_timer_def_##name +#else // define the object +#define osTimerDef(name, function) \ +uint32_t os_timer_cb_##name[6]; \ +const osTimerDef_t os_timer_def_##name = \ +{ (function), (os_timer_cb_##name) } +#endif + +/// Access a Timer definition. +/// \param name name of the timer object. +#define osTimer(name) \ +&os_timer_def_##name + +/// Create a timer. +/// \param[in] timer_def timer object referenced with \ref osTimer. +/// \param[in] type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior. +/// \param[in] argument argument to the timer call back function. +/// \return timer ID for reference by other functions or NULL in case of error. +osTimerId osTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument); + +/// Start or restart a timer. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue "Time delay" value of the timer. +/// \return status code that indicates the execution status of the function. +osStatus osTimerStart (osTimerId timer_id, uint32_t millisec); + +/// Stop the timer. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \return status code that indicates the execution status of the function. +osStatus osTimerStop (osTimerId timer_id); + +/// Delete a timer that was created by \ref osTimerCreate. +/// \param[in] timer_id timer ID obtained by \ref osTimerCreate. +/// \return status code that indicates the execution status of the function. +osStatus osTimerDelete (osTimerId timer_id); + + +// ==== Signal Management ==== + +/// Set the specified Signal Flags of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] signals specifies the signal flags of the thread that should be set. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. +int32_t osSignalSet (osThreadId thread_id, int32_t signals); + +/// Clear the specified Signal Flags of an active thread. +/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. +/// \param[in] signals specifies the signal flags of the thread that shall be cleared. +/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters or call from ISR. +int32_t osSignalClear (osThreadId thread_id, int32_t signals); + +/// Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread. +/// \param[in] signals wait until all specified signal flags set or 0 for any single signal flag. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out. +/// \return event flag information or error code. +os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec); + + +// ==== Mutex Management ==== + +/// Define a Mutex. +/// \param name name of the mutex object. +#if defined (osObjectsExternal) // object is external +#define osMutexDef(name) \ +extern const osMutexDef_t os_mutex_def_##name +#else // define the object +#define osMutexDef(name) \ +uint32_t os_mutex_cb_##name[4] = { 0 }; \ +const osMutexDef_t os_mutex_def_##name = { (os_mutex_cb_##name) } +#endif + +/// Access a Mutex definition. +/// \param name name of the mutex object. +#define osMutex(name) \ +&os_mutex_def_##name + +/// Create and Initialize a Mutex object. +/// \param[in] mutex_def mutex definition referenced with \ref osMutex. +/// \return mutex ID for reference by other functions or NULL in case of error. +osMutexId osMutexCreate (const osMutexDef_t *mutex_def); + +/// Wait until a Mutex becomes available. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out. +/// \return status code that indicates the execution status of the function. +osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec); + +/// Release a Mutex that was obtained by \ref osMutexWait. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \return status code that indicates the execution status of the function. +osStatus osMutexRelease (osMutexId mutex_id); + +/// Delete a Mutex that was created by \ref osMutexCreate. +/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. +/// \return status code that indicates the execution status of the function. +osStatus osMutexDelete (osMutexId mutex_id); + + +// ==== Semaphore Management Functions ==== + +#if (defined (osFeature_Semaphore) && (osFeature_Semaphore != 0)) // Semaphore available + +/// Define a Semaphore object. +/// \param name name of the semaphore object. +#if defined (osObjectsExternal) // object is external +#define osSemaphoreDef(name) \ +extern const osSemaphoreDef_t os_semaphore_def_##name +#else // define the object +#define osSemaphoreDef(name) \ +uint32_t os_semaphore_cb_##name[2] = { 0 }; \ +const osSemaphoreDef_t os_semaphore_def_##name = { (os_semaphore_cb_##name) } +#endif + +/// Access a Semaphore definition. +/// \param name name of the semaphore object. +#define osSemaphore(name) \ +&os_semaphore_def_##name + +/// Create and Initialize a Semaphore object used for managing resources. +/// \param[in] semaphore_def semaphore definition referenced with \ref osSemaphore. +/// \param[in] count number of available resources. +/// \return semaphore ID for reference by other functions or NULL in case of error. +osSemaphoreId osSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count); + +/// Wait until a Semaphore token becomes available. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out. +/// \return number of available tokens, or -1 in case of incorrect parameters. +int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec); + +/// Release a Semaphore token. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \return status code that indicates the execution status of the function. +osStatus osSemaphoreRelease (osSemaphoreId semaphore_id); + +/// Delete a Semaphore that was created by \ref osSemaphoreCreate. +/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. +/// \return status code that indicates the execution status of the function. +osStatus osSemaphoreDelete (osSemaphoreId semaphore_id); + +#endif // Semaphore available + + +// ==== Memory Pool Management Functions ==== + +#if (defined (osFeature_Pool) && (osFeature_Pool != 0)) // Memory Pool Management available + +/// \brief Define a Memory Pool. +/// \param name name of the memory pool. +/// \param no maximum number of blocks (objects) in the memory pool. +/// \param type data type of a single block (object). +#if defined (osObjectsExternal) // object is external +#define osPoolDef(name, no, type) \ +extern const osPoolDef_t os_pool_def_##name +#else // define the object +#define osPoolDef(name, no, type) \ +uint32_t os_pool_m_##name[3+((sizeof(type)+3)/4)*(no)]; \ +const osPoolDef_t os_pool_def_##name = \ +{ (no), sizeof(type), (os_pool_m_##name) } +#endif + +/// \brief Access a Memory Pool definition. +/// \param name name of the memory pool +#define osPool(name) \ +&os_pool_def_##name + +/// Create and Initialize a memory pool. +/// \param[in] pool_def memory pool definition referenced with \ref osPool. +/// \return memory pool ID for reference by other functions or NULL in case of error. +osPoolId osPoolCreate (const osPoolDef_t *pool_def); + +/// Allocate a memory block from a memory pool. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \return address of the allocated memory block or NULL in case of no memory available. +void *osPoolAlloc (osPoolId pool_id); + +/// Allocate a memory block from a memory pool and set memory block to zero. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \return address of the allocated memory block or NULL in case of no memory available. +void *osPoolCAlloc (osPoolId pool_id); + +/// Return an allocated memory block back to a specific memory pool. +/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. +/// \param[in] block address of the allocated memory block that is returned to the memory pool. +/// \return status code that indicates the execution status of the function. +osStatus osPoolFree (osPoolId pool_id, void *block); + +#endif // Memory Pool Management available + + +// ==== Message Queue Management Functions ==== + +#if (defined (osFeature_MessageQ) && (osFeature_MessageQ != 0)) // Message Queues available + +/// \brief Create a Message Queue Definition. +/// \param name name of the queue. +/// \param queue_sz maximum number of messages in the queue. +/// \param type data type of a single message element (for debugger). +#if defined (osObjectsExternal) // object is external +#define osMessageQDef(name, queue_sz, type) \ +extern const osMessageQDef_t os_messageQ_def_##name +#else // define the object +#define osMessageQDef(name, queue_sz, type) \ +uint32_t os_messageQ_q_##name[4+(queue_sz)] = { 0 }; \ +const osMessageQDef_t os_messageQ_def_##name = \ +{ (queue_sz), (os_messageQ_q_##name) } +#endif + +/// \brief Access a Message Queue Definition. +/// \param name name of the queue +#define osMessageQ(name) \ +&os_messageQ_def_##name + +/// Create and Initialize a Message Queue. +/// \param[in] queue_def queue definition referenced with \ref osMessageQ. +/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. +/// \return message queue ID for reference by other functions or NULL in case of error. +osMessageQId osMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id); + +/// Put a Message to a Queue. +/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. +/// \param[in] info message information. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out. +/// \return status code that indicates the execution status of the function. +osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec); + +/// Get a Message or Wait for a Message from a Queue. +/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out. +/// \return event information that includes status code. +os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec); + +#endif // Message Queues available + + +// ==== Mail Queue Management Functions ==== + +#if (defined (osFeature_MailQ) && (osFeature_MailQ != 0)) // Mail Queues available + +/// \brief Create a Mail Queue Definition. +/// \param name name of the queue +/// \param queue_sz maximum number of messages in queue +/// \param type data type of a single message element +#if defined (osObjectsExternal) // object is external +#define osMailQDef(name, queue_sz, type) \ +extern const osMailQDef_t os_mailQ_def_##name +#else // define the object +#define osMailQDef(name, queue_sz, type) \ +uint32_t os_mailQ_q_##name[4+(queue_sz)] = { 0 }; \ +uint32_t os_mailQ_m_##name[3+((sizeof(type)+3)/4)*(queue_sz)]; \ +void * os_mailQ_p_##name[2] = { (os_mailQ_q_##name), os_mailQ_m_##name }; \ +const osMailQDef_t os_mailQ_def_##name = \ +{ (queue_sz), sizeof(type), (os_mailQ_p_##name) } +#endif + +/// \brief Access a Mail Queue Definition. +/// \param name name of the queue +#define osMailQ(name) \ +&os_mailQ_def_##name + +/// Create and Initialize mail queue. +/// \param[in] queue_def reference to the mail queue definition obtain with \ref osMailQ +/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. +/// \return mail queue ID for reference by other functions or NULL in case of error. +osMailQId osMailCreate (const osMailQDef_t *queue_def, osThreadId thread_id); + +/// Allocate a memory block from a mail. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out +/// \return pointer to memory block that can be filled with mail or NULL in case of error. +void *osMailAlloc (osMailQId queue_id, uint32_t millisec); + +/// Allocate a memory block from a mail and set memory block to zero. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out +/// \return pointer to memory block that can be filled with mail or NULL in case of error. +void *osMailCAlloc (osMailQId queue_id, uint32_t millisec); + +/// Put a mail to a queue. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc. +/// \return status code that indicates the execution status of the function. +osStatus osMailPut (osMailQId queue_id, void *mail); + +/// Get a mail from a queue. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out +/// \return event that contains mail information or error code. +os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec); + +/// Free a memory block from a mail. +/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. +/// \param[in] mail pointer to the memory block that was obtained with \ref osMailGet. +/// \return status code that indicates the execution status of the function. +osStatus osMailFree (osMailQId queue_id, void *mail); + +#endif // Mail Queues available + + +// ==== Thread Enumeration Functions ==== + +#if (defined (osFeature_ThreadEnum) && (osFeature_ThreadEnum != 0)) // Thread enumeration available + +/// Start a thread enumeration. +/// \return an enumeration ID or NULL on error. +osThreadEnumId _osThreadsEnumStart(void); + +/// Get the next task ID in the enumeration. +/// \return a thread ID or NULL on if the end of the enumeration has been reached. +osThreadId _osThreadEnumNext(osThreadEnumId enum_id); + +/// Free the enumeration structure. +/// \param[in] enum_id pointer to the enumeration ID that was obtained with \ref _osThreadsEnumStart. +/// \return status code that indicates the execution status of the function. +osStatus _osThreadEnumFree(osThreadEnumId enum_id); + +#endif // Thread Enumeration available + + +// ==== RTX Extensions ==== + +/// Suspend the RTX task scheduler. +/// \return number of ticks, for how long the system can sleep or power-down. +uint32_t os_suspend (void); + +/// Resume the RTX task scheduler +/// \param[in] sleep_time specifies how long the system was in sleep or power-down mode. +void os_resume (uint32_t sleep_time); + + +#ifdef __cplusplus +} +#endif + +#endif // _CMSIS_OS_H + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_CMSIS.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,2344 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: rt_CMSIS.c + * Purpose: CMSIS RTOS API + * Rev.: V4.80 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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_M7) || defined (__CORTEX_M7F) + #include "core_cm7.h" +#elif defined (__CORTEX_M3) + #include "core_cm3.h" +#elif defined (__CORTEX_M0) + #include "core_cm0.h" +#elif defined (__CORTEX_M0PLUS) + #include "core_cm0plus.h" +#else + #error "Missing __CORTEX_Mx definition" +#endif + +// This affects cmsis_os only, as it's not used anywhere else. This was left by kernel team +// to suppress the warning in rt_tid2ptcb about incompatible pointer assignment. +#define os_thread_cb OS_TCB + +#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" +#include "rt_OsEventObserver.h" + +#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_0(f,t,t1,...) \ +__svc_indirect(0) t _##f (t(*)(t1),t1); \ + t f (t1 a1); \ +__attribute__((always_inline)) \ +static __inline t __##f (t1 a1) { \ + _##f(f,a1); \ +} + +#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} + +#define osEvent_type __attribute__((pcs("aapcs"))) 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 __attribute__((pcs("aapcs"))) ret64 +#define osCallback_ret (ret64) {(uint32_t)ret.fp, (uint32_t)ret.arg} + +#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)) || defined (__CORTEX_M0PLUS) +#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_0(f,t,t1) \ +__attribute__((always_inline)) \ +static inline t __##f (t1 a1) { \ + SVC_Arg1(t1); \ + SVC_Call(f); \ +} + +#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 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 RET_osEvent osEvent +#define RET_osCallback osCallback + +#define SVC_Setup(f) \ + __asm( \ + "mov r12,%0\n" \ + :: "r"(&f): "r0", "r1", "r2", "r3", "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_0(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); \ + _##f(a1); \ +} + +#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 SVC_1_1 +#define SVC_1_3 SVC_1_1 +#define SVC_2_3 SVC_2_1 + +#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 + +#ifndef __MBED_CMSIS_RTOS_CM +// OS Stack Memory for Threads definitions +extern uint64_t os_stack_mem[]; +extern const uint32_t os_stack_sz; +#endif + +// 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; + +// Thread creation and destruction +osMutexDef(osThreadMutex); +osMutexId osMutexId_osThreadMutex; +void sysThreadTerminate(osThreadId id); + +// ==== Helper Functions ==== + +/// Convert timeout in millisec to system ticks +static uint16_t rt_ms2tick (uint32_t millisec) { + uint32_t tick; + + if (millisec == 0U) { return 0x0U; } // No timeout + if (millisec == osWaitForever) { return 0xFFFFU; } // Indefinite timeout + if (millisec > 4000000U) { return 0xFFFEU; } // Max ticks supported + + tick = ((1000U * millisec) + os_clockrate - 1U) / os_clockrate; + if (tick > 0xFFFEU) { return 0xFFFEU; } + + return (uint16_t)tick; +} + +/// Convert Thread ID to TCB pointer +P_TCB rt_tid2ptcb (osThreadId thread_id) { + P_TCB ptcb; + + if (thread_id == NULL) { return NULL; } + + if ((uint32_t)thread_id & 3U) { return NULL; } + +#ifdef OS_SECTIONS_LINK_INFO + if ((os_section_id$$Base != 0U) && (os_section_id$$Limit != 0U)) { + 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 & 3U) { return NULL; } + +#ifdef OS_SECTIONS_LINK_INFO + if ((os_section_id$$Base != 0U) && (os_section_id$$Limit != 0U)) { + if (id < (void *)os_section_id$$Base) { return NULL; } + if (id >= (void *)os_section_id$$Limit) { return NULL; } + } +#endif + + return id; +} + + +// ==== 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) +SVC_0_1(svcKernelSysTick, uint32_t, RET_uint32_t) + +static void sysThreadError (osStatus status); +osThreadId svcThreadCreate (const osThreadDef_t *thread_def, void *argument, void *context); +osMessageQId svcMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id); + +// Kernel Control Service Calls + +/// Initialize the RTOS Kernel for creating objects +osStatus svcKernelInitialize (void) { +#ifdef __MBED_CMSIS_RTOS_CM + if (!os_initialized) { + rt_sys_init(); // RTX System Initialization + } +#else + uint32_t ret; + + if (os_initialized == 0U) { + + // Init Thread Stack Memory (must be 8-byte aligned) + if (((uint32_t)os_stack_mem & 7U) != 0U) { return osErrorNoMemory; } + ret = rt_init_mem(os_stack_mem, os_stack_sz); + if (ret != 0U) { return osErrorNoMemory; } + + rt_sys_init(); // RTX System Initialization + } +#endif + + os_tsk.run->prio = 255U; // Highest priority + + if (os_initialized == 0U) { + // Create OS Timers resources (Message Queue & Thread) + osMessageQId_osTimerMessageQ = svcMessageCreate (&os_messageQ_def_osTimerMessageQ, NULL); + osThreadId_osTimerThread = svcThreadCreate(&os_thread_def_osTimerThread, NULL, NULL); + // Initialize thread mutex + osMutexId_osThreadMutex = osMutexCreate(osMutex(osThreadMutex)); + } + + sysThreadError(osOK); + + os_initialized = 1U; + os_running = 0U; + + return osOK; +} + +/// Start the RTOS Kernel +osStatus svcKernelStart (void) { + + if (os_running) { return osOK; } + + rt_tsk_prio(0U, os_tsk.run->prio_base); // Restore priority + if (os_tsk.run->task_id == 0xFFU) { // Idle Thread + __set_PSP(os_tsk.run->tsk_stack + (8U*4U)); // Setup PSP + } + if (os_tsk.new_tsk == NULL) { // Force context switch + os_tsk.new_tsk = os_tsk.run; + os_tsk.run = NULL; + } + + rt_sys_start(); + + os_running = 1U; + + return osOK; +} + +/// Check if the RTOS kernel is already started +int32_t svcKernelRunning (void) { + return (int32_t)os_running; +} + +/// Get the RTOS kernel system timer counter +uint32_t svcKernelSysTick (void) { + uint32_t tick, tick0; + + tick = os_tick_val(); + if (os_tick_ovf()) { + tick0 = os_tick_val(); + if (tick0 < tick) { tick = tick0; } + tick += (os_trv + 1U) * (os_time + 1U); + } else { + tick += (os_trv + 1U) * os_time; + } + + return tick; +} + +// Kernel Control Public API + +/// Initialize the RTOS Kernel for creating objects +osStatus osKernelInitialize (void) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return osErrorISR; // Not allowed in ISR + } + if ((__get_CONTROL() & 1U) == 0U) { // Privileged mode + return svcKernelInitialize(); + } else { + return __svcKernelInitialize(); + } +} + +/// Start the RTOS Kernel +osStatus osKernelStart (void) { + uint32_t stack[8]; + + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return osErrorISR; // Not allowed in ISR + } + + /* Call the pre-start event (from unprivileged mode) if the handler exists + * and the kernel is not running. */ + /* FIXME osEventObs needs to be readable but not writable from unprivileged + * code. */ + if (!osKernelRunning() && osEventObs && osEventObs->pre_start) { + osEventObs->pre_start(); + } + + switch (__get_CONTROL() & 0x03U) { + case 0x00U: // Privileged Thread mode & MSP + __set_PSP((uint32_t)(stack + 8)); // Initial PSP + if (os_flags & 1U) { + __set_CONTROL(0x02U); // Set Privileged Thread mode & PSP + } else { + __set_CONTROL(0x03U); // Set Unprivileged Thread mode & PSP + } + __DSB(); + __ISB(); + break; + case 0x01U: // Unprivileged Thread mode & MSP + return osErrorOS; + case 0x02U: // Privileged Thread mode & PSP + if ((os_flags & 1U) == 0U) { // Unprivileged Thread mode requested + __set_CONTROL(0x03U); // Set Unprivileged Thread mode & PSP + __DSB(); + __ISB(); + } + break; + case 0x03U: // Unprivileged Thread mode & PSP + if (os_flags & 1U) { return osErrorOS; } // Privileged Thread mode requested + break; + } + return __svcKernelStart(); +} + +/// Check if the RTOS kernel is already started +int32_t osKernelRunning (void) { + if ((__get_PRIMASK() != 0U || __get_IPSR() != 0U) || ((__get_CONTROL() & 1U) == 0U)) { + // in ISR or Privileged + return (int32_t)os_running; + } else { + return __svcKernelRunning(); + } +} + +/// Get the RTOS kernel system timer counter +uint32_t osKernelSysTick (void) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { return 0U; } // Not allowed in ISR + return __svcKernelSysTick(); +} + + +// ==== 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_3_1(svcThreadCreate, osThreadId, const osThreadDef_t *, void *, 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) +SVC_2_3(svcThreadGetInfo, os_InRegs osEvent, osThreadId, osThreadInfo, RET_osEvent) + +// 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, void *context) { + 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; + } + +#ifdef __MBED_CMSIS_RTOS_CM + if (thread_def->stacksize != 0) { // Custom stack size + stk = (void *)thread_def->stack_pointer; + } else { // Default stack size + stk = NULL; + } +#else + 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; + } +#endif + + tsk = rt_tsk_create( // Create task + (FUNCP)thread_def->pthread, // Task function pointer + (uint32_t) + (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 == 0U) { // Invalid task ID +#ifndef __MBED_CMSIS_RTOS_CM + if (stk != NULL) { + rt_free_mem(os_stack_mem, stk); // Free allocated stack + } +#endif + sysThreadError(osErrorNoMemory); // Create task failed (Out of memory) + return NULL; + } + + ptcb = (P_TCB)os_active_TCB[tsk - 1U]; // TCB pointer + + *((uint32_t *)ptcb->tsk_stack + 13) = (uint32_t)osThreadExit; + + if (osEventObs && osEventObs->thread_create) { + ptcb->context = osEventObs->thread_create(ptcb->task_id, context); + } else { + ptcb->context = context; + } + + return ptcb; +} + +/// Return the thread ID of the current running thread +osThreadId svcThreadGetId (void) { + OS_TID tsk; + + tsk = rt_tsk_self(); + if (tsk == 0U) { return NULL; } + return (P_TCB)os_active_TCB[tsk - 1U]; +} + +/// Terminate execution of a thread and remove it from ActiveThreads +osStatus svcThreadTerminate (osThreadId thread_id) { + OS_RESULT res; + P_TCB ptcb; +#ifndef __MBED_CMSIS_RTOS_CM + void *stk; +#endif + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) { + return osErrorParameter; + } + +#ifndef __MBED_CMSIS_RTOS_CM + stk = ptcb->priv_stack ? ptcb->stack : NULL; // Private stack +#endif + + if (osEventObs && osEventObs->thread_destroy) { + osEventObs->thread_destroy(ptcb->context); + } + + res = rt_tsk_delete(ptcb->task_id); // Delete task + + if (res == OS_R_NOK) { + return osErrorResource; // Delete task failed + } + +#ifndef __MBED_CMSIS_RTOS_CM + if (stk != NULL) { + rt_free_mem(os_stack_mem, stk); // Free private stack + } +#endif + + 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 + (uint8_t)(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); +} + +/// Get info from an active thread +os_InRegs osEvent_type svcThreadGetInfo (osThreadId thread_id, osThreadInfo info) { + P_TCB ptcb; + osEvent ret; + ret.status = osOK; + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) { + ret.status = osErrorValue; + return osEvent_ret_status; + } + + if (osThreadInfoStackSize == info) { + uint32_t size; + size = ptcb->priv_stack; + if (0 == size) { + // This is an OS task - always a fixed size + size = os_stackinfo & 0x3FFFF; + } + ret.value.v = size; + return osEvent_ret_value; + } + + if (osThreadInfoStackMax == info) { + uint32_t i; + uint32_t *stack_ptr; + uint32_t stack_size; + if (!(os_stackinfo & (1 << 28))) { + // Stack init must be turned on for max stack usage + ret.status = osErrorResource; + return osEvent_ret_status; + } + stack_ptr = (uint32_t*)ptcb->stack; + stack_size = ptcb->priv_stack; + if (0 == stack_size) { + // This is an OS task - always a fixed size + stack_size = os_stackinfo & 0x3FFFF; + } + for (i = 1; i <stack_size / 4; i++) { + if (stack_ptr[i] != MAGIC_PATTERN) { + break; + } + } + ret.value.v = stack_size - i * 4; + return osEvent_ret_value; + } + + if (osThreadInfoEntry == info) { + ret.value.p = (void*)ptcb->ptask; + return osEvent_ret_value; + } + + if (osThreadInfoArg == info) { + ret.value.p = (void*)ptcb->argv; + return osEvent_ret_value; + } + + // Unsupported option so return error + ret.status = osErrorParameter; + return osEvent_ret_status; +} + +// 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) { + return osThreadContextCreate(thread_def, argument, NULL); +} +osThreadId osThreadContextCreate (const osThreadDef_t *thread_def, void *argument, void *context) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return NULL; // Not allowed in ISR + } + if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) { + // Privileged and not running + return svcThreadCreate(thread_def, argument, context); + } else { + osThreadId id; + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + // Thread mutex must be held when a thread is created or terminated + id = __svcThreadCreate(thread_def, argument, context); + osMutexRelease(osMutexId_osThreadMutex); + return id; + } +} + +/// Return the thread ID of the current running thread +osThreadId osThreadGetId (void) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return NULL; // Not allowed in ISR + } + return __svcThreadGetId(); +} + +/// Terminate execution of a thread and remove it from ActiveThreads +osStatus osThreadTerminate (osThreadId thread_id) { + osStatus status; + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return osErrorISR; // Not allowed in ISR + } + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + sysThreadTerminate(thread_id); + // Thread mutex must be held when a thread is created or terminated + status = __svcThreadTerminate(thread_id); + osMutexRelease(osMutexId_osThreadMutex); + return status; +} + +/// Pass control to next thread that is in state READY +osStatus osThreadYield (void) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return osErrorISR; // Not allowed in ISR + } + return __svcThreadYield(); +} + +/// Change priority of an active thread +osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return osErrorISR; // Not allowed in ISR + } + return __svcThreadSetPriority(thread_id, priority); +} + +/// Get current priority of an active thread +osPriority osThreadGetPriority (osThreadId thread_id) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + 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) { + osThreadId id; + // Thread mutex must be held when a thread is created or terminated + // Note - the mutex will be released automatically by the os when + // the thread is terminated + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + id = __svcThreadGetId(); + sysThreadTerminate(id); + __svcThreadTerminate(id); + for (;;); // Should never come here +} + +#ifdef __MBED_CMSIS_RTOS_CM +/// Get current thread state +uint8_t osThreadGetState (osThreadId thread_id) { + P_TCB ptcb; + + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) return osErrorISR; // Not allowed in ISR + + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer + if (ptcb == NULL) return INACTIVE; + + return ptcb->state; +} +#endif + +/// Get the requested info from the specified active thread +os_InRegs osEvent _osThreadGetInfo(osThreadId thread_id, osThreadInfo info) { + osEvent ret; + + if (__get_IPSR() != 0U) { // Not allowed in ISR + ret.status = osErrorISR; + return ret; + } + return __svcThreadGetInfo(thread_id, info); +} + +osThreadEnumId _osThreadsEnumStart() { + static uint32_t thread_enum_index; + osMutexWait(osMutexId_osThreadMutex, osWaitForever); + thread_enum_index = 0; + return &thread_enum_index; +} + +osThreadId _osThreadEnumNext(osThreadEnumId enum_id) { + uint32_t i; + osThreadId id = NULL; + uint32_t *index = (uint32_t*)enum_id; + for (i = *index; i < os_maxtaskrun; i++) { + if (os_active_TCB[i] != NULL) { + id = (osThreadId)os_active_TCB[i]; + break; + } + } + if (i == os_maxtaskrun) { + // Include the idle task at the end of the enumeration + id = &os_idle_TCB; + } + *index = i + 1; + return id; +} + +osStatus _osThreadEnumFree(osThreadEnumId enum_id) { + uint32_t *index = (uint32_t*)enum_id; + *index = 0; + osMutexRelease(osMutexId_osThreadMutex); + return osOK; +} + +// ==== 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 == 0U) { 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 == 0U) { + ret.status = osOK; + return osEvent_ret_status; + } + + /* To Do: osEventSignal, osEventMessage, osEventMail */ + rt_dly_wait(rt_ms2tick(millisec)); + ret.status = osEventTimeout; + + return osEvent_ret_status; +} +#endif + + +// Generic Wait API + +/// Wait for Timeout (Time Delay) +osStatus osDelay (uint32_t millisec) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { // Not allowed in ISR + ret.status = osErrorISR; + return ret; + } + return __svcWait(millisec); +#endif +} + + +// ==== Timer Management ==== + +// Timer definitions +#define osTimerInvalid 0U +#define osTimerStopped 1U +#define osTimerRunning 2U + +// 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 + uint32_t tcnt; // Timer Delay Count + uint32_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 = 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 int32_t 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->next = 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; + } + + if (millisec == 0U) { return osErrorValue; } + + tcnt = (uint32_t)(((1000U * (uint64_t)millisec) + os_clockrate - 1U) / os_clockrate); + + switch (pt->state) { + case osTimerRunning: + if (rt_timer_remove(pt) != 0) { + return osErrorResource; + } + break; + case osTimerStopped: + pt->state = osTimerRunning; + pt->icnt = 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; + return osCallback_ret; + } + + ret.fp = (void *)pt->timer->ptimer; + ret.arg = pt->arg; + + return osCallback_ret; +} + +osStatus isrMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec); + +/// Timer Tick (called each SysTick) +void sysTimerTick (void) { + os_timer_cb *pt, *p; + osStatus status; + + p = os_timer_head; + if (p == NULL) { return; } + + p->tcnt--; + while ((p != NULL) && (p->tcnt == 0U)) { + pt = p; + p = p->next; + os_timer_head = p; + status = isrMessagePut(osMessageQId_osTimerMessageQ, (uint32_t)pt, 0U); + if (status != osOK) { + os_error(OS_ERR_TIMER_OVF); + } + if (pt->type == (uint8_t)osTimerPeriodic) { + rt_timer_insert(pt, pt->icnt); + } else { + pt->state = osTimerStopped; + } + } +} + +/// Get user timers wake-up time +uint32_t sysUserTimerWakeupTime (void) { + + if (os_timer_head) { + return os_timer_head->tcnt; + } + return 0xFFFFFFFFU; +} + +/// Update user timers on resume +void sysUserTimerUpdate (uint32_t sleep_time) { + + while ((os_timer_head != NULL) && (sleep_time != 0U)) { + if (sleep_time >= os_timer_head->tcnt) { + sleep_time -= os_timer_head->tcnt; + os_timer_head->tcnt = 1U; + sysTimerTick(); + } else { + os_timer_head->tcnt -= sleep_time; + break; + } + } +} + + +// Timer Management Public API + +/// Create timer +osTimerId osTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return NULL; // Not allowed in ISR + } + if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) { + // 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return osErrorISR; // Not allowed in ISR + } + return __svcTimerStart(timer_id, millisec); +} + +/// Stop timer +osStatus osTimerStop (osTimerId timer_id) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return osErrorISR; // Not allowed in ISR + } + return __svcTimerStop(timer_id); +} + +/// Delete timer +osStatus osTimerDelete (osTimerId timer_id) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + 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_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 (int32_t)0x80000000U; + } + + if ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) { + return (int32_t)0x80000000U; + } + + sig = (int32_t)ptcb->events; // Previous signal flags + + rt_evt_set((uint16_t)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 (int32_t)0x80000000U; + } + + if ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) { + return (int32_t)0x80000000U; + } + + sig = (int32_t)ptcb->events; // Previous signal flags + + rt_evt_clr((uint16_t)signals, ptcb->task_id); // Clear event flags + + return sig; +} + +/// 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 ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) { + ret.status = osErrorValue; + return osEvent_ret_status; + } + + if (signals != 0) { // Wait for all specified signals + res = rt_evt_wait((uint16_t)signals, rt_ms2tick(millisec), __TRUE); + } else { // Wait for any signal + res = rt_evt_wait(0xFFFFU, rt_ms2tick(millisec), __FALSE); + } + + if (res == OS_R_EVT) { + ret.status = osEventSignal; + ret.value.signals = (signals != 0) ? signals : (int32_t)os_tsk.run->waits; + } else { + ret.status = (millisec != 0U) ? osEventTimeout : osOK; + ret.value.signals = 0; + } + + return osEvent_ret_value; +} + + +// Signal ISR Calls + +/// Set the specified Signal Flags of an active thread +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 (int32_t)0x80000000U; + } + + if ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) { + return (int32_t)0x80000000U; + } + + sig = (int32_t)ptcb->events; // Previous signal flags + + isr_evt_set((uint16_t)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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { // 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return (int32_t)0x80000000U; // Not allowed in ISR + } + return __svcSignalClear(thread_id, signals); +} + +/// 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { // 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 != 0U) { + 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 != 0U) ? 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return NULL; // Not allowed in ISR + } + if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) { + // 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return osErrorISR; // Not allowed in ISR + } + return __svcMutexRelease(mutex_id); +} + +/// Delete a Mutex that was created by osMutexCreate +osStatus osMutexDelete (osMutexId mutex_id) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + 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 != 0U) { + sysThreadError(osErrorParameter); + return NULL; + } + + if (count > osFeature_Semaphore) { + sysThreadError(osErrorValue); + return NULL; + } + + rt_sem_init(sem, (uint16_t)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 (int32_t)(((P_SCB)sem)->tokens + 1U); +} + +/// 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 ((int32_t)((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 +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 ((int32_t)((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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return NULL; // Not allowed in ISR + } + if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) { + // 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return -1; // Not allowed in ISR + } + return __svcSemaphoreWait(semaphore_id, millisec); +} + +/// Release a Semaphore +osStatus osSemaphoreRelease (osSemaphoreId semaphore_id) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { // 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + 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_mem != NULL) && (box != NULL)) { + p = box; + for (n = ((P_BM)box_mem)->blk_size; n; n -= 4U) { + *p++ = 0U; + } + } +} + +// Memory Management Service Calls declarations +SVC_1_1(svcPoolCreate, osPoolId, const osPoolDef_t *, RET_pointer) +SVC_1_1(sysPoolAlloc, void *, osPoolId, 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 == 0U) || + (pool_def->item_sz == 0U) || + (pool_def->pool == NULL)) { + sysThreadError(osErrorParameter); + return NULL; + } + + blk_sz = (pool_def->item_sz + 3U) & (uint32_t)~3U; + + _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) { + void *mem; + + if (pool_id == NULL) { + return NULL; + } + + mem = rt_alloc_box(pool_id); + + return mem; +} + +/// Return an allocated memory block back to a specific memory pool +osStatus sysPoolFree (osPoolId pool_id, void *block) { + uint32_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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return NULL; // Not allowed in ISR + } + if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) { + // 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_PRIMASK() != 0U || __get_IPSR() != 0U) || ((__get_CONTROL() & 1U) == 0U)) { // in ISR or Privileged + return sysPoolAlloc(pool_id); + } else { // in Thread + return __sysPoolAlloc(pool_id); + } +} + +/// Allocate a memory block from a memory pool and set memory block to zero +void *osPoolCAlloc (osPoolId pool_id) { + void *mem; + + if ((__get_PRIMASK() != 0U || __get_IPSR() != 0U) || ((__get_CONTROL() & 1U) == 0U)) { // in ISR or Privileged + mem = sysPoolAlloc(pool_id); + } else { // in Thread + mem = __sysPoolAlloc(pool_id); + } + + rt_clr_box(pool_id, mem); + + return mem; +} + +/// Return an allocated memory block back to a specific memory pool +osStatus osPoolFree (osPoolId pool_id, void *block) { + if ((__get_PRIMASK() != 0U || __get_IPSR() != 0U) || ((__get_CONTROL() & 1U) == 0U)) { // 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 == 0U) || + (queue_def->pool == NULL)) { + sysThreadError(osErrorParameter); + return NULL; + } + + if (((P_MCB)queue_def->pool)->cb_type != 0U) { + sysThreadError(osErrorParameter); + return NULL; + } + + rt_mbx_init(queue_def->pool, (uint16_t)(4U*(queue_def->queue_sz + 4U))); + + 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 != 0U) ? 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; + return osEvent_ret_status; + } + + if (((P_MCB)queue_id)->cb_type != MCB) { + ret.status = osErrorParameter; + return osEvent_ret_status; + } + + res = rt_mbx_wait(queue_id, &ret.value.p, rt_ms2tick(millisec)); + + if (res == OS_R_TMO) { + ret.status = (millisec != 0U) ? osEventTimeout : osOK; + return osEvent_ret_value; + } + + ret.status = osEventMessage; + + return osEvent_ret_value; +} + + +// Message Queue ISR Calls + +/// Put a Message to a Queue +osStatus isrMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) { + + if ((queue_id == NULL) || (millisec != 0U)) { + return osErrorParameter; + } + + if (((P_MCB)queue_id)->cb_type != MCB) { + return osErrorParameter; + } + + if (rt_mbx_check(queue_id) == 0U) { // 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 +os_InRegs osEvent isrMessageGet (osMessageQId queue_id, uint32_t millisec) { + OS_RESULT res; + osEvent ret; + + if ((queue_id == NULL) || (millisec != 0U)) { + 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return NULL; // Not allowed in ISR + } + if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) { + // 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { // 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { // 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_3_1(sysMailAlloc, void *, osMailQId, 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 == 0U) || + (queue_def->item_sz == 0U) || + (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 != 0U)) { + sysThreadError(osErrorParameter); + return NULL; + } + + blk_sz = (queue_def->item_sz + 3U) & (uint32_t)~3U; + + _init_box(pool, sizeof(struct OS_BM) + (queue_def->queue_sz * blk_sz), blk_sz); + + rt_mbx_init(pmcb, (uint16_t)(4U*(queue_def->queue_sz + 4U))); + + return queue_def->pool; +} + +/// Allocate a memory block from a mail +void *sysMailAlloc (osMailQId queue_id, uint32_t millisec, uint32_t isr) { + 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 != 0U) && (millisec != 0U)) { + return NULL; + } + + mem = rt_alloc_box(pool); + + if ((mem == NULL) && (millisec != 0U)) { + // 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 = 3U; + } + 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; + uint32_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 != 0U) { + return osErrorValue; + } + + if ((pmcb->p_lnk != NULL) && (pmcb->state == 3U)) { + // Task is waiting to allocate a message + if (isr != 0U) { + 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); + 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { + return NULL; // Not allowed in ISR + } + if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) { + // 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 (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { // in ISR + return sysMailAlloc(queue_id, millisec, 1U); + } else { // in Thread + return __sysMailAlloc(queue_id, millisec, 0U); + } +} + +/// Allocate a memory block from a mail and set memory block to zero +void *osMailCAlloc (osMailQId queue_id, uint32_t millisec) { + void *pool; + void *mem; + + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { // in ISR + mem = sysMailAlloc(queue_id, millisec, 1U); + } else { // in Thread + mem = __sysMailAlloc(queue_id, millisec, 0U); + } + + pool = *(((void **)queue_id) + 1); + + rt_clr_box(pool, mem); + + return mem; +} + +/// Free a memory block from a mail +osStatus osMailFree (osMailQId queue_id, void *mail) { + if (__get_PRIMASK() != 0U || __get_IPSR() != 0U) { // in ISR + return sysMailFree(queue_id, mail, 1U); + } else { // in Thread + return __sysMailFree(queue_id, mail, 0U); + } +} + +/// 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, 0U); +} + +/// 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; +} + + +// ==== RTX Extensions ==== + +// Service Calls declarations +SVC_0_1(rt_suspend, uint32_t, RET_uint32_t) +SVC_1_0(rt_resume, void, uint32_t) + + +// Public API + +/// Suspends the OS task scheduler +uint32_t os_suspend (void) { + return __rt_suspend(); +} + +/// Resumes the OS task scheduler +void os_resume (uint32_t sleep_time) { + __rt_resume(sleep_time); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Event.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,190 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_EVENT.C + * Purpose: Implements waits and wake-ups for event flags + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_evt_wait -----------------------------------*/ + +OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait) { + /* Wait for one or more event flags with optional time-out. */ + /* "wait_flags" identifies the flags to wait for. */ + /* "timeout" is the time-out limit in system ticks (0xffff if no time-out) */ + /* "and_wait" specifies the AND-ing of "wait_flags" as condition to be met */ + /* to complete the wait. (OR-ing if set to 0). */ + U32 block_state; + + if (and_wait) { + /* Check for AND-connected events */ + if ((os_tsk.run->events & wait_flags) == wait_flags) { + os_tsk.run->events &= ~wait_flags; + return (OS_R_EVT); + } + block_state = WAIT_AND; + } + else { + /* Check for OR-connected events */ + if (os_tsk.run->events & wait_flags) { + os_tsk.run->waits = os_tsk.run->events & wait_flags; + os_tsk.run->events &= ~wait_flags; + return (OS_R_EVT); + } + block_state = WAIT_OR; + } + /* Task has to wait */ + os_tsk.run->waits = wait_flags; + rt_block (timeout, (U8)block_state); + return (OS_R_TMO); +} + + +/*--------------------------- rt_evt_set ------------------------------------*/ + +void rt_evt_set (U16 event_flags, OS_TID task_id) { + /* Set one or more event flags of a selectable task. */ + P_TCB p_tcb; + + p_tcb = os_active_TCB[task_id-1U]; + if (p_tcb == NULL) { + return; + } + p_tcb->events |= event_flags; + event_flags = p_tcb->waits; + /* If the task is not waiting for an event, it should not be put */ + /* to ready state. */ + if (p_tcb->state == WAIT_AND) { + /* Check for AND-connected events */ + if ((p_tcb->events & event_flags) == event_flags) { + goto wkup; + } + } + if (p_tcb->state == WAIT_OR) { + /* Check for OR-connected events */ + if (p_tcb->events & event_flags) { + p_tcb->waits &= p_tcb->events; +wkup: p_tcb->events &= ~event_flags; + rt_rmv_dly (p_tcb); + p_tcb->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val2(p_tcb, 0x08U/*osEventSignal*/, p_tcb->waits); +#else + rt_ret_val (p_tcb, OS_R_EVT); +#endif + rt_dispatch (p_tcb); + } + } +} + + +/*--------------------------- rt_evt_clr ------------------------------------*/ + +void rt_evt_clr (U16 clear_flags, OS_TID task_id) { + /* Clear one or more event flags (identified by "clear_flags") of a */ + /* selectable task (identified by "task"). */ + P_TCB task = os_active_TCB[task_id-1U]; + + if (task == NULL) { + return; + } + task->events &= ~clear_flags; +} + + +/*--------------------------- isr_evt_set -----------------------------------*/ + +void isr_evt_set (U16 event_flags, OS_TID task_id) { + /* Same function as "os_evt_set", but to be called by ISRs. */ + P_TCB p_tcb = os_active_TCB[task_id-1U]; + + if (p_tcb == NULL) { + return; + } + rt_psq_enq (p_tcb, event_flags); + rt_psh_req (); +} + + +/*--------------------------- rt_evt_get ------------------------------------*/ + +U16 rt_evt_get (void) { + /* Get events of a running task after waiting for OR connected events. */ + return (os_tsk.run->waits); +} + + +/*--------------------------- rt_evt_psh ------------------------------------*/ + +void rt_evt_psh (P_TCB p_CB, U16 set_flags) { + /* Check if task has to be waken up */ + U16 event_flags; + + p_CB->events |= set_flags; + event_flags = p_CB->waits; + if (p_CB->state == WAIT_AND) { + /* Check for AND-connected events */ + if ((p_CB->events & event_flags) == event_flags) { + goto rdy; + } + } + if (p_CB->state == WAIT_OR) { + /* Check for OR-connected events */ + if (p_CB->events & event_flags) { + p_CB->waits &= p_CB->events; +rdy: p_CB->events &= ~event_flags; + rt_rmv_dly (p_CB); + p_CB->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val2(p_CB, 0x08U/*osEventSignal*/, p_CB->waits); +#else + rt_ret_val (p_CB, OS_R_EVT); +#endif + rt_put_prio (&os_rdy, p_CB); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Event.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,51 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_EVENT.H + * Purpose: Implements waits and wake-ups for event flags + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait); +extern void rt_evt_set (U16 event_flags, OS_TID task_id); +extern void rt_evt_clr (U16 clear_flags, OS_TID task_id); +extern void isr_evt_set (U16 event_flags, OS_TID task_id); +extern U16 rt_evt_get (void); +extern void rt_evt_psh (P_TCB p_CB, U16 set_flags); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_HAL_CM.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,344 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_HAL_CM.H + * Purpose: Hardware Abstraction Layer for Cortex-M definitions + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Definitions */ +#define INITIAL_xPSR 0x01000000U +#define DEMCR_TRCENA 0x01000000U +#define ITM_ITMENA 0x00000001U +#define MAGIC_WORD 0xE25A2EA5U +#define MAGIC_PATTERN 0xCCCCCCCCU + +#if defined (__CC_ARM) /* ARM Compiler */ + +#if ((defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M)) && !defined(NO_EXCLUSIVE_ACCESS)) + #define __USE_EXCLUSIVE_ACCESS +#else + #undef __USE_EXCLUSIVE_ACCESS +#endif + +/* Supress __ldrex and __strex deprecated warnings - "#3731-D: intrinsic is deprecated" */ +#ifdef __USE_EXCLUSIVE_ACCESS +#pragma diag_suppress 3731 +#endif + +#ifndef __CMSIS_GENERIC + +__attribute__((always_inline)) static inline U32 __get_PRIMASK(void) +{ + register U32 primask __asm("primask"); + return primask; +} + +#define __DMB() do {\ + __schedule_barrier();\ + __dmb(0xF);\ + __schedule_barrier();\ + } while (0) + +#endif + +#elif defined (__GNUC__) /* GNU Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if defined (__CORTEX_M0) || defined (__CORTEX_M0PLUS) +#define __TARGET_ARCH_6S_M +#endif + +#if defined (__VFP_FP__) && !defined(__SOFTFP__) +#define __TARGET_FPU_VFP +#endif + +#define __inline inline +#define __weak __attribute__((weak)) + +#ifndef __CMSIS_GENERIC + +__attribute__((always_inline)) static inline U32 __get_PRIMASK(void) +{ + U32 result; + + __asm volatile ("mrs %0, primask" : "=r" (result)); + return result; +} + +__attribute__((always_inline)) static inline void __enable_irq(void) +{ + __asm volatile ("cpsie i"); +} + +__attribute__((always_inline)) static inline U32 __disable_irq(void) +{ + U32 result; + + __asm volatile ("mrs %0, primask" : "=r" (result)); + __asm volatile ("cpsid i"); + return(result & 1); +} + +__attribute__((always_inline)) static inline void __DMB(void) +{ + __asm volatile ("dmb 0xF":::"memory"); +} + +#endif + +__attribute__(( always_inline)) static inline U8 __clz(U32 value) +{ + U8 result; + + __asm volatile ("clz %0, %1" : "=r" (result) : "r" (value)); + return(result); +} + +#elif defined (__ICCARM__) /* IAR Compiler */ + +#undef __USE_EXCLUSIVE_ACCESS + +#if (__CORE__ == __ARM6M__) +#define __TARGET_ARCH_6S_M 1 +#endif + +#if defined __ARMVFP__ +#define __TARGET_FPU_VFP 1 +#endif + +#define __inline inline + +#ifndef __CMSIS_GENERIC + +static inline U32 __get_PRIMASK(void) +{ + U32 result; + + __asm volatile ("mrs %0, primask" : "=r" (result)); + return result; +} + +static inline void __enable_irq(void) +{ + __asm volatile ("cpsie i"); +} + +static inline U32 __disable_irq(void) +{ + U32 result; + + __asm volatile ("mrs %0, primask" : "=r" (result)); + __asm volatile ("cpsid i"); + return(result & 1); +} + +#endif + +static inline U8 __clz(U32 value) +{ + U8 result; + + __asm volatile ("clz %0, %1" : "=r" (result) : "r" (value)); + return(result); +} + +#endif + +/* NVIC registers */ +#define NVIC_ST_CTRL (*((volatile U32 *)0xE000E010U)) +#define NVIC_ST_RELOAD (*((volatile U32 *)0xE000E014U)) +#define NVIC_ST_CURRENT (*((volatile U32 *)0xE000E018U)) +#define NVIC_ISER ((volatile U32 *)0xE000E100U) +#define NVIC_ICER ((volatile U32 *)0xE000E180U) +#if defined(__TARGET_ARCH_6S_M) +#define NVIC_IP ((volatile U32 *)0xE000E400U) +#else +#define NVIC_IP ((volatile U8 *)0xE000E400U) +#endif +#define NVIC_INT_CTRL (*((volatile U32 *)0xE000ED04U)) +#define NVIC_AIR_CTRL (*((volatile U32 *)0xE000ED0CU)) +#define NVIC_SYS_PRI2 (*((volatile U32 *)0xE000ED1CU)) +#define NVIC_SYS_PRI3 (*((volatile U32 *)0xE000ED20U)) + +#define OS_PEND_IRQ() NVIC_INT_CTRL = (1UL<<28) +#define OS_PENDING ((NVIC_INT_CTRL >> 26) & 5U) +#define OS_UNPEND(fl) NVIC_INT_CTRL = (U32)(fl = (U8)OS_PENDING) << 25 +#define OS_PEND(fl,p) NVIC_INT_CTRL = (U32)(fl | (U8)(p<<2)) << 26 +#define OS_LOCK() NVIC_ST_CTRL = 0x0005U +#define OS_UNLOCK() NVIC_ST_CTRL = 0x0007U + +#define OS_X_PENDING ((NVIC_INT_CTRL >> 28) & 1U) +#define OS_X_UNPEND(fl) NVIC_INT_CTRL = (U32)(fl = (U8)OS_X_PENDING) << 27 +#define OS_X_PEND(fl,p) NVIC_INT_CTRL = (U32)(fl | p) << 28 +#if defined(__TARGET_ARCH_6S_M) +#define OS_X_INIT(n) NVIC_IP[n>>2] |= (U32)0xFFU << ((n & 0x03U) << 3); \ + NVIC_ISER[n>>5] = (U32)1U << (n & 0x1FU) +#else +#define OS_X_INIT(n) NVIC_IP[n] = 0xFFU; \ + NVIC_ISER[n>>5] = (U32)1U << (n & 0x1FU) +#endif +#define OS_X_LOCK(n) NVIC_ICER[n>>5] = (U32)1U << (n & 0x1FU) +#define OS_X_UNLOCK(n) NVIC_ISER[n>>5] = (U32)1U << (n & 0x1FU) + +/* Core Debug registers */ +#define DEMCR (*((volatile U32 *)0xE000EDFCU)) + +/* ITM registers */ +#define ITM_CONTROL (*((volatile U32 *)0xE0000E80U)) +#define ITM_ENABLE (*((volatile U32 *)0xE0000E00U)) +#define ITM_PORT30_U32 (*((volatile U32 *)0xE0000078U)) +#define ITM_PORT31_U32 (*((volatile U32 *)0xE000007CU)) +#define ITM_PORT31_U16 (*((volatile U16 *)0xE000007CU)) +#define ITM_PORT31_U8 (*((volatile U8 *)0xE000007CU)) + +/* Variables */ +extern BIT dbg_msg; + +/* Functions */ +#ifdef __USE_EXCLUSIVE_ACCESS + #define rt_inc(p) while(__strex((__ldrex(p)+1U),p)) + #define rt_dec(p) while(__strex((__ldrex(p)-1U),p)) +#else + #define rt_inc(p) do {\ + U32 primask = __get_PRIMASK();\ + __disable_irq();\ + (*p)++;\ + if (!primask) {\ + __enable_irq();\ + }\ + } while (0) + #define rt_dec(p) do {\ + U32 primask = __get_PRIMASK();\ + __disable_irq();\ + (*p)--;\ + if (!primask) {\ + __enable_irq();\ + }\ + } while (0) +#endif + +__inline static U32 rt_inc_qi (U32 size, U8 *count, U8 *first) { + U32 cnt,c2; +#ifdef __USE_EXCLUSIVE_ACCESS + do { + if ((cnt = __ldrex(count)) == size) { + __clrex(); + return (cnt); } + } while (__strex(cnt+1U, count)); + do { + c2 = (cnt = __ldrex(first)) + 1U; + if (c2 == size) { c2 = 0U; } + } while (__strex(c2, first)); +#else + U32 primask = __get_PRIMASK(); + __disable_irq(); + if ((cnt = *count) < size) { + *count = (U8)(cnt+1U); + c2 = (cnt = *first) + 1U; + if (c2 == size) { c2 = 0U; } + *first = (U8)c2; + } + if (!primask) { + __enable_irq (); + } +#endif + return (cnt); +} + +__inline static void rt_systick_init (void) { + NVIC_ST_RELOAD = os_trv; + NVIC_ST_CURRENT = 0U; + NVIC_ST_CTRL = 0x0007U; + NVIC_SYS_PRI3 |= 0xFF000000U; +} + +__inline static U32 rt_systick_val (void) { + return (os_trv - NVIC_ST_CURRENT); +} + +__inline static U32 rt_systick_ovf (void) { + return ((NVIC_INT_CTRL >> 26) & 1U); +} + +__inline static void rt_svc_init (void) { +#if !defined(__TARGET_ARCH_6S_M) + U32 sh,prigroup; +#endif + NVIC_SYS_PRI3 |= 0x00FF0000U; +#if defined(__TARGET_ARCH_6S_M) + NVIC_SYS_PRI2 |= (NVIC_SYS_PRI3<<(8+1)) & 0xFC000000U; +#else + sh = 8U - __clz(~((NVIC_SYS_PRI3 << 8) & 0xFF000000U)); + prigroup = ((NVIC_AIR_CTRL >> 8) & 0x07U); + if (prigroup >= sh) { + sh = prigroup + 1U; + } + +/* Only change the SVCall priority if uVisor is not present. */ +#if !(defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED)) + NVIC_SYS_PRI2 = ((0xFEFFFFFFU << sh) & 0xFF000000U) | (NVIC_SYS_PRI2 & 0x00FFFFFFU); +#endif /* !(defined(FEATURE_UVISOR) && defined(TARGET_UVISOR_SUPPORTED)) */ +#endif +} + +extern void rt_set_PSP (U32 stack); +extern U32 rt_get_PSP (void); +extern void os_set_env (void); +extern void *_alloc_box (void *box_mem); +extern U32 _free_box (void *box_mem, void *box); + +extern void rt_init_stack (P_TCB p_TCB, FUNCP task_body); +extern void rt_ret_val (P_TCB p_TCB, U32 v0); +extern void rt_ret_val2 (P_TCB p_TCB, U32 v0, U32 v1); + +extern void dbg_init (void); +extern void dbg_task_notify (P_TCB p_tcb, BOOL create); +extern void dbg_task_switch (U32 task_id); + +#ifdef DBG_MSG +#define DBG_INIT() dbg_init() +#define DBG_TASK_NOTIFY(p_tcb,create) if (dbg_msg) dbg_task_notify(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) if (dbg_msg && (os_tsk.new_tsk!=os_tsk.run)) \ + dbg_task_switch(task_id) +#else +#define DBG_INIT() +#define DBG_TASK_NOTIFY(p_tcb,create) +#define DBG_TASK_SWITCH(task_id) +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_List.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,318 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_LIST.C + * Purpose: Functions for the management of different lists + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Time.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* List head of chained ready tasks */ +struct OS_XCB os_rdy; +/* List head of chained delay tasks */ +struct OS_XCB os_dly; + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_put_prio -----------------------------------*/ + +void rt_put_prio (P_XCB p_CB, P_TCB p_task) { + /* Put task identified with "p_task" into list ordered by priority. */ + /* "p_CB" points to head of list; list has always an element at end with */ + /* a priority less than "p_task->prio". */ + P_TCB p_CB2; + U32 prio; + BOOL sem_mbx = __FALSE; + + if ((p_CB->cb_type == SCB) || (p_CB->cb_type == MCB) || (p_CB->cb_type == MUCB)) { + sem_mbx = __TRUE; + } + prio = p_task->prio; + p_CB2 = p_CB->p_lnk; + /* Search for an entry in the list */ + while ((p_CB2 != NULL) && (prio <= p_CB2->prio)) { + p_CB = (P_XCB)p_CB2; + p_CB2 = p_CB2->p_lnk; + } + /* Entry found, insert the task into the list */ + p_task->p_lnk = p_CB2; + p_CB->p_lnk = p_task; + if (sem_mbx) { + if (p_CB2 != NULL) { + p_CB2->p_rlnk = p_task; + } + p_task->p_rlnk = (P_TCB)p_CB; + } + else { + p_task->p_rlnk = NULL; + } +} + + +/*--------------------------- rt_get_first ----------------------------------*/ + +P_TCB rt_get_first (P_XCB p_CB) { + /* Get task at head of list: it is the task with highest priority. */ + /* "p_CB" points to head of list. */ + P_TCB p_first; + + p_first = p_CB->p_lnk; + p_CB->p_lnk = p_first->p_lnk; + if ((p_CB->cb_type == SCB) || (p_CB->cb_type == MCB) || (p_CB->cb_type == MUCB)) { + if (p_first->p_lnk != NULL) { + p_first->p_lnk->p_rlnk = (P_TCB)p_CB; + p_first->p_lnk = NULL; + } + p_first->p_rlnk = NULL; + } + else { + p_first->p_lnk = NULL; + } + return (p_first); +} + + +/*--------------------------- rt_put_rdy_first ------------------------------*/ + +void rt_put_rdy_first (P_TCB p_task) { + /* Put task identified with "p_task" at the head of the ready list. The */ + /* task must have at least a priority equal to highest priority in list. */ + p_task->p_lnk = os_rdy.p_lnk; + p_task->p_rlnk = NULL; + os_rdy.p_lnk = p_task; +} + + +/*--------------------------- rt_get_same_rdy_prio --------------------------*/ + +P_TCB rt_get_same_rdy_prio (void) { + /* Remove a task of same priority from ready list if any exists. Other- */ + /* wise return NULL. */ + P_TCB p_first; + + p_first = os_rdy.p_lnk; + if (p_first->prio == os_tsk.run->prio) { + os_rdy.p_lnk = os_rdy.p_lnk->p_lnk; + return (p_first); + } + return (NULL); +} + + +/*--------------------------- rt_resort_prio --------------------------------*/ + +void rt_resort_prio (P_TCB p_task) { + /* Re-sort ordered lists after the priority of 'p_task' has changed. */ + P_TCB p_CB; + + if (p_task->p_rlnk == NULL) { + if (p_task->state == READY) { + /* Task is chained into READY list. */ + p_CB = (P_TCB)&os_rdy; + goto res; + } + } + else { + p_CB = p_task->p_rlnk; + while (p_CB->cb_type == TCB) { + /* Find a header of this task chain list. */ + p_CB = p_CB->p_rlnk; + } +res:rt_rmv_list (p_task); + rt_put_prio ((P_XCB)p_CB, p_task); + } +} + + +/*--------------------------- rt_put_dly ------------------------------------*/ + +void rt_put_dly (P_TCB p_task, U16 delay) { + /* Put a task identified with "p_task" into chained delay wait list using */ + /* a delay value of "delay". */ + P_TCB p; + U32 delta,idelay = delay; + + p = (P_TCB)&os_dly; + if (p->p_dlnk == NULL) { + /* Delay list empty */ + delta = 0U; + goto last; + } + delta = os_dly.delta_time; + while (delta < idelay) { + if (p->p_dlnk == NULL) { + /* End of list found */ +last: p_task->p_dlnk = NULL; + p->p_dlnk = p_task; + p_task->p_blnk = p; + p->delta_time = (U16)(idelay - delta); + p_task->delta_time = 0U; + return; + } + p = p->p_dlnk; + delta += p->delta_time; + } + /* Right place found */ + p_task->p_dlnk = p->p_dlnk; + p->p_dlnk = p_task; + p_task->p_blnk = p; + if (p_task->p_dlnk != NULL) { + p_task->p_dlnk->p_blnk = p_task; + } + p_task->delta_time = (U16)(delta - idelay); + p->delta_time -= p_task->delta_time; +} + + +/*--------------------------- rt_dec_dly ------------------------------------*/ + +void rt_dec_dly (void) { + /* Decrement delta time of list head: remove tasks having a value of zero.*/ + P_TCB p_rdy; + + if (os_dly.p_dlnk == NULL) { + return; + } + os_dly.delta_time--; + while ((os_dly.delta_time == 0U) && (os_dly.p_dlnk != NULL)) { + p_rdy = os_dly.p_dlnk; + if (p_rdy->p_rlnk != NULL) { + /* Task is really enqueued, remove task from semaphore/mailbox */ + /* timeout waiting list. */ + p_rdy->p_rlnk->p_lnk = p_rdy->p_lnk; + if (p_rdy->p_lnk != NULL) { + p_rdy->p_lnk->p_rlnk = p_rdy->p_rlnk; + p_rdy->p_lnk = NULL; + } + p_rdy->p_rlnk = NULL; + } + rt_put_prio (&os_rdy, p_rdy); + os_dly.delta_time = p_rdy->delta_time; + if (p_rdy->state == WAIT_ITV) { + /* Calculate the next time for interval wait. */ + p_rdy->delta_time = p_rdy->interval_time + (U16)os_time; + } + p_rdy->state = READY; + os_dly.p_dlnk = p_rdy->p_dlnk; + if (p_rdy->p_dlnk != NULL) { + p_rdy->p_dlnk->p_blnk = (P_TCB)&os_dly; + p_rdy->p_dlnk = NULL; + } + p_rdy->p_blnk = NULL; + } +} + + +/*--------------------------- rt_rmv_list -----------------------------------*/ + +void rt_rmv_list (P_TCB p_task) { + /* Remove task identified with "p_task" from ready, semaphore or mailbox */ + /* waiting list if enqueued. */ + P_TCB p_b; + + if (p_task->p_rlnk != NULL) { + /* A task is enqueued in semaphore / mailbox waiting list. */ + p_task->p_rlnk->p_lnk = p_task->p_lnk; + if (p_task->p_lnk != NULL) { + p_task->p_lnk->p_rlnk = p_task->p_rlnk; + } + return; + } + + p_b = (P_TCB)&os_rdy; + while (p_b != NULL) { + /* Search the ready list for task "p_task" */ + if (p_b->p_lnk == p_task) { + p_b->p_lnk = p_task->p_lnk; + return; + } + p_b = p_b->p_lnk; + } +} + + +/*--------------------------- rt_rmv_dly ------------------------------------*/ + +void rt_rmv_dly (P_TCB p_task) { + /* Remove task identified with "p_task" from delay list if enqueued. */ + P_TCB p_b; + + p_b = p_task->p_blnk; + if (p_b != NULL) { + /* Task is really enqueued */ + p_b->p_dlnk = p_task->p_dlnk; + if (p_task->p_dlnk != NULL) { + /* 'p_task' is in the middle of list */ + p_b->delta_time += p_task->delta_time; + p_task->p_dlnk->p_blnk = p_b; + p_task->p_dlnk = NULL; + } + else { + /* 'p_task' is at the end of list */ + p_b->delta_time = 0U; + } + p_task->p_blnk = NULL; + } +} + + +/*--------------------------- rt_psq_enq ------------------------------------*/ + +void rt_psq_enq (OS_ID entry, U32 arg) { + /* Insert post service request "entry" into ps-queue. */ + U32 idx; + + idx = rt_inc_qi (os_psq->size, &os_psq->count, &os_psq->first); + if (idx < os_psq->size) { + os_psq->q[idx].id = entry; + os_psq->q[idx].arg = arg; + } + else { + os_error (OS_ERR_FIFO_OVF); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_List.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,72 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_LIST.H + * Purpose: Functions for the management of different lists + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Definitions */ + +/* Values for 'cb_type' */ +#define TCB 0U +#define MCB 1U +#define SCB 2U +#define MUCB 3U +#define HCB 4U + +/* Variables */ +extern struct OS_XCB os_rdy; +extern struct OS_XCB os_dly; + +/* Functions */ +extern void rt_put_prio (P_XCB p_CB, P_TCB p_task); +extern P_TCB rt_get_first (P_XCB p_CB); +extern void rt_put_rdy_first (P_TCB p_task); +extern P_TCB rt_get_same_rdy_prio (void); +extern void rt_resort_prio (P_TCB p_task); +extern void rt_put_dly (P_TCB p_task, U16 delay); +extern void rt_dec_dly (void); +extern void rt_rmv_list (P_TCB p_task); +extern void rt_rmv_dly (P_TCB p_task); +extern void rt_psq_enq (OS_ID entry, U32 arg); + +/* This is a fast macro generating in-line code */ +#define rt_rdy_prio(void) (os_rdy.p_lnk->prio) + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Mailbox.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,293 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MAILBOX.C + * Purpose: Implements waits and wake-ups for mailbox messages + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Mailbox.h" +#include "rt_MemBox.h" +#include "rt_Task.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_mbx_init -----------------------------------*/ + +void rt_mbx_init (OS_ID mailbox, U16 mbx_size) { + /* Initialize a mailbox */ + P_MCB p_MCB = mailbox; + + p_MCB->cb_type = MCB; + p_MCB->state = 0U; + p_MCB->isr_st = 0U; + p_MCB->p_lnk = NULL; + p_MCB->first = 0U; + p_MCB->last = 0U; + p_MCB->count = 0U; + p_MCB->size = (U16)((mbx_size - (sizeof(struct OS_MCB) - (sizeof(void *)))) + / sizeof(void *)); +} + + +/*--------------------------- rt_mbx_send -----------------------------------*/ + +OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout) { + /* Send message to a mailbox */ + P_MCB p_MCB = mailbox; + P_TCB p_TCB; + + if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 1U)) { + /* A task is waiting for message */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val2(p_TCB, 0x10U/*osEventMessage*/, (U32)p_msg); +#else + *p_TCB->msg = p_msg; + rt_ret_val (p_TCB, OS_R_MBX); +#endif + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + /* Store message in mailbox queue */ + if (p_MCB->count == p_MCB->size) { + /* No free message entry, wait for one. If message queue is full, */ + /* then no task is waiting for message. The 'p_MCB->p_lnk' list */ + /* pointer can now be reused for send message waits task list. */ + if (timeout == 0U) { + return (OS_R_TMO); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + /* Task is waiting to send a message */ + p_MCB->state = 2U; + } + os_tsk.run->msg = p_msg; + rt_block (timeout, WAIT_MBX); + return (OS_R_TMO); + } + /* Yes, there is a free entry in a mailbox. */ + p_MCB->msg[p_MCB->first] = p_msg; + rt_inc (&p_MCB->count); + if (++p_MCB->first == p_MCB->size) { + p_MCB->first = 0U; + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mbx_wait -----------------------------------*/ + +OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout) { + /* Receive a message; possibly wait for it */ + P_MCB p_MCB = mailbox; + P_TCB p_TCB; + + /* If a message is available in the fifo buffer */ + /* remove it from the fifo buffer and return. */ + if (p_MCB->count) { + *message = p_MCB->msg[p_MCB->last]; + if (++p_MCB->last == p_MCB->size) { + p_MCB->last = 0U; + } + if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 2U)) { + /* A task is waiting to send message */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0U/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_OK); +#endif + p_MCB->msg[p_MCB->first] = p_TCB->msg; + if (++p_MCB->first == p_MCB->size) { + p_MCB->first = 0U; + } + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + rt_dec (&p_MCB->count); + } + return (OS_R_OK); + } + /* No message available: wait for one */ + if (timeout == 0U) { + return (OS_R_TMO); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + /* Task is waiting to receive a message */ + p_MCB->state = 1U; + } + rt_block(timeout, WAIT_MBX); +#ifndef __CMSIS_RTOS + os_tsk.run->msg = message; +#endif + return (OS_R_TMO); +} + + +/*--------------------------- rt_mbx_check ----------------------------------*/ + +OS_RESULT rt_mbx_check (OS_ID mailbox) { + /* Check for free space in a mailbox. Returns the number of messages */ + /* that can be stored to a mailbox. It returns 0 when mailbox is full. */ + P_MCB p_MCB = mailbox; + + return ((U32)(p_MCB->size - p_MCB->count)); +} + + +/*--------------------------- isr_mbx_send ----------------------------------*/ + +void isr_mbx_send (OS_ID mailbox, void *p_msg) { + /* Same function as "os_mbx_send", but to be called by ISRs. */ + P_MCB p_MCB = mailbox; + + rt_psq_enq (p_MCB, (U32)p_msg); + rt_psh_req (); +} + + +/*--------------------------- isr_mbx_receive -------------------------------*/ + +OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message) { + /* Receive a message in the interrupt function. The interrupt function */ + /* should not wait for a message since this would block the rtx os. */ + P_MCB p_MCB = mailbox; + + if (p_MCB->count) { + /* A message is available in the fifo buffer. */ + *message = p_MCB->msg[p_MCB->last]; + if (p_MCB->state == 2U) { + /* A task is locked waiting to send message */ + rt_psq_enq (p_MCB, 0U); + rt_psh_req (); + } + rt_dec (&p_MCB->count); + if (++p_MCB->last == p_MCB->size) { + p_MCB->last = 0U; + } + return (OS_R_MBX); + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mbx_psh ------------------------------------*/ + +void rt_mbx_psh (P_MCB p_CB, void *p_msg) { + /* Store the message to the mailbox queue or pass it to task directly. */ + P_TCB p_TCB; + void *mem; + + if (p_CB->p_lnk != NULL) switch (p_CB->state) { +#ifdef __CMSIS_RTOS + case 3: + /* Task is waiting to allocate memory, remove it from the waiting list */ + mem = rt_alloc_box(p_msg); + if (mem == NULL) { break; } + p_TCB = rt_get_first ((P_XCB)p_CB); + rt_ret_val(p_TCB, (U32)mem); + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; +#endif + case 2: + /* Task is waiting to send a message, remove it from the waiting list */ + p_TCB = rt_get_first ((P_XCB)p_CB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0U/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_OK); +#endif + p_CB->msg[p_CB->first] = p_TCB->msg; + rt_inc (&p_CB->count); + if (++p_CB->first == p_CB->size) { + p_CB->first = 0U; + } + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; + case 1: + /* Task is waiting for a message, pass the message to the task directly */ + p_TCB = rt_get_first ((P_XCB)p_CB); +#ifdef __CMSIS_RTOS + rt_ret_val2(p_TCB, 0x10U/*osEventMessage*/, (U32)p_msg); +#else + *p_TCB->msg = p_msg; + rt_ret_val (p_TCB, OS_R_MBX); +#endif + p_TCB->state = READY; + rt_rmv_dly (p_TCB); + rt_put_prio (&os_rdy, p_TCB); + break; + default: + break; + } else { + /* No task is waiting for a message, store it to the mailbox queue */ + if (p_CB->count < p_CB->size) { + p_CB->msg[p_CB->first] = p_msg; + rt_inc (&p_CB->count); + if (++p_CB->first == p_CB->size) { + p_CB->first = 0U; + } + } + else { + os_error (OS_ERR_MBX_OVF); + } + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Mailbox.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,53 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MAILBOX.H + * Purpose: Implements waits and wake-ups for mailbox messages + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_mbx_init (OS_ID mailbox, U16 mbx_size); +extern OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout); +extern OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout); +extern OS_RESULT rt_mbx_check (OS_ID mailbox); +extern void isr_mbx_send (OS_ID mailbox, void *p_msg); +extern OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message); +extern void rt_mbx_psh (P_MCB p_CB, void *p_msg); + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_MemBox.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,168 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMBOX.C + * Purpose: Interface functions for fixed memory block management system + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_MemBox.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- _init_box -------------------------------------*/ + +U32 _init_box (void *box_mem, U32 box_size, U32 blk_size) { + /* Initialize memory block system, returns 0 if OK, 1 if fails. */ + void *end; + void *blk; + void *next; + U32 sizeof_bm; + + /* Create memory structure. */ + if (blk_size & BOX_ALIGN_8) { + /* Memory blocks 8-byte aligned. */ + blk_size = ((blk_size & ~BOX_ALIGN_8) + 7U) & ~(U32)7U; + sizeof_bm = (sizeof (struct OS_BM) + 7U) & ~(U32)7U; + } + else { + /* Memory blocks 4-byte aligned. */ + blk_size = (blk_size + 3U) & ~(U32)3U; + sizeof_bm = sizeof (struct OS_BM); + } + if (blk_size == 0U) { + return (1U); + } + if ((blk_size + sizeof_bm) > box_size) { + return (1U); + } + /* Create a Memory structure. */ + blk = ((U8 *) box_mem) + sizeof_bm; + ((P_BM) box_mem)->free = blk; + end = ((U8 *) box_mem) + box_size; + ((P_BM) box_mem)->end = end; + ((P_BM) box_mem)->blk_size = blk_size; + + /* Link all free blocks using offsets. */ + end = ((U8 *) end) - blk_size; + while (1) { + next = ((U8 *) blk) + blk_size; + if (next > end) { break; } + *((void **)blk) = next; + blk = next; + } + /* end marker */ + *((void **)blk) = 0U; + return (0U); +} + +/*--------------------------- rt_alloc_box ----------------------------------*/ + +void *rt_alloc_box (void *box_mem) { + /* Allocate a memory block and return start address. */ + void **free; +#ifndef __USE_EXCLUSIVE_ACCESS + U32 irq_mask; + + irq_mask = (U32)__disable_irq (); + free = ((P_BM) box_mem)->free; + if (free) { + ((P_BM) box_mem)->free = *free; + } + if (irq_mask == 0U) { __enable_irq (); } +#else + do { + if ((free = (void **)__ldrex(&((P_BM) box_mem)->free)) == 0U) { + __clrex(); + break; + } + } while (__strex((U32)*free, &((P_BM) box_mem)->free)); +#endif + return (free); +} + + +/*--------------------------- _calloc_box -----------------------------------*/ + +void *_calloc_box (void *box_mem) { + /* Allocate a 0-initialized memory block and return start address. */ + void *free; + U32 *p; + U32 i; + + free = _alloc_box (box_mem); + if (free) { + p = free; + for (i = ((P_BM) box_mem)->blk_size; i; i -= 4U) { + *p = 0U; + p++; + } + } + return (free); +} + + +/*--------------------------- rt_free_box -----------------------------------*/ + +U32 rt_free_box (void *box_mem, void *box) { + /* Free a memory block, returns 0 if OK, 1 if box does not belong to box_mem */ +#ifndef __USE_EXCLUSIVE_ACCESS + U32 irq_mask; +#endif + + if ((box < box_mem) || (box >= ((P_BM) box_mem)->end)) { + return (1U); + } + +#ifndef __USE_EXCLUSIVE_ACCESS + irq_mask = (U32)__disable_irq (); + *((void **)box) = ((P_BM) box_mem)->free; + ((P_BM) box_mem)->free = box; + if (irq_mask == 0U) { __enable_irq (); } +#else + do { + do { + *((void **)box) = ((P_BM) box_mem)->free; + __DMB(); + } while (*(void**)box != (void *)__ldrex(&((P_BM) box_mem)->free)); + } while (__strex ((U32)box, &((P_BM) box_mem)->free)); +#endif + return (0U); +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_MemBox.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,50 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMBOX.H + * Purpose: Interface functions for fixed memory block management system + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +#define rt_init_box _init_box +#define rt_calloc_box _calloc_box +extern U32 _init_box (void *box_mem, U32 box_size, U32 blk_size); +extern void *rt_alloc_box (void *box_mem); +extern void * _calloc_box (void *box_mem); +extern U32 rt_free_box (void *box_mem, void *box); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Memory.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,140 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMORY.C + * Purpose: Interface functions for Dynamic Memory Management System + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "rt_Memory.h" + + +/* Functions */ + +// Initialize Dynamic Memory pool +// Parameters: +// pool: Pointer to memory pool +// size: Size of memory pool in bytes +// Return: 0 - OK, 1 - Error + +U32 rt_init_mem (void *pool, U32 size) { + MEMP *ptr; + + if ((pool == NULL) || (size < sizeof(MEMP))) { return (1U); } + + ptr = (MEMP *)pool; + ptr->next = (MEMP *)((U32)pool + size - sizeof(MEMP *)); + ptr->next->next = NULL; + ptr->len = 0U; + + return (0U); +} + +// Allocate Memory from Memory pool +// Parameters: +// pool: Pointer to memory pool +// size: Size of memory in bytes to allocate +// Return: Pointer to allocated memory + +void *rt_alloc_mem (void *pool, U32 size) { + MEMP *p, *p_search, *p_new; + U32 hole_size; + + if ((pool == NULL) || (size == 0U)) { return NULL; } + + /* Add header offset to 'size' */ + size += sizeof(MEMP); + /* Make sure that block is 4-byte aligned */ + size = (size + 3U) & ~(U32)3U; + + p_search = (MEMP *)pool; + while (1) { + hole_size = (U32)p_search->next - (U32)p_search; + hole_size -= p_search->len; + /* Check if hole size is big enough */ + if (hole_size >= size) { break; } + p_search = p_search->next; + if (p_search->next == NULL) { + /* Failed, we are at the end of the list */ + return NULL; + } + } + + if (p_search->len == 0U) { + /* No block is allocated, set the Length of the first element */ + p_search->len = size; + p = (MEMP *)(((U32)p_search) + sizeof(MEMP)); + } else { + /* Insert new list element into the memory list */ + p_new = (MEMP *)((U32)p_search + p_search->len); + p_new->next = p_search->next; + p_new->len = size; + p_search->next = p_new; + p = (MEMP *)(((U32)p_new) + sizeof(MEMP)); + } + + return (p); +} + +// Free Memory and return it to Memory pool +// Parameters: +// pool: Pointer to memory pool +// mem: Pointer to memory to free +// Return: 0 - OK, 1 - Error + +U32 rt_free_mem (void *pool, void *mem) { + MEMP *p_search, *p_prev, *p_return; + + if ((pool == NULL) || (mem == NULL)) { return (1U); } + + p_return = (MEMP *)((U32)mem - sizeof(MEMP)); + + /* Set list header */ + p_prev = NULL; + p_search = (MEMP *)pool; + while (p_search != p_return) { + p_prev = p_search; + p_search = p_search->next; + if (p_search == NULL) { + /* Valid Memory block not found */ + return (1U); + } + } + + if (p_prev == NULL) { + /* First block to be released, only set length to 0 */ + p_search->len = 0U; + } else { + /* Discard block from chain list */ + p_prev->next = p_search->next; + } + + return (0U); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Memory.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,49 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MEMORY.H + * Purpose: Interface functions for Dynamic Memory Management System + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Types */ +typedef struct mem { /* << Memory Pool management struct >> */ + struct mem *next; /* Next Memory Block in the list */ + U32 len; /* Length of data block */ +} MEMP; + +/* Functions */ +extern U32 rt_init_mem (void *pool, U32 size); +extern void *rt_alloc_mem (void *pool, U32 size); +extern U32 rt_free_mem (void *pool, void *mem); + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Mutex.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,259 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MUTEX.C + * Purpose: Implements mutex synchronization objects + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Mutex.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_mut_init -----------------------------------*/ + +void rt_mut_init (OS_ID mutex) { + /* Initialize a mutex object */ + P_MUCB p_MCB = mutex; + + p_MCB->cb_type = MUCB; + p_MCB->level = 0U; + p_MCB->p_lnk = NULL; + p_MCB->owner = NULL; + p_MCB->p_mlnk = NULL; +} + + +/*--------------------------- rt_mut_delete ---------------------------------*/ + +#ifdef __CMSIS_RTOS +OS_RESULT rt_mut_delete (OS_ID mutex) { + /* Delete a mutex object */ + P_MUCB p_MCB = mutex; + P_TCB p_TCB; + P_MUCB p_mlnk; + U8 prio; + + if (p_MCB->level != 0U) { + + p_TCB = p_MCB->owner; + + /* Remove mutex from task mutex owner list. */ + p_mlnk = p_TCB->p_mlnk; + if (p_mlnk == p_MCB) { + p_TCB->p_mlnk = p_MCB->p_mlnk; + } + else { + while (p_mlnk) { + if (p_mlnk->p_mlnk == p_MCB) { + p_mlnk->p_mlnk = p_MCB->p_mlnk; + break; + } + p_mlnk = p_mlnk->p_mlnk; + } + } + + /* Restore owner task's priority. */ + prio = p_TCB->prio_base; + p_mlnk = p_TCB->p_mlnk; + while (p_mlnk) { + if ((p_mlnk->p_lnk != NULL) && (p_mlnk->p_lnk->prio > prio)) { + /* A task with higher priority is waiting for mutex. */ + prio = p_mlnk->p_lnk->prio; + } + p_mlnk = p_mlnk->p_mlnk; + } + if (p_TCB->prio != prio) { + p_TCB->prio = prio; + if (p_TCB != os_tsk.run) { + rt_resort_prio (p_TCB); + } + } + + } + + while (p_MCB->p_lnk != NULL) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); + rt_ret_val(p_TCB, 0U/*osOK*/); + rt_rmv_dly(p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + } + + if ((os_rdy.p_lnk != NULL) && (os_rdy.p_lnk->prio > os_tsk.run->prio)) { + /* preempt running task */ + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + + p_MCB->cb_type = 0U; + + return (OS_R_OK); +} +#endif + + +/*--------------------------- rt_mut_release --------------------------------*/ + +OS_RESULT rt_mut_release (OS_ID mutex) { + /* Release a mutex object */ + P_MUCB p_MCB = mutex; + P_TCB p_TCB; + P_MUCB p_mlnk; + U8 prio; + + if ((p_MCB->level == 0U) || (p_MCB->owner != os_tsk.run)) { + /* Unbalanced mutex release or task is not the owner */ + return (OS_R_NOK); + } + if (--p_MCB->level != 0U) { + return (OS_R_OK); + } + + /* Remove mutex from task mutex owner list. */ + p_mlnk = os_tsk.run->p_mlnk; + if (p_mlnk == p_MCB) { + os_tsk.run->p_mlnk = p_MCB->p_mlnk; + } + else { + while (p_mlnk) { + if (p_mlnk->p_mlnk == p_MCB) { + p_mlnk->p_mlnk = p_MCB->p_mlnk; + break; + } + p_mlnk = p_mlnk->p_mlnk; + } + } + + /* Restore owner task's priority. */ + prio = os_tsk.run->prio_base; + p_mlnk = os_tsk.run->p_mlnk; + while (p_mlnk) { + if ((p_mlnk->p_lnk != NULL) && (p_mlnk->p_lnk->prio > prio)) { + /* A task with higher priority is waiting for mutex. */ + prio = p_mlnk->p_lnk->prio; + } + p_mlnk = p_mlnk->p_mlnk; + } + os_tsk.run->prio = prio; + + if (p_MCB->p_lnk != NULL) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 0U/*osOK*/); +#else + rt_ret_val(p_TCB, OS_R_MUT); +#endif + rt_rmv_dly (p_TCB); + /* A waiting task becomes the owner of this mutex. */ + p_MCB->level = 1U; + p_MCB->owner = p_TCB; + p_MCB->p_mlnk = p_TCB->p_mlnk; + p_TCB->p_mlnk = p_MCB; + /* Priority inversion, check which task continues. */ + if (os_tsk.run->prio >= rt_rdy_prio()) { + rt_dispatch (p_TCB); + } + else { + /* Ready task has higher priority than running task. */ + rt_put_prio (&os_rdy, os_tsk.run); + rt_put_prio (&os_rdy, p_TCB); + os_tsk.run->state = READY; + p_TCB->state = READY; + rt_dispatch (NULL); + } + } + else { + /* Check if own priority lowered by priority inversion. */ + if (rt_rdy_prio() > os_tsk.run->prio) { + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_mut_wait -----------------------------------*/ + +OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout) { + /* Wait for a mutex, continue when mutex is free. */ + P_MUCB p_MCB = mutex; + + if (p_MCB->level == 0U) { + p_MCB->owner = os_tsk.run; + p_MCB->p_mlnk = os_tsk.run->p_mlnk; + os_tsk.run->p_mlnk = p_MCB; + goto inc; + } + if (p_MCB->owner == os_tsk.run) { + /* OK, running task is the owner of this mutex. */ +inc:p_MCB->level++; + return (OS_R_OK); + } + /* Mutex owned by another task, wait until released. */ + if (timeout == 0U) { + return (OS_R_TMO); + } + /* Raise the owner task priority if lower than current priority. */ + /* This priority inversion is called priority inheritance. */ + if (p_MCB->owner->prio < os_tsk.run->prio) { + p_MCB->owner->prio = os_tsk.run->prio; + rt_resort_prio (p_MCB->owner); + } + if (p_MCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_MCB, os_tsk.run); + } + else { + p_MCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_MCB; + } + rt_block(timeout, WAIT_MUT); + return (OS_R_TMO); +} + + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Mutex.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,49 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_MUTEX.H + * Purpose: Implements mutex synchronization objects + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_mut_init (OS_ID mutex); +extern OS_RESULT rt_mut_delete (OS_ID mutex); +extern OS_RESULT rt_mut_release (OS_ID mutex); +extern OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_OsEventObserver.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,61 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: rt_OsEventObserver.c + * Purpose: OS Event Callbacks for CMSIS RTOS + * Rev.: VX.XX + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_OsEventObserver.h" + +/* + * _____ _____ ____ __ _____ + * | ___|_ _\ \/ / \/ | ____| + * | |_ | | \ /| |\/| | _| + * | _| | | / \| | | | |___ + * |_| |___/_/\_\_| |_|_____| + * + * FIXME: + * The osEventObs variable must be in protected memory. If not every box + * and box 0 can modify osEventObs to point to any handler to run code + * privileged. This issue is tracked at + * <https://github.com/ARMmbed/uvisor/issues/235>. + */ +const OsEventObserver *osEventObs; + +void osRegisterForOsEvents(const OsEventObserver *observer) +{ + static uint8_t has_been_called = 0; + if (has_been_called) { + return; + } + has_been_called = 1; + + osEventObs = observer; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_OsEventObserver.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,63 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: os_events.h + * Purpose: OS Event Callbacks for CMSIS RTOS + * Rev.: VX.XX + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2016 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. + *---------------------------------------------------------------------------*/ +#ifndef _RT_OS_EVENT_OBSERVER_H +#define _RT_OS_EVENT_OBSERVER_H + +#include <stdint.h> + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + uint32_t version; + void (*pre_start)(void); + void *(*thread_create)(int thread_id, void *context); + void (*thread_destroy)(void *context); + void (*thread_switch)(void *context); +} OsEventObserver; +extern const OsEventObserver *osEventObs; + +void osRegisterForOsEvents(const OsEventObserver *observer); + +#ifdef __cplusplus +}; +#endif + +#endif + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Robin.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,83 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_ROBIN.C + * Purpose: Round Robin Task switching + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Time.h" +#include "rt_Robin.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +struct OS_ROBIN os_robin; + + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +/*--------------------------- rt_init_robin ---------------------------------*/ + +__weak void rt_init_robin (void) { + /* Initialize Round Robin variables. */ + os_robin.task = NULL; + os_robin.tout = (U16)os_rrobin; +} + +/*--------------------------- rt_chk_robin ----------------------------------*/ + +__weak void rt_chk_robin (void) { + /* Check if Round Robin timeout expired and switch to the next ready task.*/ + P_TCB p_new; + + if (os_robin.task != os_rdy.p_lnk) { + /* New task was suspended, reset Round Robin timeout. */ + os_robin.task = os_rdy.p_lnk; + os_robin.time = (U16)os_time + os_robin.tout - 1U; + } + if (os_robin.time == (U16)os_time) { + /* Round Robin timeout has expired, swap Robin tasks. */ + os_robin.task = NULL; + p_new = rt_get_first (&os_rdy); + rt_put_prio ((P_XCB)&os_rdy, p_new); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Robin.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,50 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_ROBIN.H + * Purpose: Round Robin Task switching definitions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern struct OS_ROBIN os_robin; + +/* Functions */ +extern void rt_init_robin (void); +extern void rt_chk_robin (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Semaphore.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,182 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_SEMAPHORE.C + * Purpose: Implements binary and counting semaphores + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_List.h" +#include "rt_Task.h" +#include "rt_Semaphore.h" +#include "rt_HAL_CM.h" + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_sem_init -----------------------------------*/ + +void rt_sem_init (OS_ID semaphore, U16 token_count) { + /* Initialize a semaphore */ + P_SCB p_SCB = semaphore; + + p_SCB->cb_type = SCB; + p_SCB->p_lnk = NULL; + p_SCB->tokens = token_count; +} + + +/*--------------------------- rt_sem_delete ---------------------------------*/ + +#ifdef __CMSIS_RTOS +OS_RESULT rt_sem_delete (OS_ID semaphore) { + /* Delete semaphore */ + P_SCB p_SCB = semaphore; + P_TCB p_TCB; + + while (p_SCB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_SCB); + rt_ret_val(p_TCB, 0U); + rt_rmv_dly(p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + } + + if ((os_rdy.p_lnk != NULL) && (os_rdy.p_lnk->prio > os_tsk.run->prio)) { + /* preempt running task */ + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + + p_SCB->cb_type = 0U; + + return (OS_R_OK); +} +#endif + + +/*--------------------------- rt_sem_send -----------------------------------*/ + +OS_RESULT rt_sem_send (OS_ID semaphore) { + /* Return a token to semaphore */ + P_SCB p_SCB = semaphore; + P_TCB p_TCB; + + if (p_SCB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_SCB); +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 1U); +#else + rt_ret_val(p_TCB, OS_R_SEM); +#endif + rt_rmv_dly (p_TCB); + rt_dispatch (p_TCB); + } + else { + /* Store token. */ + p_SCB->tokens++; + } + return (OS_R_OK); +} + + +/*--------------------------- rt_sem_wait -----------------------------------*/ + +OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout) { + /* Obtain a token; possibly wait for it */ + P_SCB p_SCB = semaphore; + + if (p_SCB->tokens) { + p_SCB->tokens--; + return (OS_R_OK); + } + /* No token available: wait for one */ + if (timeout == 0U) { + return (OS_R_TMO); + } + if (p_SCB->p_lnk != NULL) { + rt_put_prio ((P_XCB)p_SCB, os_tsk.run); + } + else { + p_SCB->p_lnk = os_tsk.run; + os_tsk.run->p_lnk = NULL; + os_tsk.run->p_rlnk = (P_TCB)p_SCB; + } + rt_block(timeout, WAIT_SEM); + return (OS_R_TMO); +} + + +/*--------------------------- isr_sem_send ----------------------------------*/ + +void isr_sem_send (OS_ID semaphore) { + /* Same function as "os_sem_send", but to be called by ISRs */ + P_SCB p_SCB = semaphore; + + rt_psq_enq (p_SCB, 0U); + rt_psh_req (); +} + + +/*--------------------------- rt_sem_psh ------------------------------------*/ + +void rt_sem_psh (P_SCB p_CB) { + /* Check if task has to be waken up */ + P_TCB p_TCB; + + if (p_CB->p_lnk != NULL) { + /* A task is waiting for token */ + p_TCB = rt_get_first ((P_XCB)p_CB); + rt_rmv_dly (p_TCB); + p_TCB->state = READY; +#ifdef __CMSIS_RTOS + rt_ret_val(p_TCB, 1U); +#else + rt_ret_val(p_TCB, OS_R_SEM); +#endif + rt_put_prio (&os_rdy, p_TCB); + } + else { + /* Store token */ + p_CB->tokens++; + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Semaphore.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,51 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_SEMAPHORE.H + * Purpose: Implements binary and counting semaphores + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Functions */ +extern void rt_sem_init (OS_ID semaphore, U16 token_count); +extern OS_RESULT rt_sem_delete(OS_ID semaphore); +extern OS_RESULT rt_sem_send (OS_ID semaphore); +extern OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout); +extern void isr_sem_send (OS_ID semaphore); +extern void rt_sem_psh (P_SCB p_CB); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_System.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,337 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_SYSTEM.C + * Purpose: System Task Manager + * Rev.: V4.80 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_Task.h" +#include "rt_System.h" +#include "rt_Event.h" +#include "rt_List.h" +#include "rt_Mailbox.h" +#include "rt_Semaphore.h" +#include "rt_Time.h" +#include "rt_Timer.h" +#include "rt_Robin.h" +#include "rt_HAL_CM.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +S32 os_tick_irqn; + +/*---------------------------------------------------------------------------- + * Local Variables + *---------------------------------------------------------------------------*/ + +static volatile BIT os_lock; +static volatile BIT os_psh_flag; +static U8 pend_flags; + +/*---------------------------------------------------------------------------- + * Global Functions + *---------------------------------------------------------------------------*/ + +#define RL_RTX_VER 0x480 + +#if defined (__CC_ARM) +__asm void $$RTX$$version (void) { + /* Export a version number symbol for a version control. */ + + EXPORT __RL_RTX_VER + +__RL_RTX_VER EQU RL_RTX_VER +} +#endif + + +/*--------------------------- rt_suspend ------------------------------------*/ + +extern U32 sysUserTimerWakeupTime(void); + +U32 rt_suspend (void) { + /* Suspend OS scheduler */ + U32 delta = 0xFFFFU; +#ifdef __CMSIS_RTOS + U32 sleep; +#endif + + rt_tsk_lock(); + + if (os_dly.p_dlnk) { + delta = os_dly.delta_time; + } +#ifdef __CMSIS_RTOS + sleep = sysUserTimerWakeupTime(); + if (sleep < delta) { delta = sleep; } +#else + if (os_tmr.next) { + if (os_tmr.tcnt < delta) delta = os_tmr.tcnt; + } +#endif + + return (delta); +} + + +/*--------------------------- rt_resume -------------------------------------*/ + +extern void sysUserTimerUpdate (U32 sleep_time); + +void rt_resume (U32 sleep_time) { + /* Resume OS scheduler after suspend */ + P_TCB next; + U32 delta; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + os_robin.task = NULL; + + /* Update delays. */ + if (os_dly.p_dlnk) { + delta = sleep_time; + if (delta >= os_dly.delta_time) { + delta -= os_dly.delta_time; + os_time += os_dly.delta_time; + os_dly.delta_time = 1U; + while (os_dly.p_dlnk) { + rt_dec_dly(); + if (delta == 0U) { break; } + delta--; + os_time++; + } + } else { + os_time += delta; + os_dly.delta_time -= (U16)delta; + } + } else { + os_time += sleep_time; + } + + /* Check the user timers. */ +#ifdef __CMSIS_RTOS + sysUserTimerUpdate(sleep_time); +#else + if (os_tmr.next) { + delta = sleep_time; + if (delta >= os_tmr.tcnt) { + delta -= os_tmr.tcnt; + os_tmr.tcnt = 1U; + while (os_tmr.next) { + rt_tmr_tick(); + if (delta == 0U) { break; } + delta--; + } + } else { + os_tmr.tcnt -= delta; + } + } +#endif + + /* Switch back to highest ready task */ + next = rt_get_first (&os_rdy); + rt_switch_req (next); + + rt_tsk_unlock(); +} + + +/*--------------------------- rt_tsk_lock -----------------------------------*/ + +void rt_tsk_lock (void) { + /* Prevent task switching by locking out scheduler */ + if (os_tick_irqn < 0) { + OS_LOCK(); + os_lock = __TRUE; + OS_UNPEND(pend_flags); + } else { + OS_X_LOCK((U32)os_tick_irqn); + os_lock = __TRUE; + OS_X_UNPEND(pend_flags); + } +} + + +/*--------------------------- rt_tsk_unlock ---------------------------------*/ + +void rt_tsk_unlock (void) { + /* Unlock scheduler and re-enable task switching */ + if (os_tick_irqn < 0) { + OS_UNLOCK(); + os_lock = __FALSE; + OS_PEND(pend_flags, os_psh_flag); + os_psh_flag = __FALSE; + } else { + OS_X_UNLOCK((U32)os_tick_irqn); + os_lock = __FALSE; + OS_X_PEND(pend_flags, os_psh_flag); + os_psh_flag = __FALSE; + } +} + + +/*--------------------------- rt_psh_req ------------------------------------*/ + +void rt_psh_req (void) { + /* Initiate a post service handling request if required. */ + if (os_lock == __FALSE) { + OS_PEND_IRQ(); + } + else { + os_psh_flag = __TRUE; + } +} + + +/*--------------------------- rt_pop_req ------------------------------------*/ + +void rt_pop_req (void) { + /* Process an ISR post service requests. */ + struct OS_XCB *p_CB; + P_TCB next; + U32 idx; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + idx = os_psq->last; + while (os_psq->count) { + p_CB = os_psq->q[idx].id; + if (p_CB->cb_type == TCB) { + /* Is of TCB type */ + rt_evt_psh ((P_TCB)p_CB, (U16)os_psq->q[idx].arg); + } + else if (p_CB->cb_type == MCB) { + /* Is of MCB type */ + rt_mbx_psh ((P_MCB)p_CB, (void *)os_psq->q[idx].arg); + } + else { + /* Must be of SCB type */ + rt_sem_psh ((P_SCB)p_CB); + } + if (++idx == os_psq->size) { idx = 0U; } + rt_dec (&os_psq->count); + } + os_psq->last = (U8)idx; + + next = rt_get_first (&os_rdy); + rt_switch_req (next); +} + + +/*--------------------------- os_tick_init ----------------------------------*/ + +__weak S32 os_tick_init (void) { + /* Initialize SysTick timer as system tick timer. */ + rt_systick_init(); + return (-1); /* Return IRQ number of SysTick timer */ +} + +/*--------------------------- os_tick_val -----------------------------------*/ + +__weak U32 os_tick_val (void) { + /* Get SysTick timer current value (0 .. OS_TRV). */ + return rt_systick_val(); +} + +/*--------------------------- os_tick_ovf -----------------------------------*/ + +__weak U32 os_tick_ovf (void) { + /* Get SysTick timer overflow flag */ + return rt_systick_ovf(); +} + +/*--------------------------- os_tick_irqack --------------------------------*/ + +__weak void os_tick_irqack (void) { + /* Acknowledge timer interrupt. */ +} + + +/*--------------------------- rt_systick ------------------------------------*/ + +extern void sysTimerTick(void); + +void rt_systick (void) { + /* Check for system clock update, suspend running task. */ + P_TCB next; + + os_tsk.run->state = READY; + rt_put_rdy_first (os_tsk.run); + + /* Check Round Robin timeout. */ + rt_chk_robin (); + + /* Update delays. */ + os_time++; + rt_dec_dly (); + + /* Check the user timers. */ +#ifdef __CMSIS_RTOS + sysTimerTick(); +#else + rt_tmr_tick (); +#endif + + /* Switch back to highest ready task */ + next = rt_get_first (&os_rdy); + rt_switch_req (next); +} + +/*--------------------------- rt_stk_check ----------------------------------*/ + +__weak void rt_stk_check (void) { +#ifdef __MBED_CMSIS_RTOS_CM + /* Check for stack overflow. */ + if (os_tsk.run->task_id == MAIN_THREAD_ID) { + // TODO: For the main thread the check should be done against the main heap pointer + } else { + if ((os_tsk.run->tsk_stack < (U32)os_tsk.run->stack) || + (os_tsk.run->stack[0] != MAGIC_WORD)) { + os_error (OS_ERR_STK_OVF); + } + } +#else + if ((os_tsk.run->tsk_stack < (U32)os_tsk.run->stack) || + (os_tsk.run->stack[0] != MAGIC_WORD)) { + os_error (OS_ERR_STK_OVF); + } +#endif +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_System.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,57 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_SYSTEM.H + * Purpose: System Task Manager definitions + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Variables */ +#define os_psq ((P_PSQ)&os_fifo) +extern S32 os_tick_irqn; + +/* Functions */ +extern U32 rt_suspend (void); +extern void rt_resume (U32 sleep_time); +extern void rt_tsk_lock (void); +extern void rt_tsk_unlock (void); +extern void rt_psh_req (void); +extern void rt_pop_req (void); +extern void rt_systick (void); +extern void rt_stk_check (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Task.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,456 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TASK.C + * Purpose: Task functions and system start up. + * Rev.: V4.80 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_System.h" +#include "rt_Task.h" +#include "rt_List.h" +#include "rt_MemBox.h" +#include "rt_Robin.h" +#include "rt_HAL_CM.h" +#include "rt_OsEventObserver.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* Running and next task info. */ +struct OS_TSK os_tsk; + +/* Task Control Blocks of idle demon */ +struct OS_TCB os_idle_TCB; + + +/*---------------------------------------------------------------------------- + * Local Functions + *---------------------------------------------------------------------------*/ + +static OS_TID rt_get_TID (void) { + U32 tid; + + for (tid = 1U; tid <= os_maxtaskrun; tid++) { + if (os_active_TCB[tid-1U] == NULL) { + return ((OS_TID)tid); + } + } + return (0U); +} + + +/*--------------------------- rt_init_context -------------------------------*/ + +static void rt_init_context (P_TCB p_TCB, U8 priority, FUNCP task_body) { + /* Initialize general part of the Task Control Block. */ + p_TCB->cb_type = TCB; + p_TCB->state = READY; + p_TCB->prio = priority; + p_TCB->prio_base = priority; + p_TCB->p_lnk = NULL; + p_TCB->p_rlnk = NULL; + p_TCB->p_dlnk = NULL; + p_TCB->p_blnk = NULL; + p_TCB->p_mlnk = NULL; + p_TCB->delta_time = 0U; + p_TCB->interval_time = 0U; + p_TCB->events = 0U; + p_TCB->waits = 0U; + p_TCB->stack_frame = 0U; + + if (p_TCB->priv_stack == 0U) { + /* Allocate the memory space for the stack. */ + p_TCB->stack = rt_alloc_box (mp_stk); + } + rt_init_stack (p_TCB, task_body); +} + + +/*--------------------------- rt_switch_req ---------------------------------*/ + +void rt_switch_req (P_TCB p_new) { + /* Switch to next task (identified by "p_new"). */ + os_tsk.new_tsk = p_new; + p_new->state = RUNNING; + if (osEventObs && osEventObs->thread_switch) { + osEventObs->thread_switch(p_new->context); + } + DBG_TASK_SWITCH(p_new->task_id); +} + + +/*--------------------------- rt_dispatch -----------------------------------*/ + +void rt_dispatch (P_TCB next_TCB) { + /* Dispatch next task if any identified or dispatch highest ready task */ + /* "next_TCB" identifies a task to run or has value NULL (=no next task) */ + if (next_TCB == NULL) { + /* Running task was blocked: continue with highest ready task */ + next_TCB = rt_get_first (&os_rdy); + rt_switch_req (next_TCB); + } + else { + /* Check which task continues */ + if (next_TCB->prio > os_tsk.run->prio) { + /* preempt running task */ + rt_put_rdy_first (os_tsk.run); + os_tsk.run->state = READY; + rt_switch_req (next_TCB); + } + else { + /* put next task into ready list, no task switch takes place */ + next_TCB->state = READY; + rt_put_prio (&os_rdy, next_TCB); + } + } +} + + +/*--------------------------- rt_block --------------------------------------*/ + +void rt_block (U16 timeout, U8 block_state) { + /* Block running task and choose next ready task. */ + /* "timeout" sets a time-out value or is 0xffff (=no time-out). */ + /* "block_state" defines the appropriate task state */ + P_TCB next_TCB; + + if (timeout) { + if (timeout < 0xFFFFU) { + rt_put_dly (os_tsk.run, timeout); + } + os_tsk.run->state = block_state; + next_TCB = rt_get_first (&os_rdy); + rt_switch_req (next_TCB); + } +} + + +/*--------------------------- rt_tsk_pass -----------------------------------*/ + +void rt_tsk_pass (void) { + /* Allow tasks of same priority level to run cooperatively.*/ + P_TCB p_new; + + p_new = rt_get_same_rdy_prio(); + if (p_new != NULL) { + rt_put_prio ((P_XCB)&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_switch_req (p_new); + } +} + + +/*--------------------------- rt_tsk_self -----------------------------------*/ + +OS_TID rt_tsk_self (void) { + /* Return own task identifier value. */ + if (os_tsk.run == NULL) { + return (0U); + } + return ((OS_TID)os_tsk.run->task_id); +} + + +/*--------------------------- rt_tsk_prio -----------------------------------*/ + +OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio) { + /* Change execution priority of a task to "new_prio". */ + P_TCB p_task; + + if (task_id == 0U) { + /* Change execution priority of calling task. */ + os_tsk.run->prio = new_prio; + os_tsk.run->prio_base = new_prio; +run:if (rt_rdy_prio() > new_prio) { + rt_put_prio (&os_rdy, os_tsk.run); + os_tsk.run->state = READY; + rt_dispatch (NULL); + } + return (OS_R_OK); + } + + /* Find the task in the "os_active_TCB" array. */ + if ((task_id > os_maxtaskrun) || (os_active_TCB[task_id-1U] == NULL)) { + /* Task with "task_id" not found or not started. */ + return (OS_R_NOK); + } + p_task = os_active_TCB[task_id-1U]; + p_task->prio = new_prio; + p_task->prio_base = new_prio; + if (p_task == os_tsk.run) { + goto run; + } + rt_resort_prio (p_task); + if (p_task->state == READY) { + /* Task enqueued in a ready list. */ + p_task = rt_get_first (&os_rdy); + rt_dispatch (p_task); + } + return (OS_R_OK); +} + + +/*--------------------------- rt_tsk_create ---------------------------------*/ + +OS_TID rt_tsk_create (FUNCP task, U32 prio_stksz, void *stk, void *argv) { + /* Start a new task declared with "task". */ + P_TCB task_context; + U32 i; + + /* Priority 0 is reserved for idle task! */ + if ((prio_stksz & 0xFFU) == 0U) { + prio_stksz += 1U; + } + task_context = rt_alloc_box (mp_tcb); + if (task_context == NULL) { + return (0U); + } + /* If "size != 0" use a private user provided stack. */ + task_context->stack = stk; + task_context->priv_stack = prio_stksz >> 8; + + /* Find a free entry in 'os_active_TCB' table. */ + i = rt_get_TID (); + if (i == 0U) { + return (0U); + } + task_context->task_id = (U8)i; + /* Pass parameter 'argv' to 'rt_init_context' */ + task_context->msg = argv; + task_context->argv = argv; + /* For 'size == 0' system allocates the user stack from the memory pool. */ + rt_init_context (task_context, (U8)(prio_stksz & 0xFFU), task); + + os_active_TCB[i-1U] = task_context; + DBG_TASK_NOTIFY(task_context, __TRUE); + rt_dispatch (task_context); + return ((OS_TID)i); +} + + +/*--------------------------- rt_tsk_delete ---------------------------------*/ + +OS_RESULT rt_tsk_delete (OS_TID task_id) { + /* Terminate the task identified with "task_id". */ + P_TCB task_context; + P_TCB p_TCB; + P_MUCB p_MCB, p_MCB0; + + if ((task_id == 0U) || (task_id == os_tsk.run->task_id)) { + /* Terminate itself. */ + os_tsk.run->state = INACTIVE; + os_tsk.run->tsk_stack = rt_get_PSP (); + rt_stk_check (); + p_MCB = os_tsk.run->p_mlnk; + while (p_MCB) { + /* Release mutexes owned by this task */ + if (p_MCB->p_lnk) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val (p_TCB, 0U/*osOK*/); +#else + rt_ret_val (p_TCB, OS_R_MUT); +#endif + rt_rmv_dly (p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + /* A waiting task becomes the owner of this mutex. */ + p_MCB0 = p_MCB->p_mlnk; + p_MCB->level = 1U; + p_MCB->owner = p_TCB; + p_MCB->p_mlnk = p_TCB->p_mlnk; + p_TCB->p_mlnk = p_MCB; + p_MCB = p_MCB0; + } + else { + p_MCB0 = p_MCB->p_mlnk; + p_MCB->level = 0U; + p_MCB->owner = NULL; + p_MCB->p_mlnk = NULL; + p_MCB = p_MCB0; + } + } + os_active_TCB[os_tsk.run->task_id-1U] = NULL; + rt_free_box (mp_stk, os_tsk.run->stack); + os_tsk.run->stack = NULL; + DBG_TASK_NOTIFY(os_tsk.run, __FALSE); + rt_free_box (mp_tcb, os_tsk.run); + os_tsk.run = NULL; + rt_dispatch (NULL); + /* The program should never come to this point. */ + } + else { + /* Find the task in the "os_active_TCB" array. */ + if ((task_id > os_maxtaskrun) || (os_active_TCB[task_id-1U] == NULL)) { + /* Task with "task_id" not found or not started. */ + return (OS_R_NOK); + } + task_context = os_active_TCB[task_id-1U]; + rt_rmv_list (task_context); + rt_rmv_dly (task_context); + p_MCB = task_context->p_mlnk; + while (p_MCB) { + /* Release mutexes owned by this task */ + if (p_MCB->p_lnk) { + /* A task is waiting for mutex. */ + p_TCB = rt_get_first ((P_XCB)p_MCB); +#ifdef __CMSIS_RTOS + rt_ret_val (p_TCB, 0U/*osOK*/); +#else + rt_ret_val (p_TCB, OS_R_MUT); +#endif + rt_rmv_dly (p_TCB); + p_TCB->state = READY; + rt_put_prio (&os_rdy, p_TCB); + /* A waiting task becomes the owner of this mutex. */ + p_MCB0 = p_MCB->p_mlnk; + p_MCB->level = 1U; + p_MCB->owner = p_TCB; + p_MCB->p_mlnk = p_TCB->p_mlnk; + p_TCB->p_mlnk = p_MCB; + p_MCB = p_MCB0; + } + else { + p_MCB0 = p_MCB->p_mlnk; + p_MCB->level = 0U; + p_MCB->owner = NULL; + p_MCB->p_mlnk = NULL; + p_MCB = p_MCB0; + } + } + os_active_TCB[task_id-1U] = NULL; + rt_free_box (mp_stk, task_context->stack); + task_context->stack = NULL; + DBG_TASK_NOTIFY(task_context, __FALSE); + rt_free_box (mp_tcb, task_context); + if (rt_rdy_prio() > os_tsk.run->prio) { + /* Ready task has higher priority than running task. */ + os_tsk.run->state = READY; + rt_put_prio (&os_rdy, os_tsk.run); + rt_dispatch (NULL); + } + } + return (OS_R_OK); +} + + +/*--------------------------- rt_sys_init -----------------------------------*/ + +#ifdef __CMSIS_RTOS +void rt_sys_init (void) { +#else +void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk) { +#endif + /* Initialize system and start up task declared with "first_task". */ + U32 i; + + DBG_INIT(); + + /* Initialize dynamic memory and task TCB pointers to NULL. */ + for (i = 0U; i < os_maxtaskrun; i++) { + os_active_TCB[i] = NULL; + } + rt_init_box (mp_tcb, (U32)mp_tcb_size, sizeof(struct OS_TCB)); + rt_init_box (mp_stk, mp_stk_size, BOX_ALIGN_8 | (U16)(os_stackinfo)); + rt_init_box ((U32 *)m_tmr, (U32)mp_tmr_size, sizeof(struct OS_TMR)); + + /* Set up TCB of idle demon */ + os_idle_TCB.task_id = 255U; + os_idle_TCB.priv_stack = 0U; + rt_init_context (&os_idle_TCB, 0U, os_idle_demon); + + /* Set up ready list: initially empty */ + os_rdy.cb_type = HCB; + os_rdy.p_lnk = NULL; + /* Set up delay list: initially empty */ + os_dly.cb_type = HCB; + os_dly.p_dlnk = NULL; + os_dly.p_blnk = NULL; + os_dly.delta_time = 0U; + + /* Fix SP and system variables to assume idle task is running */ + /* Transform main program into idle task by assuming idle TCB */ +#ifndef __CMSIS_RTOS + rt_set_PSP (os_idle_TCB.tsk_stack+32U); +#endif + os_tsk.run = &os_idle_TCB; + os_tsk.run->state = RUNNING; + + /* Set the current thread to idle, so that on exit from this SVCall we do not + * de-reference a NULL TCB. */ + rt_switch_req(&os_idle_TCB); + + /* Initialize ps queue */ + os_psq->first = 0U; + os_psq->last = 0U; + os_psq->size = os_fifo_size; + + rt_init_robin (); + +#ifndef __CMSIS_RTOS + /* Initialize SVC and PendSV */ + rt_svc_init (); + + /* Initialize and start system clock timer */ + os_tick_irqn = os_tick_init (); + if (os_tick_irqn >= 0) { + OS_X_INIT((U32)os_tick_irqn); + } + + /* Start up first user task before entering the endless loop */ + rt_tsk_create (first_task, prio_stksz, stk, NULL); +#endif +} + + +/*--------------------------- rt_sys_start ----------------------------------*/ + +#ifdef __CMSIS_RTOS +void rt_sys_start (void) { + /* Start system */ + + /* Initialize SVC and PendSV */ + rt_svc_init (); + + /* Initialize and start system clock timer */ + os_tick_irqn = os_tick_init (); + if (os_tick_irqn >= 0) { + OS_X_INIT((U32)os_tick_irqn); + } +} +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Task.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,88 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TASK.H + * Purpose: Task functions and system start up. + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +/* Definitions */ + +#include "cmsis_os.h" + +/* Values for 'state' */ +#define INACTIVE 0U +#define READY 1U +#define RUNNING 2U +#define WAIT_DLY 3U +#define WAIT_ITV 4U +#define WAIT_OR 5U +#define WAIT_AND 6U +#define WAIT_SEM 7U +#define WAIT_MBX 8U +#define WAIT_MUT 9U + +/* Return codes */ +#define OS_R_TMO 0x01U +#define OS_R_EVT 0x02U +#define OS_R_SEM 0x03U +#define OS_R_MBX 0x04U +#define OS_R_MUT 0x05U + +#define OS_R_OK 0x00U +#define OS_R_NOK 0xFFU + +/* Variables */ +extern struct OS_TSK os_tsk; +extern struct OS_TCB os_idle_TCB; + +/* Functions */ +extern void rt_switch_req (P_TCB p_new); +extern void rt_dispatch (P_TCB next_TCB); +extern void rt_block (U16 timeout, U8 block_state); +extern void rt_tsk_pass (void); +extern OS_TID rt_tsk_self (void); +extern OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio); +extern OS_TID rt_tsk_create (FUNCP task, U32 prio_stksz, void *stk, void *argv); +extern OS_RESULT rt_tsk_delete (OS_TID task_id); +#ifdef __CMSIS_RTOS +extern void rt_sys_init (void); +extern void rt_sys_start (void); +#else +extern void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk); +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Time.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,93 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIME.C + * Purpose: Delay and interval wait functions + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_Task.h" +#include "rt_Time.h" + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* Free running system tick counter */ +U32 os_time; + + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + + +/*--------------------------- rt_time_get -----------------------------------*/ + +U32 rt_time_get (void) { + /* Get system time tick */ + return (os_time); +} + + +/*--------------------------- rt_dly_wait -----------------------------------*/ + +void rt_dly_wait (U16 delay_time) { + /* Delay task by "delay_time" */ + rt_block (delay_time, WAIT_DLY); +} + + +/*--------------------------- rt_itv_set ------------------------------------*/ + +void rt_itv_set (U16 interval_time) { + /* Set interval length and define start of first interval */ + os_tsk.run->interval_time = interval_time; + os_tsk.run->delta_time = interval_time + (U16)os_time; +} + + +/*--------------------------- rt_itv_wait -----------------------------------*/ + +void rt_itv_wait (void) { + /* Wait for interval end and define start of next one */ + U16 delta; + + delta = os_tsk.run->delta_time - (U16)os_time; + os_tsk.run->delta_time += os_tsk.run->interval_time; + if ((delta & 0x8000U) == 0U) { + rt_block (delta, WAIT_ITV); + } +} + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Time.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,52 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIME.H + * Purpose: Delay and interval wait functions definitions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern U32 os_time; + +/* Functions */ +extern U32 rt_time_get (void); +extern void rt_dly_wait (U16 delay_time); +extern void rt_itv_set (U16 interval_time); +extern void rt_itv_wait (void); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Timer.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,135 @@ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIMER.C + * Purpose: User timer functions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +#include "rt_TypeDef.h" +#include "RTX_Config.h" +#include "rt_Timer.h" +#include "rt_MemBox.h" +#include "cmsis_os.h" + +#ifndef __CMSIS_RTOS + + +/*---------------------------------------------------------------------------- + * Global Variables + *---------------------------------------------------------------------------*/ + +/* User Timer list pointer */ +struct OS_XTMR os_tmr; + +/*---------------------------------------------------------------------------- + * Functions + *---------------------------------------------------------------------------*/ + +/*--------------------------- rt_tmr_tick -----------------------------------*/ + +void rt_tmr_tick (void) { + /* Decrement delta count of timer list head. Timers having the value of */ + /* zero are removed from the list and the callback function is called. */ + P_TMR p; + + if (os_tmr.next == NULL) { + return; + } + os_tmr.tcnt--; + while ((os_tmr.tcnt == 0U) && ((p = os_tmr.next) != NULL)) { + /* Call a user provided function to handle an elapsed timer */ + os_tmr_call (p->info); + os_tmr.tcnt = p->tcnt; + os_tmr.next = p->next; + rt_free_box ((U32 *)m_tmr, p); + } +} + +/*--------------------------- rt_tmr_create ---------------------------------*/ + +OS_ID rt_tmr_create (U16 tcnt, U16 info) { + /* Create an user timer and put it into the chained timer list using */ + /* a timeout count value of "tcnt". User parameter "info" is used as a */ + /* parameter for the user provided callback function "os_tmr_call ()". */ + P_TMR p_tmr, p; + U32 delta,itcnt = tcnt; + + if ((tcnt == 0U) || (m_tmr == NULL)) { + return (NULL); + } + p_tmr = rt_alloc_box ((U32 *)m_tmr); + if (!p_tmr) { + return (NULL); + } + p_tmr->info = info; + p = (P_TMR)&os_tmr; + delta = p->tcnt; + while ((delta < itcnt) && (p->next != NULL)) { + p = p->next; + delta += p->tcnt; + } + /* Right place found, insert timer into the list */ + p_tmr->next = p->next; + p_tmr->tcnt = (U16)(delta - itcnt); + p->next = p_tmr; + p->tcnt -= p_tmr->tcnt; + return (p_tmr); +} + +/*--------------------------- rt_tmr_kill -----------------------------------*/ + +OS_ID rt_tmr_kill (OS_ID timer) { + /* Remove user timer from the chained timer list. */ + P_TMR p, p_tmr; + + p_tmr = (P_TMR)timer; + p = (P_TMR)&os_tmr; + /* Search timer list for requested timer */ + while (p->next != p_tmr) { + if (p->next == NULL) { + /* Failed, "timer" is not in the timer list */ + return (p_tmr); + } + p = p->next; + } + /* Timer was found, remove it from the list */ + p->next = p_tmr->next; + p->tcnt += p_tmr->tcnt; + rt_free_box ((U32 *)m_tmr, p_tmr); + /* Timer killed */ + return (NULL); +} + + +#endif + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_Timer.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,50 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TIMER.H + * Purpose: User timer functions + * Rev.: V4.70 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2013 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. + *---------------------------------------------------------------------------*/ + +/* Variables */ +extern struct OS_XTMR os_tmr; + +/* Functions */ +extern void rt_tmr_tick (void); +extern OS_ID rt_tmr_create (U16 tcnt, U16 info); +extern OS_ID rt_tmr_kill (OS_ID timer); + +/*---------------------------------------------------------------------------- + * end of file + *---------------------------------------------------------------------------*/ + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/rtx/TARGET_CORTEX_M/rt_TypeDef.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,175 @@ + +/** \addtogroup rtos */ +/** @{*/ +/*---------------------------------------------------------------------------- + * CMSIS-RTOS - RTX + *---------------------------------------------------------------------------- + * Name: RT_TYPEDEF.H + * Purpose: Type Definitions + * Rev.: V4.79 + *---------------------------------------------------------------------------- + * + * Copyright (c) 1999-2009 KEIL, 2009-2015 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. + *---------------------------------------------------------------------------*/ +#ifndef RT_TYPE_DEF_H +#define RT_TYPE_DEF_H + +/* Types */ +typedef char S8; +typedef unsigned char U8; +typedef short S16; +typedef unsigned short U16; +typedef int S32; +typedef unsigned int U32; +typedef long long S64; +typedef unsigned long long U64; +typedef unsigned char BIT; +typedef unsigned int BOOL; +typedef void (*FUNCP)(void); + +typedef U32 OS_TID; +typedef void *OS_ID; +typedef U32 OS_RESULT; + +typedef struct OS_TCB { + /* General part: identical for all implementations. */ + U8 cb_type; /* Control Block Type */ + U8 state; /* Task state */ + U8 prio; /* Execution priority */ + U8 task_id; /* Task ID value for optimized TCB access */ + struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */ + struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */ + struct OS_TCB *p_dlnk; /* Link pointer for delay list */ + struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */ + U16 delta_time; /* Time until time out */ + U16 interval_time; /* Time interval for periodic waits */ + U16 events; /* Event flags */ + U16 waits; /* Wait flags */ + void **msg; /* Direct message passing when task waits */ + struct OS_MUCB *p_mlnk; /* Link pointer for mutex owner list */ + U8 prio_base; /* Base priority */ + + /* Hardware dependant part: specific for CM processor */ + U8 stack_frame; /* Stack frame: 0=Basic, 1=Extended, */ + U16 reserved; /* Two reserved bytes for alignment */ + /* (2=VFP/D16 stacked, 4=NEON/D32 stacked) */ + U32 priv_stack; /* Private stack size, 0= system assigned */ + U32 tsk_stack; /* Current task Stack pointer (R13) */ + U32 *stack; /* Pointer to Task Stack memory block */ + + /* Task entry point used for uVision debugger */ + FUNCP ptask; /* Task entry address */ + void *argv; /* Task argument */ + void *context; /* Pointer to thread context */ +} *P_TCB; +#define TCB_STACKF 37 /* 'stack_frame' offset */ +#define TCB_TSTACK 44 /* 'tsk_stack' offset */ + +typedef struct OS_PSFE { /* Post Service Fifo Entry */ + void *id; /* Object Identification */ + U32 arg; /* Object Argument */ +} *P_PSFE; + +typedef struct OS_PSQ { /* Post Service Queue */ + U8 first; /* FIFO Head Index */ + U8 last; /* FIFO Tail Index */ + U8 count; /* Number of stored items in FIFO */ + U8 size; /* FIFO Size */ + struct OS_PSFE q[1]; /* FIFO Content */ +} *P_PSQ; + +typedef struct OS_TSK { + P_TCB run; /* Current running task */ + P_TCB new_tsk; /* Scheduled task to run */ +} *P_TSK; + +typedef struct OS_ROBIN { /* Round Robin Control */ + P_TCB task; /* Round Robin task */ + U16 time; /* Round Robin switch time */ + U16 tout; /* Round Robin timeout */ +} *P_ROBIN; + +typedef struct OS_XCB { + U8 cb_type; /* Control Block Type */ + struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */ + struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */ + struct OS_TCB *p_dlnk; /* Link pointer for delay list */ + struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */ + U16 delta_time; /* Time until time out */ +} *P_XCB; + +typedef struct OS_MCB { + U8 cb_type; /* Control Block Type */ + U8 state; /* State flag variable */ + U8 isr_st; /* State flag variable for isr functions */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for message */ + U16 first; /* Index of the message list begin */ + U16 last; /* Index of the message list end */ + U16 count; /* Actual number of stored messages */ + U16 size; /* Maximum number of stored messages */ + void *msg[1]; /* FIFO for Message pointers 1st element */ +} *P_MCB; + +typedef struct OS_SCB { + U8 cb_type; /* Control Block Type */ + U8 mask; /* Semaphore token mask */ + U16 tokens; /* Semaphore tokens */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for tokens */ +} *P_SCB; + +typedef struct OS_MUCB { + U8 cb_type; /* Control Block Type */ + U16 level; /* Call nesting level */ + struct OS_TCB *p_lnk; /* Chain of tasks waiting for mutex */ + struct OS_TCB *owner; /* Mutex owner task */ + struct OS_MUCB *p_mlnk; /* Chain of mutexes by owner task */ +} *P_MUCB; + +typedef struct OS_XTMR { + struct OS_TMR *next; + U16 tcnt; +} *P_XTMR; + +typedef struct OS_TMR { + struct OS_TMR *next; /* Link pointer to Next timer */ + U16 tcnt; /* Timer delay count */ + U16 info; /* User defined call info */ +} *P_TMR; + +typedef struct OS_BM { + void *free; /* Pointer to first free memory block */ + void *end; /* Pointer to memory block end */ + U32 blk_size; /* Memory block size */ +} *P_BM; + +/* Definitions */ +#define __TRUE 1U +#define __FALSE 0U +#define NULL ((void *) 0) + +#endif + +/** @}*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_ARM_SSG/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,40 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016-2017 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#if defined(TARGET_BEETLE) || defined(TARGET_CM3DS_MPS2) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20020000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 7 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 24000000 +#endif + +#endif + +#endif // MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_Freescale/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,318 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#if defined(TARGET_K20D50M) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x10008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 96000000 +#endif + +#elif defined(TARGET_TEENSY3_1) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 96000000 +#endif + +#elif defined(TARGET_MCU_K22F) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20010000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 80000000 +#endif + +#elif defined(TARGET_K66F) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20030000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 120000000 +#endif + +#elif defined(TARGET_KL27Z) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20003000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_KL43Z) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20006000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_KL05Z) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20000C00UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_KL25Z) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20003000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_KL26Z) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20003000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_KL46Z) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20006000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_KL82Z) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20012000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif + +#elif defined(TARGET_K64F) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20030000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#if defined(__CC_ARM) || defined(__GNUC__) +#define ISR_STACK_SIZE (0x1000) +#endif + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 120000000 +#endif + +#elif defined(TARGET_KW24D) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_KW41Z) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20018000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 40000000 +#endif + +#elif defined(TARGET_K82F) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20030000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 120000000 +#endif + +#elif defined(TARGET_RO359B) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20030000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#if defined(__CC_ARM) || defined(__GNUC__) +#define ISR_STACK_SIZE (0x1000) +#endif + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 96000000 +#endif + +#endif + +#endif // MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_Maxim/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,112 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#if defined(TARGET_MAX32600) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 24000000 +#endif + +#elif defined(TARGET_MAX32610) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 24000000 +#endif + +#elif defined(TARGET_MAX32620) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20040000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_MAX32625) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20028000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 96000000 +#endif + +#elif defined(TARGET_MAX32630) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20080000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 96000000 +#endif + +#endif + +#endif // MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_NORDIC/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,86 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#if defined(TARGET_MCU_NRF51822) + +#ifndef INITIAL_SP +# if defined(TARGET_MCU_NORDIC_32K) +# define INITIAL_SP (0x20008000UL) +# elif defined(TARGET_MCU_NORDIC_16K) +# define INITIAL_SP (0x20004000UL) +# endif +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 7 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 512 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 32768 +#endif +#ifndef OS_SYSTICK +#define OS_SYSTICK 0 +#endif + +#elif defined(TARGET_MCU_NRF52832) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20010000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 7 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 512 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 64000000 +#endif + +#elif defined(TARGET_MCU_NRF52840) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20040000UL) +#endif + +// More than 256 bytes are needed for the idle thread stack on the NRF52840 +#define OS_IDLE_THREAD_STACK_SIZE 512 + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 24 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 2048 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 64000000 +#endif + +#endif // defined(TARGET_MCU_NRF51822)... + +#endif // #ifndef MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_NUVOTON/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,100 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#include <stdint.h> + +#if defined(TARGET_NUMAKER_PFM_NUC472) + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 84000000 +#endif + +#if defined(__CC_ARM) + extern uint32_t Image$$ARM_LIB_HEAP$$ZI$$Base[]; + extern uint32_t Image$$ARM_LIB_HEAP$$ZI$$Length[]; + extern uint32_t Image$$ARM_LIB_STACK$$ZI$$Base[]; + extern uint32_t Image$$ARM_LIB_STACK$$ZI$$Length[]; + #define HEAP_START ((unsigned char*) Image$$ARM_LIB_HEAP$$ZI$$Base) + #define HEAP_SIZE ((uint32_t) Image$$ARM_LIB_HEAP$$ZI$$Length) + #define ISR_STACK_START ((unsigned char*)Image$$ARM_LIB_STACK$$ZI$$Base) + #define ISR_STACK_SIZE ((uint32_t)Image$$ARM_LIB_STACK$$ZI$$Length) +#elif defined(__GNUC__) + extern uint32_t __StackTop[]; + extern uint32_t __StackLimit[]; + extern uint32_t __end__[]; + extern uint32_t __HeapLimit[]; + #define HEAP_START ((unsigned char*)__end__) + #define HEAP_SIZE ((uint32_t)((uint32_t)__HeapLimit - (uint32_t)HEAP_START)) + #define ISR_STACK_START ((unsigned char*)__StackLimit) + #define ISR_STACK_SIZE ((uint32_t)((uint32_t)__StackTop - (uint32_t)__StackLimit)) +#elif defined(__ICCARM__) + /* No region declarations needed */ +#else + #error "no toolchain defined" +#endif + +#elif defined(TARGET_NUMAKER_PFM_M453) + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif + +#if defined(__CC_ARM) + extern uint32_t Image$$ARM_LIB_HEAP$$ZI$$Base[]; + extern uint32_t Image$$ARM_LIB_HEAP$$ZI$$Length[]; + extern uint32_t Image$$ARM_LIB_STACK$$ZI$$Base[]; + extern uint32_t Image$$ARM_LIB_STACK$$ZI$$Length[]; + #define HEAP_START ((unsigned char*) Image$$ARM_LIB_HEAP$$ZI$$Base) + #define HEAP_SIZE ((uint32_t) Image$$ARM_LIB_HEAP$$ZI$$Length) + #define ISR_STACK_START ((unsigned char*)Image$$ARM_LIB_STACK$$ZI$$Base) + #define ISR_STACK_SIZE ((uint32_t)Image$$ARM_LIB_STACK$$ZI$$Length) +#elif defined(__GNUC__) + extern uint32_t __StackTop[]; + extern uint32_t __StackLimit[]; + extern uint32_t __end__[]; + extern uint32_t __HeapLimit[]; + #define HEAP_START ((unsigned char*)__end__) + #define HEAP_SIZE ((uint32_t)((uint32_t)__HeapLimit - (uint32_t)HEAP_START)) + #define ISR_STACK_START ((unsigned char*)__StackLimit) + #define ISR_STACK_SIZE ((uint32_t)((uint32_t)__StackTop - (uint32_t)__StackLimit)) +#elif defined(__ICCARM__) + /* No region declarations needed */ +#else + #error "no toolchain defined" +#endif + +#endif + +#endif // MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_NXP/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,205 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#if defined(TARGET_LPC11U68) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x10008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_LPC11U24) \ + || defined(TARGET_LPC11U35_401) \ + || defined(TARGET_LPC11U35_501) \ + || defined(TARGET_LPCCAPPUCCINO) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x10002000UL) +#endif + + // RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_LPC1114) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x10001000UL) +#endif + + // RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_LPC1347) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x10002000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif + +#elif defined(TARGET_LPC1549) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x02009000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif + +#elif defined(TARGET_LPC1768) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x10008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 96000000 +#endif + +#elif defined(TARGET_LPC4088) || defined(TARGET_LPC4088_DM) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x10010000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 120000000 +#endif + +#elif defined(TARGET_LPC4330) || defined(TARGET_LPC4337) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x10008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 204000000 +#endif + +#elif defined(TARGET_LPC812) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x10001000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 36000000 +#endif + +#elif defined(TARGET_LPC824) || defined(TARGET_SSCI824) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x10002000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 30000000 +#endif + +#endif + +#endif // MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_ONSEMI/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,40 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#if defined(TARGET_NCS36510) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x40000000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 32000000 +#endif + +#endif + +#endif // MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_RENESAS/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,25 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#if defined(TARGET_RZ_A1H) || defined(TARGET_VK_RZ_A1H) +#ifndef OS_CLOCK +#define OS_CLOCK 12000000 +#endif +#endif + +#endif // MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_STM/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,869 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#if defined(TARGET_STM32F051R8) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20002000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_STM32L031K6) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20002000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 32000000 +#endif + +#elif defined(TARGET_STM32F070RB) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20004000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_STM32F072RB) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20004000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_STM32F091RC) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_STM32F100RB) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20002000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 24000000 +#endif + +#elif defined(TARGET_STM32F103RB) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20005000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif + +#elif defined(TARGET_STM32F207ZG) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20020000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 120000000 +#endif + +#elif defined(TARGET_STM32F303VC) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x2000A000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif + +#elif defined(TARGET_STM32F334C8) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20003000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif + +#elif defined(TARGET_STM32F302R8) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20004000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif + +#elif defined(TARGET_STM32F303K8) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20003000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 64000000 +#endif + +#elif defined(TARGET_STM32F303RE) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20010000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif + +#elif defined(TARGET_STM32F303ZE) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20010000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif + +#elif defined(TARGET_STM32F334R8) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20003000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 72000000 +#endif + +#elif defined(TARGET_STM32F446VE) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20020000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 180000000 +#endif + +#elif defined(TARGET_STM32F401VC) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20010000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 84000000 +#endif + +#elif (defined(TARGET_STM32F429ZI) || defined(TARGET_STM32F439ZI)) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20030000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 168000000 +#endif + +#elif defined(TARGET_UBLOX_EVK_ODIN_W2) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20030000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 512 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 168000000 +#endif + +#elif defined(TARGET_UBLOX_C030) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20030000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 512 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 168000000 +#endif + +#elif defined(TARGET_STM32F469NI) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20050000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 168000000 +#endif + +#elif defined(TARGET_STM32F405RG) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20020000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif + +#elif defined(TARGET_STM32F401RE) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20018000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 84000000 +#endif + +#elif defined(TARGET_STM32F410RB) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 100000000 +#endif + +#elif defined(TARGET_MTS_MDOT_F411RE) || defined (TARGET_MTS_DRAGONFLY_F411RE) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20020000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 1024 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 96000000 +#endif + +#elif defined(TARGET_STM32F411RE) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20020000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 100000000 +#endif + +#elif defined(TARGET_STM32F412ZG) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20040000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 100000000 +#endif + +#elif defined(TARGET_STM32F413ZH) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20050000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 100000000 +#endif + + +#elif defined(TARGET_STM32F446RE) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20020000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 180000000 +#endif + +#elif defined(TARGET_STM32F446ZE) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20020000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 180000000 +#endif + +#elif defined(TARGET_STM32F407VG) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20020000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 168000000 +#endif + +#elif defined(TARGET_STM32F746NG) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20050000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 216000000 +#endif + +#elif (defined(TARGET_STM32F746ZG) || defined(TARGET_STM32F756ZG)) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20050000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 216000000 +#endif + +#elif defined(TARGET_STM32F767ZI) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20080000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 216000000 +#endif + +#elif defined(TARGET_STM32F769NI) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20080000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 216000000 +#endif + +#elif defined(TARGET_STM32L053C8) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20002000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 32000000 +#endif + +#elif defined(TARGET_STM32L031K6) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20002000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 32000000 +#endif + +#elif defined(TARGET_STM32L053R8) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20002000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 32000000 +#endif + +#elif defined(TARGET_STM32L072CZ) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20005000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 32000000 +#endif + +#elif defined(TARGET_STM32L073RZ) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20005000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 32000000 +#endif + +#elif defined(TARGET_STM32L152RC) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 24000000 +#endif + +#elif defined(TARGET_STM32L152RE) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20014000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 32000000 +#endif + +#elif defined(TARGET_NZ32_SC151) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 32000000 +#endif + +#elif defined(TARGET_XDOT_L151CC) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 32000000 +#endif + +#elif defined(TARGET_STM32L476VG) || defined(TARGET_STM32L475VG) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20018000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 80000000 +#endif + +#elif defined(TARGET_STM32L432KC) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x2000C000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 80000000 +#endif + +#elif (defined(TARGET_STM32L476RG) || defined(TARGET_STM32L486RG)) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20018000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 80000000 +#endif + +#endif + +#endif // MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_Silicon_Labs/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,134 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#include <stdint.h> +#include "clocking.h" + +#ifndef OS_CLOCK +#define OS_CLOCK REFERENCE_FREQUENCY +#endif + +#if defined(TARGET_EFM32GG_STK3700) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20020000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif + +#elif defined(TARGET_EFM32HG_STK3400) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20002000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 112 +#endif + +#elif defined(TARGET_EFM32LG_STK3600) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif + +#elif defined(TARGET_EFM32PG_STK3401) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif + +#elif defined(TARGET_EFM32WG_STK3800) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20008000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif + +#elif defined(TARGET_EFR32MG1) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20007C00UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 5 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif + +#elif defined(TARGET_EFR32MG12) || defined(TARGET_EFM32PG12) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20040000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 14 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 256 +#endif + +#endif + +#endif // MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_WIZNET/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,76 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#if defined(TARGET_WIZWIKI_W7500) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20004000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 20000000 +#endif + +#elif defined(TARGET_WIZWIKI_W7500P) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20004000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 20000000 +#endif + +#elif defined(TARGET_WIZWIKI_W7500ECO) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x20004000UL) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 20000000 +#endif + +#endif // + +#endif // MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-rtos/targets/TARGET_ublox/mbed_rtx4.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,39 @@ +/* mbed Microcontroller Library + * Copyright (c) 2016 u-blox + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_MBED_RTX_H +#define MBED_MBED_RTX_H + +#if defined(TARGET_HI2110) + +#ifndef INITIAL_SP +#define INITIAL_SP (0x01000000 + 0x05000 - 256) +#endif + +// RTX 4 only config below, for backward-compability + +#ifndef OS_TASKCNT +#define OS_TASKCNT 6 +#endif +#ifndef OS_MAINSTKSIZE +#define OS_MAINSTKSIZE 128 +#endif +#ifndef OS_CLOCK +#define OS_CLOCK 48000000 +#endif +#endif + +#endif // MBED_MBED_RTX_H
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_NUVOTON/TARGET_M451/USBHALHost_M451.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,347 @@ +/* mbed Microcontroller Library + * Copyright (c) 2015-2016 Nuvoton + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if defined(TARGET_M451) + +#include "mbed.h" +#include "USBHALHost.h" +#include "dbg.h" +#include "pinmap.h" + +#define HCCA_SIZE sizeof(HCCA) +#define ED_SIZE sizeof(HCED) +#define TD_SIZE sizeof(HCTD) + +#define TOTAL_SIZE (HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE) + (MAX_TD*TD_SIZE)) + +#ifndef USBH_HcRhDescriptorA_POTPGT_Pos +#define USBH_HcRhDescriptorA_POTPGT_Pos (24) +#endif +#ifndef USBH_HcRhDescriptorA_POTPGT_Msk +#define USBH_HcRhDescriptorA_POTPGT_Msk (0xfful << USBH_HcRhDescriptorA_POTPGT_Pos) +#endif + +static volatile MBED_ALIGN(256) uint8_t usb_buf[TOTAL_SIZE]; // 256 bytes aligned! + +USBHALHost * USBHALHost::instHost; + +USBHALHost::USBHALHost() +{ + instHost = this; + memInit(); + memset((void*)usb_hcca, 0, HCCA_SIZE); + for (int i = 0; i < MAX_ENDPOINT; i++) { + edBufAlloc[i] = false; + } + for (int i = 0; i < MAX_TD; i++) { + tdBufAlloc[i] = false; + } +} + +void USBHALHost::init() +{ + // Unlock protected registers + SYS_UnlockReg(); + + // Enable USBH clock + CLK_EnableModuleClock(USBH_MODULE); + // Set USBH clock source/divider + CLK_SetModuleClock(USBH_MODULE, 0, CLK_CLKDIV0_USB(3)); + + // Configure OTG function as Host-Only + SYS->USBPHY = SYS_USBPHY_LDO33EN_Msk | SYS_USBPHY_USBROLE_STD_USBH; + + /* Below settings is use power switch IC to enable/disable USB Host power. + Set PA.2 is VBUS_EN function pin and PA.3 VBUS_ST function pin */ + pin_function(PA_3, SYS_GPA_MFPL_PA3MFP_USB_VBUS_ST); + pin_function(PA_2, SYS_GPA_MFPL_PA2MFP_USB_VBUS_EN); + + // Enable OTG clock + CLK_EnableModuleClock(OTG_MODULE); + + // Lock protected registers + SYS_LockReg(); + + // Overcurrent flag is low active + USBH->HcMiscControl |= USBH_HcMiscControl_OCAL_Msk; + + // Disable HC interrupts + USBH->HcInterruptDisable = OR_INTR_ENABLE_MIE; + + // Needed by some controllers + USBH->HcControl = 0; + + // Software reset + USBH->HcCommandStatus = OR_CMD_STATUS_HCR; + while (USBH->HcCommandStatus & OR_CMD_STATUS_HCR); + + // Put HC in reset state + USBH->HcControl = (USBH->HcControl & ~OR_CONTROL_HCFS) | OR_CONTROL_HC_RSET; + // HCD must wait 10ms for HC reset complete + wait_ms(100); + + USBH->HcControlHeadED = 0; // Initialize Control ED list head to 0 + USBH->HcBulkHeadED = 0; // Initialize Bulk ED list head to 0 + USBH->HcHCCA = (uint32_t) usb_hcca; + + USBH->HcFmInterval = DEFAULT_FMINTERVAL; // Frame interval = 12000 - 1 + // MPS = 10,104 + USBH->HcPeriodicStart = FI * 90 / 100; // 90% of frame interval + USBH->HcLSThreshold = 0x628; // Low speed threshold + + // Put HC in operational state + USBH->HcControl = (USBH->HcControl & (~OR_CONTROL_HCFS)) | OR_CONTROL_HC_OPER; + + // FIXME + USBH->HcRhDescriptorA = USBH->HcRhDescriptorA & ~(USBH_HcRhDescriptorA_NOCP_Msk | USBH_HcRhDescriptorA_OCPM_Msk | USBH_HcRhDescriptorA_PSM_Msk); + // Issue SetGlobalPower command + USBH->HcRhStatus = USBH_HcRhStatus_LPSC_Msk; + // Power On To Power Good Time, in 2 ms units + wait_ms(((USBH->HcRhDescriptorA & USBH_HcRhDescriptorA_POTPGT_Msk) >> USBH_HcRhDescriptorA_POTPGT_Pos) * 2); + + // Clear Interrrupt Status + USBH->HcInterruptStatus |= USBH->HcInterruptStatus; + // Enable interrupts we care about + USBH->HcInterruptEnable = OR_INTR_ENABLE_MIE | OR_INTR_ENABLE_WDH | OR_INTR_ENABLE_RHSC; + + NVIC_SetVector(USBH_IRQn, (uint32_t)(_usbisr)); + NVIC_EnableIRQ(USBH_IRQn); + + // Check for any connected devices + if (USBH->HcRhPortStatus[0] & OR_RH_PORT_CCS) { + // Device connected + wait_ms(150); + deviceConnected(0, 1, USBH->HcRhPortStatus[0] & OR_RH_PORT_LSDA); + } +} + +uint32_t USBHALHost::controlHeadED() +{ + return USBH->HcControlHeadED; +} + +uint32_t USBHALHost::bulkHeadED() +{ + return USBH->HcBulkHeadED; +} + +uint32_t USBHALHost::interruptHeadED() +{ + // FIXME: Only support one INT ED? + return usb_hcca->IntTable[0]; +} + +void USBHALHost::updateBulkHeadED(uint32_t addr) +{ + USBH->HcBulkHeadED = addr; +} + + +void USBHALHost::updateControlHeadED(uint32_t addr) +{ + USBH->HcControlHeadED = addr; +} + +void USBHALHost::updateInterruptHeadED(uint32_t addr) +{ + // FIXME: Only support one INT ED? + usb_hcca->IntTable[0] = addr; +} + + +void USBHALHost::enableList(ENDPOINT_TYPE type) +{ + switch(type) { + case CONTROL_ENDPOINT: + USBH->HcCommandStatus = OR_CMD_STATUS_CLF; + USBH->HcControl |= OR_CONTROL_CLE; + break; + case ISOCHRONOUS_ENDPOINT: + // FIXME + break; + case BULK_ENDPOINT: + USBH->HcCommandStatus = OR_CMD_STATUS_BLF; + USBH->HcControl |= OR_CONTROL_BLE; + break; + case INTERRUPT_ENDPOINT: + USBH->HcControl |= OR_CONTROL_PLE; + break; + } +} + + +bool USBHALHost::disableList(ENDPOINT_TYPE type) +{ + switch(type) { + case CONTROL_ENDPOINT: + if(USBH->HcControl & OR_CONTROL_CLE) { + USBH->HcControl &= ~OR_CONTROL_CLE; + return true; + } + return false; + case ISOCHRONOUS_ENDPOINT: + // FIXME + return false; + case BULK_ENDPOINT: + if(USBH->HcControl & OR_CONTROL_BLE){ + USBH->HcControl &= ~OR_CONTROL_BLE; + return true; + } + return false; + case INTERRUPT_ENDPOINT: + if(USBH->HcControl & OR_CONTROL_PLE) { + USBH->HcControl &= ~OR_CONTROL_PLE; + return true; + } + return false; + } + return false; +} + + +void USBHALHost::memInit() +{ + usb_hcca = (volatile HCCA *)usb_buf; + usb_edBuf = usb_buf + HCCA_SIZE; + usb_tdBuf = usb_buf + HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE); +} + +volatile uint8_t * USBHALHost::getED() +{ + for (int i = 0; i < MAX_ENDPOINT; i++) { + if ( !edBufAlloc[i] ) { + edBufAlloc[i] = true; + return (volatile uint8_t *)(usb_edBuf + i*ED_SIZE); + } + } + perror("Could not allocate ED\r\n"); + return NULL; //Could not alloc ED +} + +volatile uint8_t * USBHALHost::getTD() +{ + int i; + for (i = 0; i < MAX_TD; i++) { + if ( !tdBufAlloc[i] ) { + tdBufAlloc[i] = true; + return (volatile uint8_t *)(usb_tdBuf + i*TD_SIZE); + } + } + perror("Could not allocate TD\r\n"); + return NULL; //Could not alloc TD +} + + +void USBHALHost::freeED(volatile uint8_t * ed) +{ + int i; + i = (ed - usb_edBuf) / ED_SIZE; + edBufAlloc[i] = false; +} + +void USBHALHost::freeTD(volatile uint8_t * td) +{ + int i; + i = (td - usb_tdBuf) / TD_SIZE; + tdBufAlloc[i] = false; +} + + +void USBHALHost::resetRootHub() +{ + // Reset port1 + USBH->HcRhPortStatus[0] = OR_RH_PORT_PRS; + while (USBH->HcRhPortStatus[0] & OR_RH_PORT_PRS); + USBH->HcRhPortStatus[0] = OR_RH_PORT_PRSC; +} + + +void USBHALHost::_usbisr(void) +{ + if (instHost) { + instHost->UsbIrqhandler(); + } +} + +void USBHALHost::UsbIrqhandler() +{ + uint32_t ints = USBH->HcInterruptStatus; + + // Root hub status change interrupt + if (ints & OR_INTR_STATUS_RHSC) { + uint32_t ints_roothub = USBH->HcRhStatus; + uint32_t ints_port1 = USBH->HcRhPortStatus[0]; + uint32_t ints_port2 = USBH->HcRhPortStatus[1]; + + // Port1: ConnectStatusChange + if (ints_port1 & OR_RH_PORT_CSC) { + if (ints_roothub & OR_RH_STATUS_DRWE) { + // When DRWE is on, Connect Status Change means a remote wakeup event. + } else { + if (ints_port1 & OR_RH_PORT_CCS) { + // Root device connected + + // wait 150ms to avoid bounce + wait_ms(150); + + //Hub 0 (root hub), Port 1 (count starts at 1), Low or High speed + deviceConnected(0, 1, ints_port1 & OR_RH_PORT_LSDA); + } else { + // Root device disconnected + + if (!(ints & OR_INTR_STATUS_WDH)) { + usb_hcca->DoneHead = 0; + } + + // wait 200ms to avoid bounce + wait_ms(200); + + deviceDisconnected(0, 1, NULL, usb_hcca->DoneHead & 0xFFFFFFFE); + + if (ints & OR_INTR_STATUS_WDH) { + usb_hcca->DoneHead = 0; + USBH->HcInterruptStatus = OR_INTR_STATUS_WDH; + } + } + } + USBH->HcRhPortStatus[0] = OR_RH_PORT_CSC; + } + // Port1: Reset completed + if (ints_port1 & OR_RH_PORT_PRSC) { + USBH->HcRhPortStatus[0] = OR_RH_PORT_PRSC; + } + // Port1: PortEnableStatusChange + if (ints_port1 & OR_RH_PORT_PESC) { + USBH->HcRhPortStatus[0] = OR_RH_PORT_PESC; + } + + // Port2: PortOverCurrentIndicatorChange + if (ints_port2 & OR_RH_PORT_OCIC) { + USBH->HcRhPortStatus[1] = OR_RH_PORT_OCIC; + } + + USBH->HcInterruptStatus = OR_INTR_STATUS_RHSC; + } + + // Writeback Done Head interrupt + if (ints & OR_INTR_STATUS_WDH) { + transferCompleted(usb_hcca->DoneHead & 0xFFFFFFFE); + USBH->HcInterruptStatus = OR_INTR_STATUS_WDH; + } + + +} +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/USBHALHost_NUC472.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,365 @@ +/* mbed Microcontroller Library + * Copyright (c) 2015-2016 Nuvoton + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if defined(TARGET_NUC472) + +#include "mbed.h" +#include "USBHALHost.h" +#include "dbg.h" +#include "pinmap.h" + +#define HCCA_SIZE sizeof(HCCA) +#define ED_SIZE sizeof(HCED) +#define TD_SIZE sizeof(HCTD) + +#define TOTAL_SIZE (HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE) + (MAX_TD*TD_SIZE)) + +static volatile MBED_ALIGN(256) uint8_t usb_buf[TOTAL_SIZE]; // 256 bytes aligned! + +USBHALHost * USBHALHost::instHost; + +USBHALHost::USBHALHost() +{ + instHost = this; + memInit(); + memset((void*)usb_hcca, 0, HCCA_SIZE); + for (int i = 0; i < MAX_ENDPOINT; i++) { + edBufAlloc[i] = false; + } + for (int i = 0; i < MAX_TD; i++) { + tdBufAlloc[i] = false; + } +} + +void USBHALHost::init() +{ + // Unlock protected registers + SYS_UnlockReg(); + + // NOTE: Configure as OTG device first; otherwise, program will trap in wait loop CLK_STATUS_PLL2STB_Msk below. + SYS->USBPHY = SYS_USBPHY_LDO33EN_Msk | SYS_USBPHY_USBROLE_ON_THE_GO; + + // NOTE: Enable OTG here; otherwise, program will trap in wait loop CLK_STATUS_PLL2STB_Msk below. + CLK_EnableModuleClock(OTG_MODULE); + OTG->PHYCTL = (OTG->PHYCTL | OTG_PHYCTL_OTGPHYEN_Msk) & ~OTG_PHYCTL_IDDETEN_Msk; + //OTG->CTL |= OTG_CTL_OTGEN_Msk | OTG_CTL_BUSREQ_Msk; + + // PB.0: USB0 external VBUS regulator status + // USB_OC + // PB.1: USB0 external VBUS regulator enable + // NCT3520U low active (USB_PWR_EN) + pin_function(PB_0, SYS_GPB_MFPL_PB0MFP_USB0_OTG5V_ST); + pin_function(PB_1, SYS_GPB_MFPL_PB1MFP_USB0_OTG5V_EN); + + // PB.2: USB1 differential signal D- + // PB.3: USB1 differential signal D+ + //pin_function(PB_2, SYS_GPB_MFPL_PB2MFP_USB1_D_N); + //pin_function(PB_3, SYS_GPB_MFPL_PB3MFP_USB1_D_P); + + // Set PB.4 output high to enable USB power + //gpio_t gpio; + //gpio_init_out_ex(&gpio, PB_4, 1); + + // NOTE: + // 1. Set USBH clock source to PLL2; otherwise, program will trap in wait loop CLK_STATUS_PLL2STB_Msk below. + // 2. Don't set CLK_PLL2CTL_PLL2CKEN_Msk. USBH will work abnormally with it enabled. + CLK->CLKSEL0 &= ~CLK_CLKSEL0_USBHSEL_Msk; + // Enable PLL2, 480 MHz / 2 / (1+4) => 48 MHz output + CLK->PLL2CTL = /*CLK_PLL2CTL_PLL2CKEN_Msk | */ (4 << CLK_PLL2CTL_PLL2DIV_Pos); + // Wait PLL2 stable ... + while (!(CLK->STATUS & CLK_STATUS_PLL2STB_Msk)); + + // Select USB Host clock source from PLL2, clock divied by 1 + CLK_SetModuleClock(USBH_MODULE, CLK_CLKSEL0_USBHSEL_PLL2, CLK_CLKDIV0_USB(1)); + + // Enable USB Host clock + CLK_EnableModuleClock(USBH_MODULE); + + // Lock protected registers + SYS_LockReg(); + + // Overcurrent flag is high active + USBH->HcMiscControl &= ~USBH_HcMiscControl_OCAL_Msk; + + // Disable HC interrupts + USBH->HcInterruptDisable = OR_INTR_ENABLE_MIE; + + // Needed by some controllers + USBH->HcControl = 0; + + // Software reset + USBH->HcCommandStatus = OR_CMD_STATUS_HCR; + while (USBH->HcCommandStatus & OR_CMD_STATUS_HCR); + + // Put HC in reset state + USBH->HcControl = (USBH->HcControl & ~OR_CONTROL_HCFS) | OR_CONTROL_HC_RSET; + // HCD must wait 10ms for HC reset complete + wait_ms(100); + + USBH->HcControlHeadED = 0; // Initialize Control ED list head to 0 + USBH->HcBulkHeadED = 0; // Initialize Bulk ED list head to 0 + USBH->HcHCCA = (uint32_t) usb_hcca; + + USBH->HcFmInterval = DEFAULT_FMINTERVAL; // Frame interval = 12000 - 1 + // MPS = 10,104 + USBH->HcPeriodicStart = FI * 90 / 100; // 90% of frame interval + USBH->HcLSThreshold = 0x628; // Low speed threshold + + // Put HC in operational state + USBH->HcControl = (USBH->HcControl & (~OR_CONTROL_HCFS)) | OR_CONTROL_HC_OPER; + + // FIXME: Ports are power switched. All ports are powered at the same time. Doesn't match BSP sample. + USBH->HcRhDescriptorA = USBH->HcRhDescriptorA & ~USBH_HcRhDescriptorA_NPS_Msk & ~USBH_HcRhDescriptorA_PSM_Msk; + // Issue SetGlobalPower command + USBH->HcRhStatus = USBH_HcRhStatus_LPSC_Msk; + // Power On To Power Good Time, in 2 ms units + wait_ms(((USBH->HcRhDescriptorA & USBH_HcRhDescriptorA_POTPGT_Msk) >> USBH_HcRhDescriptorA_POTPGT_Pos) * 2); + + // Clear Interrrupt Status + USBH->HcInterruptStatus |= USBH->HcInterruptStatus; + // Enable interrupts we care about + USBH->HcInterruptEnable = OR_INTR_ENABLE_MIE | OR_INTR_ENABLE_WDH | OR_INTR_ENABLE_RHSC; + + + // Unlock protected registers + SYS_UnlockReg(); + + // NOTE: Configure as USB host after USBH init above; otherwise system will crash. + SYS->USBPHY = (SYS->USBPHY & ~SYS_USBPHY_USBROLE_Msk) | SYS_USBPHY_USBROLE_STD_USBH; + + // Lock protected registers + SYS_LockReg(); + + NVIC_SetVector(USBH_IRQn, (uint32_t)(_usbisr)); + NVIC_EnableIRQ(USBH_IRQn); + + // Check for any connected devices + if (USBH->HcRhPortStatus[0] & OR_RH_PORT_CCS) { + // Device connected + wait_ms(150); + deviceConnected(0, 1, USBH->HcRhPortStatus[0] & OR_RH_PORT_LSDA); + } +} + +uint32_t USBHALHost::controlHeadED() +{ + return USBH->HcControlHeadED; +} + +uint32_t USBHALHost::bulkHeadED() +{ + return USBH->HcBulkHeadED; +} + +uint32_t USBHALHost::interruptHeadED() +{ + // FIXME: Only support one INT ED? + return usb_hcca->IntTable[0]; +} + +void USBHALHost::updateBulkHeadED(uint32_t addr) +{ + USBH->HcBulkHeadED = addr; +} + + +void USBHALHost::updateControlHeadED(uint32_t addr) +{ + USBH->HcControlHeadED = addr; +} + +void USBHALHost::updateInterruptHeadED(uint32_t addr) +{ + // FIXME: Only support one INT ED? + usb_hcca->IntTable[0] = addr; +} + + +void USBHALHost::enableList(ENDPOINT_TYPE type) +{ + switch(type) { + case CONTROL_ENDPOINT: + USBH->HcCommandStatus = OR_CMD_STATUS_CLF; + USBH->HcControl |= OR_CONTROL_CLE; + break; + case ISOCHRONOUS_ENDPOINT: + // FIXME + break; + case BULK_ENDPOINT: + USBH->HcCommandStatus = OR_CMD_STATUS_BLF; + USBH->HcControl |= OR_CONTROL_BLE; + break; + case INTERRUPT_ENDPOINT: + USBH->HcControl |= OR_CONTROL_PLE; + break; + } +} + + +bool USBHALHost::disableList(ENDPOINT_TYPE type) +{ + switch(type) { + case CONTROL_ENDPOINT: + if(USBH->HcControl & OR_CONTROL_CLE) { + USBH->HcControl &= ~OR_CONTROL_CLE; + return true; + } + return false; + case ISOCHRONOUS_ENDPOINT: + // FIXME + return false; + case BULK_ENDPOINT: + if(USBH->HcControl & OR_CONTROL_BLE){ + USBH->HcControl &= ~OR_CONTROL_BLE; + return true; + } + return false; + case INTERRUPT_ENDPOINT: + if(USBH->HcControl & OR_CONTROL_PLE) { + USBH->HcControl &= ~OR_CONTROL_PLE; + return true; + } + return false; + } + return false; +} + + +void USBHALHost::memInit() +{ + usb_hcca = (volatile HCCA *)usb_buf; + usb_edBuf = usb_buf + HCCA_SIZE; + usb_tdBuf = usb_buf + HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE); +} + +volatile uint8_t * USBHALHost::getED() +{ + for (int i = 0; i < MAX_ENDPOINT; i++) { + if ( !edBufAlloc[i] ) { + edBufAlloc[i] = true; + return (volatile uint8_t *)(usb_edBuf + i*ED_SIZE); + } + } + perror("Could not allocate ED\r\n"); + return NULL; //Could not alloc ED +} + +volatile uint8_t * USBHALHost::getTD() +{ + int i; + for (i = 0; i < MAX_TD; i++) { + if ( !tdBufAlloc[i] ) { + tdBufAlloc[i] = true; + return (volatile uint8_t *)(usb_tdBuf + i*TD_SIZE); + } + } + perror("Could not allocate TD\r\n"); + return NULL; //Could not alloc TD +} + + +void USBHALHost::freeED(volatile uint8_t * ed) +{ + int i; + i = (ed - usb_edBuf) / ED_SIZE; + edBufAlloc[i] = false; +} + +void USBHALHost::freeTD(volatile uint8_t * td) +{ + int i; + i = (td - usb_tdBuf) / TD_SIZE; + tdBufAlloc[i] = false; +} + + +void USBHALHost::resetRootHub() +{ + // Reset port1 + USBH->HcRhPortStatus[0] = OR_RH_PORT_PRS; + while (USBH->HcRhPortStatus[0] & OR_RH_PORT_PRS); + USBH->HcRhPortStatus[0] = OR_RH_PORT_PRSC; +} + + +void USBHALHost::_usbisr(void) +{ + if (instHost) { + instHost->UsbIrqhandler(); + } +} + +void USBHALHost::UsbIrqhandler() +{ + uint32_t ints = USBH->HcInterruptStatus; + + // Root hub status change interrupt + if (ints & OR_INTR_STATUS_RHSC) { + uint32_t ints_roothub = USBH->HcRhStatus; + uint32_t ints_port1 = USBH->HcRhPortStatus[0]; + + // Port1: ConnectStatusChange + if (ints_port1 & OR_RH_PORT_CSC) { + if (ints_roothub & OR_RH_STATUS_DRWE) { + // When DRWE is on, Connect Status Change means a remote wakeup event. + } else { + if (ints_port1 & OR_RH_PORT_CCS) { + // Root device connected + + // wait 150ms to avoid bounce + wait_ms(150); + + //Hub 0 (root hub), Port 1 (count starts at 1), Low or High speed + deviceConnected(0, 1, ints_port1 & OR_RH_PORT_LSDA); + } else { + // Root device disconnected + + if (!(ints & OR_INTR_STATUS_WDH)) { + usb_hcca->DoneHead = 0; + } + + // wait 200ms to avoid bounce + wait_ms(200); + + deviceDisconnected(0, 1, NULL, usb_hcca->DoneHead & 0xFFFFFFFE); + + if (ints & OR_INTR_STATUS_WDH) { + usb_hcca->DoneHead = 0; + USBH->HcInterruptStatus = OR_INTR_STATUS_WDH; + } + } + } + USBH->HcRhPortStatus[0] = OR_RH_PORT_CSC; + } + // Port1: Reset completed + if (ints_port1 & OR_RH_PORT_PRSC) { + USBH->HcRhPortStatus[0] = OR_RH_PORT_PRSC; + } + // Port1: PortEnableStatusChange + if (ints_port1 & OR_RH_PORT_PESC) { + USBH->HcRhPortStatus[0] = OR_RH_PORT_PESC; + } + + USBH->HcInterruptStatus = OR_INTR_STATUS_RHSC; + } + + // Writeback Done Head interrupt + if (ints & OR_INTR_STATUS_WDH) { + transferCompleted(usb_hcca->DoneHead & 0xFFFFFFFE); + USBH->HcInterruptStatus = OR_INTR_STATUS_WDH; + } +} +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_NXP/USBHALHost_LPC17.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,325 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if defined(TARGET_LPC1768) || defined(TARGET_LPC2460) + +#include "mbed.h" +#include "USBHALHost.h" +#include "dbg.h" + +// bits of the USB/OTG clock control register +#define HOST_CLK_EN (1<<0) +#define DEV_CLK_EN (1<<1) +#define PORTSEL_CLK_EN (1<<3) +#define AHB_CLK_EN (1<<4) + +// bits of the USB/OTG clock status register +#define HOST_CLK_ON (1<<0) +#define DEV_CLK_ON (1<<1) +#define PORTSEL_CLK_ON (1<<3) +#define AHB_CLK_ON (1<<4) + +// we need host clock, OTG/portsel clock and AHB clock +#define CLOCK_MASK (HOST_CLK_EN | PORTSEL_CLK_EN | AHB_CLK_EN) + +#define HCCA_SIZE sizeof(HCCA) +#define ED_SIZE sizeof(HCED) +#define TD_SIZE sizeof(HCTD) + +#define TOTAL_SIZE (HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE) + (MAX_TD*TD_SIZE)) + +static volatile uint8_t usb_buf[TOTAL_SIZE] __attribute((section("AHBSRAM1"),aligned(256))); //256 bytes aligned! + +USBHALHost * USBHALHost::instHost; + +USBHALHost::USBHALHost() { + instHost = this; + memInit(); + memset((void*)usb_hcca, 0, HCCA_SIZE); + for (int i = 0; i < MAX_ENDPOINT; i++) { + edBufAlloc[i] = false; + } + for (int i = 0; i < MAX_TD; i++) { + tdBufAlloc[i] = false; + } +} + +void USBHALHost::init() { + NVIC_DisableIRQ(USB_IRQn); + + //Cut power + LPC_SC->PCONP &= ~(1UL<<31); + wait_ms(100); + + // turn on power for USB + LPC_SC->PCONP |= (1UL<<31); + + // Enable USB host clock, port selection and AHB clock + LPC_USB->USBClkCtrl |= CLOCK_MASK; + + // Wait for clocks to become available + while ((LPC_USB->USBClkSt & CLOCK_MASK) != CLOCK_MASK); + + // it seems the bits[0:1] mean the following + // 0: U1=device, U2=host + // 1: U1=host, U2=host + // 2: reserved + // 3: U1=host, U2=device + // NB: this register is only available if OTG clock (aka "port select") is enabled!! + // since we don't care about port 2, set just bit 0 to 1 (U1=host) + LPC_USB->OTGStCtrl |= 1; + + // now that we've configured the ports, we can turn off the portsel clock + LPC_USB->USBClkCtrl &= ~PORTSEL_CLK_EN; + + // configure USB D+/D- pins + // P0[29] = USB_D+, 01 + // P0[30] = USB_D-, 01 + LPC_PINCON->PINSEL1 &= ~((3<<26) | (3<<28)); + LPC_PINCON->PINSEL1 |= ((1<<26) | (1<<28)); + + LPC_USB->HcControl = 0; // HARDWARE RESET + LPC_USB->HcControlHeadED = 0; // Initialize Control list head to Zero + LPC_USB->HcBulkHeadED = 0; // Initialize Bulk list head to Zero + + // Wait 100 ms before apply reset + wait_ms(100); + + // software reset + LPC_USB->HcCommandStatus = OR_CMD_STATUS_HCR; + + // Write Fm Interval and Largest Data Packet Counter + LPC_USB->HcFmInterval = DEFAULT_FMINTERVAL; + LPC_USB->HcPeriodicStart = FI * 90 / 100; + + // Put HC in operational state + LPC_USB->HcControl = (LPC_USB->HcControl & (~OR_CONTROL_HCFS)) | OR_CONTROL_HC_OPER; + // Set Global Power + LPC_USB->HcRhStatus = OR_RH_STATUS_LPSC; + + LPC_USB->HcHCCA = (uint32_t)(usb_hcca); + + // Clear Interrrupt Status + LPC_USB->HcInterruptStatus |= LPC_USB->HcInterruptStatus; + + LPC_USB->HcInterruptEnable = OR_INTR_ENABLE_MIE | OR_INTR_ENABLE_WDH | OR_INTR_ENABLE_RHSC; + + // Enable the USB Interrupt + NVIC_SetVector(USB_IRQn, (uint32_t)(_usbisr)); + LPC_USB->HcRhPortStatus1 = OR_RH_PORT_CSC; + LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRSC; + + NVIC_EnableIRQ(USB_IRQn); + + // Check for any connected devices + if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_CCS) { + //Device connected + wait_ms(150); + USB_DBG("Device connected (%08x)\n\r", LPC_USB->HcRhPortStatus1); + deviceConnected(0, 1, LPC_USB->HcRhPortStatus1 & OR_RH_PORT_LSDA); + } +} + +uint32_t USBHALHost::controlHeadED() { + return LPC_USB->HcControlHeadED; +} + +uint32_t USBHALHost::bulkHeadED() { + return LPC_USB->HcBulkHeadED; +} + +uint32_t USBHALHost::interruptHeadED() { + return usb_hcca->IntTable[0]; +} + +void USBHALHost::updateBulkHeadED(uint32_t addr) { + LPC_USB->HcBulkHeadED = addr; +} + + +void USBHALHost::updateControlHeadED(uint32_t addr) { + LPC_USB->HcControlHeadED = addr; +} + +void USBHALHost::updateInterruptHeadED(uint32_t addr) { + usb_hcca->IntTable[0] = addr; +} + + +void USBHALHost::enableList(ENDPOINT_TYPE type) { + switch(type) { + case CONTROL_ENDPOINT: + LPC_USB->HcCommandStatus = OR_CMD_STATUS_CLF; + LPC_USB->HcControl |= OR_CONTROL_CLE; + break; + case ISOCHRONOUS_ENDPOINT: + break; + case BULK_ENDPOINT: + LPC_USB->HcCommandStatus = OR_CMD_STATUS_BLF; + LPC_USB->HcControl |= OR_CONTROL_BLE; + break; + case INTERRUPT_ENDPOINT: + LPC_USB->HcControl |= OR_CONTROL_PLE; + break; + } +} + + +bool USBHALHost::disableList(ENDPOINT_TYPE type) { + switch(type) { + case CONTROL_ENDPOINT: + if(LPC_USB->HcControl & OR_CONTROL_CLE) { + LPC_USB->HcControl &= ~OR_CONTROL_CLE; + return true; + } + return false; + case ISOCHRONOUS_ENDPOINT: + return false; + case BULK_ENDPOINT: + if(LPC_USB->HcControl & OR_CONTROL_BLE){ + LPC_USB->HcControl &= ~OR_CONTROL_BLE; + return true; + } + return false; + case INTERRUPT_ENDPOINT: + if(LPC_USB->HcControl & OR_CONTROL_PLE) { + LPC_USB->HcControl &= ~OR_CONTROL_PLE; + return true; + } + return false; + } + return false; +} + + +void USBHALHost::memInit() { + usb_hcca = (volatile HCCA *)usb_buf; + usb_edBuf = usb_buf + HCCA_SIZE; + usb_tdBuf = usb_buf + HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE); +} + +volatile uint8_t * USBHALHost::getED() { + for (int i = 0; i < MAX_ENDPOINT; i++) { + if ( !edBufAlloc[i] ) { + edBufAlloc[i] = true; + return (volatile uint8_t *)(usb_edBuf + i*ED_SIZE); + } + } + perror("Could not allocate ED\r\n"); + return NULL; //Could not alloc ED +} + +volatile uint8_t * USBHALHost::getTD() { + int i; + for (i = 0; i < MAX_TD; i++) { + if ( !tdBufAlloc[i] ) { + tdBufAlloc[i] = true; + return (volatile uint8_t *)(usb_tdBuf + i*TD_SIZE); + } + } + perror("Could not allocate TD\r\n"); + return NULL; //Could not alloc TD +} + + +void USBHALHost::freeED(volatile uint8_t * ed) { + int i; + i = (ed - usb_edBuf) / ED_SIZE; + edBufAlloc[i] = false; +} + +void USBHALHost::freeTD(volatile uint8_t * td) { + int i; + i = (td - usb_tdBuf) / TD_SIZE; + tdBufAlloc[i] = false; +} + + +void USBHALHost::resetRootHub() { + // Initiate port reset + LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRS; + + while (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_PRS); + + // ...and clear port reset signal + LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRSC; +} + + +void USBHALHost::_usbisr(void) { + if (instHost) { + instHost->UsbIrqhandler(); + } +} + +void USBHALHost::UsbIrqhandler() { + if( LPC_USB->HcInterruptStatus & LPC_USB->HcInterruptEnable ) //Is there something to actually process? + { + + uint32_t int_status = LPC_USB->HcInterruptStatus & LPC_USB->HcInterruptEnable; + + // Root hub status change interrupt + if (int_status & OR_INTR_STATUS_RHSC) { + if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_CSC) { + if (LPC_USB->HcRhStatus & OR_RH_STATUS_DRWE) { + // When DRWE is on, Connect Status Change + // means a remote wakeup event. + } else { + + //Root device connected + if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_CCS) { + + // wait 150ms to avoid bounce + wait_ms(150); + + //Hub 0 (root hub), Port 1 (count starts at 1), Low or High speed + deviceConnected(0, 1, LPC_USB->HcRhPortStatus1 & OR_RH_PORT_LSDA); + } + + //Root device disconnected + else { + + if (!(int_status & OR_INTR_STATUS_WDH)) { + usb_hcca->DoneHead = 0; + } + + // wait 200ms to avoid bounce + wait_ms(200); + + deviceDisconnected(0, 1, NULL, usb_hcca->DoneHead & 0xFFFFFFFE); + + if (int_status & OR_INTR_STATUS_WDH) { + usb_hcca->DoneHead = 0; + LPC_USB->HcInterruptStatus = OR_INTR_STATUS_WDH; + } + } + } + LPC_USB->HcRhPortStatus1 = OR_RH_PORT_CSC; + } + if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_PRSC) { + LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRSC; + } + LPC_USB->HcInterruptStatus = OR_INTR_STATUS_RHSC; + } + + // Writeback Done Head interrupt + if (int_status & OR_INTR_STATUS_WDH) { + transferCompleted(usb_hcca->DoneHead & 0xFFFFFFFE); + LPC_USB->HcInterruptStatus = OR_INTR_STATUS_WDH; + } + } +} +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/inc/devdrv_usb_host_api.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,329 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : devdrv_usb_host_api.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB_HOST_API_H +#define USB_HOST_API_H + +#include "r_typedefs.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define USB_HOST_PORTNUM (2) + +#define USB_HOST_ELT_INTERRUPT_LEVEL (9) + +#define USBHCLOCK_X1_48MHZ (0x0000u) /* USB_X1_48MHz */ +#define USBHCLOCK_EXTAL_12MHZ (0x0004u) /* EXTAL_12MHz */ + +#define USB_HOST_MAX_DEVICE (10) + +#define USB_HOST_ON (1) +#define USB_HOST_OFF (0) +#define USB_HOST_YES (1) +#define USB_HOST_NO (0) + +#define USB_HOST_NON_SPEED (0) +#define USB_HOST_LOW_SPEED (1) +#define USB_HOST_FULL_SPEED (2) +#define USB_HOST_HIGH_SPEED (3) + +/* DEVDRV_SUCCESS(0) & DEVDRV_ERROR(-1) is dev_drv.h */ +#define DEVDRV_USBH_STALL (-2) +#define DEVDRV_USBH_TIMEOUT (-3) +#define DEVDRV_USBH_NAK_TIMEOUT (-4) +#define DEVDRV_USBH_DETACH_ERR (-5) +#define DEVDRV_USBH_SETUP_ERR (-6) +#define DEVDRV_USBH_CTRL_COM_ERR (-7) +#define DEVDRV_USBH_COM_ERR (-8) +#define DEVDRV_USBH_DEV_ADDR_ERR (-9) + +#define USB_HOST_ATTACH (1) +#define USB_HOST_DETACH (0) + +#define USB_HOST_MAX_PIPE_NO (9u) +#define USB_HOST_PIPE0 (0) +#define USB_HOST_PIPE1 (1) +#define USB_HOST_PIPE2 (2) +#define USB_HOST_PIPE3 (3) +#define USB_HOST_PIPE4 (4) +#define USB_HOST_PIPE5 (5) +#define USB_HOST_PIPE6 (6) +#define USB_HOST_PIPE7 (7) +#define USB_HOST_PIPE8 (8) +#define USB_HOST_PIPE9 (9) + +#define USB_HOST_ISO (0xc000u) +#define USB_HOST_INTERRUPT (0x8000u) +#define USB_HOST_BULK (0x4000u) + +#define USB_HOST_PIPE_IDLE (0x00) +#define USB_HOST_PIPE_WAIT (0x01) +#define USB_HOST_PIPE_DONE (0x02) +#define USB_HOST_PIPE_NORES (0x03) +#define USB_HOST_PIPE_STALL (0x04) +#define USB_HOST_PIPE_ERROR (0x05) + +#define USB_HOST_NONE (0x0000u) +#define USB_HOST_BFREFIELD (0x0400u) +#define USB_HOST_BFREON (0x0400u) +#define USB_HOST_BFREOFF (0x0000u) +#define USB_HOST_DBLBFIELD (0x0200u) +#define USB_HOST_DBLBON (0x0200u) +#define USB_HOST_DBLBOFF (0x0000u) +#define USB_HOST_CNTMDFIELD (0x0100u) +#define USB_HOST_CNTMDON (0x0100u) +#define USB_HOST_CNTMDOFF (0x0000u) +#define USB_HOST_SHTNAKON (0x0080u) +#define USB_HOST_SHTNAKOFF (0x0000u) +#define USB_HOST_DIRFIELD (0x0010u) +#define USB_HOST_DIR_H_OUT (0x0010u) +#define USB_HOST_DIR_H_IN (0x0000u) +#define USB_HOST_EPNUMFIELD (0x000fu) + +#define USB_HOST_CUSE (0) +#define USB_HOST_D0USE (1) +#define USB_HOST_D0DMA (2) +#define USB_HOST_D1USE (3) +#define USB_HOST_D1DMA (4) + +#define USB_HOST_CFIFO_USE (0x0000) +#define USB_HOST_D0FIFO_USE (0x1000) +#define USB_HOST_D1FIFO_USE (0x2000) +#define USB_HOST_D0FIFO_DMA (0x5000) +#define USB_HOST_D1FIFO_DMA (0x6000) + +#define USB_HOST_BUF2FIFO (0) +#define USB_HOST_FIFO2BUF (1) + +#define USB_HOST_DRV_DETACHED (0x0000) +#define USB_HOST_DRV_ATTACHED (0x0001) +#define USB_HOST_DRV_GET_DEVICE_DESC_64 (0x0002) +#define USB_HOST_DRV_POWERED (0x0003) +#define USB_HOST_DRV_DEFAULT (0x0004) +#define USB_HOST_DRV_SET_ADDRESS (0x0005) +#define USB_HOST_DRV_ADDRESSED (0x0006) +#define USB_HOST_DRV_GET_DEVICE_DESC_18 (0x0007) +#define USB_HOST_DRV_GET_CONGIG_DESC_9 (0x0008) +#define USB_HOST_DRV_GET_CONGIG_DESC (0x0009) +#define USB_HOST_DRV_SET_CONFIG (0x000a) +#define USB_HOST_DRV_CONFIGURED (0x000b) +#define USB_HOST_DRV_SUSPEND (0x1000) +#define USB_HOST_DRV_NORES (0x0100) +#define USB_HOST_DRV_STALL (0x0200) + +#define USB_HOST_TESTMODE_FORCE (0x000du) +#define USB_HOST_TESTMODE_TESTPACKET (0x000cu) +#define USB_HOST_TESTMODE_SE0_NAK (0x000bu) +#define USB_HOST_TESTMODE_K (0x000au) +#define USB_HOST_TESTMODE_J (0x0009u) +#define USB_HOST_TESTMODE_NORMAL (0x0000u) + +#define USB_HOST_DT_DEVICE (0x01) +#define USB_HOST_DT_CONFIGURATION (0x02) +#define USB_HOST_DT_STRING (0x03) +#define USB_HOST_DT_INTERFACE (0x04) +#define USB_HOST_DT_ENDPOINT (0x05) +#define USB_HOST_DT_DEVICE_QUALIFIER (0x06) +#define USB_HOST_DT_OTHER_SPEED_CONFIGURATION (0x07) +#define USB_HOST_DT_INTERFACE_POWER (0x08) + +#define USB_HOST_IF_CLS_NOT (0x00) +#define USB_HOST_IF_CLS_AUDIO (0x01) +#define USB_HOST_IF_CLS_CDC_CTRL (0x02) +#define USB_HOST_IF_CLS_HID (0x03) +#define USB_HOST_IF_CLS_PHYSICAL (0x05) +#define USB_HOST_IF_CLS_IMAGE (0x06) +#define USB_HOST_IF_CLS_PRINTER (0x07) +#define USB_HOST_IF_CLS_MASS (0x08) +#define USB_HOST_IF_CLS_HUB (0x09) +#define USB_HOST_IF_CLS_CDC_DATA (0x0a) +#define USB_HOST_IF_CLS_CRAD (0x0b) +#define USB_HOST_IF_CLS_CONTENT (0x0d) +#define USB_HOST_IF_CLS_VIDEO (0x0e) +#define USB_HOST_IF_CLS_DIAG (0xdc) +#define USB_HOST_IF_CLS_WIRELESS (0xe0) +#define USB_HOST_IF_CLS_APL (0xfe) +#define USB_HOST_IF_CLS_VENDOR (0xff) +#define USB_HOST_IF_CLS_HELE (0xaa) + +#define USB_HOST_EP_DIR_MASK (0x80) +#define USB_HOST_EP_OUT (0x00) +#define USB_HOST_EP_IN (0x80) +#define USB_HOST_EP_TYPE (0x03) +#define USB_HOST_EP_CNTRL (0x00) +#define USB_HOST_EP_ISO (0x01) +#define USB_HOST_EP_BULK (0x02) +#define USB_HOST_EP_INT (0x03) +#define USB_HOST_EP_NUM_MASK (0x0f) + +#define USB_HOST_PIPE_IN (0) +#define USB_HOST_PIPE_OUT (1) + +#define USB_END_POINT_ERROR (0xffff) + +#define USB_HOST_REQ_GET_STATUS (0x0000) +#define USB_HOST_REQ_CLEAR_FEATURE (0x0100) +#define USB_HOST_REQ_RESERVED2 (0x0200) +#define USB_HOST_REQ_SET_FEATURE (0x0300) +#define USB_HOST_REQ_RESERVED4 (0x0400) +#define USB_HOST_REQ_SET_ADDRESS (0x0500) +#define USB_HOST_REQ_GET_DESCRIPTOR (0x0600) +#define USB_HOST_REQ_SET_DESCRIPTOR (0x0700) +#define USB_HOST_REQ_GET_CONFIGURATION (0x0800) +#define USB_HOST_REQ_SET_CONFIGURATION (0x0900) +#define USB_HOST_REQ_GET_INTERFACE (0x0a00) +#define USB_HOST_REQ_SET_INTERFACE (0x0b00) +#define USB_HOST_REQ_SYNCH_FRAME (0x0c00) + +#define USB_HOST_REQTYPE_HOST_TO_DEVICE (0x0000) +#define USB_HOST_REQTYPE_DEVICE_TO_HOST (0x0080) +#define USB_HOST_REQTYPE_STANDARD (0x0020) +#define USB_HOST_REQTYPE_CLASS (0x0040) +#define USB_HOST_REQTYPE_VENDOR (0x0060) +#define USB_HOST_REQTYPE_DEVICE (0x0000) +#define USB_HOST_REQTYPE_INTERFACE (0x0001) +#define USB_HOST_REQTYPE_ENDPOINT (0x0002) +#define USB_HOST_REQTYPE_OTHER (0x0003) + +#define USB_HOST_DESCTYPE_DEVICE (0x0100) +#define USB_HOST_DESCTYPE_CONFIGURATION (0x0200) +#define USB_HOST_DESCTYPE_STRING (0x0300) +#define USB_HOST_DESCTYPE_INTERFACE (0x0400) +#define USB_HOST_DESCTYPE_ENDPOINT (0x0500) +#define USB_HOST_DESCTYPE_DEVICE_QUALIFIER (0x0600) +#define USB_HOST_DESCTYPE_OTHER_SPEED_CONFIGURATION (0x0700) +#define USB_HOST_DESCTYPE_INTERFACE_POWER (0x0800) + + +/******************************************************************************* +Variable Externs +*******************************************************************************/ +typedef struct +{ + uint16_t pipe_number; + uint16_t pipe_cfg; + uint16_t pipe_buf; + uint16_t pipe_max_pktsize; + uint16_t pipe_cycle; + uint16_t fifo_port; +} USB_HOST_CFG_PIPETBL_t; + +typedef struct +{ + uint32_t fifo; + uint32_t buffer; + uint32_t bytes; + uint32_t dir; + uint32_t size; +} USB_HOST_DMA_t; + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +uint16_t R_USB_api_host_init(uint16_t root, uint8_t int_level, uint16_t mode, uint16_t clockmode); +int32_t R_USB_api_host_enumeration(uint16_t root, uint16_t devadr); +int32_t R_USB_api_host_detach(uint16_t root); +int32_t R_USB_api_host_data_in(uint16_t root, uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t R_USB_api_host_data_in2(uint16_t root, uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf, uint32_t *bytes); +int32_t R_USB_api_host_data_out(uint16_t root, uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t R_USB_api_host_control_transfer(uint16_t root, uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len, uint8_t *Buf); +int32_t R_USB_api_host_set_endpoint(uint16_t root, uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t *configdescriptor); +int32_t R_USB_api_host_clear_endpoint(uint16_t root, USB_HOST_CFG_PIPETBL_t *user_table); +int32_t R_USB_api_host_clear_endpoint_pipe(uint16_t root, uint16_t pipe_sel, USB_HOST_CFG_PIPETBL_t *user_table); +uint16_t R_USB_api_host_SetEndpointTable(uint16_t root, uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t* Table); + +int32_t R_USB_api_host_GetDeviceDescriptor(uint16_t root, uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t R_USB_api_host_GetConfigDescriptor(uint16_t root, uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t R_USB_api_host_SetConfig(uint16_t root, uint16_t devadr, uint16_t confignum); +int32_t R_USB_api_host_SetInterface(uint16_t root, uint16_t devadr, uint16_t interface_alt, uint16_t interface_index); +int32_t R_USB_api_host_ClearStall(uint16_t root, uint16_t devadr, uint16_t ep_dir); +uint16_t R_USB_api_host_GetUsbDeviceState(uint16_t root); + +void R_USB_api_host_elt_clocksel(uint16_t clockmode); +void R_USB_api_host_elt_4_4(uint16_t root); +void R_USB_api_host_elt_4_5(uint16_t root); +void R_USB_api_host_elt_4_6(uint16_t root); +void R_USB_api_host_elt_4_7(uint16_t root); +void R_USB_api_host_elt_4_8(uint16_t root); +void R_USB_api_host_elt_4_9(uint16_t root); +void R_USB_api_host_elt_get_desc(uint16_t root); + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host_api.h" +#include "usb1_host_api.h" + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +#ifdef USB0_HOST_API_H +uint16_t Userdef_USB_usb0_host_d0fifo_dmaintid(void); +uint16_t Userdef_USB_usb0_host_d1fifo_dmaintid(void); +void Userdef_USB_usb0_host_attach(void); +void Userdef_USB_usb0_host_detach(void); +void Userdef_USB_usb0_host_delay_1ms(void); +void Userdef_USB_usb0_host_delay_xms(uint32_t msec); +void Userdef_USB_usb0_host_delay_10us(uint32_t usec); +void Userdef_USB_usb0_host_delay_500ns(void); +void Userdef_USB_usb0_host_start_dma(USB_HOST_DMA_t * dma, uint16_t dfacc); +uint32_t Userdef_USB_usb0_host_stop_dma0(void); +uint32_t Userdef_USB_usb0_host_stop_dma1(void); +void Userdef_USB_usb0_host_notice(const char * format); +void Userdef_USB_usb0_host_user_rdy(const char * format, uint16_t data); +#endif + +#ifdef USB1_HOST_API_H +uint16_t Userdef_USB_usb1_host_d0fifo_dmaintid(void); +uint16_t Userdef_USB_usb1_host_d1fifo_dmaintid(void); +void Userdef_USB_usb1_host_attach(void); +void Userdef_USB_usb1_host_detach(void); +void Userdef_USB_usb1_host_delay_1ms(void); +void Userdef_USB_usb1_host_delay_xms(uint32_t msec); +void Userdef_USB_usb1_host_delay_10us(uint32_t usec); +void Userdef_USB_usb1_host_delay_500ns(void); +void Userdef_USB_usb1_host_start_dma(USB_HOST_DMA_t * dma, uint16_t dfacc); +uint32_t Userdef_USB_usb1_host_stop_dma0(void); +uint32_t Userdef_USB_usb1_host_stop_dma1(void); +void Userdef_USB_usb1_host_notice(const char * format); +void Userdef_USB_usb1_host_user_rdy(const char * format, uint16_t data); +#endif + +#endif /* USB_HOST_API_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/inc/usb_host.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,201 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb_host.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB_HOST_H +#define USB_HOST_H + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "r_typedefs.h" +#include "iodefine.h" +#include "rza_io_regrw.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define USB_HOST_DEVICE_0 (0u) +#define USB_HOST_DEVICE_1 (1u) +#define USB_HOST_DEVICE_2 (2u) +#define USB_HOST_DEVICE_3 (3u) +#define USB_HOST_DEVICE_4 (4u) +#define USB_HOST_DEVICE_5 (5u) +#define USB_HOST_DEVICE_6 (6u) +#define USB_HOST_DEVICE_7 (7u) +#define USB_HOST_DEVICE_8 (8u) +#define USB_HOST_DEVICE_9 (9u) +#define USB_HOST_DEVICE_10 (10u) + +#define USB_HOST_ENDPOINT_DESC (0x05) + +#define USB_HOST_BITUPLLE (0x0002u) +#define USB_HOST_BITUCKSEL (0x0004u) +#define USB_HOST_BITBWAIT (0x003fu) + +#define USB_HOST_BUSWAIT_02 (0x0000u) +#define USB_HOST_BUSWAIT_03 (0x0001u) +#define USB_HOST_BUSWAIT_04 (0x0002u) +#define USB_HOST_BUSWAIT_05 (0x0003u) +#define USB_HOST_BUSWAIT_06 (0x0004u) +#define USB_HOST_BUSWAIT_07 (0x0005u) +#define USB_HOST_BUSWAIT_08 (0x0006u) +#define USB_HOST_BUSWAIT_09 (0x0007u) +#define USB_HOST_BUSWAIT_10 (0x0008u) +#define USB_HOST_BUSWAIT_11 (0x0009u) +#define USB_HOST_BUSWAIT_12 (0x000au) +#define USB_HOST_BUSWAIT_13 (0x000bu) +#define USB_HOST_BUSWAIT_14 (0x000cu) +#define USB_HOST_BUSWAIT_15 (0x000du) +#define USB_HOST_BUSWAIT_16 (0x000eu) +#define USB_HOST_BUSWAIT_17 (0x000fu) + +#define USB_HOST_FS_JSTS (0x0001u) +#define USB_HOST_LS_JSTS (0x0002u) + +#define USB_HOST_BITRST (0x0040u) +#define USB_HOST_BITRESUME (0x0020u) +#define USB_HOST_BITUACT (0x0010u) +#define USB_HOST_HSPROC (0x0004u) +#define USB_HOST_HSMODE (0x0003u) +#define USB_HOST_FSMODE (0x0002u) +#define USB_HOST_LSMODE (0x0001u) +#define USB_HOST_UNDECID (0x0000u) + +#define USB_HOST_BITRCNT (0x8000u) +#define USB_HOST_BITDREQE (0x1000u) +#define USB_HOST_BITMBW (0x0c00u) +#define USB_HOST_BITMBW_8 (0x0000u) +#define USB_HOST_BITMBW_16 (0x0400u) +#define USB_HOST_BITMBW_32 (0x0800u) +#define USB_HOST_BITBYTE_LITTLE (0x0000u) +#define USB_HOST_BITBYTE_BIG (0x0100u) +#define USB_HOST_BITISEL (0x0020u) +#define USB_HOST_BITCURPIPE (0x000fu) + +#define USB_HOST_CFIFO_READ (0x0000u) +#define USB_HOST_CFIFO_WRITE (0x0020u) + +#define USB_HOST_BITBVAL (0x8000u) +#define USB_HOST_BITBCLR (0x4000u) +#define USB_HOST_BITFRDY (0x2000u) +#define USB_HOST_BITDTLN (0x0fffu) + +#define USB_HOST_BITBEMPE (0x0400u) +#define USB_HOST_BITNRDYE (0x0200u) +#define USB_HOST_BITBRDYE (0x0100u) +#define USB_HOST_BITBEMP (0x0400u) +#define USB_HOST_BITNRDY (0x0200u) +#define USB_HOST_BITBRDY (0x0100u) + +#define USB_HOST_BITBCHGE (0x4000u) +#define USB_HOST_BITDTCHE (0x1000u) +#define USB_HOST_BITATTCHE (0x0800u) +#define USB_HOST_BITEOFERRE (0x0040u) +#define USB_HOST_BITBCHG (0x4000u) +#define USB_HOST_BITDTCH (0x1000u) +#define USB_HOST_BITATTCH (0x0800u) +#define USB_HOST_BITEOFERR (0x0040u) + +#define USB_HOST_BITSIGNE (0x0020u) +#define USB_HOST_BITSACKE (0x0010u) +#define USB_HOST_BITSIGN (0x0020u) +#define USB_HOST_BITSACK (0x0010u) + +#define USB_HOST_BITSUREQ (0x4000u) +#define USB_HOST_BITSQSET (0x0080u) +#define USB_HOST_PID_STALL2 (0x0003u) +#define USB_HOST_PID_STALL (0x0002u) +#define USB_HOST_PID_BUF (0x0001u) +#define USB_HOST_PID_NAK (0x0000u) + +#define USB_HOST_PIPExBUF (64u) + +#define USB_HOST_D0FIFO (0) +#define USB_HOST_D1FIFO (1) +#define USB_HOST_DMA_READY (0) +#define USB_HOST_DMA_BUSY (1) +#define USB_HOST_DMA_BUSYEND (2) + +#define USB_HOST_FIFO_USE (0x7000) + +#define USB_HOST_FIFOERROR (0xffff) +#define USB_HOST_WRITEEND (0) +#define USB_HOST_WRITESHRT (1) +#define USB_HOST_WRITING (2) +#define USB_HOST_WRITEDMA (3) +#define USB_HOST_READEND (0) +#define USB_HOST_READSHRT (1) +#define USB_HOST_READING (2) +#define USB_HOST_READOVER (3) +#define USB_HOST_READZERO (4) + +#define USB_HOST_CMD_IDLE (0x0000) +#define USB_HOST_CMD_DOING (0x0001) +#define USB_HOST_CMD_DONE (0x0002) +#define USB_HOST_CMD_NORES (0x0003) +#define USB_HOST_CMD_STALL (0x0004) +#define USB_HOST_CMD_FIELD (0x000f) + +#if 0 +#define USB_HOST_CHG_CMDFIELD( r, v ) do { r &= ( ~USB_HOST_CMD_FIELD ); \ + r |= v; } while(0) +#endif + +#define USB_HOST_MODE_WRITE (0x0100) +#define USB_HOST_MODE_READ (0x0200) +#define USB_HOST_MODE_NO_DATA (0x0300) +#define USB_HOST_MODE_FIELD (0x0f00) + +#define USB_HOST_STAGE_SETUP (0x0010) +#define USB_HOST_STAGE_DATA (0x0020) +#define USB_HOST_STAGE_STATUS (0x0030) +#define USB_HOST_STAGE_FIELD (0x00f0) + +#if 0 +#define USB_HOST_CHG_STAGEFIELD( r, v ) do { r &= ( ~USB_HOST_STAGE_FIELD ); \ + r |= v; } while(0) +#endif + +#define USB_HOST_DEVADD_MASK (0x7fc0) + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +extern uint16_t g_usb_host_elt_clockmode; + +#endif /* USB_HOST_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/inc/usb_host_version.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,32 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb_host_version.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ + +#define USB_HOST_LOCAL_Rev "VER080_140709" + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/ohci_wrapp_RZ_A1.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,1492 @@ +/* Copyright (c) 2010-2011 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#include <string.h> +#include "cmsis.h" +#include "cmsis_os.h" +#include "ohci_wrapp_RZ_A1.h" +#include "ohci_wrapp_RZ_A1_local.h" +#include "rza_io_regrw.h" +#include "usb_host_setting.h" + +/* ------------------ HcControl Register --------------------- */ +#define OR_CONTROL_PLE (0x00000004) +#define OR_CONTROL_IE (0x00000008) +#define OR_CONTROL_CLE (0x00000010) +#define OR_CONTROL_BLE (0x00000020) +/* ----------------- HcCommandStatus Register ----------------- */ +#define OR_CMD_STATUS_HCR (0x00000001) +#define OR_CMD_STATUS_CLF (0x00000002) +#define OR_CMD_STATUS_BLF (0x00000004) +#define OR_CMD_STATUS_OCR (0x00000008) +/* --------------- HcInterruptStatus Register ----------------- */ +#define OR_INTR_STATUS_WDH (0x00000002) +#define OR_INTR_STATUS_RHSC (0x00000040) +/* --------------- HcInterruptEnable Register ----------------- */ +#define OR_INTR_ENABLE_WDH (0x00000002) +#define OR_INTR_ENABLE_RHSC (0x00000040) +/* -------------- HcRhPortStatus[1:NDP] Register -------------- */ +#define OR_RH_PORT_CSC (0x00010000) +#define OR_RH_PORT_LSDA (0x00000200) +#define OR_RH_PORT_PRS (0x00000010) +#define OR_RH_PORT_POCI (0x00000008) +#define OR_RH_PORT_CCS (0x00000001) + +#define ED_FORMAT (0x00008000) /* Format */ +#define ED_SKIP (0x00004000) /* Skip this ep in queue */ +#define ED_TOGLE_CARRY (0x00000002) +#define ED_HALTED (0x00000001) + +#define TD_SETUP (0x00000000) /* Direction of Setup Packet */ +#define TD_OUT (0x00080000) /* Direction Out */ +#define TD_TOGGLE_0 (0x02000000) /* Toggle 0 */ +#define TD_TOGGLE_1 (0x03000000) /* Toggle 1 */ + +/* -------------- USB Standard Requests -------------- */ +#define GET_STATUS (0x00) +#define SET_FEATURE (0x03) +#define SET_ADDRESS (0x05) + +#define TD_CTL_MSK_DP (0x00180000) +#define TD_CTL_MSK_T (0x03000000) +#define TD_CTL_MSK_CC (0xF0000000) +#define TD_CTL_MSK_EC (0x0C000000) +#define TD_CTL_SHFT_CC (28) +#define TD_CTL_SHFT_EC (26) +#define TD_CTL_SHFT_T (24) +#define ED_SHFT_TOGLE_CARRY (1) +#define SIG_GEN_LIST_REQ (1) +#if (ISO_TRANS_MAX_NUM > 0) +#define TD_PSW_MSK_CC (0xF000) +#define TD_PSW_SHFT_CC (12) +#define TD_CTL_MSK_FC (0x07000000) +#define TD_CTL_SHFT_FC (24) +#endif + +#define CTL_TRANS_TIMEOUT (1000) +#define BLK_TRANS_TIMEOUT (5) +#define TOTAL_SEM_NUM (5 + (2 * INT_TRANS_MAX_NUM) + (2 * ISO_TRANS_MAX_NUM)) + +#define PORT_LOW_SPEED (0x00000200) +#define PORT_HIGH_SPEED (0x00000400) +#define PORT_NUM (16 + 1) /* num + root(1) */ + +typedef struct tag_hctd { + uint32_t control; /* Transfer descriptor control */ + uint8_t *currBufPtr; /* Physical address of current buffer pointer */ + struct tag_hctd *nextTD; /* Physical pointer to next Transfer Descriptor */ + uint8_t *bufEnd; /* Physical address of end of buffer */ +} hctd_t; + +#if (ISO_TRANS_MAX_NUM > 0) +#define PSW_NUM (8) +typedef struct tag_hcisotd { + uint32_t control; /* Transfer descriptor control */ + uint8_t *bufferPage0; /* Buffer Page 0 */ + struct tag_hcisotd *nextTD; /* Physical pointer to next Transfer Descriptor */ + uint8_t *bufEnd; /* Physical address of end of buffer */ + uint16_t offsetPSW[PSW_NUM]; /* Offset/PSW */ +} hcisotd_t; +#endif + +typedef struct tag_hced { + uint32_t control; /* Endpoint descriptor control */ + uint32_t tailTD; /* Physical address of tail in Transfer descriptor list */ + uint32_t headTD; /* Physcial address of head in Transfer descriptor list */ + struct tag_hced *nextED; /* Physical address of next Endpoint descriptor */ +} hced_t; + +typedef struct tag_hcca { + uint32_t IntTable[32]; /* Interrupt Table */ + uint32_t FrameNumber; /* Frame Number */ + uint32_t DoneHead; /* Done Head */ + volatile uint8_t Reserved[116]; /* Reserved for future use */ + volatile uint8_t Unknown[4]; /* Unused */ +} hcca_t; + +typedef struct tag_usb_ohci_reg { + volatile uint32_t HcRevision; + volatile uint32_t HcControl; + volatile uint32_t HcCommandStatus; + volatile uint32_t HcInterruptStatus; + volatile uint32_t HcInterruptEnable; + volatile uint32_t HcInterruptDisable; + volatile uint32_t HcHCCA; + volatile uint32_t HcPeriodCurrentED; + volatile uint32_t HcControlHeadED; + volatile uint32_t HcControlCurrentED; + volatile uint32_t HcBulkHeadED; + volatile uint32_t HcBulkCurrentED; + volatile uint32_t HcDoneHead; + volatile uint32_t HcFmInterval; + volatile uint32_t HcFmRemaining; + volatile uint32_t HcFmNumber; + volatile uint32_t HcPeriodicStart; + volatile uint32_t HcLSThreshold; + volatile uint32_t HcRhDescriptorA; + volatile uint32_t HcRhDescriptorB; + volatile uint32_t HcRhStatus; + volatile uint32_t HcRhPortStatus1; +} usb_ohci_reg_t; + +typedef struct tag_genelal_ed { + osThreadId tskid; + osSemaphoreId semid_wait; + osSemaphoreId semid_list; + void *p_curr_td; /* pointer of hctd_t or hcisotd_t */ + hced_t *p_curr_ed; + uint32_t pipe_no; + uint32_t trans_wait; + uint32_t cycle_time; + uint8_t *p_start_buf; +#if (ISO_TRANS_MAX_NUM > 0) + uint32_t psw_idx; +#endif +} genelal_ed_t; + +typedef struct tag_tdinfo { + uint32_t count; + uint32_t direction; + uint32_t msp; + uint16_t devadr; + uint16_t speed; /* 1:Speed = Low */ + uint8_t endpoint_no; +} tdinfo_t; + +typedef struct tag_split_trans { + uint16_t root_devadr; + uint16_t get_port; + uint16_t port_speed; + uint16_t reset_port; + uint32_t seq_cnt; + uint32_t port_sts_bits[PORT_NUM]; +} split_trans_t; + +static void callback_task(void const * argument); +static void control_ed_task(void const * argument); +static void bulk_ed_task(void const * argument); +static void int_ed_task(void const * argument); +static int32_t int_trans_doing(hced_t *p_ed, uint32_t index); +static int32_t chk_genelal_ed(genelal_ed_t *p_g_ed); +static void chk_genelal_td_done(genelal_ed_t *p_g_ed); +static void chk_split_trans_setting(genelal_ed_t *p_g_ed); +static void set_split_trans_setting(void); +static void control_trans(genelal_ed_t *p_g_ed); +static void bulk_trans(genelal_ed_t *p_g_ed); +static void int_trans_setting(genelal_ed_t *p_g_ed, uint32_t index); +static uint32_t chk_cycle(hced_t *p_ed); +static void int_trans(genelal_ed_t *p_g_ed); +static void get_td_info(genelal_ed_t *p_g_ed, tdinfo_t *p_td_info); +static void set_togle(uint32_t pipe, hctd_t *p_td, hced_t *p_ed); +#if (ISO_TRANS_MAX_NUM > 0) +static void iso_ed_task(void const * argument); +static int32_t iso_trans_doing(hced_t *p_ed, uint32_t index); +static void chk_iso_td_done(genelal_ed_t *p_g_ed); +static int32_t chk_iso_ed(genelal_ed_t *p_g_ed); +static void iso_trans_setting(genelal_ed_t *p_g_ed, uint32_t index); +static void iso_trans(genelal_ed_t *p_g_ed); +#endif +static void connect_check(void); + +extern USB_HOST_CFG_PIPETBL_t usb_host_blk_ep_tbl1[]; +extern USB_HOST_CFG_PIPETBL_t usb_host_int_ep_tbl1[]; +#if (ISO_TRANS_MAX_NUM > 0) +extern USB_HOST_CFG_PIPETBL_t usb_host_iso_ep_tbl1[]; +#endif + +static usb_ohci_reg_t usb_reg; +static usb_ohci_reg_t *p_usb_reg = &usb_reg; +static usbisr_fnc_t *p_usbisr_cb = NULL; +static osSemaphoreId semid_cb = NULL; +static uint32_t connect_change = 0xFFFFFFFF; +static uint32_t connect_status = 0; +static uint32_t init_end = 0; +static genelal_ed_t ctl_ed; +static genelal_ed_t blk_ed; +static genelal_ed_t int_ed[INT_TRANS_MAX_NUM]; +static split_trans_t split_ctl; + +#if (ISO_TRANS_MAX_NUM > 0) +static genelal_ed_t iso_ed[ISO_TRANS_MAX_NUM]; +#endif + +osSemaphoreDef(ohciwrapp_sem_01); +osSemaphoreDef(ohciwrapp_sem_02); +osSemaphoreDef(ohciwrapp_sem_03); +osSemaphoreDef(ohciwrapp_sem_04); +osSemaphoreDef(ohciwrapp_sem_05); +osSemaphoreDef(ohciwrapp_sem_06); +osSemaphoreDef(ohciwrapp_sem_07); +#if (INT_TRANS_MAX_NUM >= 2) +osSemaphoreDef(ohciwrapp_sem_08); +osSemaphoreDef(ohciwrapp_sem_09); +#endif +#if (INT_TRANS_MAX_NUM >= 3) +osSemaphoreDef(ohciwrapp_sem_10); +osSemaphoreDef(ohciwrapp_sem_11); +#endif +#if (INT_TRANS_MAX_NUM >= 4) +osSemaphoreDef(ohciwrapp_sem_12); +osSemaphoreDef(ohciwrapp_sem_13); +#endif +#if (ISO_TRANS_MAX_NUM >= 1) +osSemaphoreDef(ohciwrapp_sem_14); +osSemaphoreDef(ohciwrapp_sem_15); +#endif +#if (ISO_TRANS_MAX_NUM >= 2) +osSemaphoreDef(ohciwrapp_sem_16); +osSemaphoreDef(ohciwrapp_sem_17); +#endif + +osThreadDef(callback_task, osPriorityHigh, 512); +osThreadDef(control_ed_task, osPriorityNormal, 512); +osThreadDef(bulk_ed_task, osPriorityNormal, 512); +static void int_ed_task_1(void const * argument) { + int_ed_task(argument); +} +osThreadDef(int_ed_task_1, osPriorityNormal, 512); +#if (INT_TRANS_MAX_NUM >= 2) +static void int_ed_task_2(void const * argument) { + int_ed_task(argument); +} +osThreadDef(int_ed_task_2, osPriorityNormal, 512); +#endif +#if (INT_TRANS_MAX_NUM >= 3) +static void int_ed_task_3(void const * argument) { + int_ed_task(argument); +} +osThreadDef(int_ed_task_3, osPriorityNormal, 512); +#endif +#if (INT_TRANS_MAX_NUM >= 4) +static void int_ed_task_4(void const * argument) { + int_ed_task(argument); +} +osThreadDef(int_ed_task_4, osPriorityNormal, 512); +#endif + +#if (ISO_TRANS_MAX_NUM >= 1) +static void iso_ed_task_1(void const * argument) { + iso_ed_task(argument); +} +osThreadDef(iso_ed_task_1, osPriorityAboveNormal, 512); +#endif +#if (ISO_TRANS_MAX_NUM >= 2) +static void iso_ed_task_2(void const * argument) { + iso_ed_task(argument); +} +osThreadDef(iso_ed_task_2, osPriorityAboveNormal, 512); +#endif + +void ohciwrapp_init(usbisr_fnc_t *p_usbisr_fnc) { + static const osSemaphoreDef_t * const sem_def_tbl[TOTAL_SEM_NUM] = { + osSemaphore(ohciwrapp_sem_01), osSemaphore(ohciwrapp_sem_02), osSemaphore(ohciwrapp_sem_03) + , osSemaphore(ohciwrapp_sem_04), osSemaphore(ohciwrapp_sem_05), osSemaphore(ohciwrapp_sem_06) + , osSemaphore(ohciwrapp_sem_07) +#if (INT_TRANS_MAX_NUM >= 2) + , osSemaphore(ohciwrapp_sem_08), osSemaphore(ohciwrapp_sem_09) +#endif +#if (INT_TRANS_MAX_NUM >= 3) + , osSemaphore(ohciwrapp_sem_10), osSemaphore(ohciwrapp_sem_11) +#endif +#if (INT_TRANS_MAX_NUM >= 4) + , osSemaphore(ohciwrapp_sem_12), osSemaphore(ohciwrapp_sem_13) +#endif +#if (ISO_TRANS_MAX_NUM >= 1) + , osSemaphore(ohciwrapp_sem_14), osSemaphore(ohciwrapp_sem_15) +#endif +#if (ISO_TRANS_MAX_NUM >= 2) + , osSemaphore(ohciwrapp_sem_16), osSemaphore(ohciwrapp_sem_17) +#endif + }; + static const osThreadDef_t * const int_tsk_def_tbl[INT_TRANS_MAX_NUM] = { + osThread(int_ed_task_1) +#if (INT_TRANS_MAX_NUM >= 2) + , osThread(int_ed_task_2) +#endif +#if (INT_TRANS_MAX_NUM >= 3) + , osThread(int_ed_task_3) +#endif +#if (INT_TRANS_MAX_NUM >= 4) + , osThread(int_ed_task_4) +#endif + }; +#if (ISO_TRANS_MAX_NUM > 0) + static const osThreadDef_t * const iso_tsk_def_tbl[ISO_TRANS_MAX_NUM] = { + osThread(iso_ed_task_1) +#if (ISO_TRANS_MAX_NUM >= 2) + , osThread(iso_ed_task_2) +#endif + }; +#endif + + uint32_t cnt; + uint32_t index = 0; + + /* Disables interrupt for usb */ + GIC_DisableIRQ(USBIXUSBIX); + +#if (USB_HOST_CH == 0) + /* P4_1(USB0_EN) */ + GPIOP4 &= ~0x0002; /* Outputs low level */ + GPIOPMC4 &= ~0x0002; /* Port mode */ + GPIOPM4 &= ~0x0002; /* Output mode */ +#endif + + p_usbisr_cb = p_usbisr_fnc; +#if (USB_HOST_HISPEED == 0) + g_usbx_host_SupportUsbDeviceSpeed = USB_HOST_FULL_SPEED; +#else + g_usbx_host_SupportUsbDeviceSpeed = USB_HOST_HIGH_SPEED; +#endif + p_usb_reg->HcRevision = 0x00000010; + p_usb_reg->HcControl = 0x00000000; + p_usb_reg->HcCommandStatus = 0x00000000; + p_usb_reg->HcInterruptStatus = 0x00000000; + p_usb_reg->HcInterruptEnable = 0x00000000; + p_usb_reg->HcInterruptDisable = 0x00000000; + p_usb_reg->HcHCCA = 0x00000000; + p_usb_reg->HcPeriodCurrentED = 0x00000000; + p_usb_reg->HcControlHeadED = 0x00000000; + p_usb_reg->HcControlCurrentED = 0x00000000; + p_usb_reg->HcBulkHeadED = 0x00000000; + p_usb_reg->HcBulkCurrentED = 0x00000000; + p_usb_reg->HcDoneHead = 0x00000000; + p_usb_reg->HcFmInterval = 0x00002EDF; + p_usb_reg->HcFmRemaining = 0x00002EDF; + p_usb_reg->HcFmNumber = 0x00000000; + p_usb_reg->HcPeriodicStart = 0x00000000; + p_usb_reg->HcLSThreshold = 0x00000628; + p_usb_reg->HcRhDescriptorA = 0xFF000901; + p_usb_reg->HcRhDescriptorB = 0x00020000; + p_usb_reg->HcRhStatus = 0x00000000; + p_usb_reg->HcRhPortStatus1 = 0x00000000; + +#if (USB_HOST_CH == 0) + GPIOP4 |= 0x0002; /* P4_1 Outputs high level */ + osDelay(5); + GPIOP4 &= ~0x0002; /* P4_1 Outputs low level */ + osDelay(10); +#else + osDelay(15); +#endif + + if (init_end == 0) { + (void)memset(&ctl_ed, 0, sizeof(ctl_ed)); + (void)memset(&blk_ed, 0, sizeof(blk_ed)); + (void)memset(&int_ed[0], 0, sizeof(int_ed)); +#if (ISO_TRANS_MAX_NUM > 0) + (void)memset(&iso_ed[0], 0, sizeof(iso_ed)); +#endif + + /* callback */ + semid_cb = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + (void)osThreadCreate(osThread(callback_task), 0); + + /* control transfer */ + ctl_ed.semid_wait = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + ctl_ed.semid_list = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + ctl_ed.tskid = osThreadCreate(osThread(control_ed_task), 0); + + /* bulk transfer */ + blk_ed.semid_wait = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + blk_ed.semid_list = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + blk_ed.tskid = osThreadCreate(osThread(bulk_ed_task), 0); + + /* interrupt transfer */ + for (cnt = 0; cnt < INT_TRANS_MAX_NUM; cnt++) { + int_ed[cnt].semid_wait = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + int_ed[cnt].semid_list = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + int_ed[cnt].tskid = osThreadCreate(int_tsk_def_tbl[cnt], (void *)cnt); + } + +#if (ISO_TRANS_MAX_NUM > 0) + /* isochronous transfer */ + for (cnt = 0; cnt < ISO_TRANS_MAX_NUM; cnt++) { + iso_ed[cnt].semid_wait = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + iso_ed[cnt].semid_list = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + iso_ed[cnt].tskid = osThreadCreate(iso_tsk_def_tbl[cnt], (void *)cnt); + } +#endif + init_end = 1; + } +} + +uint32_t ohciwrapp_reg_r(uint32_t reg_ofs) { + if (init_end == 0) { + return 0; + } + + return *(uint32_t *)((uint8_t *)p_usb_reg + reg_ofs); +} + +void ohciwrapp_reg_w(uint32_t reg_ofs, uint32_t set_data) { + uint32_t cnt; + uint32_t last_data; + hcca_t *p_hcca; + + if (init_end == 0) { + return; + } + + switch (reg_ofs) { + case OHCI_REG_CONTROL: + last_data = p_usb_reg->HcControl; + p_usb_reg->HcControl = (set_data & 0x000007FF); + if ((last_data & OR_CONTROL_CLE) != (set_data & OR_CONTROL_CLE)) { + /* change CLE */ + if ((set_data & OR_CONTROL_CLE) != 0) { + (void)osSemaphoreRelease(ctl_ed.semid_list); + } else { + if (ctl_ed.trans_wait == 1) { + ctl_ed.trans_wait = 0; + (void)osSemaphoreRelease(ctl_ed.semid_wait); + } + (void)osSemaphoreWait(ctl_ed.semid_list, osWaitForever); + } + } + if ((last_data & OR_CONTROL_BLE) != (set_data & OR_CONTROL_BLE)) { + /* change BLE */ + if ((set_data & OR_CONTROL_BLE) != 0) { + (void)osSemaphoreRelease(blk_ed.semid_list); + } else { + if (blk_ed.trans_wait == 1) { + blk_ed.trans_wait = 0; + (void)osSemaphoreRelease(blk_ed.semid_wait); + } + (void)osSemaphoreWait(blk_ed.semid_list, osWaitForever); + } + } +#if (ISO_TRANS_MAX_NUM > 0) + if ((last_data & OR_CONTROL_IE) != (set_data & OR_CONTROL_IE)) { + /* change IE */ + for (cnt = 0; cnt < ISO_TRANS_MAX_NUM; cnt++) { + if ((set_data & OR_CONTROL_IE) != 0) { + (void)osSemaphoreRelease(iso_ed[cnt].semid_list); + } else { + if (iso_ed[cnt].trans_wait == 1) { + iso_ed[cnt].trans_wait = 0; + (void)osSemaphoreRelease(iso_ed[cnt].semid_wait); + } + (void)osSemaphoreWait(iso_ed[cnt].semid_list, osWaitForever); + } + } + } +#endif + if ((last_data & OR_CONTROL_PLE) != (set_data & OR_CONTROL_PLE)) { + /* change PLE */ + for (cnt = 0; cnt < INT_TRANS_MAX_NUM; cnt++) { + if ((set_data & OR_CONTROL_PLE) != 0) { + (void)osSemaphoreRelease(int_ed[cnt].semid_list); + } else { + if (int_ed[cnt].trans_wait == 1) { + int_ed[cnt].trans_wait = 0; + (void)osSemaphoreRelease(int_ed[cnt].semid_wait); + } + (void)osSemaphoreWait(int_ed[cnt].semid_list, osWaitForever); + } + } + } + break; + case OHCI_REG_COMMANDSTATUS: + if ((set_data & OR_CMD_STATUS_HCR) != 0) { /* HostController Reset */ + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_HCR; + if (usbx_api_host_init(16, g_usbx_host_SupportUsbDeviceSpeed, USBHCLOCK_X1_48MHZ) == USB_HOST_ATTACH) { + ohciwrapp_loc_Connect(1); + } + p_usb_reg->HcCommandStatus &= ~OR_CMD_STATUS_HCR; + } + if ((set_data & OR_CMD_STATUS_CLF) != 0) { + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_CLF; + osSignalSet(ctl_ed.tskid, SIG_GEN_LIST_REQ); + } + if ((set_data & OR_CMD_STATUS_BLF) != 0) { + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_BLF; + osSignalSet(blk_ed.tskid, SIG_GEN_LIST_REQ); + } + if ((set_data & OR_CMD_STATUS_OCR) != 0) { + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_OCR; + } else { + p_usb_reg->HcCommandStatus &= ~OR_CMD_STATUS_OCR; + } + break; + case OHCI_REG_INTERRUPTSTATUS: + if (((p_usb_reg->HcInterruptStatus & OR_INTR_STATUS_WDH) != 0) + && ((set_data & OR_INTR_STATUS_WDH) != 0)) { + if (p_usb_reg->HcDoneHead != 0x00000000) { + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + p_hcca->DoneHead = p_usb_reg->HcDoneHead; + p_usb_reg->HcDoneHead = 0x00000000; + p_usb_reg->HcInterruptStatus |= OR_INTR_STATUS_WDH; + (void)osSemaphoreRelease(semid_cb); + } else { + p_usb_reg->HcInterruptStatus &= ~OR_INTR_STATUS_WDH; + } + } + if ((set_data & OR_INTR_STATUS_RHSC) != 0) { + p_usb_reg->HcInterruptStatus &= ~OR_INTR_STATUS_RHSC; + } + break; + case OHCI_REG_INTERRUPTENABLE: + case OHCI_REG_INTERRUPTDISABLE: + case OHCI_REG_HCCA: + case OHCI_REG_CONTROLHEADED: + case OHCI_REG_CONTROLCURRENTED: + case OHCI_REG_BULKHEADED: + case OHCI_REG_BULKCURRENTED: + case OHCI_REG_FMINTERVAL: + case OHCI_REG_FMREMAINING: + case OHCI_REG_PERIODICSTART: + case OHCI_REG_LSTHRESHOLD: + case OHCI_REG_RHDESCRIPTORA: + case OHCI_REG_RHDESCRIPTORB: + case OHCI_REG_RHSTATUS: + *(uint32_t *)((uint8_t *)p_usb_reg + reg_ofs) = set_data; + break; + case OHCI_REG_RHPORTSTATUS1: + p_usb_reg->HcRhPortStatus1 &= ~(set_data & 0xFFFF0000); + if ((set_data & OR_RH_PORT_PRS) != 0) { /* Set Port Reset */ + p_usb_reg->HcRhPortStatus1 |= OR_RH_PORT_PRS; + usbx_host_UsbBusReset(); + p_usb_reg->HcRhPortStatus1 &= ~OR_RH_PORT_PRS; + } + break; + case OHCI_REG_REVISION: + case OHCI_REG_PERIODCURRENTED: + case OHCI_REG_DONEHEADED: + case OHCI_REG_FMNUMBER: + default: + /* Do Nothing */ + break; + } +} + +static void callback_task(void const * argument) { + usbisr_fnc_t *p_wk_cb = p_usbisr_cb; + + if (p_wk_cb == NULL) { + return; + } + + while (1) { + osSemaphoreWait(semid_cb, osWaitForever); + if (connect_change != 0xFFFFFFFF) { + connect_change = 0xFFFFFFFF; + connect_check(); + } + p_wk_cb(); + } +} + +static void control_ed_task(void const * argument) { + while (1) { + osSignalWait(SIG_GEN_LIST_REQ, osWaitForever); + (void)osSemaphoreWait(ctl_ed.semid_list, osWaitForever); + while ((p_usb_reg->HcControl & OR_CONTROL_CLE) != 0) { + if ((p_usb_reg->HcControlCurrentED == 0) + && ((p_usb_reg->HcCommandStatus & OR_CMD_STATUS_CLF) != 0)) { + p_usb_reg->HcControlCurrentED = p_usb_reg->HcControlHeadED; + p_usb_reg->HcCommandStatus &= ~OR_CMD_STATUS_CLF; + } + if (p_usb_reg->HcControlCurrentED != 0) { + ctl_ed.p_curr_ed = (hced_t *)p_usb_reg->HcControlCurrentED; + if (chk_genelal_ed(&ctl_ed) != 0) { + control_trans(&ctl_ed); + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_CLF; + } + p_usb_reg->HcControlCurrentED = (uint32_t)ctl_ed.p_curr_ed->nextED; + } else { + break; + } + } + if ((p_usb_reg->HcCommandStatus & OR_CMD_STATUS_CLF) != 0) { + osSignalSet(ctl_ed.tskid, SIG_GEN_LIST_REQ); + } + (void)osSemaphoreRelease(ctl_ed.semid_list); + } +} + +static void bulk_ed_task(void const * argument) { + while (1) { + osSignalWait(SIG_GEN_LIST_REQ, osWaitForever); + (void)osSemaphoreWait(blk_ed.semid_list, osWaitForever); + while ((p_usb_reg->HcControl & OR_CONTROL_BLE) != 0) { + if ((p_usb_reg->HcBulkCurrentED == 0) + && ((p_usb_reg->HcCommandStatus & OR_CMD_STATUS_BLF) != 0)) { + p_usb_reg->HcBulkCurrentED = p_usb_reg->HcBulkHeadED; + p_usb_reg->HcCommandStatus &= ~OR_CMD_STATUS_BLF; + } + if (p_usb_reg->HcBulkCurrentED != 0) { + blk_ed.p_curr_ed = (hced_t *)p_usb_reg->HcBulkCurrentED; + if (chk_genelal_ed(&blk_ed) != 0) { + bulk_trans(&blk_ed); + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_BLF; + } + p_usb_reg->HcBulkCurrentED = (uint32_t)blk_ed.p_curr_ed->nextED; + } else { + break; + } + } + if ((p_usb_reg->HcCommandStatus & OR_CMD_STATUS_BLF) != 0) { + osSignalSet(blk_ed.tskid, SIG_GEN_LIST_REQ); + } + (void)osSemaphoreRelease(blk_ed.semid_list); + } +} + +static void int_ed_task(void const * argument) { + genelal_ed_t *p_int_ed = &int_ed[(uint32_t)argument]; + uint32_t cnt; + uint32_t wait_cnt = 0; + hcca_t *p_hcca; + hced_t *p_ed; + + while (1) { + (void)osSemaphoreWait(p_int_ed->semid_list, osWaitForever); + if (p_int_ed->p_curr_ed == NULL) { + for (cnt = 0; (cnt < 32) && ((p_usb_reg->HcControl & OR_CONTROL_PLE) != 0) + && (p_int_ed->p_curr_ed == NULL); cnt++) { + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + p_ed = (hced_t *)p_hcca->IntTable[cnt]; + while ((p_ed != NULL) && ((p_usb_reg->HcControl & OR_CONTROL_PLE) != 0) + && (p_int_ed->p_curr_ed == NULL)) { + if (int_trans_doing(p_ed, (uint32_t)argument) == 0) { + p_int_ed->p_curr_ed = p_ed; + if (chk_genelal_ed(p_int_ed) != 0) { + int_trans_setting(p_int_ed, (uint32_t)argument); + } else { + p_int_ed->p_curr_ed = NULL; + } + } + p_ed = p_ed->nextED; + } + } + } + if (p_int_ed->p_curr_ed != NULL) { + while ((p_usb_reg->HcControl & OR_CONTROL_PLE) != 0) { + if (chk_genelal_ed(p_int_ed) != 0) { + int_trans(p_int_ed); + (void)osSemaphoreWait(p_int_ed->semid_wait, osWaitForever); + usbx_host_stop_transfer(p_int_ed->pipe_no); + wait_cnt = p_int_ed->cycle_time; + } else { + if (wait_cnt > 0) { + wait_cnt--; + } else { + p_int_ed->p_curr_ed = NULL; + } + break; + } + } + } + (void)osSemaphoreRelease(p_int_ed->semid_list); + if (p_int_ed->p_curr_ed == NULL) { + osDelay(10); + } else { + osDelay(1); + } + } +} + +static int32_t int_trans_doing(hced_t *p_ed, uint32_t index) { + uint32_t cnt; + int32_t ret = 0; + + for (cnt = 0; cnt < INT_TRANS_MAX_NUM; cnt++) { + if ((index != cnt) && (int_ed[cnt].p_curr_ed == p_ed)) { + ret = 1; + } + } + + return ret; +} + +static int32_t chk_genelal_ed(genelal_ed_t *p_g_ed){ + int32_t ret = 0; + hced_t *p_ed = p_g_ed->p_curr_ed; + + if (((p_ed->control & ED_SKIP) != 0) + || ((p_ed->control & ED_FORMAT) != 0) + || ((p_ed->headTD & ED_HALTED) != 0) + || ((p_ed->tailTD & 0xFFFFFFF0) == (p_ed->headTD & 0xFFFFFFF0))) { + /* Do Nothing */ + } else if ((p_ed->control & 0x0000007F) > 10) { + p_ed->headTD |= ED_HALTED; + } else { + p_g_ed->p_curr_td = (void *)(p_ed->headTD & 0xFFFFFFF0); + if (p_g_ed->p_curr_td == NULL) { + p_ed->headTD |= ED_HALTED; + } else { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + + p_g_ed->p_start_buf = p_td->currBufPtr; + ret = 1; + } + } + + return ret; +} + +static void chk_genelal_td_done(genelal_ed_t *p_g_ed) { + hcca_t *p_hcca; + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + uint32_t ConditionCode = RZA_IO_RegRead_32(&p_td->control, TD_CTL_SHFT_CC, TD_CTL_MSK_CC); + + if ((ConditionCode != TD_CC_NOT_ACCESSED_1) && (ConditionCode != TD_CC_NOT_ACCESSED_2)) { + p_g_ed->p_curr_ed->headTD = ((uint32_t)p_td->nextTD & 0xFFFFFFF0) + | (p_g_ed->p_curr_ed->headTD & 0x0000000F); + p_td->nextTD = (hctd_t *)p_usb_reg->HcDoneHead; + p_usb_reg->HcDoneHead = (uint32_t)p_g_ed->p_curr_td; + if ((p_usb_reg->HcInterruptStatus & OR_INTR_STATUS_WDH) == 0) { + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + p_hcca->DoneHead = p_usb_reg->HcDoneHead; + p_usb_reg->HcDoneHead = 0x00000000; + p_usb_reg->HcInterruptStatus |= OR_INTR_STATUS_WDH; + (void)osSemaphoreRelease(semid_cb); + } + } +} + +static void chk_split_trans_setting(genelal_ed_t *p_g_ed) { + uint8_t *p_buf; + tdinfo_t td_info; + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + + /* Hi-Speed mode only */ + if (g_usbx_host_UsbDeviceSpeed != USB_HOST_HIGH_SPEED) { + return; + } + + if (RZA_IO_RegRead_32(&p_td->control, TD_CTL_SHFT_CC, TD_CTL_MSK_CC) != TD_CC_NOERROR) { + return; + } + + get_td_info(p_g_ed, &td_info); + p_buf = p_g_ed->p_start_buf; + + if (td_info.direction == 0) { + uint8_t bRequest = p_buf[1]; + uint16_t wValue = (p_buf[3] << 8) + p_buf[2]; + uint16_t wIndx = (p_buf[5] << 8) + p_buf[4]; + uint16_t devadd; + + if ((td_info.devadr == 0) && (bRequest == SET_ADDRESS)) { + /* SET_ADDRESS */ + usbx_host_get_devadd(USB_HOST_DEVICE_0, &devadd); + usbx_host_set_devadd(wValue, &devadd); + if (split_ctl.root_devadr == 0) { + split_ctl.root_devadr = wValue; /* New Address */ + } + } else if ((td_info.devadr == split_ctl.root_devadr) && (bRequest == SET_FEATURE) + && (wValue == 0x0004) && (split_ctl.root_devadr != 0)) { + /* SET_FEATURE PORT_RESET */ + split_ctl.reset_port = (wIndx & 0x00FF); + } else if ((td_info.devadr == split_ctl.root_devadr) && (bRequest == GET_STATUS)) { + /* GET_STATUS */ + split_ctl.get_port = wIndx; + split_ctl.seq_cnt = 1; + } else { + /* Do Nothing */ + } + } else if (td_info.direction == 2) { + if ((td_info.devadr == split_ctl.root_devadr) && (split_ctl.seq_cnt == 1)) { + if (split_ctl.get_port < PORT_NUM) { + split_ctl.port_sts_bits[split_ctl.get_port] = (p_buf[1] << 8) + p_buf[0]; + } + split_ctl.seq_cnt = 0; + } + } else { + /* Do Nothing */ + } +} + +static void set_split_trans_setting(void) { + uint16_t port_speed; + uint16_t devadd; + + if ((split_ctl.root_devadr != 0) && (split_ctl.reset_port != 0) && (split_ctl.reset_port < PORT_NUM)) { + usbx_host_get_devadd(USB_HOST_DEVICE_0, &devadd); + RZA_IO_RegWrite_16(&devadd, split_ctl.root_devadr, USB_DEVADDn_UPPHUB_SHIFT, USB_DEVADDn_UPPHUB); + RZA_IO_RegWrite_16(&devadd, split_ctl.reset_port, USB_DEVADDn_HUBPORT_SHIFT, USB_DEVADDn_HUBPORT); + if ((split_ctl.port_sts_bits[split_ctl.reset_port] & PORT_HIGH_SPEED) != 0) { + port_speed = USB_HOST_HIGH_SPEED; + } else if ((split_ctl.port_sts_bits[split_ctl.reset_port] & PORT_LOW_SPEED) != 0) { + port_speed = USB_HOST_LOW_SPEED; + } else { + port_speed = USB_HOST_FULL_SPEED; + } + RZA_IO_RegWrite_16(&devadd, port_speed, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD); + usbx_host_set_devadd(USB_HOST_DEVICE_0, &devadd); + split_ctl.reset_port = 0; + } +} + +static void control_trans(genelal_ed_t *p_g_ed) { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + tdinfo_t td_info; + uint16_t devadd; + + get_td_info(p_g_ed, &td_info); + + if (g_usbx_host_UsbDeviceSpeed == USB_HOST_HIGH_SPEED) { + if (td_info.devadr == 0) { + set_split_trans_setting(); + } + } else { + /* When a non-Hi-Speed, the communication speed is determined from the TD. */ + usbx_host_get_devadd(USB_HOST_DEVICE_0, &devadd); + if (td_info.speed == 1) { + RZA_IO_RegWrite_16(&devadd, USB_HOST_LOW_SPEED, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD); + } else { + RZA_IO_RegWrite_16(&devadd, USB_HOST_FULL_SPEED, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD); + } + usbx_host_set_devadd(td_info.devadr, &devadd); + } + + USB20X.DCPMAXP = (td_info.devadr << 12) + td_info.msp; + if (td_info.direction == 0) { + g_usbx_host_CmdStage = (USB_HOST_STAGE_SETUP | USB_HOST_CMD_IDLE); + } else if (td_info.count != 0) { + g_usbx_host_CmdStage = (USB_HOST_STAGE_DATA | USB_HOST_CMD_IDLE); + } else { + g_usbx_host_CmdStage = (USB_HOST_STAGE_STATUS | USB_HOST_CMD_IDLE); + } + g_usbx_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_WAIT; + p_g_ed->pipe_no = USB_HOST_PIPE0; + + p_g_ed->trans_wait = 1; + if (connect_status == 0) { + ohciwrapp_loc_TransEnd(p_g_ed->pipe_no, TD_CC_DEVICENOTRESPONDING); + } else { + if (td_info.direction == 0) { + uint16_t Req = (p_td->currBufPtr[1] << 8) + p_td->currBufPtr[0]; + uint16_t Val = (p_td->currBufPtr[3] << 8) + p_td->currBufPtr[2]; + uint16_t Indx = (p_td->currBufPtr[5] << 8) + p_td->currBufPtr[4]; + uint16_t Len = (p_td->currBufPtr[7] << 8) + p_td->currBufPtr[6]; + + g_usbx_host_data_pointer[USB_HOST_PIPE0] = p_td->bufEnd; + usbx_host_SetupStage(Req, Val, Indx, Len); + } else if (td_info.direction == 1) { + usbx_host_CtrlWriteStart(td_info.count, p_td->currBufPtr); + } else { + usbx_host_CtrlReadStart(td_info.count, p_td->currBufPtr); + } + + (void)osSemaphoreWait(p_g_ed->semid_wait, CTL_TRANS_TIMEOUT); + if (p_g_ed->trans_wait == 1) { + p_g_ed->trans_wait = 0; + RZA_IO_RegWrite_32(&p_td->control, TD_CC_DEVICENOTRESPONDING, TD_CTL_SHFT_CC, TD_CTL_MSK_CC); + } + } + + g_usbx_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usbx_host_CmdStage |= USB_HOST_CMD_IDLE; + g_usbx_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_IDLE; +} + +static void bulk_trans(genelal_ed_t *p_g_ed) { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + hced_t *p_ed = p_g_ed->p_curr_ed; + tdinfo_t td_info; + USB_HOST_CFG_PIPETBL_t *user_table = &usb_host_blk_ep_tbl1[0]; + uint8_t wk_table[6]; + + get_td_info(p_g_ed, &td_info); + + wk_table[0] = 0; + wk_table[1] = USB_HOST_ENDPOINT_DESC; + wk_table[2] = td_info.endpoint_no; + if (td_info.direction == 2) { + wk_table[2] |= USB_HOST_EP_IN; + } + wk_table[3] = USB_HOST_EP_BULK; + wk_table[4] = (uint8_t)td_info.msp; + wk_table[5] = (uint8_t)(td_info.msp >> 8); + p_g_ed->pipe_no = user_table->pipe_number; + usbx_api_host_SetEndpointTable(td_info.devadr, user_table, wk_table); + + set_togle(p_g_ed->pipe_no, p_td, p_ed); + + p_g_ed->trans_wait = 1; + if (connect_status == 0) { + ohciwrapp_loc_TransEnd(p_g_ed->pipe_no, TD_CC_DEVICENOTRESPONDING); + } else { + if (td_info.direction == 1) { + usbx_host_start_send_transfer(p_g_ed->pipe_no, td_info.count, p_td->currBufPtr); + } else { + usbx_host_start_receive_transfer(p_g_ed->pipe_no, td_info.count, p_td->currBufPtr); + } + + (void)osSemaphoreWait(p_g_ed->semid_wait, BLK_TRANS_TIMEOUT); + usbx_host_stop_transfer(p_g_ed->pipe_no); + } +} + +static void int_trans_setting(genelal_ed_t *p_g_ed, uint32_t index) { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + hced_t *p_ed = p_g_ed->p_curr_ed; + tdinfo_t td_info; + USB_HOST_CFG_PIPETBL_t *user_table = &usb_host_int_ep_tbl1[index]; + uint8_t wk_table[6]; + uint32_t cycle_time; + uint16_t devadd; + + get_td_info(p_g_ed, &td_info); + + wk_table[0] = 0; + wk_table[1] = USB_HOST_ENDPOINT_DESC; + wk_table[2] = td_info.endpoint_no; + if (td_info.direction == 2) { + wk_table[2] |= USB_HOST_EP_IN; + } + wk_table[3] = USB_HOST_EP_INT; + wk_table[4] = (uint8_t)td_info.msp; + wk_table[5] = (uint8_t)(td_info.msp >> 8); + cycle_time = chk_cycle(p_ed); + p_g_ed->cycle_time = cycle_time; + user_table->pipe_cycle = 0; + while (cycle_time > 1) { + cycle_time >>= 1; + user_table->pipe_cycle++; + } + if (g_usbx_host_UsbDeviceSpeed == USB_HOST_HIGH_SPEED) { + usbx_host_get_devadd(td_info.devadr, &devadd); + if (RZA_IO_RegRead_16(&devadd, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD) == USB_HOST_HIGH_SPEED) { + user_table->pipe_cycle += 3; + if (user_table->pipe_cycle > 7) { + user_table->pipe_cycle = 7; + } + } + } + + p_g_ed->pipe_no = user_table->pipe_number; + usbx_api_host_SetEndpointTable(td_info.devadr, user_table, wk_table); + + set_togle(p_g_ed->pipe_no, p_td, p_ed); +} + +static uint32_t chk_cycle(hced_t *p_ed) { + uint32_t cnt; + uint32_t hit_cnt = 0; + uint32_t cycle_time = 1; + hcca_t *p_hcca; + hced_t *p_wk_ed; + + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + + for (cnt = 0; cnt < 32; cnt++) { + p_wk_ed = (hced_t *)p_hcca->IntTable[cnt]; + while (p_wk_ed != NULL) { + if (p_wk_ed == p_ed) { + hit_cnt++; + break; + } + p_wk_ed = p_wk_ed->nextED; + } + } + if (hit_cnt < 2) { + cycle_time = 32; + } else if (hit_cnt < 4) { + cycle_time = 16; + } else if (hit_cnt < 8) { + cycle_time = 8; + } else if (hit_cnt < 16) { + cycle_time = 4; + } else if (hit_cnt < 32) { + cycle_time = 2; + } else{ + cycle_time = 1; + } + + return cycle_time; +} + +static void int_trans(genelal_ed_t *p_g_ed) { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + tdinfo_t td_info; + + get_td_info(p_g_ed, &td_info); + p_g_ed->trans_wait = 1; + if (connect_status == 0) { + ohciwrapp_loc_TransEnd(p_g_ed->pipe_no, TD_CC_DEVICENOTRESPONDING); + } else { + if (td_info.direction == 1) { + usbx_host_start_send_transfer(p_g_ed->pipe_no, td_info.count, p_td->currBufPtr); + } else { + usbx_host_start_receive_transfer(p_g_ed->pipe_no, td_info.count, p_td->currBufPtr); + } + } +} + +static void get_td_info(genelal_ed_t *p_g_ed, tdinfo_t *p_td_info) { + hced_t *p_ed = p_g_ed->p_curr_ed; + + p_td_info->endpoint_no = (uint8_t)((p_ed->control >> 7) & 0x0000000F); + p_td_info->msp = (p_ed->control >> 16) & 0x000007FF; + p_td_info->devadr = p_ed->control & 0x0000000F; + p_td_info->speed = (p_ed->control >> 13) & 0x00000001; + p_td_info->direction = (p_ed->control >> 11) & 0x00000003; + + if ((p_ed->control & ED_FORMAT) == 0) { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + + if ((p_td_info->direction == 0) || (p_td_info->direction == 3)) { + if ((p_td->control & TD_CTL_MSK_DP) == TD_SETUP) { + p_td_info->direction = 0; + } else if ((p_td->control & TD_CTL_MSK_DP) == TD_OUT) { + p_td_info->direction = 1; + } else { + p_td_info->direction = 2; + } + } + if (p_td->currBufPtr != NULL) { + p_td_info->count = (uint32_t)p_td->bufEnd - (uint32_t)p_td->currBufPtr + 1; + } else { + p_td_info->count = 0; + } + } else { +#if (ISO_TRANS_MAX_NUM > 0) + hcisotd_t *p_isotd = (hcisotd_t *)p_g_ed->p_curr_td; + + if ((p_td_info->direction == 0) || (p_td_info->direction == 3)) { + if ((p_isotd->control & TD_CTL_MSK_DP) == TD_SETUP) { + p_td_info->direction = 0; + } else if ((p_isotd->control & TD_CTL_MSK_DP) == TD_OUT) { + p_td_info->direction = 1; + } else { + p_td_info->direction = 2; + } + } +#endif + } +} + +static void set_togle(uint32_t pipe, hctd_t *p_td, hced_t *p_ed) { + if ((p_td->control & TD_CTL_MSK_T) == TD_TOGGLE_0) { + usbx_host_set_sqclr(pipe); + } else if ((p_td->control & TD_CTL_MSK_T) == TD_TOGGLE_1) { + usbx_host_set_sqset(pipe); + } else if ((p_ed->headTD & ED_TOGLE_CARRY) == 0) { + usbx_host_set_sqclr(pipe); + } else { + usbx_host_set_sqset(pipe); + } +} + +#if (ISO_TRANS_MAX_NUM > 0) +static void iso_ed_task(void const * argument) { + genelal_ed_t *p_iso_ed = &iso_ed[(uint32_t)argument]; + uint32_t wait_cnt = 0; + hcca_t *p_hcca; + hced_t *p_ed; + + while (1) { + (void)osSemaphoreWait(p_iso_ed->semid_list, osWaitForever); + if (p_iso_ed->p_curr_ed == NULL) { + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + p_ed = (hced_t *)p_hcca->IntTable[0]; + while ((p_ed != NULL) && ((p_usb_reg->HcControl & OR_CONTROL_IE) != 0) + && (p_iso_ed->p_curr_ed == NULL)) { + if (iso_trans_doing(p_ed, (uint32_t)argument) == 0) { + p_iso_ed->p_curr_ed = p_ed; + if (chk_iso_ed(p_iso_ed) != 0) { + iso_trans_setting(p_iso_ed, (uint32_t)argument); + } else { + p_iso_ed->p_curr_ed = NULL; + } + } + p_ed = p_ed->nextED; + } + p_iso_ed->psw_idx = 0; + } + if (p_iso_ed->p_curr_ed != NULL) { + while ((p_usb_reg->HcControl & OR_CONTROL_IE) != 0) { + if (chk_iso_ed(p_iso_ed) != 0) { + hcisotd_t *p_isotd = (hcisotd_t *)p_iso_ed->p_curr_td; + uint32_t starting_frame = p_isotd->control & 0x0000FFFF; + uint32_t wait_time = 0; + uint32_t wk_HcFmNumber = p_usb_reg->HcFmNumber; + + if (starting_frame > wk_HcFmNumber) { + wait_time = starting_frame - wk_HcFmNumber; + } else { + wait_time = (0xFFFF - wk_HcFmNumber) + starting_frame; + } + if ((wait_time >= 2) && (wait_time <= 1000)) { + for (int cnt = 0; cnt < (wait_time - 1); cnt++) { + osDelay(1); + p_usb_reg->HcFmNumber = (wk_HcFmNumber + cnt) & 0x0000FFFF; + } + } + p_iso_ed->psw_idx = 0; + iso_trans(p_iso_ed); + (void)osSemaphoreWait(p_iso_ed->semid_wait, osWaitForever); + wait_cnt = 8; + } else { + if (wait_cnt > 0) { + wait_cnt--; + } else { + p_iso_ed->p_curr_ed = NULL; + } + break; + } + } + } + (void)osSemaphoreRelease(p_iso_ed->semid_list); + if (p_iso_ed->p_curr_ed == NULL) { + osDelay(10); + } else { + osDelay(1); + } + } +} + +static int32_t iso_trans_doing(hced_t *p_ed, uint32_t index) { + uint32_t cnt; + int32_t ret = 0; + + for (cnt = 0; cnt < ISO_TRANS_MAX_NUM; cnt++) { + if ((index != cnt) && (iso_ed[cnt].p_curr_ed == p_ed)) { + ret = 1; + } + } + + return ret; +} + +static void chk_iso_td_done(genelal_ed_t *p_g_ed) { + hcca_t *p_hcca; + hcisotd_t *p_isotd = (hcisotd_t *)p_g_ed->p_curr_td; + uint32_t ConditionCode = RZA_IO_RegRead_32(&p_isotd->control, TD_CTL_SHFT_CC, TD_CTL_MSK_CC); + + if ((ConditionCode != TD_CC_NOT_ACCESSED_1) && (ConditionCode != TD_CC_NOT_ACCESSED_2)) { + p_g_ed->p_curr_ed->headTD = ((uint32_t)p_isotd->nextTD & 0xFFFFFFF0) + | (p_g_ed->p_curr_ed->headTD & 0x0000000F); + p_isotd->nextTD = (hcisotd_t *)p_usb_reg->HcDoneHead; + p_usb_reg->HcDoneHead = (uint32_t)p_g_ed->p_curr_td; + if ((p_usb_reg->HcInterruptStatus & OR_INTR_STATUS_WDH) == 0) { + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + p_hcca->DoneHead = p_usb_reg->HcDoneHead; + p_usb_reg->HcDoneHead = 0x00000000; + p_usb_reg->HcInterruptStatus |= OR_INTR_STATUS_WDH; + (void)osSemaphoreRelease(semid_cb); + } + } +} + +static int32_t chk_iso_ed(genelal_ed_t *p_g_ed){ + int32_t ret = 0; + hced_t *p_ed = p_g_ed->p_curr_ed; + + if (((p_ed->control & ED_SKIP) != 0) + || ((p_ed->control & ED_FORMAT) == 0) + || ((p_ed->headTD & ED_HALTED) != 0) + || ((p_ed->tailTD & 0xFFFFFFF0) == (p_ed->headTD & 0xFFFFFFF0))) { + /* Do Nothing */ + } else if ((p_ed->control & 0x0000007F) > 10) { + p_ed->headTD |= ED_HALTED; + } else { + p_g_ed->p_curr_td = (void *)(p_ed->headTD & 0xFFFFFFF0); + if (p_g_ed->p_curr_td == NULL) { + p_ed->headTD |= ED_HALTED; + } else { + hcisotd_t *p_isotd = (hcisotd_t *)p_g_ed->p_curr_td; + + p_g_ed->p_start_buf = p_isotd->bufferPage0; + ret = 1; + } + } + + return ret; +} + +static void iso_trans_setting(genelal_ed_t *p_g_ed, uint32_t index) { + tdinfo_t td_info; + USB_HOST_CFG_PIPETBL_t *user_table = &usb_host_iso_ep_tbl1[index]; + uint8_t wk_table[6]; + uint16_t devadd; + + get_td_info(p_g_ed, &td_info); + + wk_table[0] = 0; + wk_table[1] = USB_HOST_ENDPOINT_DESC; + wk_table[2] = td_info.endpoint_no; + if (td_info.direction == 2) { + wk_table[2] |= USB_HOST_EP_IN; + } + wk_table[3] = USB_HOST_EP_ISO; + wk_table[4] = (uint8_t)td_info.msp; + wk_table[5] = (uint8_t)(td_info.msp >> 8); + p_g_ed->cycle_time = 1; + user_table->pipe_cycle = 0; + if (g_usbx_host_UsbDeviceSpeed == USB_HOST_HIGH_SPEED) { + usbx_host_get_devadd(td_info.devadr, &devadd); + if (RZA_IO_RegRead_16(&devadd, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD) == USB_HOST_HIGH_SPEED) { + user_table->pipe_cycle += 3; + } + } + + p_g_ed->pipe_no = user_table->pipe_number; + usbx_api_host_SetEndpointTable(td_info.devadr, user_table, wk_table); +} + +static void iso_trans(genelal_ed_t *p_g_ed) { + hcisotd_t *p_isotd = (hcisotd_t *)p_g_ed->p_curr_td; + tdinfo_t td_info; + uint32_t buff_addr; + uint32_t data_size; + + if (((uint32_t)p_isotd->offsetPSW[p_g_ed->psw_idx] & 0x00001000) == 0) { + buff_addr = (uint32_t)p_isotd->bufferPage0 & 0xFFFFF000; + } else { + buff_addr = (uint32_t)p_isotd->bufEnd & 0xFFFFF000; + } + buff_addr |= (uint32_t)p_isotd->offsetPSW[p_g_ed->psw_idx] & 0x00000FFF; + + if (p_g_ed->psw_idx < RZA_IO_RegRead_32(&p_isotd->control, TD_CTL_SHFT_FC, TD_CTL_MSK_FC)) { + data_size = p_isotd->offsetPSW[p_g_ed->psw_idx + 1] - p_isotd->offsetPSW[p_g_ed->psw_idx]; + } else { + data_size = (uint32_t)p_isotd->bufEnd - buff_addr + 1; + } + p_isotd->offsetPSW[p_g_ed->psw_idx] = (uint16_t)data_size; + + get_td_info(p_g_ed, &td_info); + p_g_ed->trans_wait = 1; + if (connect_status == 0) { + ohciwrapp_loc_TransEnd(p_g_ed->pipe_no, TD_CC_DEVICENOTRESPONDING); + } else { + if (td_info.direction == 1) { + usbx_host_start_send_transfer(p_g_ed->pipe_no, data_size, (uint8_t *)buff_addr); + } else { + usbx_host_start_receive_transfer(p_g_ed->pipe_no, data_size, (uint8_t *)buff_addr); + } + } +} +#endif + +static void connect_check(void) { + uint32_t type = 0; + uint16_t stat; + uint16_t devadd = 0; + uint32_t wk_HcRhPortStatus1 = p_usb_reg->HcRhPortStatus1; + + if (usbx_host_CheckAttach() == USB_HOST_ATTACH) { + type = 1; + } + + if ((((wk_HcRhPortStatus1 & OR_RH_PORT_CCS) == 0) && (type == 0)) + || (((wk_HcRhPortStatus1 & OR_RH_PORT_CCS) != 0) && (type != 0))) { + return; + } + + if (type == 0) { + usbx_host_UsbDetach(); + wk_HcRhPortStatus1 &= ~OR_RH_PORT_CCS; + } else { + usbx_host_UsbAttach(); + stat = usbx_host_UsbBusReset(); + RZA_IO_RegWrite_16(&devadd, 0, USB_DEVADDn_UPPHUB_SHIFT, USB_DEVADDn_UPPHUB); + RZA_IO_RegWrite_16(&devadd, 0, USB_DEVADDn_HUBPORT_SHIFT, USB_DEVADDn_HUBPORT); + if (stat == USB_HOST_HSMODE) { + wk_HcRhPortStatus1 &= ~OR_RH_PORT_LSDA; + RZA_IO_RegWrite_16(&USB20X.SOFCFG, 0, USB_SOFCFG_TRNENSEL_SHIFT, USB_SOFCFG_TRNENSEL); + g_usbx_host_UsbDeviceSpeed = USB_HOST_HIGH_SPEED; + } else if (stat == USB_HOST_FSMODE) { + wk_HcRhPortStatus1 &= ~OR_RH_PORT_LSDA; + RZA_IO_RegWrite_16(&USB20X.SOFCFG, 0, USB_SOFCFG_TRNENSEL_SHIFT, USB_SOFCFG_TRNENSEL); + g_usbx_host_UsbDeviceSpeed = USB_HOST_FULL_SPEED; + } else { + wk_HcRhPortStatus1 |= OR_RH_PORT_LSDA; + RZA_IO_RegWrite_16(&USB20X.SOFCFG, 1, USB_SOFCFG_TRNENSEL_SHIFT, USB_SOFCFG_TRNENSEL); + g_usbx_host_UsbDeviceSpeed = USB_HOST_LOW_SPEED; + } + RZA_IO_RegWrite_16(&devadd, g_usbx_host_UsbDeviceSpeed, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD); + usbx_host_init_pipe_status(); + usbx_host_set_devadd(USB_HOST_DEVICE_0, &devadd); + wk_HcRhPortStatus1 |= OR_RH_PORT_CCS; + } + wk_HcRhPortStatus1 |= OR_RH_PORT_CSC; + p_usb_reg->HcRhPortStatus1 = wk_HcRhPortStatus1; + p_usb_reg->HcInterruptStatus |= OR_INTR_STATUS_RHSC; + (void)memset(&split_ctl, 0, sizeof(split_ctl)); +} + +void ohciwrapp_loc_Connect(uint32_t type) { + uint32_t cnt; + + connect_status = type; + connect_change = type; + if (type == 0) { + if (ctl_ed.trans_wait == 1) { + ohciwrapp_loc_TransEnd(ctl_ed.pipe_no, TD_CC_DEVICENOTRESPONDING); + } + if (blk_ed.trans_wait == 1) { + ohciwrapp_loc_TransEnd(blk_ed.pipe_no, TD_CC_DEVICENOTRESPONDING); + } + for (cnt = 0; cnt< INT_TRANS_MAX_NUM; cnt++) { + if (int_ed[cnt].trans_wait == 1) { + ohciwrapp_loc_TransEnd(int_ed[cnt].pipe_no, TD_CC_DEVICENOTRESPONDING); + } + } +#if (ISO_TRANS_MAX_NUM > 0) + for (cnt = 0; cnt< ISO_TRANS_MAX_NUM; cnt++) { + if (iso_ed[cnt].trans_wait == 1) { + hced_t *p_ed = iso_ed[cnt].p_curr_ed; + + p_ed->headTD |= ED_HALTED; + ohciwrapp_loc_TransEnd(iso_ed[cnt].pipe_no, TD_CC_DEVICENOTRESPONDING); + } + } +#endif + } + (void)osSemaphoreRelease(semid_cb); +} + +void ohciwrapp_loc_TransEnd(uint32_t pipe, uint32_t ConditionCode) { + uint32_t periodic = 0; + uint32_t cnt; + uint32_t sqmon; + hced_t *p_ed; + genelal_ed_t *p_wait_ed = NULL; + + if (ctl_ed.pipe_no == pipe) { + p_wait_ed = &ctl_ed; + } else if (blk_ed.pipe_no == pipe) { + p_wait_ed = &blk_ed; + } else { +#if (ISO_TRANS_MAX_NUM > 0) + if (p_wait_ed == NULL) { + for (cnt = 0; cnt< ISO_TRANS_MAX_NUM; cnt++) { + if (iso_ed[cnt].pipe_no == pipe) { + p_wait_ed = &iso_ed[cnt]; + break; + } + } + } +#endif + if (p_wait_ed == NULL) { + for (cnt = 0; cnt< INT_TRANS_MAX_NUM; cnt++) { + if (int_ed[cnt].pipe_no == pipe) { + p_wait_ed = &int_ed[cnt]; + periodic = 1; + break; + } + } + } + } + + if (p_wait_ed == NULL) { + return; + } + p_ed = p_wait_ed->p_curr_ed; + if (p_ed == NULL) { + return; + } + + if ((p_ed->control & ED_FORMAT) == 0) { + hctd_t *p_td = (hctd_t *)p_wait_ed->p_curr_td; + + if (p_td != NULL) { + if (ConditionCode == TD_CC_NOERROR) { + /* ErrorCount */ + RZA_IO_RegWrite_32(&p_td->control, 0, TD_CTL_SHFT_EC, TD_CTL_MSK_EC); + + /* CurrentBufferPointer */ + p_td->currBufPtr += ((uint32_t)p_td->bufEnd - (uint32_t)p_td->currBufPtr + 1) - g_usbx_host_data_count[pipe]; + } else { + /* ErrorCount */ + RZA_IO_RegWrite_32(&p_td->control, 3, TD_CTL_SHFT_EC, TD_CTL_MSK_EC); + } + + /* DataToggle */ + sqmon = usbx_host_get_sqmon(pipe); + RZA_IO_RegWrite_32(&p_td->control, sqmon, TD_CTL_SHFT_T, TD_CTL_MSK_T); + if (sqmon == 0) { + p_ed->headTD &= ~ED_TOGLE_CARRY; + } else { + p_ed->headTD |= ED_TOGLE_CARRY; + } + + /* ConditionCode */ + RZA_IO_RegWrite_32(&p_td->control, ConditionCode, TD_CTL_SHFT_CC, TD_CTL_MSK_CC); + + if (p_wait_ed == &ctl_ed) { + chk_split_trans_setting(&ctl_ed); + } + chk_genelal_td_done(p_wait_ed); + + if (periodic != 0) { + if (chk_genelal_ed(p_wait_ed) != 0) { + int_trans(p_wait_ed); + } else { + p_wait_ed->trans_wait = 0; + (void)osSemaphoreRelease(p_wait_ed->semid_wait); + } + } else { + p_wait_ed->trans_wait = 0; + (void)osSemaphoreRelease(p_wait_ed->semid_wait); + } + } + } else { +#if (ISO_TRANS_MAX_NUM > 0) + hcisotd_t *p_isotd = (hcisotd_t *)p_wait_ed->p_curr_td; + uint32_t next_trans = 0; + + if (p_isotd != NULL) { + usbx_host_stop_transfer(pipe); + p_usb_reg->HcFmNumber = ((p_isotd->control & 0x0000FFFF) + p_wait_ed->psw_idx) & 0x0000FFFF; + + /* Size of packet */ + p_isotd->offsetPSW[p_wait_ed->psw_idx] -= g_usbx_host_data_count[pipe]; + + /* ConditionCode */ + RZA_IO_RegWrite_32(&p_isotd->control, ConditionCode, TD_CTL_SHFT_CC, TD_CTL_MSK_CC); + RZA_IO_RegWrite_16(&p_isotd->offsetPSW[p_wait_ed->psw_idx], + (uint16_t)ConditionCode, TD_PSW_SHFT_CC, TD_PSW_MSK_CC); + + if (usbx_host_CheckAttach() != USB_HOST_ATTACH) { + p_ed->headTD |= ED_HALTED; + } + if (p_wait_ed->psw_idx >= RZA_IO_RegRead_32(&p_isotd->control, TD_CTL_SHFT_FC, TD_CTL_MSK_FC)) { + p_wait_ed->psw_idx = 0; + chk_iso_td_done(p_wait_ed); + } else { + p_wait_ed->psw_idx++; + } + if (chk_iso_ed(p_wait_ed) != 0) { + iso_trans(p_wait_ed); + next_trans = 1; + } + if (next_trans == 0) { + p_wait_ed->trans_wait = 0; + (void)osSemaphoreRelease(p_wait_ed->semid_wait); + } + } +#endif + } + +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/ohci_wrapp_RZ_A1.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,60 @@ +/* Copyright (c) 2010-2011 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef OHCI_WRAPP_RZ_A1_H +#define OHCI_WRAPP_RZ_A1_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define OHCI_REG_REVISION (0x00) /* HcRevision */ +#define OHCI_REG_CONTROL (0x04) /* HcControl */ +#define OHCI_REG_COMMANDSTATUS (0x08) /* HcCommandStatus */ +#define OHCI_REG_INTERRUPTSTATUS (0x0C) /* HcInterruptStatus */ +#define OHCI_REG_INTERRUPTENABLE (0x10) /* HcInterruptEnable */ +#define OHCI_REG_INTERRUPTDISABLE (0x14) /* HcInterruptDisable */ +#define OHCI_REG_HCCA (0x18) /* HcHCCA */ +#define OHCI_REG_PERIODCURRENTED (0x1C) /* HcPeriodCurrentED */ +#define OHCI_REG_CONTROLHEADED (0x20) /* HcControlHeadED */ +#define OHCI_REG_CONTROLCURRENTED (0x24) /* HcControlCurrentED */ +#define OHCI_REG_BULKHEADED (0x28) /* HcBulkHeadED */ +#define OHCI_REG_BULKCURRENTED (0x2C) /* HcBulkCurrentED */ +#define OHCI_REG_DONEHEADED (0x30) /* HcDoneHead */ +#define OHCI_REG_FMINTERVAL (0x34) /* HcFmInterval */ +#define OHCI_REG_FMREMAINING (0x38) /* HcFmRemaining */ +#define OHCI_REG_FMNUMBER (0x3C) /* HcFmNumber */ +#define OHCI_REG_PERIODICSTART (0x40) /* HcPeriodicStart */ +#define OHCI_REG_LSTHRESHOLD (0x44) /* HcLSThreshold */ +#define OHCI_REG_RHDESCRIPTORA (0x48) /* HcRhDescriptorA */ +#define OHCI_REG_RHDESCRIPTORB (0x4C) /* HcRhDescriptorB */ +#define OHCI_REG_RHSTATUS (0x50) /* HcRhStatus */ +#define OHCI_REG_RHPORTSTATUS1 (0x54) /* HcRhPortStatus1 */ + +typedef void (usbisr_fnc_t)(void); + +extern void ohciwrapp_init(usbisr_fnc_t *p_usbisr_fnc); +extern uint32_t ohciwrapp_reg_r(uint32_t reg_ofs); +extern void ohciwrapp_reg_w(uint32_t reg_ofs, uint32_t set_data); +extern void ohciwrapp_interrupt(uint32_t int_sense); + +#ifdef __cplusplus +} +#endif + +#endif /* OHCI_WRAPP_RZ_A1_H */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/ohci_wrapp_RZ_A1_local.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,49 @@ +/* Copyright (c) 2010-2011 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef OHCI_WRAPP_RZ_A1_LOCAL_H +#define OHCI_WRAPP_RZ_A1_LOCAL_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* ConditionCode */ +#define TD_CC_NOERROR (0) +#define TD_CC_CRC (1) +#define TD_CC_BITSTUFFING (2) +#define TD_CC_DATATOGGLEMISMATCH (3) +#define TD_CC_STALL (4) +#define TD_CC_DEVICENOTRESPONDING (5) +#define TD_CC_PIDCHECKFAILURE (6) +#define TD_CC_UNEXPECTEDPID (7) +#define TD_CC_DATAOVERRUN (8) +#define TD_CC_DATAUNDERRUN (9) +#define TD_CC_BUFFEROVERRUN (12) +#define TD_CC_BUFFERUNDERRUN (13) +#define TD_CC_NOT_ACCESSED_1 (14) +#define TD_CC_NOT_ACCESSED_2 (15) + +extern void ohciwrapp_loc_Connect(uint32_t type); +extern void ohciwrapp_loc_TransEnd(uint32_t pipe, uint32_t ConditionCode); + +#ifdef __cplusplus +} +#endif + +#endif /* OHCI_WRAPP_RZ_A1_LOCAL_H */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/ohci_wrapp_pipe.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,189 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "devdrv_usb_host_api.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/********************************************************************************************************/ +/* Endpoint Configuration Data Format */ +/********************************************************************************************************/ +/* LINE1: Pipe Window Select Register */ +/* CPU Access PIPE : USB_HOST_PIPE1 to USB_HOST_PIPE9 [ ### SET ### ] */ +/* LINE2: Pipe Configuration Register */ +/* Transfer Type : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* Buffer Ready interrupt : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* Double Buffer Mode : USB_HOST_DBLBON / USB_HOST_DBLBOFF [ ### SET ### ] */ +/* Continuous Transmit: : USB_HOST_CNTMDON / USB_HOST_CNTMDOFF [ ### SET ### ] */ +/* Short NAK : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* Transfer Direction : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* Endpoint Number : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* LINE3: Pipe Buffer Configuration Register */ +/* Buffer Size : (uint16_t)((uint16_t)(((x) / 64) - 1) << 10) */ +/* [ ### SET ### ] */ +/* Buffer Top Number : (uint16_t)(x) [ ### SET ### ] */ +/* LINE4: Pipe Maxpacket Size Register */ +/* Max Packet Size : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* LINE5: Pipe Cycle Configuration Register (0x6C) */ +/* ISO Buffer Flush Mode : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* ISO Interval Value : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* LINE6: use FIFO port */ +/* : USB_HOST_CUSE [ ### SET ### ] */ +/* : USB_HOST_D0USE / USB_HOST_D1USE */ +/* : USB_HOST_D0DMA / USB_HOST_D0DMA */ +/********************************************************************************************************/ + +/* Device Address 1 */ +USB_HOST_CFG_PIPETBL_t usb_host_blk_ep_tbl1[ ] = +{ + { + USB_HOST_PIPE3, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBON | USB_HOST_CNTMDON | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((1024) / 64) - 1) << 10) | (uint16_t)(8), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D0USE + }, + + { + /* Pipe end */ + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF + } +}; + +USB_HOST_CFG_PIPETBL_t usb_host_int_ep_tbl1[ ] = +{ + { + USB_HOST_PIPE6, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBOFF | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((64) / 64) - 1) << 10) | (uint16_t)(40), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + USB_HOST_PIPE7, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBOFF | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((64) / 64) - 1) << 10) | (uint16_t)(41), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + USB_HOST_PIPE8, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBOFF | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((64) / 64) - 1) << 10) | (uint16_t)(42), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + USB_HOST_PIPE9, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBOFF | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((64) / 64) - 1) << 10) | (uint16_t)(43), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + /* Pipe end */ + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF + } +}; + +USB_HOST_CFG_PIPETBL_t usb_host_iso_ep_tbl1[ ] = +{ + { + USB_HOST_PIPE1, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBON | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((1024) / 64) - 1) << 10) | (uint16_t)(44), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + USB_HOST_PIPE2, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBON | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((1024) / 64) - 1) << 10) | (uint16_t)(76), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + /* Pipe end */ + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF + } +}; + + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/inc/usb0_host.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,156 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB0_HOST_H +#define USB0_HOST_H + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "devdrv_usb_host_api.h" +#include "usb_host.h" + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +extern const uint16_t g_usb0_host_bit_set[]; +extern uint32_t g_usb0_host_data_count[USB_HOST_MAX_PIPE_NO + 1]; +extern uint8_t *g_usb0_host_data_pointer[USB_HOST_MAX_PIPE_NO + 1]; + +extern uint16_t g_usb0_host_PipeIgnore[]; +extern uint16_t g_usb0_host_PipeTbl[]; +extern uint16_t g_usb0_host_pipe_status[]; +extern uint32_t g_usb0_host_PipeDataSize[]; + +extern USB_HOST_DMA_t g_usb0_host_DmaInfo[]; +extern uint16_t g_usb0_host_DmaPipe[]; +extern uint16_t g_usb0_host_DmaBval[]; +extern uint16_t g_usb0_host_DmaStatus[]; + +extern uint16_t g_usb0_host_driver_state; +extern uint16_t g_usb0_host_ConfigNum; +extern uint16_t g_usb0_host_CmdStage; +extern uint16_t g_usb0_host_bchg_flag; +extern uint16_t g_usb0_host_detach_flag; +extern uint16_t g_usb0_host_attach_flag; + +extern uint16_t g_usb0_host_UsbAddress; +extern uint16_t g_usb0_host_setUsbAddress; +extern uint16_t g_usb0_host_default_max_packet[USB_HOST_MAX_DEVICE + 1]; +extern uint16_t g_usb0_host_UsbDeviceSpeed; +extern uint16_t g_usb0_host_SupportUsbDeviceSpeed; + +extern uint16_t g_usb0_host_SavReq; +extern uint16_t g_usb0_host_SavVal; +extern uint16_t g_usb0_host_SavIndx; +extern uint16_t g_usb0_host_SavLen; + +extern uint16_t g_usb0_host_pipecfg[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb0_host_pipebuf[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb0_host_pipemaxp[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb0_host_pipeperi[USB_HOST_MAX_PIPE_NO + 1]; + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +/* ==== common ==== */ +void usb0_host_dma_stop_d0(uint16_t pipe, uint32_t remain); +void usb0_host_dma_stop_d1(uint16_t pipe, uint32_t remain); +uint16_t usb0_host_is_hispeed(void); +uint16_t usb0_host_is_hispeed_enable(void); +uint16_t usb0_host_start_send_transfer(uint16_t pipe, uint32_t size, uint8_t *data); +uint16_t usb0_host_write_buffer(uint16_t pipe); +uint16_t usb0_host_write_buffer_c(uint16_t pipe); +uint16_t usb0_host_write_buffer_d0(uint16_t pipe); +uint16_t usb0_host_write_buffer_d1(uint16_t pipe); +void usb0_host_start_receive_transfer(uint16_t pipe, uint32_t size, uint8_t *data); +uint16_t usb0_host_read_buffer(uint16_t pipe); +uint16_t usb0_host_read_buffer_c(uint16_t pipe); +uint16_t usb0_host_read_buffer_d0(uint16_t pipe); +uint16_t usb0_host_read_buffer_d1(uint16_t pipe); +uint16_t usb0_host_change_fifo_port(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw); +void usb0_host_set_curpipe(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw); +void usb0_host_set_curpipe2(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw, uint16_t dfacc); +uint16_t usb0_host_get_mbw(uint32_t trncount, uint32_t dtptr); +uint16_t usb0_host_read_dma(uint16_t pipe); +void usb0_host_stop_transfer(uint16_t pipe); +void usb0_host_brdy_int(uint16_t status, uint16_t int_enb); +void usb0_host_nrdy_int(uint16_t status, uint16_t int_enb); +void usb0_host_bemp_int(uint16_t status, uint16_t int_enb); +void usb0_host_setting_interrupt(uint8_t level); +void usb0_host_reset_module(uint16_t clockmode); +uint16_t usb0_host_get_buf_size(uint16_t pipe); +uint16_t usb0_host_get_mxps(uint16_t pipe); +void usb0_host_enable_brdy_int(uint16_t pipe); +void usb0_host_disable_brdy_int(uint16_t pipe); +void usb0_host_clear_brdy_sts(uint16_t pipe); +void usb0_host_enable_bemp_int(uint16_t pipe); +void usb0_host_disable_bemp_int(uint16_t pipe); +void usb0_host_clear_bemp_sts(uint16_t pipe); +void usb0_host_enable_nrdy_int(uint16_t pipe); +void usb0_host_disable_nrdy_int(uint16_t pipe); +void usb0_host_clear_nrdy_sts(uint16_t pipe); +void usb0_host_set_pid_buf(uint16_t pipe); +void usb0_host_set_pid_nak(uint16_t pipe); +void usb0_host_set_pid_stall(uint16_t pipe); +void usb0_host_clear_pid_stall(uint16_t pipe); +uint16_t usb0_host_get_pid(uint16_t pipe); +void usb0_host_set_sqclr(uint16_t pipe); +void usb0_host_set_sqset(uint16_t pipe); +void usb0_host_set_csclr(uint16_t pipe); +void usb0_host_aclrm(uint16_t pipe); +void usb0_host_set_aclrm(uint16_t pipe); +void usb0_host_clr_aclrm(uint16_t pipe); +uint16_t usb0_host_get_sqmon(uint16_t pipe); +uint16_t usb0_host_get_inbuf(uint16_t pipe); + +/* ==== host ==== */ +void usb0_host_init_pipe_status(void); +int32_t usb0_host_CtrlTransStart(uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len, uint8_t *Buf); +void usb0_host_SetupStage(uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len); +void usb0_host_CtrlReadStart(uint32_t Bsize, uint8_t *Table); +uint16_t usb0_host_CtrlWriteStart(uint32_t Bsize, uint8_t *Table); +void usb0_host_StatusStage(void); +void usb0_host_get_devadd(uint16_t addr, uint16_t *devadd); +void usb0_host_set_devadd(uint16_t addr, uint16_t *devadd); +void usb0_host_InitModule(void); +uint16_t usb0_host_CheckAttach(void); +void usb0_host_UsbDetach(void); +void usb0_host_UsbDetach2(void); +void usb0_host_UsbAttach(void); +uint16_t usb0_host_UsbBusReset(void); +int32_t usb0_host_UsbResume(void); +int32_t usb0_host_UsbSuspend(void); +void usb0_host_Enable_DetachINT(void); +void usb0_host_Disable_DetachINT(void); +void usb0_host_UsbStateManager(void); + + +#endif /* USB0_HOST_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/inc/usb0_host_api.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,112 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_api.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB0_HOST_API_H +#define USB0_HOST_API_H + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Variable Externs +*******************************************************************************/ + + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +void usb0_host_interrupt(uint32_t int_sense); +void usb0_host_dma_interrupt_d0fifo(uint32_t int_sense); +void usb0_host_dma_interrupt_d1fifo(uint32_t int_sense); + +uint16_t usb0_api_host_init(uint8_t int_level, uint16_t mode, uint16_t clockmode); +int32_t usb0_api_host_enumeration(uint16_t devadr); +int32_t usb0_api_host_detach(void); +int32_t usb0_api_host_data_in(uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t usb0_api_host_data_out(uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t usb0_api_host_control_transfer(uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len, uint8_t *Buf); +int32_t usb0_api_host_set_endpoint(uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t *configdescriptor); +int32_t usb0_api_host_clear_endpoint(USB_HOST_CFG_PIPETBL_t *user_table); +int32_t usb0_api_host_clear_endpoint_pipe(uint16_t pipe_sel, USB_HOST_CFG_PIPETBL_t *user_table); +uint16_t usb0_api_host_SetEndpointTable(uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t* Table); +int32_t usb0_api_host_data_count(uint16_t pipe, uint32_t *data_count); + +int32_t usb0_api_host_GetDeviceDescriptor(uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t usb0_api_host_GetConfigDescriptor(uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t usb0_api_host_SetConfig(uint16_t devadr, uint16_t confignum); +int32_t usb0_api_host_SetInterface(uint16_t devadr, uint16_t interface_alt, uint16_t interface_index); +int32_t usb0_api_host_ClearStall(uint16_t devadr, uint16_t ep_dir); +uint16_t usb0_api_host_GetUsbDeviceState(void); + +void usb0_api_host_elt_4_4(void); +void usb0_api_host_elt_4_5(void); +void usb0_api_host_elt_4_6(void); +void usb0_api_host_elt_4_7(void); +void usb0_api_host_elt_4_8(void); +void usb0_api_host_elt_4_9(void); +void usb0_api_host_elt_get_desc(void); + +void usb0_host_EL_ModeInit(void); +void usb0_host_EL_SetUACT(void); +void usb0_host_EL_ClearUACT(void); +void usb0_host_EL_SetTESTMODE(uint16_t mode); +void usb0_host_EL_ClearNRDYSTS(uint16_t pipe); +uint16_t usb0_host_EL_GetINTSTS1(void); +void usb0_host_EL_UsbBusReset(void); +void usb0_host_EL_UsbAttach(void); +void usb0_host_EL_SetupStage(uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len); +void usb0_host_EL_StatusStage(void); +void usb0_host_EL_CtrlReadStart(uint32_t Bsize, uint8_t *Table); +int32_t usb0_host_EL_UsbSuspend(void); +int32_t usb0_host_EL_UsbResume(void); + +#if 0 /* prototype in devdrv_usb_host_api.h */ +uint16_t Userdef_USB_usb0_host_d0fifo_dmaintid(void); +uint16_t Userdef_USB_usb0_host_d1fifo_dmaintid(void); +void Userdef_USB_usb0_host_attach(void); +void Userdef_USB_usb0_host_detach(void); +void Userdef_USB_usb0_host_delay_1ms(void); +void Userdef_USB_usb0_host_delay_xms(uint32_t msec); +void Userdef_USB_usb0_host_delay_10us(uint32_t usec); +void Userdef_USB_usb0_host_delay_500ns(void); +void Userdef_USB_usb0_host_start_dma(USB_HOST_DMA_t *dma, uint16_t dfacc); +uint32_t Userdef_USB_usb0_host_stop_dma0(void); +uint32_t Userdef_USB_usb0_host_stop_dma1(void); +#endif + +#endif /* USB0_HOST_API_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/inc/usb0_host_dmacdrv.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,139 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_dmacdrv.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB0_HOST_DMACDRV_H +#define USB0_HOST_DMACDRV_H + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ +typedef struct dmac_transinfo +{ + uint32_t src_addr; /* Transfer source address */ + uint32_t dst_addr; /* Transfer destination address */ + uint32_t count; /* Transfer byte count */ + uint32_t src_size; /* Transfer source data size */ + uint32_t dst_size; /* Transfer destination data size */ + uint32_t saddr_dir; /* Transfer source address direction */ + uint32_t daddr_dir; /* Transfer destination address direction */ +} dmac_transinfo_t; + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +/* ==== Transfer specification of the sample program ==== */ +#define DMAC_SAMPLE_SINGLE (0) /* Single transfer */ +#define DMAC_SAMPLE_CONTINUATION (1) /* Continuous transfer (use REN bit) */ + +/* ==== DMA modes ==== */ +#define DMAC_MODE_REGISTER (0) /* Register mode */ +#define DMAC_MODE_LINK (1) /* Link mode */ + +/* ==== Transfer requests ==== */ +#define DMAC_REQ_MODE_EXT (0) /* External request */ +#define DMAC_REQ_MODE_PERI (1) /* On-chip peripheral module request */ +#define DMAC_REQ_MODE_SOFT (2) /* Auto-request (request by software) */ + +/* ==== DMAC transfer sizes ==== */ +#define DMAC_TRANS_SIZE_8 (0) /* 8 bits */ +#define DMAC_TRANS_SIZE_16 (1) /* 16 bits */ +#define DMAC_TRANS_SIZE_32 (2) /* 32 bits */ +#define DMAC_TRANS_SIZE_64 (3) /* 64 bits */ +#define DMAC_TRANS_SIZE_128 (4) /* 128 bits */ +#define DMAC_TRANS_SIZE_256 (5) /* 256 bits */ +#define DMAC_TRANS_SIZE_512 (6) /* 512 bits */ +#define DMAC_TRANS_SIZE_1024 (7) /* 1024 bits */ + +/* ==== Address increment for transferring ==== */ +#define DMAC_TRANS_ADR_NO_INC (1) /* Not increment */ +#define DMAC_TRANS_ADR_INC (0) /* Increment */ + +/* ==== Method for detecting DMA request ==== */ +#define DMAC_REQ_DET_FALL (0) /* Falling edge detection */ +#define DMAC_REQ_DET_RISE (1) /* Rising edge detection */ +#define DMAC_REQ_DET_LOW (2) /* Low level detection */ +#define DMAC_REQ_DET_HIGH (3) /* High level detection */ + +/* ==== Request Direction ==== */ +#define DMAC_REQ_DIR_SRC (0) /* DMAREQ is the source/ DMAACK is active when reading */ +#define DMAC_REQ_DIR_DST (1) /* DMAREQ is the destination/ DMAACK is active when writing */ + +/* ==== Descriptors ==== */ +#define DMAC_DESC_HEADER (0) /* Header */ +#define DMAC_DESC_SRC_ADDR (1) /* Source Address */ +#define DMAC_DESC_DST_ADDR (2) /* Destination Address */ +#define DMAC_DESC_COUNT (3) /* Transaction Byte */ +#define DMAC_DESC_CHCFG (4) /* Channel Confg */ +#define DMAC_DESC_CHITVL (5) /* Channel Interval */ +#define DMAC_DESC_CHEXT (6) /* Channel Extension */ +#define DMAC_DESC_LINK_ADDR (7) /* Link Address */ + +/* ==== On-chip peripheral module requests ===== */ +typedef enum dmac_request_factor +{ + DMAC_REQ_USB0_DMA0_TX, /* USB_0 channel 0 transmit FIFO empty */ + DMAC_REQ_USB0_DMA0_RX, /* USB_0 channel 0 receive FIFO full */ + DMAC_REQ_USB0_DMA1_TX, /* USB_0 channel 1 transmit FIFO empty */ + DMAC_REQ_USB0_DMA1_RX, /* USB_0 channel 1 receive FIFO full */ + DMAC_REQ_USB1_DMA0_TX, /* USB_1 channel 0 transmit FIFO empty */ + DMAC_REQ_USB1_DMA0_RX, /* USB_1 channel 0 receive FIFO full */ + DMAC_REQ_USB1_DMA1_TX, /* USB_1 channel 1 transmit FIFO empty */ + DMAC_REQ_USB1_DMA1_RX, /* USB_1 channel 1 receive FIFO full */ +} dmac_request_factor_t; + + +/******************************************************************************* +Variable Externs +*******************************************************************************/ + + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +void usb0_host_DMAC1_PeriReqInit(const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction); +int32_t usb0_host_DMAC1_Open(uint32_t req); +void usb0_host_DMAC1_Close(uint32_t * remain); +void usb0_host_DMAC1_Load_Set(uint32_t src_addr, uint32_t dst_addr, uint32_t count); + +void usb0_host_DMAC2_PeriReqInit(const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction); +int32_t usb0_host_DMAC2_Open(uint32_t req); +void usb0_host_DMAC2_Close(uint32_t * remain); +void usb0_host_DMAC2_Load_Set(uint32_t src_addr, uint32_t dst_addr, uint32_t count); + +#endif /* USB0_HOST_DMACDRV_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/common/usb0_host_dataio.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,2835 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_dataio.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +static uint16_t g_usb0_host_mbw[(USB_HOST_MAX_PIPE_NO + 1)]; + +static void usb0_host_start_receive_trns_c(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb0_host_start_receive_trns_d0(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb0_host_start_receive_trns_d1(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb0_host_start_receive_dma_d0(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb0_host_start_receive_dma_d1(uint16_t pipe, uint32_t size, uint8_t *data); +static uint16_t usb0_host_read_dma_d0(uint16_t pipe); +static uint16_t usb0_host_read_dma_d1(uint16_t pipe); +static uint16_t usb0_host_write_dma_d0(uint16_t pipe); +static uint16_t usb0_host_write_dma_d1(uint16_t pipe); + +static void usb0_host_read_c_fifo(uint16_t pipe, uint16_t count); +static void usb0_host_write_c_fifo(uint16_t Pipe, uint16_t count); +static void usb0_host_read_d0_fifo(uint16_t pipe, uint16_t count); +static void usb0_host_write_d0_fifo(uint16_t pipe, uint16_t count); +static void usb0_host_read_d1_fifo(uint16_t pipe, uint16_t count); +static void usb0_host_write_d1_fifo(uint16_t pipe, uint16_t count); + +static void usb0_host_clear_transaction_counter(uint16_t pipe); +static void usb0_host_set_transaction_counter(uint16_t pipe, uint32_t count); + +static uint32_t usb0_host_com_get_dmasize(uint32_t trncount, uint32_t dtptr); + +static uint16_t usb0_host_set_dfacc_d0(uint16_t mbw, uint32_t count); +static uint16_t usb0_host_set_dfacc_d1(uint16_t mbw, uint32_t count); + + +/******************************************************************************* +* Function Name: usb0_host_start_send_transfer +* Description : Starts the USB data communication using pipe specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data data Address +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_start_send_transfer (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t status; + uint16_t usefifo; + uint16_t mbw; + + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + usb0_host_clear_bemp_sts(pipe); + usb0_host_clear_brdy_sts(pipe); + usb0_host_clear_nrdy_sts(pipe); + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + + usefifo = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + case USB_HOST_D0FIFO_DMA: + usefifo = USB_HOST_D0USE; + break; + + case USB_HOST_D1FIFO_USE: + case USB_HOST_D1FIFO_DMA: + usefifo = USB_HOST_D1USE; + break; + + default: + usefifo = USB_HOST_CUSE; + break; + }; + + usb0_host_set_curpipe(USB_HOST_PIPE0, usefifo, USB_HOST_NO, mbw); + + usb0_host_clear_transaction_counter(pipe); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + status = usb0_host_write_buffer(pipe); + + if (status != USB_HOST_FIFOERROR) + { + usb0_host_set_pid_buf(pipe); + } + + return status; +} + +/******************************************************************************* +* Function Name: usb0_host_write_buffer +* Description : Writes data in the buffer allocated in the pipe specified by +* : the argument. The FIFO for using is set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_write_buffer (uint16_t pipe) +{ + uint16_t status; + uint16_t usefifo; + + g_usb0_host_PipeIgnore[pipe] = 0; + usefifo = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + status = usb0_host_write_buffer_d0(pipe); + break; + + case USB_HOST_D1FIFO_USE: + status = usb0_host_write_buffer_d1(pipe); + break; + + case USB_HOST_D0FIFO_DMA: + status = usb0_host_write_dma_d0(pipe); + break; + + case USB_HOST_D1FIFO_DMA: + status = usb0_host_write_dma_d1(pipe); + break; + + default: + status = usb0_host_write_buffer_c(pipe); + break; + }; + + switch (status) + { + case USB_HOST_WRITING: /* Continue of data write */ + usb0_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + usb0_host_enable_brdy_int(pipe); /* Enable Ready Interrupt */ + break; + + case USB_HOST_WRITEEND: /* End of data write */ + case USB_HOST_WRITESHRT: /* End of data write */ + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + + usb0_host_clear_nrdy_sts(pipe); + usb0_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + + /* for last transfer */ + usb0_host_enable_bemp_int(pipe); /* Enable Empty Interrupt */ + break; + + case USB_HOST_WRITEDMA: /* DMA write */ + usb0_host_clear_nrdy_sts(pipe); + usb0_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + usb0_host_disable_bemp_int(pipe); /* Disable Empty Interrupt */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_write_buffer_c +* Description : Writes data in the buffer allocated in the pipe specified in +* : the argument. Writes data by CPU transfer using CFIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_write_buffer_c (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + + if (pipe == USB_HOST_PIPE0) + { + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_CFIFO_WRITE, mbw); + } + else + { + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_NO, mbw); + } + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb0_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb0_host_write_c_fifo(pipe, (uint16_t)count); + + if (g_usb0_host_data_count[pipe] < (uint32_t)size) + { + g_usb0_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB200.CFIFOCTR, + USB_CFIFOCTR_BVAL_SHIFT, + USB_CFIFOCTR_BVAL) == 0) + { + USB200.CFIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb0_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_write_buffer_d0 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by CPU transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_write_buffer_d0 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D0USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb0_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb0_host_write_d0_fifo(pipe, (uint16_t)count); + + if (g_usb0_host_data_count[pipe] < (uint32_t)size) + { + g_usb0_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB200.D0FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + USB200.D0FIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb0_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_write_buffer_d1 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by CPU transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_write_buffer_d1 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D1USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb0_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb0_host_write_d1_fifo(pipe, (uint16_t)count); + + if (g_usb0_host_data_count[pipe] < (uint32_t)size) + { + g_usb0_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB200.D1FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + USB200.D1FIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb0_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_write_dma_d0 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by DMA transfer using D0FIFO. +* : The DMA-ch for using is specified by Userdef_USB_usb0_host_start_dma(). +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND : Write end +* : USB_HOST_WRITESHRT : short data +* : USB_HOST_WRITING : Continue of data write +* : USB_HOST_WRITEDMA : Write DMA +* : USB_HOST_FIFOERROR : FIFO status +*******************************************************************************/ +static uint16_t usb0_host_write_dma_d0 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + count = g_usb0_host_data_count[pipe]; + + if (count != 0) + { + g_usb0_host_DmaPipe[USB_HOST_D0FIFO] = pipe; + + if ((count % size) != 0) + { + g_usb0_host_DmaBval[USB_HOST_D0FIFO] = 1; + } + else + { + g_usb0_host_DmaBval[USB_HOST_D0FIFO] = 0; + } + + dfacc = usb0_host_set_dfacc_d0(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 0; /* 8bit transfer */ + } + + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].fifo = USB_HOST_D0FIFO_DMA; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].dir = USB_HOST_BUF2FIFO; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].buffer = (uint32_t)g_usb0_host_data_pointer[pipe]; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].bytes = count; + + Userdef_USB_usb0_host_start_dma(&g_usb0_host_DmaInfo[USB_HOST_D0FIFO], dfacc); + + usb0_host_set_curpipe2(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw, dfacc); + + RZA_IO_RegWrite_16(&USB200.D0FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + + g_usb0_host_data_count[pipe] = 0; + g_usb0_host_data_pointer[pipe] += count; + + status = USB_HOST_WRITEDMA; /* DMA write */ + } + else + { + if (RZA_IO_RegRead_16(&USB200.D0FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + RZA_IO_RegWrite_16(&USB200.D0FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); /* Short Packet */ + } + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_write_dma_d1 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by DMA transfer using D1FIFO. +* : The DMA-ch for using is specified by Userdef_USB_usb0_host_start_dma(). +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND : Write end +* : USB_HOST_WRITESHRT : short data +* : USB_HOST_WRITING : Continue of data write +* : USB_HOST_WRITEDMA : Write DMA +* : USB_HOST_FIFOERROR : FIFO status +*******************************************************************************/ +static uint16_t usb0_host_write_dma_d1 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + count = g_usb0_host_data_count[pipe]; + + if (count != 0) + { + g_usb0_host_DmaPipe[USB_HOST_D1FIFO] = pipe; + + if ((count % size) != 0) + { + g_usb0_host_DmaBval[USB_HOST_D1FIFO] = 1; + } + else + { + g_usb0_host_DmaBval[USB_HOST_D1FIFO] = 0; + } + + dfacc = usb0_host_set_dfacc_d1(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 0; /* 8bit transfer */ + } + + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].fifo = USB_HOST_D1FIFO_DMA; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].dir = USB_HOST_BUF2FIFO; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].buffer = (uint32_t)g_usb0_host_data_pointer[pipe]; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].bytes = count; + + Userdef_USB_usb0_host_start_dma(&g_usb0_host_DmaInfo[USB_HOST_D1FIFO], dfacc); + + usb0_host_set_curpipe2(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw, dfacc); + + RZA_IO_RegWrite_16(&USB200.D1FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + + g_usb0_host_data_count[pipe] = 0; + g_usb0_host_data_pointer[pipe] += count; + + status = USB_HOST_WRITEDMA; /* DMA write */ + } + else + { + if (RZA_IO_RegRead_16(&USB200.D1FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + RZA_IO_RegWrite_16(&USB200.D1FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); /* Short Packet */ + } + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_transfer +* Description : Starts USB data reception using the pipe specified in the argument. +* : The FIFO for using is set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +void usb0_host_start_receive_transfer (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t usefifo; + + usb0_host_clear_bemp_sts(pipe); + usb0_host_clear_brdy_sts(pipe); + usb0_host_clear_nrdy_sts(pipe); + + usefifo = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + usb0_host_start_receive_trns_d0(pipe, size, data); + break; + + case USB_HOST_D1FIFO_USE: + usb0_host_start_receive_trns_d1(pipe, size, data); + break; + + case USB_HOST_D0FIFO_DMA: + usb0_host_start_receive_dma_d0(pipe, size, data); + break; + + case USB_HOST_D1FIFO_DMA: + usb0_host_start_receive_dma_d1(pipe, size, data); + break; + + default: + usb0_host_start_receive_trns_c(pipe, size, data); + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_trns_c +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using CFIFO. +* : When storing data in the buffer allocated in the pipe specified in the +* : argument, BRDY interrupt is generated to read data +* : in the interrupt. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb0_host_start_receive_trns_c (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb0_host_set_pid_nak(pipe); + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_PipeIgnore[pipe] = 0; + + g_usb0_host_PipeDataSize[pipe] = size; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_CFIFO_READ, mbw); + USB200.CFIFOCTR = USB_HOST_BITBCLR; + + usb0_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + + usb0_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_trns_d0 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, BRDY interrupt is generated to read data in the +* : interrupt. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb0_host_start_receive_trns_d0 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb0_host_set_pid_nak(pipe); + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_PipeIgnore[pipe] = 0; + + g_usb0_host_PipeDataSize[pipe] = size; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, mbw); + + usb0_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + + usb0_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_trns_d1 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using D1FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, BRDY interrupt is generated to read data. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb0_host_start_receive_trns_d1 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb0_host_set_pid_nak(pipe); + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_PipeIgnore[pipe] = 0; + + g_usb0_host_PipeDataSize[pipe] = size; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, mbw); + + usb0_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + + usb0_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_dma_d0 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by DMA transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, delivered read request to DMAC to read data from +* : the buffer by DMAC. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb0_host_start_receive_dma_d0 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb0_host_set_pid_nak(pipe); + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_PipeIgnore[pipe] = 0; + + g_usb0_host_PipeDataSize[pipe] = 0; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, mbw); + + usb0_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + usb0_host_read_dma(pipe); + + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + } + else + { + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + } + + usb0_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_dma_d1 +* Description : Read data from the buffer allocated in the pipe specified in the argument. +* : Reads data by DMA transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, delivered read request to DMAC to read data from +* : the buffer by DMAC. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb0_host_start_receive_dma_d1 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb0_host_set_pid_nak(pipe); + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_PipeIgnore[pipe] = 0; + + g_usb0_host_PipeDataSize[pipe] = 0; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, mbw); + + usb0_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + usb0_host_read_dma(pipe); + + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + } + else + { + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + } + + usb0_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_read_buffer +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Uses FIF0 set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_read_buffer (uint16_t pipe) +{ + uint16_t status; + + g_usb0_host_PipeIgnore[pipe] = 0; + + if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_USE) + { + status = usb0_host_read_buffer_d0(pipe); + } + else if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_USE) + { + status = usb0_host_read_buffer_d1(pipe); + } + else + { + status = usb0_host_read_buffer_c(pipe); + } + + switch (status) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb0_host_disable_brdy_int(pipe); + g_usb0_host_PipeDataSize[pipe] -= g_usb0_host_data_count[pipe]; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + break; + + case USB_HOST_READOVER: /* buffer over */ + if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_USE) + { + USB200.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_USE) + { + USB200.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + USB200.CFIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#else + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; +#endif + g_usb0_host_PipeDataSize[pipe] -= g_usb0_host_data_count[pipe]; + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_buffer_c +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using CFIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_read_buffer_c (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb0_host_data_count[pipe]; + } + else if (g_usb0_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + } + + if (count == 0) /* 0 length packet */ + { + USB200.CFIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb0_host_read_c_fifo(pipe, (uint16_t)count); + } + + g_usb0_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_buffer_d0 +* Description : Reads data from the buffer allocated in the pipe specified in +* : the argument. +* : Reads data by CPU transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_read_buffer_d0 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t pipebuf_size; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D0USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb0_host_data_count[pipe]; + } + else if (g_usb0_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + else + { + pipebuf_size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + } + } + + if (count == 0) /* 0 length packet */ + { + USB200.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb0_host_read_d0_fifo(pipe, (uint16_t)count); + } + + g_usb0_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_buffer_d1 +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by CPU transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_read_buffer_d1 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t pipebuf_size; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D1USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb0_host_data_count[pipe]; + } + else if (g_usb0_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) !=0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + else + { + pipebuf_size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + } + } + + if (count == 0) /* 0 length packet */ + { + USB200.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb0_host_read_d1_fifo(pipe, (uint16_t)count); + } + + g_usb0_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_dma +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by DMA transfer using D0FIFO or D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_read_dma (uint16_t pipe) +{ + uint16_t status; + + g_usb0_host_PipeIgnore[pipe] = 0; + + if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_DMA) + { + status = usb0_host_read_dma_d0(pipe); + } + else + { + status = usb0_host_read_dma_d1(pipe); + } + + switch (status) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READZERO: /* End of data read */ + usb0_host_disable_brdy_int(pipe); + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb0_host_disable_brdy_int(pipe); + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + g_usb0_host_PipeDataSize[pipe] -= g_usb0_host_data_count[pipe]; + } + break; + + case USB_HOST_READOVER: /* buffer over */ + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + g_usb0_host_PipeDataSize[pipe] -= g_usb0_host_data_count[pipe]; + } +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#else + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; +#endif + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_dma_d0 +* Description : Writes data in the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by DMA transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +static uint16_t usb0_host_read_dma_d0 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + uint16_t pipebuf_size; + + g_usb0_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_READY; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + count = g_usb0_host_data_count[pipe]; + status = USB_HOST_READING; + } + else + { + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + count = g_usb0_host_data_count[pipe]; + } + else if (g_usb0_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + else + { + pipebuf_size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + } + } + + if (count == 0) /* 0 length packet */ + { + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + USB200.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear B_CLR */ + status = USB_HOST_READZERO; /* Null Packet receive */ + } + else + { + usb0_host_set_curpipe(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + /* transaction counter No set */ + /* FRDY = 1, DTLN = 0 -> BRDY */ + } + } + else + { + dfacc = usb0_host_set_dfacc_d0(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 0; /* 8bit transfer */ + } + + g_usb0_host_DmaPipe[USB_HOST_D0FIFO] = pipe; /* not use in read operation */ + g_usb0_host_DmaBval[USB_HOST_D0FIFO] = 0; /* not use in read operation */ + + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].fifo = USB_HOST_D0FIFO_DMA; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].dir = USB_HOST_FIFO2BUF; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].buffer = (uint32_t)g_usb0_host_data_pointer[pipe]; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].bytes = count; + + if (status == USB_HOST_READING) + { + g_usb0_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_BUSY; + } + else + { + g_usb0_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_BUSYEND; + } + + Userdef_USB_usb0_host_start_dma(&g_usb0_host_DmaInfo[USB_HOST_D0FIFO], dfacc); + + usb0_host_set_curpipe2(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw, dfacc); + + RZA_IO_RegWrite_16(&USB200.D0FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + g_usb0_host_data_count[pipe] -= count; + g_usb0_host_data_pointer[pipe] += count; + g_usb0_host_PipeDataSize[pipe] += count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_dma_d1 +* Description : Reads data from the buffer allocated in the pipe specified in +* : the argument. +* : Reads data by DMA transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +static uint16_t usb0_host_read_dma_d1 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + uint16_t pipebuf_size; + + g_usb0_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_READY; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + count = g_usb0_host_data_count[pipe]; + status = USB_HOST_READING; + } + else + { + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + count = g_usb0_host_data_count[pipe]; + } + else if (g_usb0_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + else + { + pipebuf_size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + } + } + + if (count == 0) /* 0 length packet */ + { + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + USB200.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + status = USB_HOST_READZERO; /* Null Packet receive */ + } + else + { + usb0_host_set_curpipe(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + /* transaction counter No set */ + /* FRDY = 1, DTLN = 0 -> BRDY */ + } + } + else + { + dfacc = usb0_host_set_dfacc_d1(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 0; /* 8bit transfer */ + } + + g_usb0_host_DmaPipe[USB_HOST_D1FIFO] = pipe; /* not use in read operation */ + g_usb0_host_DmaBval[USB_HOST_D1FIFO] = 0; /* not use in read operation */ + + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].fifo = USB_HOST_D1FIFO_DMA; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].dir = USB_HOST_FIFO2BUF; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].buffer = (uint32_t)g_usb0_host_data_pointer[pipe]; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].bytes = count; + + if (status == USB_HOST_READING) + { + g_usb0_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_BUSY; + } + else + { + g_usb0_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_BUSYEND; + } + + Userdef_USB_usb0_host_start_dma(&g_usb0_host_DmaInfo[USB_HOST_D1FIFO], dfacc); + + usb0_host_set_curpipe2(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw, dfacc); + + RZA_IO_RegWrite_16(&USB200.D1FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + g_usb0_host_data_count[pipe] -= count; + g_usb0_host_data_pointer[pipe] += count; + g_usb0_host_PipeDataSize[pipe] += count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_change_fifo_port +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument. After allocating FIF0, waits in the software +* : till the corresponding pipe becomes ready. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* Return Value : USB_HOST_FIFOERROR ; Error +* : Others ; CFIFOCTR/D0FIFOCTR/D1FIFOCTR Register Value +*******************************************************************************/ +uint16_t usb0_host_change_fifo_port (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw) +{ + uint16_t buffer; + uint32_t loop; + volatile uint32_t loop2; + + usb0_host_set_curpipe(pipe, fifosel, isel, mbw); + + for (loop = 0; loop < 4; loop++) + { + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB200.CFIFOCTR; + break; + + case USB_HOST_D0USE: + case USB_HOST_D0DMA: + buffer = USB200.D0FIFOCTR; + break; + + case USB_HOST_D1USE: + case USB_HOST_D1DMA: + buffer = USB200.D1FIFOCTR; + break; + + default: + buffer = 0; + break; + } + + if ((buffer & USB_HOST_BITFRDY) == USB_HOST_BITFRDY) + { + return buffer; + } + + loop2 = 25; + + while (loop2-- > 0) + { + /* wait */ + } + } + + return USB_HOST_FIFOERROR; +} + +/******************************************************************************* +* Function Name: usb0_host_set_curpipe +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* Return Value : none +*******************************************************************************/ +void usb0_host_set_curpipe (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw) +{ + uint16_t buffer; + uint32_t loop; + volatile uint32_t loop2; + + g_usb0_host_mbw[pipe] = mbw; + + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB200.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(~isel & USB_HOST_BITISEL); + USB200.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(isel | pipe | mbw); + USB200.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D0DMA: + case USB_HOST_D0USE: + buffer = USB200.D0FIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + USB200.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB200.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D1DMA: + case USB_HOST_D1USE: + buffer = USB200.D1FIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + USB200.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB200.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + default: + break; + } + + /* Cautions !!! + * Depending on the external bus speed of CPU, you may need to wait for 450ns here. + * For details, please look at the data sheet. */ + loop2 = 100; + + while (loop2-- > 0) + { + /* wait */ + } +} + +/******************************************************************************* +* Function Name: usb0_host_set_curpipe2 +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument.(DFACC) +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* : uint16_t dfacc ; DFACC Access mode +* Return Value : none +*******************************************************************************/ +void usb0_host_set_curpipe2 (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw, uint16_t dfacc) +{ + uint16_t buffer; + uint32_t loop; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + uint32_t dummy; +#endif + volatile uint32_t loop2; + + g_usb0_host_mbw[pipe] = mbw; + + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB200.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(~isel & USB_HOST_BITISEL); + USB200.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(isel | pipe | mbw); + USB200.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D0DMA: + case USB_HOST_D0USE: + buffer = USB200.D0FIFOSEL; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + + if (dfacc != 0) + { + buffer |= (uint16_t)(USB_HOST_BITMBW_32); + } +#else + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); +#endif + USB200.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + +#ifdef __USB_HOST_DF_ACC_ENABLE__ + if (dfacc != 0) + { + dummy = USB200.D0FIFO.UINT32; + } +#endif + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB200.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D1DMA: + case USB_HOST_D1USE: + buffer = USB200.D1FIFOSEL; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + + if (dfacc != 0) + { + buffer |= (uint16_t)(USB_HOST_BITMBW_32); + } +#else + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); +#endif + USB200.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + +#ifdef __USB_HOST_DF_ACC_ENABLE__ + if (dfacc != 0) + { + dummy = USB200.D1FIFO.UINT32; + loop = dummy; // avoid warning. + } +#endif + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB200.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + default: + break; + } + + /* Cautions !!! + * Depending on the external bus speed of CPU, you may need to wait for 450ns here. + * For details, please look at the data sheet. */ + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } +} + +/******************************************************************************* +* Function Name: usb0_host_write_c_fifo +* Description : Writes data in CFIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_write_c_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB200.CFIFO.UINT8[HH] = *g_usb0_host_data_pointer[pipe]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB200.CFIFO.UINT16[H] = *((uint16_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB200.CFIFO.UINT32 = *((uint32_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_read_c_fifo +* Description : Reads data from CFIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_read_c_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb0_host_data_pointer[pipe] = USB200.CFIFO.UINT8[HH]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb0_host_data_pointer[pipe]) = USB200.CFIFO.UINT16[H]; + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb0_host_data_pointer[pipe]) = USB200.CFIFO.UINT32; + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_write_d0_fifo +* Description : Writes data in D0FIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_write_d0_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB200.D0FIFO.UINT8[HH] = *g_usb0_host_data_pointer[pipe]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB200.D0FIFO.UINT16[H] = *((uint16_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB200.D0FIFO.UINT32 = *((uint32_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_read_d0_fifo +* Description : Reads data from D0FIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating DOFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t Pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_read_d0_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb0_host_data_pointer[pipe] = USB200.D0FIFO.UINT8[HH]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb0_host_data_pointer[pipe]) = USB200.D0FIFO.UINT16[H]; + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb0_host_data_pointer[pipe]) = USB200.D0FIFO.UINT32; + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_write_d1_fifo +* Description : Writes data in D1FIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating D1FIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_write_d1_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB200.D1FIFO.UINT8[HH] = *g_usb0_host_data_pointer[pipe]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB200.D1FIFO.UINT16[H] = *((uint16_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB200.D1FIFO.UINT32 = *((uint32_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_read_d1_fifo +* Description : Reads data from D1FIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating D1FIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_read_d1_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb0_host_data_pointer[pipe] = USB200.D1FIFO.UINT8[HH]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb0_host_data_pointer[pipe]) = USB200.D1FIFO.UINT16[H]; + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb0_host_data_pointer[pipe]) = USB200.D1FIFO.UINT32; + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_com_get_dmasize +* Description : Calculates access width of DMA transfer by the argument to + return as the Return Value. +* Arguments : uint32_t trncount : transfer byte +* : uint32_t dtptr : transfer data pointer +* Return Value : DMA transfer size : 0 8bit +* : : 1 16bit +* : : 2 32bit +*******************************************************************************/ +static uint32_t usb0_host_com_get_dmasize (uint32_t trncount, uint32_t dtptr) +{ + uint32_t size; + + if (((trncount & 0x0001) != 0) || ((dtptr & 0x00000001) != 0)) + { + /* When transfer byte count is odd */ + /* or transfer data area is 8-bit alignment */ + size = 0; /* 8bit */ + } + else if (((trncount & 0x0003) != 0) || ((dtptr & 0x00000003) != 0)) + { + /* When the transfer byte count is multiples of 2 */ + /* or the transfer data area is 16-bit alignment */ + size = 1; /* 16bit */ + } + else + { + /* When the transfer byte count is multiples of 4 */ + /* or the transfer data area is 32-bit alignment */ + size = 2; /* 32bit */ + } + + return size; +} + +/******************************************************************************* +* Function Name: usb0_host_get_mbw +* Description : Calculates access width of DMA to return the value set in MBW. +* Arguments : uint32_t trncount : transfer byte +* : uint32_t dtptr : transfer data pointer +* Return Value : FIFO transfer size : USB_HOST_BITMBW_8 8bit +* : : USB_HOST_BITMBW_16 16bit +* : : USB_HOST_BITMBW_32 32bit +*******************************************************************************/ +uint16_t usb0_host_get_mbw (uint32_t trncount, uint32_t dtptr) +{ + uint32_t size; + uint16_t mbw; + + size = usb0_host_com_get_dmasize(trncount, dtptr); + + if (size == 0) + { + /* 8bit */ + mbw = USB_HOST_BITMBW_8; + } + else if (size == 1) + { + /* 16bit */ + mbw = USB_HOST_BITMBW_16; + } + else + { + /* 32bit */ + mbw = USB_HOST_BITMBW_32; + } + + return mbw; +} + +/******************************************************************************* +* Function Name: usb0_host_set_transaction_counter +* Description : Sets transaction counter by the argument(PIPEnTRN). +* : Clears transaction before setting to enable transaction counter setting. +* Arguments : uint16_t pipe ; Pipe number +* : uint32_t bsize : Data transfer size +* Return Value : none +*******************************************************************************/ +static void usb0_host_set_transaction_counter (uint16_t pipe, uint32_t bsize) +{ + uint16_t mxps; + uint16_t cnt; + + if (bsize == 0) + { + return; + } + + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if ((bsize % mxps) == 0) + { + cnt = (uint16_t)(bsize / mxps); + } + else + { + cnt = (uint16_t)((bsize / mxps) + 1); + } + + switch (pipe) + { + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE1TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE1TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE2TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE2TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE3TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE3TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE4TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE4TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE5TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE5TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE9TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE9TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_clear_transaction_counter +* Description : Clears the transaction counter by the argument. +* : After executing this function, the transaction counter is invalid. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb0_host_clear_transaction_counter (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE1TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE2TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE3TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE4TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE5TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE9TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_stop_transfer +* Description : Stops the USB transfer in the pipe specified by the argument. +* : After stopping the USB transfer, clears the buffer allocated in +* : the pipe. +* : After executing this function, allocation in FIF0 becomes USB_HOST_PIPE0; +* : invalid. After executing this function, BRDY/NRDY/BEMP interrupt +* : in the corresponding pipe becomes invalid. Sequence bit is also +* : cleared. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_stop_transfer (uint16_t pipe) +{ + uint16_t usefifo; + uint32_t remain; + + usb0_host_set_pid_nak(pipe); + + usefifo = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + usb0_host_clear_transaction_counter(pipe); + USB200.D0FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D1FIFO_USE: + usb0_host_clear_transaction_counter(pipe); + USB200.D1FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D0FIFO_DMA: + remain = Userdef_USB_usb0_host_stop_dma0(); + usb0_host_dma_stop_d0(pipe, remain); + usb0_host_clear_transaction_counter(pipe); + USB200.D0FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D1FIFO_DMA: + remain = Userdef_USB_usb0_host_stop_dma1(); + usb0_host_dma_stop_d1(pipe, remain); + usb0_host_clear_transaction_counter(pipe); + USB200.D1FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + default: + usb0_host_clear_transaction_counter(pipe); + USB200.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + } + + /* Interrupt of pipe set is disabled */ + usb0_host_disable_brdy_int(pipe); + usb0_host_disable_nrdy_int(pipe); + usb0_host_disable_bemp_int(pipe); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + usb0_host_set_csclr(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_set_dfacc_d0 +* Description : Sets the DFACC setting value in D0FIFO using the transfer size. +* Arguments : uint16_t mbw ; MBW +* : uint16_t count ; data count +* Return Value : DFACC Access mode +*******************************************************************************/ +static uint16_t usb0_host_set_dfacc_d0 (uint16_t mbw, uint32_t count) +{ + uint16_t dfacc = 0; + +#ifndef __USB_HOST_DF_ACC_ENABLE__ + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; +#else + if (mbw == USB_HOST_BITMBW_32) + { + if ((count % 32) == 0) + { + /* 32byte transfer */ + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 2, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 2; + } + else if ((count % 16) == 0) + { + /* 16byte transfer */ + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 1, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 1; + } + else + { + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + } + else if (mbw == USB_HOST_BITMBW_16) + { + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + else + { + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } +#endif + + return dfacc; +} + +/******************************************************************************* +* Function Name: usb0_host_set_dfacc_d1 +* Description : Sets the DFACC setting value in D1FIFO using the transfer size. +* Arguments : uint16_t mbw ; MBW +* : uint16_t count ; data count +* Return Value : DFACC Access mode +*******************************************************************************/ +static uint16_t usb0_host_set_dfacc_d1 (uint16_t mbw, uint32_t count) +{ + uint16_t dfacc = 0; + +#ifndef __USB_HOST_DF_ACC_ENABLE__ + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; +#else + if (mbw == USB_HOST_BITMBW_32) + { + if ((count % 32) == 0) + { + /* 32byte transfer */ + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 2, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 2; + } + else if ((count % 16) == 0) + { + /* 16byte transfer */ + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 1, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 1; + } + else + { + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + } + else if (mbw == USB_HOST_BITMBW_16) + { + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + else + { + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } +#endif + + return dfacc; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/common/usb0_host_dma.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,355 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_dma.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +/* #include "usb0_host_dmacdrv.h" */ + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +static void usb0_host_dmaint(uint16_t fifo); +static void usb0_host_dmaint_buf2fifo(uint16_t pipe); +static void usb0_host_dmaint_fifo2buf(uint16_t pipe); + + +/******************************************************************************* +* Function Name: usb0_host_dma_stop_d0 +* Description : D0FIFO DMA stop +* Arguments : uint16_t pipe : pipe number +* : uint32_t remain : transfer byte +* Return Value : none +*******************************************************************************/ +void usb0_host_dma_stop_d0 (uint16_t pipe, uint32_t remain) +{ + uint16_t dtln; + uint16_t dfacc; + uint16_t buffer; + uint16_t sds_b = 1; + + dfacc = RZA_IO_RegRead_16(&USB200.D0FBCFG, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + if (dfacc == 2) + { + sds_b = 32; + } + else if (dfacc == 1) + { + sds_b = 16; + } + else + { + if (g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size == 2) + { + sds_b = 4; + } + else if (g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size == 1) + { + sds_b = 2; + } + else + { + sds_b = 1; + } + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + if (g_usb0_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + buffer = USB200.D0FIFOCTR; + dtln = (buffer & USB_HOST_BITDTLN); + + if ((dtln % sds_b) != 0) + { + remain += (sds_b - (dtln % sds_b)); + } + g_usb0_host_PipeDataSize[pipe] = (g_usb0_host_data_count[pipe] - remain); + g_usb0_host_data_count[pipe] = remain; + } + } + + RZA_IO_RegWrite_16(&USB200.D0FIFOSEL, + 0, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); +} + +/******************************************************************************* +* Function Name: usb0_host_dma_stop_d1 +* Description : D1FIFO DMA stop +* Arguments : uint16_t pipe : pipe number +* : uint32_t remain : transfer byte +* Return Value : none +*******************************************************************************/ +void usb0_host_dma_stop_d1 (uint16_t pipe, uint32_t remain) +{ + uint16_t dtln; + uint16_t dfacc; + uint16_t buffer; + uint16_t sds_b = 1; + + dfacc = RZA_IO_RegRead_16(&USB200.D1FBCFG, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + if (dfacc == 2) + { + sds_b = 32; + } + else if (dfacc == 1) + { + sds_b = 16; + } + else + { + if (g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size == 2) + { + sds_b = 4; + } + else if (g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size == 1) + { + sds_b = 2; + } + else + { + sds_b = 1; + } + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + if (g_usb0_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + buffer = USB200.D1FIFOCTR; + dtln = (buffer & USB_HOST_BITDTLN); + + if ((dtln % sds_b) != 0) + { + remain += (sds_b - (dtln % sds_b)); + } + g_usb0_host_PipeDataSize[pipe] = (g_usb0_host_data_count[pipe] - remain); + g_usb0_host_data_count[pipe] = remain; + } + } + + RZA_IO_RegWrite_16(&USB200.D1FIFOSEL, + 0, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); +} + +/******************************************************************************* +* Function Name: usb0_host_dma_interrupt_d0fifo +* Description : This function is DMA interrupt handler entry. +* : Execute usb1_host_dmaint() after disabling DMA interrupt in this function. +* : Disable DMA interrupt to DMAC executed when USB_HOST_D0FIFO_DMA is +* : specified by dma->fifo. +* : Register this function as DMA complete interrupt. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb0_host_dma_interrupt_d0fifo (uint32_t int_sense) +{ + usb0_host_dmaint(USB_HOST_D0FIFO); + g_usb0_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_READY; +} + +/******************************************************************************* +* Function Name: usb0_host_dma_interrupt_d1fifo +* Description : This function is DMA interrupt handler entry. +* : Execute usb0_host_dmaint() after disabling DMA interrupt in this function. +* : Disable DMA interrupt to DMAC executed when USB_HOST_D1FIFO_DMA is +* : specified by dma->fifo. +* : Register this function as DMA complete interrupt. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb0_host_dma_interrupt_d1fifo (uint32_t int_sense) +{ + usb0_host_dmaint(USB_HOST_D1FIFO); + g_usb0_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_READY; +} + +/******************************************************************************* +* Function Name: usb0_host_dmaint +* Description : This function is DMA transfer end interrupt +* Arguments : uint16_t fifo ; fifo number +* : ; USB_HOST_D0FIFO +* : ; USB_HOST_D1FIFO +* Return Value : none +*******************************************************************************/ +static void usb0_host_dmaint (uint16_t fifo) +{ + uint16_t pipe; + + pipe = g_usb0_host_DmaPipe[fifo]; + + if (g_usb0_host_DmaInfo[fifo].dir == USB_HOST_BUF2FIFO) + { + usb0_host_dmaint_buf2fifo(pipe); + } + else + { + usb0_host_dmaint_fifo2buf(pipe); + } +} + +/******************************************************************************* +* Function Name: usb0_host_dmaint_fifo2buf +* Description : Executes read completion from FIFO by DMAC. +* Arguments : uint16_t pipe : pipe number +* Return Value : none +*******************************************************************************/ +static void usb0_host_dmaint_fifo2buf (uint16_t pipe) +{ + uint32_t remain; + uint16_t useport; + + if (g_usb0_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + useport = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + if (useport == USB_HOST_D0FIFO_DMA) + { + remain = Userdef_USB_usb0_host_stop_dma0(); + usb0_host_dma_stop_d0(pipe, remain); + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + if (g_usb0_host_DmaStatus[USB_HOST_D0FIFO] == USB_HOST_DMA_BUSYEND) + { + USB200.D0FIFOCTR = USB_HOST_BITBCLR; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + else + { + usb0_host_enable_brdy_int(pipe); + } + } + } + else + { + remain = Userdef_USB_usb0_host_stop_dma1(); + usb0_host_dma_stop_d1(pipe, remain); + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + if (g_usb0_host_DmaStatus[USB_HOST_D1FIFO] == USB_HOST_DMA_BUSYEND) + { + USB200.D1FIFOCTR = USB_HOST_BITBCLR; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + else + { + usb0_host_enable_brdy_int(pipe); + } + } + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_dmaint_buf2fifo +* Description : Executes write completion in FIFO by DMAC. +* Arguments : uint16_t pipe : pipe number +* Return Value : none +*******************************************************************************/ +static void usb0_host_dmaint_buf2fifo (uint16_t pipe) +{ + uint16_t useport; + uint32_t remain; + + useport = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + if (useport == USB_HOST_D0FIFO_DMA) + { + remain = Userdef_USB_usb0_host_stop_dma0(); + usb0_host_dma_stop_d0(pipe, remain); + + if (g_usb0_host_DmaBval[USB_HOST_D0FIFO] != 0) + { + RZA_IO_RegWrite_16(&USB200.D0FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); + } + } + else + { + remain = Userdef_USB_usb0_host_stop_dma1(); + usb0_host_dma_stop_d1(pipe, remain); + + if (g_usb0_host_DmaBval[USB_HOST_D1FIFO] != 0) + { + RZA_IO_RegWrite_16(&USB200.D1FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); + } + } + + usb0_host_enable_bemp_int(pipe); +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/common/usb0_host_intrn.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,285 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_intrn.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#if(1) /* ohci_wrapp */ +#include "ohci_wrapp_RZ_A1_local.h" +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_brdy_int +* Description : Executes BRDY interrupt(USB_HOST_PIPE1-9). +* : According to the pipe that interrupt is generated in, +* : reads/writes buffer allocated in the pipe. +* : This function is executed in the BRDY interrupt handler. +* : This function clears BRDY interrupt status and BEMP interrupt +* : status. +* Arguments : uint16_t status ; BRDYSTS Register Value +* : uint16_t int_enb ; BRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_brdy_int (uint16_t status, uint16_t int_enb) +{ + uint32_t int_sense = 0; + uint16_t pipe; + uint16_t pipebit; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + pipebit = g_usb0_host_bit_set[pipe]; + + if ((status & pipebit) && (int_enb & pipebit)) + { + USB200.BRDYSTS = (uint16_t)~pipebit; + USB200.BEMPSTS = (uint16_t)~pipebit; + + if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_DMA) + { + if (g_usb0_host_DmaStatus[USB_HOST_D0FIFO] != USB_HOST_DMA_READY) + { + usb0_host_dma_interrupt_d0fifo(int_sense); + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + usb0_host_read_dma(pipe); + usb0_host_disable_brdy_int(pipe); + } + else + { + USB200.D0FIFOCTR = USB_HOST_BITBCLR; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + } + else if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_DMA) + { + if (g_usb0_host_DmaStatus[USB_HOST_D1FIFO] != USB_HOST_DMA_READY) + { + usb0_host_dma_interrupt_d1fifo(int_sense); + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + usb0_host_read_dma(pipe); + usb0_host_disable_brdy_int(pipe); + } + else + { + USB200.D1FIFOCTR = USB_HOST_BITBCLR; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + } + else + { + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 0) + { + usb0_host_read_buffer(pipe); + } + else + { + usb0_host_write_buffer(pipe); + } + } +#if(1) /* ohci_wrapp */ + switch (g_usb0_host_pipe_status[pipe]) + { + case USB_HOST_PIPE_DONE: + ohciwrapp_loc_TransEnd(pipe, TD_CC_NOERROR); + break; + case USB_HOST_PIPE_NORES: + case USB_HOST_PIPE_STALL: + case USB_HOST_PIPE_ERROR: + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); + break; + default: + /* Do Nothing */ + break; + } +#endif + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_nrdy_int +* Description : Executes NRDY interrupt(USB_HOST_PIPE1-9). +* : Checks NRDY interrupt cause by PID. When the cause if STALL, +* : regards the pipe state as STALL and ends the processing. +* : Then the cause is not STALL, increments the error count to +* : communicate again. When the error count is 3, determines +* : the pipe state as USB_HOST_PIPE_NORES and ends the processing. +* : This function is executed in the NRDY interrupt handler. +* : This function clears NRDY interrupt status. +* Arguments : uint16_t status ; NRDYSTS Register Value +* : uint16_t int_enb ; NRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_nrdy_int (uint16_t status, uint16_t int_enb) +{ + uint16_t pid; + uint16_t pipe; + uint16_t bitcheck; + + bitcheck = (uint16_t)(status & int_enb); + + USB200.NRDYSTS = (uint16_t)~status; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + if ((bitcheck&g_usb0_host_bit_set[pipe]) == g_usb0_host_bit_set[pipe]) + { + if (RZA_IO_RegRead_16(&USB200.SYSCFG0, + USB_SYSCFG_DCFM_SHIFT, + USB_SYSCFG_DCFM) == 1) + { + if (g_usb0_host_pipe_status[pipe] == USB_HOST_PIPE_WAIT) + { + pid = usb0_host_get_pid(pipe); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_STALL; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); +#endif + } + else + { +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_NORES; + ohciwrapp_loc_TransEnd(pipe, TD_CC_DEVICENOTRESPONDING); +#else + g_usb0_host_PipeIgnore[pipe]++; + + if (g_usb0_host_PipeIgnore[pipe] == 3) + { + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_NORES; + } + else + { + usb0_host_set_pid_buf(pipe); + } +#endif + } + } + } + else + { + /* USB Function */ + } + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_bemp_int +* Description : Executes BEMP interrupt(USB_HOST_PIPE1-9). +* Arguments : uint16_t status ; BEMPSTS Register Value +* : uint16_t int_enb ; BEMPENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_bemp_int (uint16_t status, uint16_t int_enb) +{ + uint16_t pid; + uint16_t pipe; + uint16_t bitcheck; + uint16_t inbuf; + + bitcheck = (uint16_t)(status & int_enb); + + USB200.BEMPSTS = (uint16_t)~status; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + if ((bitcheck&g_usb0_host_bit_set[pipe]) == g_usb0_host_bit_set[pipe]) + { + pid = usb0_host_get_pid(pipe); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_STALL; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); +#endif + } + else + { + inbuf = usb0_host_get_inbuf(pipe); + + if (inbuf == 0) + { + usb0_host_disable_bemp_int(pipe); + usb0_host_set_pid_nak(pipe); + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_NOERROR); +#endif + } + } + } + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/common/usb0_host_lib.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,1580 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_lib.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#if(1) /* ohci_wrapp */ +#include "MBRZA1H.h" /* INTC Driver Header */ +#else +#include "devdrv_intc.h" /* INTC Driver Header */ +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_enable_brdy_int +* Description : Enables BRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : BRDY. Enables BRDY interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_enable_brdy_int (uint16_t pipe) +{ + /* enable brdy interrupt */ + USB200.BRDYENB |= (uint16_t)g_usb0_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb0_host_disable_brdy_int +* Description : Disables BRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : BRDY. Enables BRDY interrupt in the pipe specified by the argument +* : in the disabled status. After disabling BRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_disable_brdy_int (uint16_t pipe) +{ + /* disable brdy interrupt */ + USB200.BRDYENB &= (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_clear_brdy_sts +* Description : Clear BRDY interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_clear_brdy_sts (uint16_t pipe) +{ + /* clear brdy status */ + USB200.BRDYSTS = (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_enable_bemp_int +* Description : Enables BEMP interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : BEMP. Enables BEMP interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BEMP, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_enable_bemp_int (uint16_t pipe) +{ + /* enable bemp interrupt */ + USB200.BEMPENB |= (uint16_t)g_usb0_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb0_host_disable_bemp_int +* Description : Disables BEMP interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : BEMP. Enables BEMP interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BEMP, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_disable_bemp_int (uint16_t pipe) +{ + /* disable bemp interrupt */ + USB200.BEMPENB &= (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_clear_bemp_sts +* Description : Clear BEMP interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_clear_bemp_sts (uint16_t pipe) +{ + /* clear bemp status */ + USB200.BEMPSTS = (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_enable_nrdy_int +* Description : Enables NRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : NRDY. Enables NRDY interrupt in the pipe specified by the argument +* : in the disabled status. After enabling NRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_enable_nrdy_int (uint16_t pipe) +{ + /* enable nrdy interrupt */ + USB200.NRDYENB |= (uint16_t)g_usb0_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb0_host_disable_nrdy_int +* Description : Disables NRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : NRDY. Disables NRDY interrupt in the pipe specified by the argument +* : in the disabled status. After disabling NRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_disable_nrdy_int (uint16_t pipe) +{ + /* disable nrdy interrupt */ + USB200.NRDYENB &= (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_clear_nrdy_sts +* Description : Clear NRDY interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_clear_nrdy_sts (uint16_t pipe) +{ + /* clear nrdy status */ + USB200.NRDYSTS = (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_is_hispeed +* Description : Returns the result of USB reset hand shake (RHST) as +* : return value. +* Arguments : none +* Return Value : USB_HOST_HIGH_SPEED ; Hi-Speed +* : USB_HOST_FULL_SPEED ; Full-Speed +* : USB_HOST_LOW_SPEED ; Low-Speed +* : USB_HOST_NON_SPEED ; error +*******************************************************************************/ +uint16_t usb0_host_is_hispeed (void) +{ + uint16_t rhst; + uint16_t speed; + + rhst = RZA_IO_RegRead_16(&USB200.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (rhst == USB_HOST_HSMODE) + { + speed = USB_HOST_HIGH_SPEED; + } + else if (rhst == USB_HOST_FSMODE) + { + speed = USB_HOST_FULL_SPEED; + } + else if (rhst == USB_HOST_LSMODE) + { + speed = USB_HOST_LOW_SPEED; + } + else + { + speed = USB_HOST_NON_SPEED; + } + + return speed; +} + +/******************************************************************************* +* Function Name: usb0_host_is_hispeed_enable +* Description : Returns the USB High-Speed connection enabled status as +* : return value. +* Arguments : none +* Return Value : USB_HOST_YES : Hi-Speed Enable +* : USB_HOST_NO : Hi-Speed Disable +*******************************************************************************/ +uint16_t usb0_host_is_hispeed_enable (void) +{ + uint16_t ret; + + ret = USB_HOST_NO; + + if (RZA_IO_RegRead_16(&USB200.SYSCFG0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE) == 1) + { + ret = USB_HOST_YES; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_host_set_pid_buf +* Description : Enables communicaqtion in the pipe specified by the argument +* : (BUF). +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_pid_buf (uint16_t pipe) +{ + uint16_t pid; + + pid = usb0_host_get_pid(pipe); + + if (pid == USB_HOST_PID_STALL2) + { + usb0_host_set_pid_nak(pipe); + } + + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + USB_HOST_PID_BUF, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_set_pid_nak +* Description : Disables communication (NAK) in the pipe specified by the argument. +* : When the pipe status was enabling communication (BUF) before +* : executing before executing this function, waits in the software +* : until the pipe becomes ready after setting disabled. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_pid_nak (uint16_t pipe) +{ + uint16_t pid; + uint16_t pbusy; + uint32_t loop; + + pid = usb0_host_get_pid(pipe); + + if (pid == USB_HOST_PID_STALL2) + { + usb0_host_set_pid_stall(pipe); + } + + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + USB_HOST_PID_NAK, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + + if (pid == USB_HOST_PID_BUF) + { + for (loop = 0; loop < 200; loop++) + { + switch (pipe) + { + case USB_HOST_PIPE0: + pbusy = RZA_IO_RegRead_16(&USB200.DCPCTR, + USB_DCPCTR_PBUSY_SHIFT, + USB_DCPCTR_PBUSY); + break; + + case USB_HOST_PIPE1: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE1CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE2: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE2CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE3: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE3CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE4: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE4CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE5: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE5CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE6: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE6CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE7: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE7CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE8: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE8CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE9: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE9CTR, + USB_PIPEnCTR_9_PBUSY_SHIFT, + USB_PIPEnCTR_9_PBUSY); + break; + + default: + pbusy = 1; + break; + } + + if (pbusy == 0) + { + break; + } + + Userdef_USB_usb0_host_delay_500ns(); + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_set_pid_stall +* Description : Disables communication (STALL) in the pipe specified by the +* : argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_pid_stall (uint16_t pipe) +{ + uint16_t pid; + + pid = usb0_host_get_pid(pipe); + + if (pid == USB_HOST_PID_BUF) + { + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + USB_HOST_PID_STALL2, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + } + else + { + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + USB_HOST_PID_STALL, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_clear_pid_stall +* Description : Disables communication (NAK) in the pipe specified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_clear_pid_stall (uint16_t pipe) +{ + usb0_host_set_pid_nak(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_get_pid +* Description : Returns the pipe state specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : PID +*******************************************************************************/ +uint16_t usb0_host_get_pid (uint16_t pipe) +{ + uint16_t pid; + + switch (pipe) + { + case USB_HOST_PIPE0: + pid = RZA_IO_RegRead_16(&USB200.DCPCTR, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + pid = RZA_IO_RegRead_16(&USB200.PIPE1CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + pid = RZA_IO_RegRead_16(&USB200.PIPE2CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + pid = RZA_IO_RegRead_16(&USB200.PIPE3CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + pid = RZA_IO_RegRead_16(&USB200.PIPE4CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + pid = RZA_IO_RegRead_16(&USB200.PIPE5CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + pid = RZA_IO_RegRead_16(&USB200.PIPE6CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + pid = RZA_IO_RegRead_16(&USB200.PIPE7CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + pid = RZA_IO_RegRead_16(&USB200.PIPE8CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + pid = RZA_IO_RegRead_16(&USB200.PIPE9CTR, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + pid = 0; + break; + } + + return pid; +} + +/******************************************************************************* +* Function Name: usb0_host_set_csclr +* Description : CSPLIT status clear setting of sprit transaction in specified +* : pipe is performed. +* : When SQSET bit or SQCLR bit, and SQSET bit or SQCLR bit +* : in DCPCTR register are continuously changed (when the sequence +* : toggle bit of data PID is continuously changed over two or more pipes), +* : the access cycle with 120 ns and more than 5 cycle bus clock is necessary. +* : Do not set both SQCLR bit and SQSET bit to 1 at the same time. +* : In addition, both bits should be operated after PID is set to NAK. +* : However, when it is set to the isochronous transfer as the transfer type +* : (TYPE=11), writing in SQSET bit is disabled. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_csclr (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + 1, + USB_DCPCTR_CSCLR_SHIFT, + USB_DCPCTR_CSCLR); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + 1, + USB_PIPEnCTR_9_CSCLR_SHIFT, + USB_PIPEnCTR_9_CSCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_set_sqclr +* Description : Sets the sequence bit of the pipe specified by the argument to +* : DATA0. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_sqclr (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + 1, + USB_DCPCTR_SQCLR_SHIFT, + USB_DCPCTR_SQCLR); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + 1, + USB_PIPEnCTR_9_SQCLR_SHIFT, + USB_PIPEnCTR_9_SQCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_set_sqset +* Description : Sets the sequence bit of the pipe specified by the argument to +* : DATA1. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_sqset (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + 1, + USB_DCPCTR_SQSET_SHIFT, + USB_DCPCTR_SQSET); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + 1, + USB_PIPEnCTR_9_SQSET_SHIFT, + USB_PIPEnCTR_9_SQSET); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_get_sqmon +* Description : Toggle bit of specified pipe is obtained +* Arguments : uint16_t pipe ; Pipe number +* Return Value : sqmon +*******************************************************************************/ +uint16_t usb0_host_get_sqmon (uint16_t pipe) +{ + uint16_t sqmon; + + switch (pipe) + { + case USB_HOST_PIPE0: + sqmon = RZA_IO_RegRead_16(&USB200.DCPCTR, + USB_DCPCTR_SQMON_SHIFT, + USB_DCPCTR_SQMON); + break; + + case USB_HOST_PIPE1: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE1CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE2: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE2CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE3: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE3CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE4: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE4CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE5: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE5CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE6: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE6CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE7: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE7CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE8: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE8CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE9: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE9CTR, + USB_PIPEnCTR_9_SQMON_SHIFT, + USB_PIPEnCTR_9_SQMON); + break; + + default: + sqmon = 0; + break; + } + + return sqmon; +} + +/******************************************************************************* +* Function Name: usb0_host_aclrm +* Description : The buffer of specified pipe is initialized +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb0_host_aclrm (uint16_t pipe) +{ + usb0_host_set_aclrm(pipe); + usb0_host_clr_aclrm(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_set_aclrm +* Description : The auto buffer clear mode of specified pipe is enabled +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb0_host_set_aclrm (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + 1, + USB_PIPEnCTR_9_ACLRM_SHIFT, + USB_PIPEnCTR_9_ACLRM); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_clr_aclrm +* Description : The auto buffer clear mode of specified pipe is enabled +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb0_host_clr_aclrm (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + 0, + USB_PIPEnCTR_9_ACLRM_SHIFT, + USB_PIPEnCTR_9_ACLRM); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_get_inbuf +* Description : Returns INBUFM of the pipe specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : inbuf +*******************************************************************************/ +uint16_t usb0_host_get_inbuf (uint16_t pipe) +{ + uint16_t inbuf; + + switch (pipe) + { + case USB_HOST_PIPE0: + inbuf = 0; + break; + + case USB_HOST_PIPE1: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE1CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE2: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE2CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE3: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE3CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE4: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE4CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE5: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE5CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE6: + inbuf = 0; + break; + + case USB_HOST_PIPE7: + inbuf = 0; + break; + + case USB_HOST_PIPE8: + inbuf = 0; + break; + + case USB_HOST_PIPE9: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE9CTR, + USB_PIPEnCTR_9_INBUFM_SHIFT, + USB_PIPEnCTR_9_INBUFM); + break; + + default: + inbuf = 0; + break; + } + + return inbuf; +} + +/******************************************************************************* +* Function Name: usb0_host_setting_interrupt +* Description : Sets the USB module interrupt level. +* Arguments : uint8_t level ; interrupt level +* Return Value : none +*******************************************************************************/ +void usb0_host_setting_interrupt (uint8_t level) +{ +#if(1) /* ohci_wrapp */ + IRQn_Type d0fifo_dmaintid; + IRQn_Type d1fifo_dmaintid; + + InterruptHandlerRegister(USBI0_IRQn, usb0_host_interrupt); + GIC_SetPriority(USBI0_IRQn, level); + GIC_EnableIRQ(USBI0_IRQn); + + d0fifo_dmaintid = (IRQn_Type)Userdef_USB_usb0_host_d0fifo_dmaintid(); + + if (d0fifo_dmaintid != 0xFFFF) + { + InterruptHandlerRegister(d0fifo_dmaintid, usb0_host_dma_interrupt_d0fifo); + GIC_SetPriority(d0fifo_dmaintid, level); + GIC_EnableIRQ(d0fifo_dmaintid); + } + + d1fifo_dmaintid = (IRQn_Type)Userdef_USB_usb0_host_d1fifo_dmaintid(); + + if (d1fifo_dmaintid != 0xFFFF) + { + InterruptHandlerRegister(d1fifo_dmaintid, usb0_host_dma_interrupt_d1fifo); + GIC_SetPriority(d1fifo_dmaintid, level); + GIC_EnableIRQ(d1fifo_dmaintid); + } +#else + uint16_t d0fifo_dmaintid; + uint16_t d1fifo_dmaintid; + + R_INTC_RegistIntFunc(INTC_ID_USBI0, usb0_host_interrupt); + R_INTC_SetPriority(INTC_ID_USBI0, level); + R_INTC_Enable(INTC_ID_USBI0); + + d0fifo_dmaintid = Userdef_USB_usb0_host_d0fifo_dmaintid(); + + if (d0fifo_dmaintid != 0xFFFF) + { + R_INTC_RegistIntFunc(d0fifo_dmaintid, usb0_host_dma_interrupt_d0fifo); + R_INTC_SetPriority(d0fifo_dmaintid, level); + R_INTC_Enable(d0fifo_dmaintid); + } + + d1fifo_dmaintid = Userdef_USB_usb0_host_d1fifo_dmaintid(); + + if (d1fifo_dmaintid != 0xFFFF) + { + R_INTC_RegistIntFunc(d1fifo_dmaintid, usb0_host_dma_interrupt_d1fifo); + R_INTC_SetPriority(d1fifo_dmaintid, level); + R_INTC_Enable(d1fifo_dmaintid); + } +#endif +} + +/******************************************************************************* +* Function Name: usb0_host_reset_module +* Description : Initializes the USB module. +* : Enables providing clock to the USB module. +* : Sets USB bus wait register. +* Arguments : uint16_t clockmode ; 48MHz ; USBHCLOCK_X1_48MHZ +* : ; 12MHz ; USBHCLOCK_EXTAL_12MHZ +* Return Value : none +*******************************************************************************/ +void usb0_host_reset_module (uint16_t clockmode) +{ + if (RZA_IO_RegRead_16(&USB200.SYSCFG0, + USB_SYSCFG_UPLLE_SHIFT, + USB_SYSCFG_UPLLE) == 1) + { + if ((USB200.SYSCFG0 & USB_HOST_BITUCKSEL) != clockmode) + { + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + USB200.SYSCFG0 = 0; + USB200.SYSCFG0 = (USB_HOST_BITUPLLE | clockmode); + Userdef_USB_usb0_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + else + { + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + Userdef_USB_usb0_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + } + else + { + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + USB200.SYSCFG0 = 0; + USB200.SYSCFG0 = (USB_HOST_BITUPLLE | clockmode); + Userdef_USB_usb0_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + + USB200.BUSWAIT = (uint16_t)(USB_HOST_BUSWAIT_05 & USB_HOST_BITBWAIT); +} + +/******************************************************************************* +* Function Name: usb0_host_get_buf_size +* Description : Obtains pipe buffer size specified by the argument and +* : maximum packet size of the USB device in use. +* : When USB_HOST_PIPE0 is specified by the argument, obtains the maximum +* : packet size of the USB device using the corresponding pipe. +* : For the case that USB_HOST_PIPE0 is not assigned by the argument, when the +* : corresponding pipe is in continuous transfer mode, +* : obtains the buffer size allocated in the corresponcing pipe, +* : when incontinuous transfer, obtains maximum packet size. +* Arguments : uint16_t ; pipe Number +* Return Value : Maximum packet size or buffer size +*******************************************************************************/ +uint16_t usb0_host_get_buf_size (uint16_t pipe) +{ + uint16_t size; + uint16_t bufsize; + + if (pipe == USB_HOST_PIPE0) + { + size = RZA_IO_RegRead_16(&USB200.DCPMAXP, + USB_DCPMAXP_MXPS_SHIFT, + USB_DCPMAXP_MXPS); + } + else + { + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_CNTMD_SHIFT, USB_PIPECFG_CNTMD) == 1) + { + bufsize = RZA_IO_RegRead_16(&g_usb0_host_pipebuf[pipe], USB_PIPEBUF_BUFSIZE_SHIFT, USB_PIPEBUF_BUFSIZE); + size = (uint16_t)((bufsize + 1) * USB_HOST_PIPExBUF); + } + else + { + size = RZA_IO_RegRead_16(&g_usb0_host_pipemaxp[pipe], USB_PIPEMAXP_MXPS_SHIFT, USB_PIPEMAXP_MXPS); + } + } + return size; +} + +/******************************************************************************* +* Function Name: usb0_host_get_mxps +* Description : Obtains maximum packet size of the USB device using the pipe +* : specified by the argument. +* Arguments : uint16_t ; Pipe Number +* Return Value : Max Packet Size +*******************************************************************************/ +uint16_t usb0_host_get_mxps (uint16_t pipe) +{ + uint16_t size; + + if (pipe == USB_HOST_PIPE0) + { + size = RZA_IO_RegRead_16(&USB200.DCPMAXP, + USB_DCPMAXP_MXPS_SHIFT, + USB_DCPMAXP_MXPS); + } + else + { + size = RZA_IO_RegRead_16(&g_usb0_host_pipemaxp[pipe], USB_PIPEMAXP_MXPS_SHIFT, USB_PIPEMAXP_MXPS); + } + + return size; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/host/usb0_host_controlrw.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,434 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_controlrw.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_CtrlTransStart +* Description : Executes USB control transfer. +* Arguments : uint16_t devadr ; device address +* : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* : uint8_t *Buf ; Data buffer +* Return Value : DEVDRV_SUCCESS ; SUCCESS +* : DEVDRV_ERROR ; ERROR +*******************************************************************************/ +int32_t usb0_host_CtrlTransStart (uint16_t devadr, uint16_t Req, uint16_t Val, + uint16_t Indx, uint16_t Len, uint8_t * Buf) +{ + if (g_usb0_host_UsbDeviceSpeed == USB_HOST_LOW_SPEED) + { + RZA_IO_RegWrite_16(&USB200.SOFCFG, + 1, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + else + { + RZA_IO_RegWrite_16(&USB200.SOFCFG, + 0, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + + USB200.DCPMAXP = (uint16_t)((uint16_t)(devadr << 12) + g_usb0_host_default_max_packet[devadr]); + + if (g_usb0_host_pipe_status[USB_HOST_PIPE0] == USB_HOST_PIPE_IDLE) + { + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_WAIT; + g_usb0_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + g_usb0_host_CmdStage = (USB_HOST_STAGE_SETUP | USB_HOST_CMD_IDLE); + + if (Len == 0) + { + g_usb0_host_CmdStage |= USB_HOST_MODE_NO_DATA; /* No-data Control */ + } + else + { + if ((Req & 0x0080) != 0) + { + g_usb0_host_CmdStage |= USB_HOST_MODE_READ; /* Control Read */ + } + else + { + g_usb0_host_CmdStage |= USB_HOST_MODE_WRITE; /* Control Write */ + } + } + + g_usb0_host_SavReq = Req; /* save request */ + g_usb0_host_SavVal = Val; + g_usb0_host_SavIndx = Indx; + g_usb0_host_SavLen = Len; + } + else + { + if ((g_usb0_host_SavReq != Req) || (g_usb0_host_SavVal != Val) + || (g_usb0_host_SavIndx != Indx) || (g_usb0_host_SavLen != Len)) + { + return DEVDRV_ERROR; + } + } + + switch ((g_usb0_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + /* --------------- SETUP STAGE --------------- */ + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_IDLE): + usb0_host_SetupStage(Req, Val, Indx, Len); + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_DONE): /* goto next stage */ + g_usb0_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + switch ((g_usb0_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_WRITE: + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_DATA; + break; + + case USB_HOST_MODE_READ: + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_DATA; + break; + + case USB_HOST_MODE_NO_DATA: + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_STATUS; + break; + + default: + break; + } + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_NORES): + if (g_usb0_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb0_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_IDLE; + } + break; + + /* --------------- DATA STAGE --------------- */ + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_IDLE): + switch ((g_usb0_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_WRITE: + usb0_host_CtrlWriteStart((uint32_t)Len, Buf); + break; + + case USB_HOST_MODE_READ: + usb0_host_CtrlReadStart((uint32_t)Len, Buf); + break; + + default: + break; + } + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DONE): /* goto next stage */ + g_usb0_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_STATUS; + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_NORES): + if (g_usb0_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb0_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DOING; + usb0_host_clear_pid_stall(USB_HOST_PIPE0); + usb0_host_set_pid_buf(USB_HOST_PIPE0); + } + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_STALL): + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + break; + + /* --------------- STATUS STAGE --------------- */ + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_IDLE): + usb0_host_StatusStage(); + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DONE): /* end of Control transfer */ + usb0_host_set_pid_nak(USB_HOST_PIPE0); + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_DONE; /* exit DONE */ + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_NORES): + if (g_usb0_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb0_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DOING; + usb0_host_clear_pid_stall(USB_HOST_PIPE0); + usb0_host_set_pid_buf(USB_HOST_PIPE0); + } + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_STALL): + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + break; + + default: + break; + } + + if (g_usb0_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_WAIT) + { + RZA_IO_RegWrite_16(&USB200.SOFCFG, + 0, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb0_host_SetupStage +* Description : Executes USB control transfer/set up stage. +* Arguments : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* Return Value : none +*******************************************************************************/ +void usb0_host_SetupStage (uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len) +{ + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DOING; + + USB200.INTSTS1 = (uint16_t)~(USB_HOST_BITSACK | USB_HOST_BITSIGN); /* Status Clear */ + USB200.USBREQ = Req; + USB200.USBVAL = Val; + USB200.USBINDX = Indx; + USB200.USBLENG = Len; + USB200.DCPCTR = USB_HOST_BITSUREQ; /* PID=NAK & Send Setup */ +} + +/******************************************************************************* +* Function Name: usb0_host_StatusStage +* Description : Executes USB control transfer/status stage. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_StatusStage (void) +{ + uint8_t Buf1[16]; + + switch ((g_usb0_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_READ: + usb0_host_CtrlWriteStart((uint32_t)0, (uint8_t *)&Buf1); + break; + + case USB_HOST_MODE_WRITE: + usb0_host_CtrlReadStart((uint32_t)0, (uint8_t *)&Buf1); + break; + + case USB_HOST_MODE_NO_DATA: + usb0_host_CtrlReadStart((uint32_t)0, (uint8_t *)&Buf1); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_CtrlWriteStart +* Description : Executes USB control transfer/data stage(write). +* Arguments : uint32_t Bsize ; Data Size +* : uint8_t *Table ; Data Table Address +* Return Value : USB_HOST_WRITESHRT ; End of data write +* : USB_HOST_WRITEEND ; End of data write (not null) +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_FIFOERROR ; FIFO access error +*******************************************************************************/ +uint16_t usb0_host_CtrlWriteStart (uint32_t Bsize, uint8_t * Table) +{ + uint16_t EndFlag_K; + uint16_t mbw; + + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DOING; + + usb0_host_set_pid_nak(USB_HOST_PIPE0); /* Set NAK */ + g_usb0_host_data_count[USB_HOST_PIPE0] = Bsize; /* Transfer size set */ + g_usb0_host_data_pointer[USB_HOST_PIPE0] = Table; /* Transfer address set */ + + USB200.DCPCTR = USB_HOST_BITSQSET; /* SQSET=1, PID=NAK */ +#if(1) /* ohci_wrapp */ + Userdef_USB_usb0_host_delay_10us(3); +#endif + RZA_IO_RegWrite_16(&USB200.DCPCFG, + 1, + USB_DCPCFG_DIR_SHIFT, + USB_DCPCFG_DIR); + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[USB_HOST_PIPE0], (uint32_t)g_usb0_host_data_pointer[USB_HOST_PIPE0]); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_BITISEL, mbw); + USB200.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + + usb0_host_clear_pid_stall(USB_HOST_PIPE0); + EndFlag_K = usb0_host_write_buffer_c(USB_HOST_PIPE0); + /* Host Control sequence */ + switch (EndFlag_K) + { + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_STATUS; + usb0_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb0_host_enable_bemp_int(USB_HOST_PIPE0); /* Enable Empty Interrupt */ + break; + + case USB_HOST_WRITEEND: /* End of data write (not null) */ + case USB_HOST_WRITING: /* Continue of data write */ + usb0_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb0_host_enable_bemp_int(USB_HOST_PIPE0); /* Enable Empty Interrupt */ + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + break; + + default: + break; + } + usb0_host_set_pid_buf(USB_HOST_PIPE0); /* Set BUF */ + return (EndFlag_K); /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_CtrlReadStart +* Description : Executes USB control transfer/data stage(read). +* Arguments : uint32_t Bsize ; Data Size +* : uint8_t *Table ; Data Table Address +* Return Value : none +*******************************************************************************/ +void usb0_host_CtrlReadStart (uint32_t Bsize, uint8_t * Table) +{ + uint16_t mbw; + + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DOING; + + usb0_host_set_pid_nak(USB_HOST_PIPE0); /* Set NAK */ + g_usb0_host_data_count[USB_HOST_PIPE0] = Bsize; /* Transfer size set */ + g_usb0_host_data_pointer[USB_HOST_PIPE0] = Table; /* Transfer address set */ + + USB200.DCPCTR = USB_HOST_BITSQSET; /* SQSET=1, PID=NAK */ +#if(1) /* ohci_wrapp */ + Userdef_USB_usb0_host_delay_10us(3); +#endif + RZA_IO_RegWrite_16(&USB200.DCPCFG, + 0, + USB_DCPCFG_DIR_SHIFT, + USB_DCPCFG_DIR); + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[USB_HOST_PIPE0], (uint32_t)g_usb0_host_data_pointer[USB_HOST_PIPE0]); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_NO, mbw); + USB200.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + + usb0_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb0_host_enable_brdy_int(USB_HOST_PIPE0); /* Ok */ + usb0_host_clear_pid_stall(USB_HOST_PIPE0); + usb0_host_set_pid_buf(USB_HOST_PIPE0); /* Set BUF */ +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/host/usb0_host_drv_api.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,889 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_drv_api.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb0_host_resetEP(USB_HOST_CFG_PIPETBL_t *tbl); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_api_host_init +* Description : Initializes USB module in the USB host mode. +* : USB connection is executed when executing this function in +* : the states that USB device isconnected to the USB port. +* Arguments : uint8_t int_level : USB Module interrupt level +* : USBU16 mode : USB_HOST_HIGH_SPEED +* : USB_HOST_FULL_SPEED +* : uint16_t clockmode : USB Clock mode +* Return Value : USB detach or attach +* : USB_HOST_ATTACH +* : USB_HOST_DETACH +*******************************************************************************/ +uint16_t usb0_api_host_init (uint8_t int_level, uint16_t mode, uint16_t clockmode) +{ + uint16_t connect; + volatile uint8_t dummy_buf; + + CPG.STBCR7 &= 0xfd; /*The clock of USB0 modules is permitted */ + dummy_buf = CPG.STBCR7; /* (Dummy read) */ + + g_usb0_host_SupportUsbDeviceSpeed = mode; + + usb0_host_setting_interrupt(int_level); + usb0_host_reset_module(clockmode); + + g_usb0_host_bchg_flag = USB_HOST_NO; + g_usb0_host_detach_flag = USB_HOST_NO; + g_usb0_host_attach_flag = USB_HOST_NO; + + g_usb0_host_driver_state = USB_HOST_DRV_DETACHED; + g_usb0_host_default_max_packet[USB_HOST_DEVICE_0] = 64; + + usb0_host_InitModule(); + + connect = usb0_host_CheckAttach(); + + if (connect == USB_HOST_ATTACH) + { + g_usb0_host_attach_flag = USB_HOST_YES; + } + else + { + usb0_host_UsbDetach2(); + } + + return connect; +} + +#if(1) /* ohci_wrapp */ +#else +/******************************************************************************* +* Function Name: usb0_api_host_enumeration +* Description : Initializes USB module in the USB host mode. +* : USB connection is executed when executing this function in +* : the states that USB device isconnected to the USB port. +* Arguments : uint16_t devadr : device address +* Return Value : DEVDRV_USBH_DETACH_ERR : device detach +* : DEVDRV_SUCCESS : device enumeration success +* : DEVDRV_ERROR : device enumeration error +*******************************************************************************/ +int32_t usb0_api_host_enumeration (uint16_t devadr) +{ + int32_t ret; + uint16_t driver_sts; + + g_usb0_host_setUsbAddress = devadr; + + while (1) + { + driver_sts = usb0_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + ret = DEVDRV_USBH_DETACH_ERR; + break; + } + else if (driver_sts == USB_HOST_DRV_CONFIGURED) + { + ret = DEVDRV_SUCCESS; + break; + } + else if (driver_sts == USB_HOST_DRV_STALL) + { + ret = DEVDRV_ERROR; + break; + } + else if (driver_sts == USB_HOST_DRV_NORES) + { + ret = DEVDRV_ERROR; + break; + } + else + { + /* Do Nothing */ + } + } + + if (driver_sts == USB_HOST_DRV_NORES) + { + while (1) + { + driver_sts = usb0_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + break; + } + } + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_api_host_detach +* Description : USB detach routine +* Arguments : none +* Return Value : USB_HOST_DETACH : USB detach +* : USB_HOST_ATTACH : USB attach +* : DEVDRV_ERROR : error +*******************************************************************************/ +int32_t usb0_api_host_detach (void) +{ + int32_t ret; + uint16_t driver_sts; + + while (1) + { + driver_sts = usb0_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + ret = USB_HOST_DETACH; + break; + } + else if (driver_sts == USB_HOST_DRV_CONFIGURED) + { + ret = USB_HOST_ATTACH; + break; + } + else if (driver_sts == USB_HOST_DRV_STALL) + { + ret = DEVDRV_ERROR; + break; + } + else if (driver_sts == USB_HOST_DRV_NORES) + { + ret = DEVDRV_ERROR; + break; + } + else + { + /* Do Nothing */ + } + } + + if (driver_sts == USB_HOST_DRV_NORES) + { + while (1) + { + driver_sts = usb0_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + break; + } + } + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_api_host_data_in +* Description : Executes USB transfer as data-in in the argument specified pipe. +* Arguments : uint16_t devadr ; device address +* : uint16_t Pipe ; Pipe Number +* : uint32_t Size ; Data Size +* : uint8_t *data_buf ; Data data_buf Address +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_data_in (uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t * data_buf) +{ + int32_t ret; + + if (Pipe == USB_HOST_PIPE0) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipemaxp[Pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL) != devadr) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[Pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 1) + { + return DEVDRV_ERROR; + } + + if (g_usb0_host_pipe_status[Pipe] == USB_HOST_PIPE_IDLE) + { + usb0_host_start_receive_transfer(Pipe, Size, data_buf); + } + else + { + return DEVDRV_ERROR; /* Now pipe is busy */ + } + + /* waiting for completing routine */ + do + { + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb0_host_pipe_status[Pipe] != USB_HOST_PIPE_IDLE) && (g_usb0_host_pipe_status[Pipe] != USB_HOST_PIPE_WAIT)) + { + break; + } + + } while (1); + + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb0_host_pipe_status[Pipe]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + usb0_host_stop_transfer(Pipe); + + g_usb0_host_pipe_status[Pipe] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_api_host_data_out +* Description : Executes USB transfer as data-out in the argument specified pipe. +* Arguments : uint16_t devadr ; device address +* : uint16_t Pipe ; Pipe Number +* : uint32_t Size ; Data Size +* : uint8_t *data_buf ; Data data_buf Address +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_data_out (uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t * data_buf) +{ + int32_t ret; + + if (Pipe == USB_HOST_PIPE0) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipemaxp[Pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL) != devadr) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[Pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 0) + { + return DEVDRV_ERROR; + } + + if (g_usb0_host_pipe_status[Pipe] == USB_HOST_PIPE_IDLE) + { + usb0_host_start_send_transfer(Pipe, Size, data_buf); + } + else + { + return DEVDRV_ERROR; /* Now pipe is busy */ + } + + /* waiting for completing routine */ + do + { + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb0_host_pipe_status[Pipe] != USB_HOST_PIPE_IDLE) && (g_usb0_host_pipe_status[Pipe] != USB_HOST_PIPE_WAIT)) + { + break; + } + + } while (1); + + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb0_host_pipe_status[Pipe]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + usb0_host_stop_transfer(Pipe); + + g_usb0_host_pipe_status[Pipe] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_api_host_control_transfer +* Description : Executes USB control transfer. +* Arguments : uint16_t devadr ; device address +* : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* : uint8_t *buf ; Buffer +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_USBH_DETACH_ERR ; device detach +* : DEVDRV_USBH_CTRL_COM_ERR ; device no response +* : DEVDRV_USBH_STALL ; STALL +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_control_transfer (uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, + uint16_t Len, uint8_t * Buf) +{ + int32_t ret; + + do + { + ret = usb0_host_CtrlTransStart(devadr, Req, Val, Indx, Len, Buf); + + if (ret == DEVDRV_SUCCESS) + { + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb0_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_IDLE) + && (g_usb0_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_WAIT)) + { + break; + } + } + else + { + return DEVDRV_ERROR; + } + } while (1); + + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb0_host_pipe_status[USB_HOST_PIPE0]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_CTRL_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_api_host_set_endpoint +* Description : Sets end point on the information specified in the argument. +* Arguments : uint16_t devadr ; device address +* : uint8_t *configdescriptor ; device configration descriptor +* : USB_HOST_CFG_PIPETBL_t *user_table ; pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_set_endpoint (uint16_t devadr, USB_HOST_CFG_PIPETBL_t * user_table, uint8_t * configdescriptor) +{ + uint16_t ret; + uint32_t end_point; + uint32_t offset; + uint32_t totalLength; + USB_HOST_CFG_PIPETBL_t * pipe_table; + + /* End Point Search */ + end_point = 0; + offset = configdescriptor[0]; + totalLength = (uint16_t)(configdescriptor[2] + ((uint16_t)configdescriptor[3] << 8)); + + do + { + if (configdescriptor[offset + 1] == USB_HOST_ENDPOINT_DESC) + { + pipe_table = &user_table[end_point]; + + if (pipe_table->pipe_number == 0xffff) + { + break; + } + + ret = usb0_api_host_SetEndpointTable(devadr, pipe_table, (uint8_t *)&configdescriptor[offset]); + + if ((ret != USB_HOST_PIPE_IN) && (ret != USB_HOST_PIPE_OUT)) + { + return DEVDRV_ERROR; + } + + ++end_point; + } + + /* Next End Point Search */ + offset += configdescriptor[offset]; + + } while (offset < totalLength); + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb0_api_host_clear_endpoint +* Description : Clears the pipe definition table specified in the argument. +* Arguments : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_clear_endpoint (USB_HOST_CFG_PIPETBL_t * user_table) +{ + uint16_t pipe; + + for (pipe = USB_HOST_PIPE0; pipe <= USB_HOST_MAX_PIPE_NO; ++pipe) + { + if (user_table->pipe_number == 0xffff) + { + break; + } + user_table->pipe_cfg &= (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD); + user_table->pipe_max_pktsize = 0; + user_table->pipe_cycle = 0; + + user_table++; + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb0_api_host_clear_endpoint_pipe +* Description : Clears the pipe definition table specified in the argument. +* Arguments : uint16_t pipe_sel : Pipe Number +* : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_clear_endpoint_pipe (uint16_t pipe_sel, USB_HOST_CFG_PIPETBL_t * user_table) +{ + uint16_t pipe; + + for (pipe = USB_HOST_PIPE0; pipe <= USB_HOST_MAX_PIPE_NO; ++pipe) + { + if (user_table->pipe_number == 0xffff) + { + break; + } + + if (user_table->pipe_number == pipe_sel) + { + user_table->pipe_cfg &= (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD); + user_table->pipe_max_pktsize = 0; + user_table->pipe_cycle = 0; + break; + } + + user_table++; + } + + return DEVDRV_SUCCESS; +} +#endif + +/******************************************************************************* +* Function Name: usb0_api_host_SetEndpointTable +* Description : Sets the end point on the information specified by the argument. +* Arguments : uint16_t devadr : device address +* : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* : uint8_t *Table : Endpoint descriptor +* Return Value : USB_HOST_DIR_H_IN ; IN endpoint +* : USB_HOST_DIR_H_OUT ; OUT endpoint +* : USB_END_POINT_ERROR ; error +*******************************************************************************/ +uint16_t usb0_api_host_SetEndpointTable (uint16_t devadr, USB_HOST_CFG_PIPETBL_t * user_table, uint8_t * Table) +{ + uint16_t PipeCfg; + uint16_t PipeMaxp; + uint16_t pipe_number; + uint16_t ret; + uint16_t ret_flag = 0; // avoid warning. + + pipe_number = user_table->pipe_number; + + if (Table[1] != USB_HOST_ENDPOINT_DESC) + { + return USB_END_POINT_ERROR; + } + + switch (Table[3] & USB_HOST_EP_TYPE) + { + case USB_HOST_EP_CNTRL: + ret_flag = USB_END_POINT_ERROR; + break; + + case USB_HOST_EP_ISO: + if ((pipe_number != USB_HOST_PIPE1) && (pipe_number != USB_HOST_PIPE2)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_ISO; + break; + + case USB_HOST_EP_BULK: + if ((pipe_number < USB_HOST_PIPE1) || (pipe_number > USB_HOST_PIPE5)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_BULK; + break; + + case USB_HOST_EP_INT: + if ((pipe_number < USB_HOST_PIPE6) || (pipe_number > USB_HOST_PIPE9)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_INTERRUPT; + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + + /* Set pipe configuration table */ + if ((Table[2] & USB_HOST_EP_DIR_MASK) == USB_HOST_EP_IN) /* IN(receive) */ + { + if (PipeCfg == USB_HOST_ISO) + { + /* Transfer Type is ISO*/ + PipeCfg |= USB_HOST_DIR_H_IN; + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + case USB_HOST_D0USE: + case USB_HOST_D1USE: + case USB_HOST_D0DMA: + case USB_HOST_D1DMA: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & USB_HOST_DBLBFIELD); + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + } + else + { + /* Transfer Type is BULK or INT */ + PipeCfg |= (USB_HOST_SHTNAKON | USB_HOST_DIR_H_IN); /* Compulsory SHTNAK */ + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + case USB_HOST_D0USE: + case USB_HOST_D1USE: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); + break; + + case USB_HOST_D0DMA: + case USB_HOST_D1DMA: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); +#ifdef __USB_DMA_BFRE_ENABLE__ + /* this routine cannnot be perfomred if read operation is executed in buffer size */ + PipeCfg |= USB_HOST_BFREON; +#endif + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + } + ret = USB_HOST_PIPE_IN; + } + else /* OUT(send) */ + { + if (PipeCfg == USB_HOST_ISO) + { + /* Transfer Type is ISO*/ + PipeCfg |= (uint16_t)(user_table->pipe_cfg & USB_HOST_DBLBFIELD); + } + else + { + /* Transfer Type is BULK or INT */ + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); + } + PipeCfg |= USB_HOST_DIR_H_OUT; + ret = USB_HOST_PIPE_OUT; + } + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + g_usb0_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_CFIFO_USE; + break; + + case USB_HOST_D0USE: + g_usb0_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D0FIFO_USE; + break; + + case USB_HOST_D1USE: + g_usb0_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D1FIFO_USE; + break; + + case USB_HOST_D0DMA: + g_usb0_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D0FIFO_DMA; + break; + + case USB_HOST_D1DMA: + g_usb0_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D1FIFO_DMA; + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + + /* Endpoint number set */ + PipeCfg |= (uint16_t)(Table[2] & USB_HOST_EP_NUM_MASK); + g_usb0_host_PipeTbl[pipe_number] |= (uint16_t)(Table[2] & USB_HOST_EP_NUM_MASK); + + /* Max packet size set */ + PipeMaxp = (uint16_t)((uint16_t)Table[4] | (uint16_t)((uint16_t)Table[5] << 8)); + + if (PipeMaxp == 0u) + { + return USB_END_POINT_ERROR; + } + + /* Set device address */ + PipeMaxp |= (uint16_t)(devadr << 12); + + user_table->pipe_cfg = PipeCfg; + user_table->pipe_max_pktsize = PipeMaxp; + + usb0_host_resetEP(user_table); + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_host_resetEP +* Description : Sets the end point on the information specified by the argument. +* Arguments : USB_HOST_CFG_PIPETBL_t *tbl : pipe table +* Return Value : none +*******************************************************************************/ +static void usb0_host_resetEP (USB_HOST_CFG_PIPETBL_t * tbl) +{ + + uint16_t pipe; + + /* Host pipe */ + /* The pipe number of pipe definition table is obtained */ + pipe = (uint16_t)(tbl->pipe_number & USB_HOST_BITCURPIPE); /* Pipe Number */ + + /* FIFO port access pipe is set to initial value */ + /* The connection with FIFO should be cut before setting the pipe */ + if (RZA_IO_RegRead_16(&USB200.CFIFOSEL, + USB_CFIFOSEL_CURPIPE_SHIFT, + USB_CFIFOSEL_CURPIPE) == pipe) + { + usb0_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + if (RZA_IO_RegRead_16(&USB200.D0FIFOSEL, + USB_DnFIFOSEL_CURPIPE_SHIFT, + USB_DnFIFOSEL_CURPIPE) == pipe) + { + usb0_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + if (RZA_IO_RegRead_16(&USB200.D1FIFOSEL, + USB_DnFIFOSEL_CURPIPE_SHIFT, + USB_DnFIFOSEL_CURPIPE) == pipe) + { + usb0_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + /* Interrupt of pipe set is disabled */ + usb0_host_disable_brdy_int(pipe); + usb0_host_disable_nrdy_int(pipe); + usb0_host_disable_bemp_int(pipe); + + /* Pipe to set is set to NAK */ + usb0_host_set_pid_nak(pipe); + + /* Pipe is set */ + USB200.PIPESEL = pipe; + + USB200.PIPECFG = tbl->pipe_cfg; + USB200.PIPEBUF = tbl->pipe_buf; + USB200.PIPEMAXP = tbl->pipe_max_pktsize; + USB200.PIPEPERI = tbl->pipe_cycle; + + g_usb0_host_pipecfg[pipe] = tbl->pipe_cfg; + g_usb0_host_pipebuf[pipe] = tbl->pipe_buf; + g_usb0_host_pipemaxp[pipe] = tbl->pipe_max_pktsize; + g_usb0_host_pipeperi[pipe] = tbl->pipe_cycle; + + /* Sequence bit clear */ + usb0_host_set_sqclr(pipe); + + usb0_host_aclrm(pipe); + usb0_host_set_csclr(pipe); + + /* Pipe window selection is set to unused */ + USB200.PIPESEL = USB_HOST_PIPE0; + +} + +#if(1) /* ohci_wrapp */ +#else +/******************************************************************************* +* Function Name: usb0_api_host_data_count +* Description : Get g_usb0_host_data_count[pipe] +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t *data_count ; return g_usb0_data_count[pipe] +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_data_count (uint16_t pipe, uint32_t * data_count) +{ + if (pipe > USB_HOST_MAX_PIPE_NO) + { + return DEVDRV_ERROR; + } + + *data_count = g_usb0_host_PipeDataSize[pipe]; + + return DEVDRV_SUCCESS; +} +#endif + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/host/usb0_host_global.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,137 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_global.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +const uint16_t g_usb0_host_bit_set[16] = +{ + 0x0001, 0x0002, 0x0004, 0x0008, + 0x0010, 0x0020, 0x0040, 0x0080, + 0x0100, 0x0200, 0x0400, 0x0800, + 0x1000, 0x2000, 0x4000, 0x8000 +}; + +uint32_t g_usb0_host_data_count[USB_HOST_MAX_PIPE_NO + 1]; +uint8_t * g_usb0_host_data_pointer[USB_HOST_MAX_PIPE_NO + 1]; + +uint16_t g_usb0_host_PipeIgnore[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb0_host_PipeTbl[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb0_host_pipe_status[USB_HOST_MAX_PIPE_NO + 1]; +uint32_t g_usb0_host_PipeDataSize[USB_HOST_MAX_PIPE_NO + 1]; + +USB_HOST_DMA_t g_usb0_host_DmaInfo[2]; + +uint16_t g_usb0_host_DmaPipe[2]; +uint16_t g_usb0_host_DmaBval[2]; +uint16_t g_usb0_host_DmaStatus[2]; + +uint16_t g_usb0_host_driver_state; +uint16_t g_usb0_host_ConfigNum; +uint16_t g_usb0_host_CmdStage; +uint16_t g_usb0_host_bchg_flag; +uint16_t g_usb0_host_detach_flag; +uint16_t g_usb0_host_attach_flag; + +uint16_t g_usb0_host_UsbAddress; +uint16_t g_usb0_host_setUsbAddress; +uint16_t g_usb0_host_default_max_packet[USB_HOST_MAX_DEVICE + 1]; +uint16_t g_usb0_host_UsbDeviceSpeed; +uint16_t g_usb0_host_SupportUsbDeviceSpeed; + +uint16_t g_usb0_host_SavReq; +uint16_t g_usb0_host_SavVal; +uint16_t g_usb0_host_SavIndx; +uint16_t g_usb0_host_SavLen; + +uint16_t g_usb0_host_pipecfg[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb0_host_pipebuf[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb0_host_pipemaxp[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb0_host_pipeperi[USB_HOST_MAX_PIPE_NO + 1]; + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_init_pipe_status +* Description : Initialize pipe status. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_init_pipe_status (void) +{ + uint16_t loop; + + g_usb0_host_ConfigNum = 0; + + for (loop = 0; loop < (USB_HOST_MAX_PIPE_NO + 1); ++loop) + { + g_usb0_host_pipe_status[loop] = USB_HOST_PIPE_IDLE; + g_usb0_host_PipeDataSize[loop] = 0; + + /* pipe configuration in usb0_host_resetEP() */ + g_usb0_host_pipecfg[loop] = 0; + g_usb0_host_pipebuf[loop] = 0; + g_usb0_host_pipemaxp[loop] = 0; + g_usb0_host_pipeperi[loop] = 0; + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/host/usb0_host_usbint.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,496 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_usbint.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#if(1) /* ohci_wrapp */ +#include "ohci_wrapp_RZ_A1_local.h" +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb0_host_interrupt1(void); +static void usb0_host_BRDYInterrupt(uint16_t Status, uint16_t Int_enbl); +static void usb0_host_NRDYInterrupt(uint16_t Status, uint16_t Int_enbl); +static void usb0_host_BEMPInterrupt(uint16_t Status, uint16_t Int_enbl); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_interrupt +* Description : Executes USB interrupt. +* : Register this function in the USB interrupt handler. +* : Set CFIF0 in the pipe set before the interrupt after executing +* : this function. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb0_host_interrupt (uint32_t int_sense) +{ + uint16_t savepipe1; + uint16_t savepipe2; + uint16_t buffer; + + savepipe1 = USB200.CFIFOSEL; + savepipe2 = USB200.PIPESEL; + usb0_host_interrupt1(); + + /* Control transmission changes ISEL within interruption processing. */ + /* For this reason, write return of ISEL cannot be performed. */ + buffer = USB200.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(savepipe1 & USB_HOST_BITCURPIPE); + USB200.CFIFOSEL = buffer; + USB200.PIPESEL = savepipe2; +} + +/******************************************************************************* +* Function Name: usb0_host_interrupt1 +* Description : Execue the USB interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_interrupt1 (void) +{ + uint16_t intsts0; + uint16_t intsts1; + uint16_t intenb0; + uint16_t intenb1; + uint16_t brdysts; + uint16_t nrdysts; + uint16_t bempsts; + uint16_t brdyenb; + uint16_t nrdyenb; + uint16_t bempenb; + volatile uint16_t dumy_sts; + + intsts0 = USB200.INTSTS0; + intsts1 = USB200.INTSTS1; + intenb0 = USB200.INTENB0; + intenb1 = USB200.INTENB1; + + if ((intsts1 & USB_HOST_BITBCHG) && (intenb1 & USB_HOST_BITBCHGE)) + { + USB200.INTSTS1 = (uint16_t)~USB_HOST_BITBCHG; + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); + g_usb0_host_bchg_flag = USB_HOST_YES; + } + else if ((intsts1 & USB_HOST_BITSACK) && (intenb1 & USB_HOST_BITSACKE)) + { + USB200.INTSTS1 = (uint16_t)~USB_HOST_BITSACK; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); +#else + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; +#endif + } + else if ((intsts1 & USB_HOST_BITSIGN) && (intenb1 & USB_HOST_BITSIGNE)) + { + USB200.INTSTS1 = (uint16_t)~USB_HOST_BITSIGN; +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#else + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_NORES; +#endif + } + else if (((intsts1 & USB_HOST_BITDTCH) == USB_HOST_BITDTCH) + && ((intenb1 & USB_HOST_BITDTCHE) == USB_HOST_BITDTCHE)) + { + USB200.INTSTS1 = (uint16_t)~USB_HOST_BITDTCH; + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); + g_usb0_host_detach_flag = USB_HOST_YES; + + Userdef_USB_usb0_host_detach(); + + usb0_host_UsbDetach2(); + } + else if (((intsts1 & USB_HOST_BITATTCH) == USB_HOST_BITATTCH) + && ((intenb1 & USB_HOST_BITATTCHE) == USB_HOST_BITATTCHE)) + { + USB200.INTSTS1 = (uint16_t)~USB_HOST_BITATTCH; + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); + g_usb0_host_attach_flag = USB_HOST_YES; + + Userdef_USB_usb0_host_attach(); + + usb0_host_UsbAttach(); + } + else if ((intsts0 & intenb0 & (USB_HOST_BITBEMP | USB_HOST_BITNRDY | USB_HOST_BITBRDY))) + { + brdysts = USB200.BRDYSTS; + nrdysts = USB200.NRDYSTS; + bempsts = USB200.BEMPSTS; + brdyenb = USB200.BRDYENB; + nrdyenb = USB200.NRDYENB; + bempenb = USB200.BEMPENB; + + if ((intsts0 & USB_HOST_BITBRDY) && (intenb0 & USB_HOST_BITBRDYE) && (brdysts & brdyenb)) + { + usb0_host_BRDYInterrupt(brdysts, brdyenb); + } + else if ((intsts0 & USB_HOST_BITBEMP) && (intenb0 & USB_HOST_BITBEMPE) && (bempsts & bempenb)) + { + usb0_host_BEMPInterrupt(bempsts, bempenb); + } + else if ((intsts0 & USB_HOST_BITNRDY) && (intenb0 & USB_HOST_BITNRDYE) && (nrdysts & nrdyenb)) + { + usb0_host_NRDYInterrupt(nrdysts, nrdyenb); + } + else + { + /* Do Nothing */ + } + } + else + { + /* Do Nothing */ + } + + /* Three dummy read for clearing interrupt requests */ + dumy_sts = USB200.INTSTS0; + dumy_sts = USB200.INTSTS1; + +} + +/******************************************************************************* +* Function Name: usb0_host_BRDYInterrupt +* Description : Executes USB BRDY interrupt. +* Arguments : uint16_t Status ; BRDYSTS Register Value +* : uint16_t Int_enbl ; BRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_BRDYInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t buffer; + volatile uint16_t dumy_sts; + + if ((Status & g_usb0_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb0_host_bit_set[USB_HOST_PIPE0])) + { + USB200.BRDYSTS = (uint16_t)~g_usb0_host_bit_set[USB_HOST_PIPE0]; + +#if(1) /* ohci_wrapp */ + switch ((g_usb0_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + buffer = usb0_host_read_buffer_c(USB_HOST_PIPE0); + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb0_host_read_buffer_c(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_READOVER: /* buffer over */ + USB200.CFIFOCTR = USB_HOST_BITBCLR; + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + break; + } +#else + switch ((g_usb0_host_CmdStage & (USB_HOST_MODE_FIELD | USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + case (USB_HOST_MODE_NO_DATA | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + buffer = usb0_host_read_buffer_c(USB_HOST_PIPE0); + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case (USB_HOST_MODE_READ | USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb0_host_read_buffer_c(USB_HOST_PIPE0); + + switch (buffer) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case USB_HOST_READOVER: /* buffer over */ + USB200.CFIFOCTR = USB_HOST_BITBCLR; + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + break; + } +#endif + } + else + { + usb0_host_brdy_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB200.BRDYSTS; +} + +/******************************************************************************* +* Function Name: usb0_host_NRDYInterrupt +* Description : Executes USB NRDY interrupt. +* Arguments : uint16_t Status ; NRDYSTS Register Value +* : uint16_t Int_enbl ; NRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_NRDYInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t pid; + volatile uint16_t dumy_sts; + + if ((Status & g_usb0_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb0_host_bit_set[USB_HOST_PIPE0])) + { + USB200.NRDYSTS = (uint16_t)~g_usb0_host_bit_set[USB_HOST_PIPE0]; + pid = usb0_host_get_pid(USB_HOST_PIPE0); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_STALL; +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + } + else if (pid == USB_HOST_PID_NAK) + { + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_NORES; +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + } + else + { + /* Do Nothing */ + } + } + else + { + usb0_host_nrdy_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB200.NRDYSTS; +} + +/******************************************************************************* +* Function Name: usb0_host_BEMPInterrupt +* Description : Executes USB BEMP interrupt. +* Arguments : uint16_t Status ; BEMPSTS Register Value +* : uint16_t Int_enbl ; BEMPENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_BEMPInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t buffer; + uint16_t pid; + volatile uint16_t dumy_sts; + + if ((Status & g_usb0_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb0_host_bit_set[USB_HOST_PIPE0])) + { + USB200.BEMPSTS = (uint16_t)~g_usb0_host_bit_set[USB_HOST_PIPE0]; + pid = usb0_host_get_pid(USB_HOST_PIPE0); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_STALL; +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + } + else + { +#if(1) /* ohci_wrapp */ + switch ((g_usb0_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb0_host_write_buffer(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_WRITING: /* Continue of data write */ + case USB_HOST_WRITEEND: /* End of data write (zero-length) */ + break; + + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_STATUS; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + /* do nothing */ + break; + } +#else + switch ((g_usb0_host_CmdStage & (USB_HOST_MODE_FIELD | USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_MODE_READ | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb0_host_write_buffer(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_WRITING: /* Continue of data write */ + case USB_HOST_WRITEEND: /* End of data write (zero-length) */ + break; + + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_STATUS; + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + default: + /* do nothing */ + break; + } +#endif + } + } + else + { + usb0_host_bemp_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB200.BEMPSTS; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/host/usb0_host_usbsig.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,637 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_usbsig.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb0_host_EnableINT_Module(void); +static void usb0_host_Enable_AttachINT(void); +static void usb0_host_Disable_AttachINT(void); +static void usb0_host_Disable_BchgINT(void); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_InitModule +* Description : Initializes the USB module in USB host module. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_InitModule (void) +{ + uint16_t buf1; + uint16_t buf2; + uint16_t buf3; + + usb0_host_init_pipe_status(); + + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 1, + USB_SYSCFG_DCFM_SHIFT, + USB_SYSCFG_DCFM); /* HOST mode */ + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 1, + USB_SYSCFG_DRPD_SHIFT, + USB_SYSCFG_DRPD); /* PORT0 D+, D- setting */ + + do + { + buf1 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb0_host_delay_xms(50); + buf2 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb0_host_delay_xms(50); + buf3 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + + } while ((buf1 != buf2) || (buf1 != buf3)); + + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 1, + USB_SYSCFG_USBE_SHIFT, + USB_SYSCFG_USBE); + + USB200.CFIFOSEL = (uint16_t)(USB_HOST_BITRCNT | USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); + USB200.D0FIFOSEL = (uint16_t)( USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); + USB200.D1FIFOSEL = (uint16_t)( USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); +} + +/******************************************************************************* +* Function Name: usb0_host_CheckAttach +* Description : Returns the USB device connection state. +* Arguments : none +* Return Value : uint16_t ; USB_HOST_ATTACH : Attached +* : ; USB_HOST_DETACH : not Attached +*******************************************************************************/ +uint16_t usb0_host_CheckAttach (void) +{ + uint16_t buf1; + uint16_t buf2; + uint16_t buf3; + uint16_t rhst; + + do + { + buf1 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb0_host_delay_xms(50); + buf2 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb0_host_delay_xms(50); + buf3 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + + } while ((buf1 != buf2) || (buf1 != buf3)); + + rhst = RZA_IO_RegRead_16(&USB200.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (rhst == USB_HOST_UNDECID) + { + if (buf1 == USB_HOST_FS_JSTS) + { + if (g_usb0_host_SupportUsbDeviceSpeed == USB_HOST_HIGH_SPEED) + { + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 1, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + } + else + { + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + } + return USB_HOST_ATTACH; + } + else if (buf1 == USB_HOST_LS_JSTS) + { + /* Low Speed Device */ + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + return USB_HOST_ATTACH; + } + else + { + /* Do Nothing */ + } + } + else if ((rhst == USB_HOST_HSMODE) || (rhst == USB_HOST_FSMODE)) + { + return USB_HOST_ATTACH; + } + else if (rhst == USB_HOST_LSMODE) + { + return USB_HOST_ATTACH; + } + else + { + /* Do Nothing */ + } + + return USB_HOST_DETACH; +} + +/******************************************************************************* +* Function Name: usb0_host_UsbAttach +* Description : Connects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_UsbAttach (void) +{ + usb0_host_EnableINT_Module(); + usb0_host_Disable_BchgINT(); + usb0_host_Disable_AttachINT(); + usb0_host_Enable_DetachINT(); +} + +/******************************************************************************* +* Function Name: usb0_host_UsbDetach +* Description : Disconnects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_UsbDetach (void) +{ + uint16_t pipe; + uint16_t devadr; + + g_usb0_host_driver_state = USB_HOST_DRV_DETACHED; + + /* Terminate all the pipes in which communications on port */ + /* are currently carried out */ + for (pipe = 0; pipe < (USB_HOST_MAX_PIPE_NO + 1); ++pipe) + { + if (g_usb0_host_pipe_status[pipe] != USB_HOST_PIPE_IDLE) + { + if (pipe == USB_HOST_PIPE0) + { + devadr = RZA_IO_RegRead_16(&USB200.DCPMAXP, + USB_DCPMAXP_DEVSEL_SHIFT, + USB_DCPMAXP_DEVSEL); + } + else + { + devadr = RZA_IO_RegRead_16(&g_usb0_host_pipemaxp[pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL); + } + + if (devadr == g_usb0_host_UsbAddress) + { + usb0_host_stop_transfer(pipe); + } + + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_IDLE; + } + } + + g_usb0_host_ConfigNum = 0; + g_usb0_host_UsbAddress = 0; + g_usb0_host_default_max_packet[USB_HOST_DEVICE_0] = 64; + + usb0_host_UsbDetach2(); +} + +/******************************************************************************* +* Function Name: usb0_host_UsbDetach2 +* Description : Disconnects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_UsbDetach2 (void) +{ + usb0_host_Disable_DetachINT(); + usb0_host_Disable_BchgINT(); + usb0_host_Enable_AttachINT(); +} + +/******************************************************************************* +* Function Name: usb0_host_UsbBusReset +* Description : Issues the USB bus reset signal. +* Arguments : none +* Return Value : uint16_t ; RHST +*******************************************************************************/ +uint16_t usb0_host_UsbBusReset (void) +{ + uint16_t buffer; + uint16_t loop; + + RZA_IO_RegWrite_16(&USB200.DVSTCTR0, + 1, + USB_DVSTCTR0_USBRST_SHIFT, + USB_DVSTCTR0_USBRST); + RZA_IO_RegWrite_16(&USB200.DVSTCTR0, + 0, + USB_DVSTCTR0_UACT_SHIFT, + USB_DVSTCTR0_UACT); + + Userdef_USB_usb0_host_delay_xms(50); + + buffer = USB200.DVSTCTR0; + buffer &= (uint16_t)(~(USB_HOST_BITRST)); + buffer |= USB_HOST_BITUACT; + USB200.DVSTCTR0 = buffer; + + Userdef_USB_usb0_host_delay_xms(20); + + for (loop = 0, buffer = USB_HOST_HSPROC; loop < 3; ++loop) + { + buffer = RZA_IO_RegRead_16(&USB200.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (buffer == USB_HOST_HSPROC) + { + Userdef_USB_usb0_host_delay_xms(10); + } + else + { + break; + } + } + + return buffer; +} + +/******************************************************************************* +* Function Name: usb0_host_UsbResume +* Description : Issues the USB resume signal. +* Arguments : none +* Return Value : int32_t ; DEVDRV_SUCCESS +* : ; DEVDRV_ERROR +*******************************************************************************/ +int32_t usb0_host_UsbResume (void) +{ + uint16_t buf; + + if ((g_usb0_host_driver_state & USB_HOST_DRV_SUSPEND) == 0) + { + /* not SUSPEND */ + return DEVDRV_ERROR; + } + + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); + RZA_IO_RegWrite_16(&USB200.DVSTCTR0, + 1, + USB_DVSTCTR0_RESUME_SHIFT, + USB_DVSTCTR0_RESUME); + Userdef_USB_usb0_host_delay_xms(20); + + buf = USB200.DVSTCTR0; + buf &= (uint16_t)(~(USB_HOST_BITRESUME)); + buf |= USB_HOST_BITUACT; + USB200.DVSTCTR0 = buf; + + g_usb0_host_driver_state &= (uint16_t)~USB_HOST_DRV_SUSPEND; + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb0_host_UsbSuspend +* Description : Issues the USB suspend signal. +* Arguments : none +* Return Value : int32_t ; DEVDRV_SUCCESS :not SUSPEND +* : ; DEVDRV_ERROR :SUSPEND +*******************************************************************************/ +int32_t usb0_host_UsbSuspend (void) +{ + uint16_t buf; + + if ((g_usb0_host_driver_state & USB_HOST_DRV_SUSPEND) != 0) + { + /* SUSPEND */ + return DEVDRV_ERROR; + } + + RZA_IO_RegWrite_16(&USB200.DVSTCTR0, + 0, + USB_DVSTCTR0_UACT_SHIFT, + USB_DVSTCTR0_UACT); + + Userdef_USB_usb0_host_delay_xms(5); + + buf = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + if ((buf != USB_HOST_FS_JSTS) && (buf != USB_HOST_LS_JSTS)) + { + usb0_host_UsbDetach(); + } + else + { + g_usb0_host_driver_state |= USB_HOST_DRV_SUSPEND; + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb0_host_Enable_DetachINT +* Description : Enables the USB disconnection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_Enable_DetachINT (void) +{ + USB200.INTSTS1 = (uint16_t)(~(USB_HOST_BITDTCH)); + RZA_IO_RegWrite_16(&USB200.INTENB1, + 1, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); +} + +/******************************************************************************* +* Function Name: usb0_host_Disable_DetachINT +* Description : Disables the USB disconnection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_Disable_DetachINT (void) +{ + USB200.INTSTS1 = (uint16_t)(~(USB_HOST_BITDTCH)); + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); +} + +/******************************************************************************* +* Function Name: usb0_host_Enable_AttachINT +* Description : Enables the USB connection detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_Enable_AttachINT (void) +{ + USB200.INTSTS1 = (uint16_t)(~(USB_HOST_BITATTCH)); + RZA_IO_RegWrite_16(&USB200.INTENB1, + 1, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); +} + +/******************************************************************************* +* Function Name: usb0_host_Disable_AttachINT +* Description : Disables the USB connection detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_Disable_AttachINT (void) +{ + USB200.INTSTS1 = (uint16_t)(~(USB_HOST_BITATTCH)); + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); +} + +/******************************************************************************* +* Function Name: usb0_host_Disable_BchgINT +* Description : Disables the USB bus change detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_Disable_BchgINT (void) +{ + USB200.INTSTS1 = (uint16_t)(~(USB_HOST_BITBCHG)); + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); +} + +/******************************************************************************* +* Function Name: usb0_host_set_devadd +* Description : DEVADDn register is set by specified value +* Arguments : uint16_t addr : Device address +* : uint16_t *devadd : Set value +* Return Value : none +*******************************************************************************/ +void usb0_host_set_devadd (uint16_t addr, uint16_t * devadd) +{ + uint16_t * ptr; + uint16_t ret_flag = DEVDRV_FLAG_ON; // avoid warning. + + switch (addr) + { + case USB_HOST_DEVICE_0: + ptr = (uint16_t *)&USB200.DEVADD0; + break; + + case USB_HOST_DEVICE_1: + ptr = (uint16_t *)&USB200.DEVADD1; + break; + + case USB_HOST_DEVICE_2: + ptr = (uint16_t *)&USB200.DEVADD2; + break; + + case USB_HOST_DEVICE_3: + ptr = (uint16_t *)&USB200.DEVADD3; + break; + + case USB_HOST_DEVICE_4: + ptr = (uint16_t *)&USB200.DEVADD4; + break; + + case USB_HOST_DEVICE_5: + ptr = (uint16_t *)&USB200.DEVADD5; + break; + + case USB_HOST_DEVICE_6: + ptr = (uint16_t *)&USB200.DEVADD6; + break; + + case USB_HOST_DEVICE_7: + ptr = (uint16_t *)&USB200.DEVADD7; + break; + + case USB_HOST_DEVICE_8: + ptr = (uint16_t *)&USB200.DEVADD8; + break; + + case USB_HOST_DEVICE_9: + ptr = (uint16_t *)&USB200.DEVADD9; + break; + + case USB_HOST_DEVICE_10: + ptr = (uint16_t *)&USB200.DEVADDA; + break; + + default: + ret_flag = DEVDRV_FLAG_OFF; + break; + } + + if (ret_flag == DEVDRV_FLAG_ON) + { + *ptr = (uint16_t)(*devadd & USB_HOST_DEVADD_MASK); + } +} + +/******************************************************************************* +* Function Name: usb0_host_get_devadd +* Description : DEVADDn register is obtained +* Arguments : uint16_t addr : Device address +* : uint16_t *devadd : USB_HOST_DEVADD register value +* Return Value : none +*******************************************************************************/ +void usb0_host_get_devadd (uint16_t addr, uint16_t * devadd) +{ + uint16_t * ptr; + uint16_t ret_flag = DEVDRV_FLAG_ON; // avoid warning. + + switch (addr) + { + case USB_HOST_DEVICE_0: + ptr = (uint16_t *)&USB200.DEVADD0; + break; + + case USB_HOST_DEVICE_1: + ptr = (uint16_t *)&USB200.DEVADD1; + break; + + case USB_HOST_DEVICE_2: + ptr = (uint16_t *)&USB200.DEVADD2; + break; + + case USB_HOST_DEVICE_3: + ptr = (uint16_t *)&USB200.DEVADD3; + break; + + case USB_HOST_DEVICE_4: + ptr = (uint16_t *)&USB200.DEVADD4; + break; + + case USB_HOST_DEVICE_5: + ptr = (uint16_t *)&USB200.DEVADD5; + break; + + case USB_HOST_DEVICE_6: + ptr = (uint16_t *)&USB200.DEVADD6; + break; + + case USB_HOST_DEVICE_7: + ptr = (uint16_t *)&USB200.DEVADD7; + break; + + case USB_HOST_DEVICE_8: + ptr = (uint16_t *)&USB200.DEVADD8; + break; + + case USB_HOST_DEVICE_9: + ptr = (uint16_t *)&USB200.DEVADD9; + break; + + case USB_HOST_DEVICE_10: + ptr = (uint16_t *)&USB200.DEVADDA; + break; + + default: + ret_flag = DEVDRV_FLAG_OFF; + break; + } + + if (ret_flag == DEVDRV_FLAG_ON) + { + *devadd = *ptr; + } +} + +/******************************************************************************* +* Function Name: usb0_host_EnableINT_Module +* Description : Enables BEMP/NRDY/BRDY interrupt and SIGN/SACK interrupt. +* : Enables NRDY/BEMP interrupt in the pipe0. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_EnableINT_Module (void) +{ + uint16_t buf; + + buf = USB200.INTENB0; + buf |= (USB_HOST_BITBEMPE | USB_HOST_BITNRDYE | USB_HOST_BITBRDYE); + USB200.INTENB0 = buf; + + buf = USB200.INTENB1; + buf |= (USB_HOST_BITSIGNE | USB_HOST_BITSACKE); + USB200.INTENB1 = buf; + + usb0_host_enable_nrdy_int(USB_HOST_PIPE0); + usb0_host_enable_bemp_int(USB_HOST_PIPE0); +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/userdef/usb0_host_dmacdrv.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,698 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_dmacdrv.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "r_typedefs.h" +#include "iodefine.h" +#include "rza_io_regrw.h" +#include "usb0_host_dmacdrv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define DMAC_INDEFINE (255) /* Macro definition when REQD bit is not used */ + +/* ==== Request setting information for on-chip peripheral module ==== */ +typedef enum dmac_peri_req_reg_type +{ + DMAC_REQ_MID, + DMAC_REQ_RID, + DMAC_REQ_AM, + DMAC_REQ_LVL, + DMAC_REQ_REQD +} dmac_peri_req_reg_type_t; + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +/* ==== Prototype declaration ==== */ + +/* ==== Global variable ==== */ +/* On-chip peripheral module request setting table */ +static const uint8_t usb0_host_dmac_peri_req_init_table[8][5] = +{ + /* MID,RID, AM,LVL,REQD */ + { 32, 3, 2, 1, 1}, /* USB_0 channel 0 transmit FIFO empty */ + { 32, 3, 2, 1, 0}, /* USB_0 channel 0 receive FIFO full */ + { 33, 3, 2, 1, 1}, /* USB_0 channel 1 transmit FIFO empty */ + { 33, 3, 2, 1, 0}, /* USB_0 channel 1 receive FIFO full */ + { 34, 3, 2, 1, 1}, /* USB_1 channel 0 transmit FIFO empty */ + { 34, 3, 2, 1, 0}, /* USB_1 channel 0 receive FIFO full */ + { 35, 3, 2, 1, 1}, /* USB_1 channel 1 transmit FIFO empty */ + { 35, 3, 2, 1, 0}, /* USB_1 channel 1 receive FIFO full */ +}; + + +/******************************************************************************* +* Function Name: usb0_host_DMAC1_PeriReqInit +* Description : Sets the register mode for DMA mode and the on-chip peripheral +* : module request for transfer request for DMAC channel 1. +* : Executes DMAC initial setting using the DMA information +* : specified by the argument *trans_info and the enabled/disabled +* : continuous transfer specified by the argument continuation. +* : Registers DMAC channel 1 interrupt handler function and sets +* : the interrupt priority level. Then enables transfer completion +* : interrupt. +* Arguments : dmac_transinfo_t * trans_info : Setting information to DMAC +* : : register +* : uint32_t dmamode : DMA mode (only for DMAC_MODE_REGISTER) +* : uint32_t continuation : Set continuous transfer to be valid +* : : after DMA transfer has been completed +* : DMAC_SAMPLE_CONTINUATION : Execute continuous transfer +* : DMAC_SAMPLE_SINGLE : Do not execute continuous +* : : transfer +* : uint32_t request_factor : Factor for on-chip peripheral module +* : : request +* : DMAC_REQ_OSTM0TINT : OSTM_0 compare match +* : DMAC_REQ_OSTM1TINT : OSTM_1 compare match +* : DMAC_REQ_TGI0A : MTU2_0 input capture/compare match +* : : +* : uint32_t req_direction : Setting value of CHCFG_n register +* : : REQD bit +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC1_PeriReqInit (const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction) +{ + /* ==== Register mode ==== */ + if (DMAC_MODE_REGISTER == dmamode) + { + /* ==== Next0 register set ==== */ + DMAC1.N0SA_n = trans_info->src_addr; /* Start address of transfer source */ + DMAC1.N0DA_n = trans_info->dst_addr; /* Start address of transfer destination */ + DMAC1.N0TB_n = trans_info->count; /* Total transfer byte count */ + + /* DAD : Transfer destination address counting direction */ + /* SAD : Transfer source address counting direction */ + /* DDS : Transfer destination transfer size */ + /* SDS : Transfer source transfer size */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + trans_info->daddr_dir, + DMAC1_CHCFG_n_DAD_SHIFT, + DMAC1_CHCFG_n_DAD); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + trans_info->saddr_dir, + DMAC1_CHCFG_n_SAD_SHIFT, + DMAC1_CHCFG_n_SAD); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + trans_info->dst_size, + DMAC1_CHCFG_n_DDS_SHIFT, + DMAC1_CHCFG_n_DDS); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + trans_info->src_size, + DMAC1_CHCFG_n_SDS_SHIFT, + DMAC1_CHCFG_n_SDS); + + /* DMS : Register mode */ + /* RSEL : Select Next0 register set */ + /* SBE : No discharge of buffer data when aborted */ + /* DEM : No DMA interrupt mask */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_DMS_SHIFT, + DMAC1_CHCFG_n_DMS); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_RSEL_SHIFT, + DMAC1_CHCFG_n_RSEL); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_SBE_SHIFT, + DMAC1_CHCFG_n_SBE); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_DEM_SHIFT, + DMAC1_CHCFG_n_DEM); + + /* ---- Continuous transfer ---- */ + if (DMAC_SAMPLE_CONTINUATION == continuation) + { + /* REN : Execute continuous transfer */ + /* RSW : Change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 1, + DMAC1_CHCFG_n_REN_SHIFT, + DMAC1_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 1, + DMAC1_CHCFG_n_RSW_SHIFT, + DMAC1_CHCFG_n_RSW); + } + /* ---- Single transfer ---- */ + else + { + /* REN : Do not execute continuous transfer */ + /* RSW : Do not change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_REN_SHIFT, + DMAC1_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_RSW_SHIFT, + DMAC1_CHCFG_n_RSW); + } + + /* TM : Single transfer */ + /* SEL : Channel setting */ + /* HIEN, LOEN : On-chip peripheral module request */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_TM_SHIFT, + DMAC1_CHCFG_n_TM); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 1, + DMAC1_CHCFG_n_SEL_SHIFT, + DMAC1_CHCFG_n_SEL); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 1, + DMAC1_CHCFG_n_HIEN_SHIFT, + DMAC1_CHCFG_n_HIEN); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_LOEN_SHIFT, + DMAC1_CHCFG_n_LOEN); + + /* ---- Set factor by specified on-chip peripheral module request ---- */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_AM], + DMAC1_CHCFG_n_AM_SHIFT, + DMAC1_CHCFG_n_AM); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_LVL], + DMAC1_CHCFG_n_LVL_SHIFT, + DMAC1_CHCFG_n_LVL); + if (usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD] != DMAC_INDEFINE) + { + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD], + DMAC1_CHCFG_n_REQD_SHIFT, + DMAC1_CHCFG_n_REQD); + } + else + { + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + req_direction, + DMAC1_CHCFG_n_REQD_SHIFT, + DMAC1_CHCFG_n_REQD); + } + RZA_IO_RegWrite_32(&DMAC01.DMARS, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_RID], + DMAC01_DMARS_CH1_RID_SHIFT, + DMAC01_DMARS_CH1_RID); + RZA_IO_RegWrite_32(&DMAC01.DMARS, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_MID], + DMAC01_DMARS_CH1_MID_SHIFT, + DMAC01_DMARS_CH1_MID); + + /* PR : Round robin mode */ + RZA_IO_RegWrite_32(&DMAC07.DCTRL_0_7, + 1, + DMAC07_DCTRL_0_7_PR_SHIFT, + DMAC07_DCTRL_0_7_PR); + } +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC1_Open +* Description : Enables DMAC channel 1 transfer. +* Arguments : uint32_t req : DMAC request mode +* Return Value : 0 : Succeeded in enabling DMA transfer +* : -1 : Failed to enable DMA transfer (due to DMA operation) +*******************************************************************************/ +int32_t usb0_host_DMAC1_Open (uint32_t req) +{ + int32_t ret; + volatile uint8_t dummy; + + /* Transferable? */ + if ((0 == RZA_IO_RegRead_32(&DMAC1.CHSTAT_n, + DMAC1_CHSTAT_n_EN_SHIFT, + DMAC1_CHSTAT_n_EN)) && + (0 == RZA_IO_RegRead_32(&DMAC1.CHSTAT_n, + DMAC1_CHSTAT_n_TACT_SHIFT, + DMAC1_CHSTAT_n_TACT))) + { + /* Clear Channel Status Register */ + RZA_IO_RegWrite_32(&DMAC1.CHCTRL_n, + 1, + DMAC1_CHCTRL_n_SWRST_SHIFT, + DMAC1_CHCTRL_n_SWRST); + dummy = RZA_IO_RegRead_32(&DMAC1.CHCTRL_n, + DMAC1_CHCTRL_n_SWRST_SHIFT, + DMAC1_CHCTRL_n_SWRST); + /* Enable DMA transfer */ + RZA_IO_RegWrite_32(&DMAC1.CHCTRL_n, + 1, + DMAC1_CHCTRL_n_SETEN_SHIFT, + DMAC1_CHCTRL_n_SETEN); + + /* ---- Request by software ---- */ + if (DMAC_REQ_MODE_SOFT == req) + { + /* DMA transfer Request by software */ + RZA_IO_RegWrite_32(&DMAC1.CHCTRL_n, + 1, + DMAC1_CHCTRL_n_STG_SHIFT, + DMAC1_CHCTRL_n_STG); + } + + ret = 0; + } + else + { + ret = -1; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC1_Close +* Description : Aborts DMAC channel 1 transfer. Returns the remaining transfer +* : byte count at the time of DMA transfer abort to the argument +* : *remain. +* Arguments : uint32_t * remain : Remaining transfer byte count when +* : : DMA transfer is aborted +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC1_Close (uint32_t * remain) +{ + + /* ==== Abort transfer ==== */ + RZA_IO_RegWrite_32(&DMAC1.CHCTRL_n, + 1, + DMAC1_CHCTRL_n_CLREN_SHIFT, + DMAC1_CHCTRL_n_CLREN); + + while (1 == RZA_IO_RegRead_32(&DMAC1.CHSTAT_n, + DMAC1_CHSTAT_n_TACT_SHIFT, + DMAC1_CHSTAT_n_TACT)) + { + /* Loop until transfer is aborted */ + } + + while (1 == RZA_IO_RegRead_32(&DMAC1.CHSTAT_n, + DMAC1_CHSTAT_n_EN_SHIFT, + DMAC1_CHSTAT_n_EN)) + { + /* Loop until 0 is set in EN before checking the remaining transfer byte count */ + } + /* ==== Obtain remaining transfer byte count ==== */ + *remain = DMAC1.CRTB_n; +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC1_Load_Set +* Description : Sets the transfer source address, transfer destination +* : address, and total transfer byte count respectively +* : specified by the argument src_addr, dst_addr, and count to +* : DMAC channel 1 as DMA transfer information. +* : Sets the register set selected by the CHCFG_n register +* : RSEL bit from the Next0 or Next1 register set. +* : This function should be called when DMA transfer of DMAC +* : channel 1 is aboted. +* Arguments : uint32_t src_addr : Transfer source address +* : uint32_t dst_addr : Transfer destination address +* : uint32_t count : Total transfer byte count +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC1_Load_Set (uint32_t src_addr, uint32_t dst_addr, uint32_t count) +{ + uint8_t reg_set; + + /* Obtain register set in use */ + reg_set = RZA_IO_RegRead_32(&DMAC1.CHSTAT_n, + DMAC1_CHSTAT_n_SR_SHIFT, + DMAC1_CHSTAT_n_SR); + + /* ==== Load ==== */ + if (0 == reg_set) + { + /* ---- Next0 Register Set ---- */ + DMAC1.N0SA_n = src_addr; /* Start address of transfer source */ + DMAC1.N0DA_n = dst_addr; /* Start address of transfer destination */ + DMAC1.N0TB_n = count; /* Total transfer byte count */ + } + else + { + /* ---- Next1 Register Set ---- */ + DMAC1.N1SA_n = src_addr; /* Start address of transfer source */ + DMAC1.N1DA_n = dst_addr; /* Start address of transfer destination */ + DMAC1.N1TB_n = count; /* Total transfer byte count */ + } +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC2_PeriReqInit +* Description : Sets the register mode for DMA mode and the on-chip peripheral +* : module request for transfer request for DMAC channel 2. +* : Executes DMAC initial setting using the DMA information +* : specified by the argument *trans_info and the enabled/disabled +* : continuous transfer specified by the argument continuation. +* : Registers DMAC channel 2 interrupt handler function and sets +* : the interrupt priority level. Then enables transfer completion +* : interrupt. +* Arguments : dmac_transinfo_t * trans_info : Setting information to DMAC +* : : register +* : uint32_t dmamode : DMA mode (only for DMAC_MODE_REGISTER) +* : uint32_t continuation : Set continuous transfer to be valid +* : : after DMA transfer has been completed +* : DMAC_SAMPLE_CONTINUATION : Execute continuous transfer +* : DMAC_SAMPLE_SINGLE : Do not execute continuous +* : : transfer +* : uint32_t request_factor : Factor for on-chip peripheral module +* : : request +* : DMAC_REQ_OSTM0TINT : OSTM_0 compare match +* : DMAC_REQ_OSTM1TINT : OSTM_1 compare match +* : DMAC_REQ_TGI0A : MTU2_0 input capture/compare match +* : : +* : uint32_t req_direction : Setting value of CHCFG_n register +* : : REQD bit +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC2_PeriReqInit (const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction) +{ + /* ==== Register mode ==== */ + if (DMAC_MODE_REGISTER == dmamode) + { + /* ==== Next0 register set ==== */ + DMAC2.N0SA_n = trans_info->src_addr; /* Start address of transfer source */ + DMAC2.N0DA_n = trans_info->dst_addr; /* Start address of transfer destination */ + DMAC2.N0TB_n = trans_info->count; /* Total transfer byte count */ + + /* DAD : Transfer destination address counting direction */ + /* SAD : Transfer source address counting direction */ + /* DDS : Transfer destination transfer size */ + /* SDS : Transfer source transfer size */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + trans_info->daddr_dir, + DMAC2_CHCFG_n_DAD_SHIFT, + DMAC2_CHCFG_n_DAD); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + trans_info->saddr_dir, + DMAC2_CHCFG_n_SAD_SHIFT, + DMAC2_CHCFG_n_SAD); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + trans_info->dst_size, + DMAC2_CHCFG_n_DDS_SHIFT, + DMAC2_CHCFG_n_DDS); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + trans_info->src_size, + DMAC2_CHCFG_n_SDS_SHIFT, + DMAC2_CHCFG_n_SDS); + + /* DMS : Register mode */ + /* RSEL : Select Next0 register set */ + /* SBE : No discharge of buffer data when aborted */ + /* DEM : No DMA interrupt mask */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_DMS_SHIFT, + DMAC2_CHCFG_n_DMS); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_RSEL_SHIFT, + DMAC2_CHCFG_n_RSEL); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_SBE_SHIFT, + DMAC2_CHCFG_n_SBE); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_DEM_SHIFT, + DMAC2_CHCFG_n_DEM); + + /* ---- Continuous transfer ---- */ + if (DMAC_SAMPLE_CONTINUATION == continuation) + { + /* REN : Execute continuous transfer */ + /* RSW : Change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 1, + DMAC2_CHCFG_n_REN_SHIFT, + DMAC2_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 1, + DMAC2_CHCFG_n_RSW_SHIFT, + DMAC2_CHCFG_n_RSW); + } + /* ---- Single transfer ---- */ + else + { + /* REN : Do not execute continuous transfer */ + /* RSW : Do not change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_REN_SHIFT, + DMAC2_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_RSW_SHIFT, + DMAC2_CHCFG_n_RSW); + } + + /* TM : Single transfer */ + /* SEL : Channel setting */ + /* HIEN, LOEN : On-chip peripheral module request */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_TM_SHIFT, + DMAC2_CHCFG_n_TM); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 2, + DMAC2_CHCFG_n_SEL_SHIFT, + DMAC2_CHCFG_n_SEL); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 1, + DMAC2_CHCFG_n_HIEN_SHIFT, + DMAC2_CHCFG_n_HIEN); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_LOEN_SHIFT, + DMAC2_CHCFG_n_LOEN); + + /* ---- Set factor by specified on-chip peripheral module request ---- */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_AM], + DMAC2_CHCFG_n_AM_SHIFT, + DMAC2_CHCFG_n_AM); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_LVL], + DMAC2_CHCFG_n_LVL_SHIFT, + DMAC2_CHCFG_n_LVL); + if (usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD] != DMAC_INDEFINE) + { + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD], + DMAC2_CHCFG_n_REQD_SHIFT, + DMAC2_CHCFG_n_REQD); + } + else + { + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + req_direction, + DMAC2_CHCFG_n_REQD_SHIFT, + DMAC2_CHCFG_n_REQD); + } + RZA_IO_RegWrite_32(&DMAC23.DMARS, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_RID], + DMAC23_DMARS_CH2_RID_SHIFT, + DMAC23_DMARS_CH2_RID); + RZA_IO_RegWrite_32(&DMAC23.DMARS, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_MID], + DMAC23_DMARS_CH2_MID_SHIFT, + DMAC23_DMARS_CH2_MID); + + /* PR : Round robin mode */ + RZA_IO_RegWrite_32(&DMAC07.DCTRL_0_7, + 1, + DMAC07_DCTRL_0_7_PR_SHIFT, + DMAC07_DCTRL_0_7_PR); + } +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC2_Open +* Description : Enables DMAC channel 2 transfer. +* Arguments : uint32_t req : DMAC request mode +* Return Value : 0 : Succeeded in enabling DMA transfer +* : -1 : Failed to enable DMA transfer (due to DMA operation) +*******************************************************************************/ +int32_t usb0_host_DMAC2_Open (uint32_t req) +{ + int32_t ret; + volatile uint8_t dummy; + + /* Transferable? */ + if ((0 == RZA_IO_RegRead_32(&DMAC2.CHSTAT_n, + DMAC2_CHSTAT_n_EN_SHIFT, + DMAC2_CHSTAT_n_EN)) && + (0 == RZA_IO_RegRead_32(&DMAC2.CHSTAT_n, + DMAC2_CHSTAT_n_TACT_SHIFT, + DMAC2_CHSTAT_n_TACT))) + { + /* Clear Channel Status Register */ + RZA_IO_RegWrite_32(&DMAC2.CHCTRL_n, + 1, + DMAC2_CHCTRL_n_SWRST_SHIFT, + DMAC2_CHCTRL_n_SWRST); + dummy = RZA_IO_RegRead_32(&DMAC2.CHCTRL_n, + DMAC2_CHCTRL_n_SWRST_SHIFT, + DMAC2_CHCTRL_n_SWRST); + /* Enable DMA transfer */ + RZA_IO_RegWrite_32(&DMAC2.CHCTRL_n, + 1, + DMAC2_CHCTRL_n_SETEN_SHIFT, + DMAC2_CHCTRL_n_SETEN); + + /* ---- Request by software ---- */ + if (DMAC_REQ_MODE_SOFT == req) + { + /* DMA transfer Request by software */ + RZA_IO_RegWrite_32(&DMAC2.CHCTRL_n, + 1, + DMAC2_CHCTRL_n_STG_SHIFT, + DMAC2_CHCTRL_n_STG); + } + + ret = 0; + } + else + { + ret = -1; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC2_Close +* Description : Aborts DMAC channel 2 transfer. Returns the remaining transfer +* : byte count at the time of DMA transfer abort to the argument +* : *remain. +* Arguments : uint32_t * remain : Remaining transfer byte count when +* : : DMA transfer is aborted +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC2_Close (uint32_t * remain) +{ + + /* ==== Abort transfer ==== */ + RZA_IO_RegWrite_32(&DMAC2.CHCTRL_n, + 1, + DMAC2_CHCTRL_n_CLREN_SHIFT, + DMAC2_CHCTRL_n_CLREN); + + while (1 == RZA_IO_RegRead_32(&DMAC2.CHSTAT_n, + DMAC2_CHSTAT_n_TACT_SHIFT, + DMAC2_CHSTAT_n_TACT)) + { + /* Loop until transfer is aborted */ + } + + while (1 == RZA_IO_RegRead_32(&DMAC2.CHSTAT_n, + DMAC2_CHSTAT_n_EN_SHIFT, + DMAC2_CHSTAT_n_EN)) + { + /* Loop until 0 is set in EN before checking the remaining transfer byte count */ + } + /* ==== Obtain remaining transfer byte count ==== */ + *remain = DMAC2.CRTB_n; +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC2_Load_Set +* Description : Sets the transfer source address, transfer destination +* : address, and total transfer byte count respectively +* : specified by the argument src_addr, dst_addr, and count to +* : DMAC channel 2 as DMA transfer information. +* : Sets the register set selected by the CHCFG_n register +* : RSEL bit from the Next0 or Next1 register set. +* : This function should be called when DMA transfer of DMAC +* : channel 2 is aboted. +* Arguments : uint32_t src_addr : Transfer source address +* : uint32_t dst_addr : Transfer destination address +* : uint32_t count : Total transfer byte count +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC2_Load_Set (uint32_t src_addr, uint32_t dst_addr, uint32_t count) +{ + uint8_t reg_set; + + /* Obtain register set in use */ + reg_set = RZA_IO_RegRead_32(&DMAC2.CHSTAT_n, + DMAC2_CHSTAT_n_SR_SHIFT, + DMAC2_CHSTAT_n_SR); + + /* ==== Load ==== */ + if (0 == reg_set) + { + /* ---- Next0 Register Set ---- */ + DMAC2.N0SA_n = src_addr; /* Start address of transfer source */ + DMAC2.N0DA_n = dst_addr; /* Start address of transfer destination */ + DMAC2.N0TB_n = count; /* Total transfer byte count */ + } + else + { + /* ---- Next1 Register Set ---- */ + DMAC2.N1SA_n = src_addr; /* Start address of transfer source */ + DMAC2.N1DA_n = dst_addr; /* Start address of transfer destination */ + DMAC2.N1TB_n = count; /* Total transfer byte count */ + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/userdef/usb0_host_userdef.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,778 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_userdef.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include <stdio.h> +#include "cmsis_os.h" +#include "r_typedefs.h" +#include "iodefine.h" +#include "devdrv_usb_host_api.h" +#include "usb0_host.h" +#include "MBRZA1H.h" /* INTC Driver Header */ +#include "usb0_host_dmacdrv.h" +#include "ohci_wrapp_RZ_A1_local.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define DUMMY_ACCESS OSTM0CNT + +/* #define CACHE_WRITEBACK */ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +extern int32_t io_cwb(unsigned long start, unsigned long end); + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb0_host_enable_dmac0(uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc); +static void usb0_host_enable_dmac1(uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc); +static void Userdef_USB_usb0_host_delay_10us_2(void); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_d0fifo_dmaintid +* Description : get D0FIFO DMA Interrupt ID +* Arguments : none +* Return Value : D0FIFO DMA Interrupt ID +*******************************************************************************/ +uint16_t Userdef_USB_usb0_host_d0fifo_dmaintid (void) +{ +#if(1) /* ohci_wrapp */ + return 0xFFFF; +#else + return DMAINT1_IRQn; +#endif +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_d1fifo_dmaintid +* Description : get D1FIFO DMA Interrupt ID +* Arguments : none +* Return Value : D1FIFO DMA Interrupt ID +*******************************************************************************/ +uint16_t Userdef_USB_usb0_host_d1fifo_dmaintid (void) +{ +#if(1) /* ohci_wrapp */ + return 0xFFFF; +#else + return DMAINT2_IRQn; +#endif +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_attach +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_attach (void) +{ +// printf("\n"); +// printf("channel 0 attach device\n"); +// printf("\n"); + ohciwrapp_loc_Connect(1); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_detach +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_detach (void) +{ +// printf("\n"); +// printf("channel 0 detach device\n"); +// printf("\n"); + ohciwrapp_loc_Connect(0); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_delay_1ms +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_delay_1ms (void) +{ + osDelay(1); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_delay_xms +* Description : Wait for the software in the period of time specified by the +* : argument. +* : Alter this function according to the user's system. +* Arguments : uint32_t msec ; Wait Time (msec) +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_delay_xms (uint32_t msec) +{ + osDelay(msec); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_delay_10us +* Description : Waits for software for the period specified by the argument. +* : Alter this function according to the user's system. +* Arguments : uint32_t usec ; Wait Time(x 10usec) +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_delay_10us (uint32_t usec) +{ + volatile int i; + + /* Wait 10us (Please change for your MCU) */ + for (i = 0; i < usec; ++i) + { + Userdef_USB_usb0_host_delay_10us_2(); + } +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_delay_10us_2 +* Description : Waits for software for the period specified by the argument. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +static void Userdef_USB_usb0_host_delay_10us_2 (void) +{ + volatile int i; + volatile unsigned long tmp; + + /* Wait 1us (Please change for your MCU) */ + for (i = 0; i < 14; ++i) + { + tmp = DUMMY_ACCESS; + } +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_delay_500ns +* Description : Wait for software for 500ns. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_delay_500ns (void) +{ + volatile int i; + volatile unsigned long tmp; + + /* Wait 500ns (Please change for your MCU) */ + /* Wait 500ns I clock 266MHz */ + tmp = DUMMY_ACCESS; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_start_dma +* Description : Enables DMA transfer on the information specified by the argument. +* : Set DMAC register by this function to enable DMA transfer. +* : After executing this function, USB module is set to start DMA +* : transfer. DMA transfer should not wait for DMA transfer complete. +* Arguments : USB_HOST_DMA_t *dma : DMA parameter +* : typedef struct{ +* : uint32_t fifo; FIFO for using +* : uint32_t buffer; Start address of transfer source/destination +* : uint32_t bytes; Transfer size(Byte) +* : uint32_t dir; Transfer direction(0:Buffer->FIFO, 1:FIFO->Buffer) +* : uint32_t size; DMA transfer size +* : } USB_HOST_DMA_t; +* : uint16_t dfacc ; 0 : cycle steal mode +* : 1 : 16byte continuous mode +* : 2 : 32byte continuous mode +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_start_dma (USB_HOST_DMA_t * dma, uint16_t dfacc) +{ + uint32_t trncount; + uint32_t src; + uint32_t dst; + uint32_t size; + uint32_t dir; +#ifdef CACHE_WRITEBACK + uint32_t ptr; +#endif + + trncount = dma->bytes; + dir = dma->dir; + + if (dir == USB_HOST_FIFO2BUF) + { + /* DxFIFO determination */ + dst = dma->buffer; +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB200.D1FIFO.UINT32); + } + size = dma->size; + + if (size == 0) + { + src += 3; /* byte access */ + } + else if (size == 1) + { + src += 2; /* short access */ + } + else + { + /* Do Nothing */ + } +#else + size = dma->size; + + if (size == 2) + { + /* 32bit access */ + if (dfacc == 2) + { + /* 32byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFOB0); + } + else + { + src = (uint32_t)(&USB200.D1FIFOB0); + } + } + else if (dfacc == 1) + { + /* 16byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFOB0); + } + else + { + src = (uint32_t)(&USB200.D1FIFOB0); + } + } + else + { + /* normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB200.D1FIFO.UINT32); + } + } + } + else if (size == 1) + { + /* 16bit access */ + dfacc = 0; /* force normal access */ + + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB200.D1FIFO.UINT32); + } + src += 2; /* short access */ + } + else + { + /* 8bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB200.D1FIFO.UINT32); + } + src += 3; /* byte access */ + } +#endif + } + else + { + /* DxFIFO determination */ + src = dma->buffer; +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB200.D1FIFO.UINT32); + } + size = dma->size; + + if (size == 0) + { + dst += 3; /* byte access */ + } + else if (size == 1) + { + dst += 2; /* short access */ + } + else + { + /* Do Nothing */ + } +#else + size = dma->size; + if (size == 2) + { + /* 32bit access */ + if (dfacc == 2) + { + /* 32byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFOB0); + } + else + { + dst = (uint32_t)(&USB200.D1FIFOB0); + } + } + else if (dfacc == 1) + { + /* 16byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFOB0); + } + else + { + dst = (uint32_t)(&USB200.D1FIFOB0); + } + } + else + { + /* normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB200.D1FIFO.UINT32); + } + } + } + else if (size == 1) + { + /* 16bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB200.D1FIFO.UINT32); + } + dst += 2; /* short access */ + } + else + { + /* 8bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB200.D1FIFO.UINT32); + } + dst += 3; /* byte access */ + } +#endif + } + +#ifdef CACHE_WRITEBACK + ptr = (uint32_t)dma->buffer; + if ((ptr & 0x20000000ul) == 0) + { + io_cwb((uint32_t)ptr,(uint32_t)(ptr)+trncount); + } +#endif + + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + usb0_host_enable_dmac0(src, dst, trncount, size, dir, dma->fifo, dfacc); + } + else + { + usb0_host_enable_dmac1(src, dst, trncount, size, dir, dma->fifo, dfacc); + } +} + +/******************************************************************************* +* Function Name: usb0_host_enable_dmac0 +* Description : Enables DMA transfer on the information specified by the argument. +* Arguments : uint32_t src : src address +* : uint32_t dst : dst address +* : uint32_t count : transfer byte +* : uint32_t size : transfer size +* : uint32_t dir : direction +* : uint32_t fifo : FIFO(D0FIFO or D1FIFO) +* : uint16_t dfacc : 0 : normal access +* : : 1 : 16byte access +* : : 2 : 32byte access +* Return Value : none +*******************************************************************************/ +static void usb0_host_enable_dmac0 (uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc) +{ + dmac_transinfo_t trans_info; + uint32_t request_factor = 0; + int32_t ret; + + /* ==== Variable setting for DMAC initialization ==== */ + trans_info.src_addr = (uint32_t)src; /* Start address of transfer source */ + trans_info.dst_addr = (uint32_t)dst; /* Start address of transfer destination */ + trans_info.count = (uint32_t)count; /* Total byte count to be transferred */ +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } +#else + if (dfacc == 2) + { + /* 32byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_256; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_256; /* Transfer destination transfer size */ + } + else if (dfacc == 1) + { + /* 16byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_128; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_128; /* Transfer destination transfer size */ + } + else + { + /* normal access */ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } + } +#endif + + if (dir == USB_HOST_FIFO2BUF) + { + request_factor = DMAC_REQ_USB0_DMA0_RX; /* USB_0 channel 0 receive FIFO full */ + trans_info.saddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer destination address */ + } + else if (dir == USB_HOST_BUF2FIFO) + { + request_factor = DMAC_REQ_USB0_DMA0_TX; /* USB_0 channel 0 receive FIFO empty */ + trans_info.saddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer destination address */ + } + else + { + /* Do Nothing */ + } + + /* ==== DMAC initialization ==== */ + usb0_host_DMAC1_PeriReqInit((const dmac_transinfo_t *)&trans_info, + DMAC_MODE_REGISTER, + DMAC_SAMPLE_SINGLE, + request_factor, + 0); /* Don't care DMAC_REQ_REQD is setting in usb0_host_DMAC1_PeriReqInit() */ + + /* ==== DMAC startup ==== */ + ret = usb0_host_DMAC1_Open(DMAC_REQ_MODE_PERI); + + if (ret != 0) + { +// printf("DMAC1 Open error!!\n"); + } + + return; +} + +/******************************************************************************* +* Function Name: usb0_host_enable_dmac1 +* Description : Enables DMA transfer on the information specified by the argument. +* Arguments : uint32_t src : src address +* : uint32_t dst : dst address +* : uint32_t count : transfer byte +* : uint32_t size : transfer size +* : uint32_t dir : direction +* : uint32_t fifo : FIFO(D0FIFO or D1FIFO) +* : uint16_t dfacc : 0 : normal access +* : : 1 : 16byte access +* : : 2 : 32byte access +* Return Value : none +*******************************************************************************/ +static void usb0_host_enable_dmac1 (uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc) +{ + dmac_transinfo_t trans_info; + uint32_t request_factor = 0; + int32_t ret; + + /* ==== Variable setting for DMAC initialization ==== */ + trans_info.src_addr = (uint32_t)src; /* Start address of transfer source */ + trans_info.dst_addr = (uint32_t)dst; /* Start address of transfer destination */ + trans_info.count = (uint32_t)count; /* Total byte count to be transferred */ +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } +#else + if (dfacc == 2) + { + /* 32byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_256; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_256; /* Transfer destination transfer size */ + } + else if (dfacc == 1) + { + /* 16byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_128; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_128; /* Transfer destination transfer size */ + } + else + { + /* normal access */ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } + } +#endif + + if (dir == USB_HOST_FIFO2BUF) + { + request_factor =DMAC_REQ_USB0_DMA1_RX; /* USB_0 channel 0 receive FIFO full */ + trans_info.saddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer destination address */ + } + else if (dir == USB_HOST_BUF2FIFO) + { + request_factor =DMAC_REQ_USB0_DMA1_TX; /* USB_0 channel 0 receive FIFO empty */ + trans_info.saddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer destination address */ + } + else + { + /* Do Nothing */ + } + + /* ==== DMAC initialization ==== */ + usb0_host_DMAC2_PeriReqInit((const dmac_transinfo_t *)&trans_info, + DMAC_MODE_REGISTER, + DMAC_SAMPLE_SINGLE, + request_factor, + 0); /* Don't care DMAC_REQ_REQD is setting in usb0_host_DMAC2_PeriReqInit() */ + + /* ==== DMAC startup ==== */ + ret = usb0_host_DMAC2_Open(DMAC_REQ_MODE_PERI); + + if (ret != 0) + { +// printf("DMAC2 Open error!!\n"); + } + + return; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_stop_dma0 +* Description : Disables DMA transfer. +* Arguments : none +* Return Value : uint32_t return Transfer Counter register(DMATCRn) value +* : regarding to the bus width. +* Notice : This function should be executed to DMAC executed at the time +* : of specification of D0_FIF0_DMA in dma->fifo. +*******************************************************************************/ +uint32_t Userdef_USB_usb0_host_stop_dma0 (void) +{ + uint32_t remain; + + /* ==== DMAC release ==== */ + usb0_host_DMAC1_Close(&remain); + + return remain; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_stop_dma1 +* Description : Disables DMA transfer. +* : This function should be executed to DMAC executed at the time +* : of specification of D1_FIF0_DMA in dma->fifo. +* Arguments : none +* Return Value : uint32_t return Transfer Counter register(DMATCRn) value +* : regarding to the bus width. +*******************************************************************************/ +uint32_t Userdef_USB_usb0_host_stop_dma1 (void) +{ + uint32_t remain; + + /* ==== DMAC release ==== */ + usb0_host_DMAC2_Close(&remain); + + return remain; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_notice +* Description : Notice of USER +* Arguments : const char *format +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_notice (const char * format) +{ +// printf(format); + + return; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_user_rdy +* Description : This function notify a user and wait for trigger +* Arguments : const char *format +* : uint16_t data +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_user_rdy (const char * format, uint16_t data) +{ +// printf(format, data); + getchar(); + + return; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/inc/usb1_host.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,156 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB1_HOST_H +#define USB1_HOST_H + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "devdrv_usb_host_api.h" +#include "usb_host.h" + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +extern const uint16_t g_usb1_host_bit_set[]; +extern uint32_t g_usb1_host_data_count[USB_HOST_MAX_PIPE_NO + 1]; +extern uint8_t *g_usb1_host_data_pointer[USB_HOST_MAX_PIPE_NO + 1]; + +extern uint16_t g_usb1_host_PipeIgnore[]; +extern uint16_t g_usb1_host_PipeTbl[]; +extern uint16_t g_usb1_host_pipe_status[]; +extern uint32_t g_usb1_host_PipeDataSize[]; + +extern USB_HOST_DMA_t g_usb1_host_DmaInfo[]; +extern uint16_t g_usb1_host_DmaPipe[]; +extern uint16_t g_usb1_host_DmaBval[]; +extern uint16_t g_usb1_host_DmaStatus[]; + +extern uint16_t g_usb1_host_driver_state; +extern uint16_t g_usb1_host_ConfigNum; +extern uint16_t g_usb1_host_CmdStage; +extern uint16_t g_usb1_host_bchg_flag; +extern uint16_t g_usb1_host_detach_flag; +extern uint16_t g_usb1_host_attach_flag; + +extern uint16_t g_usb1_host_UsbAddress; +extern uint16_t g_usb1_host_setUsbAddress; +extern uint16_t g_usb1_host_default_max_packet[USB_HOST_MAX_DEVICE + 1]; +extern uint16_t g_usb1_host_UsbDeviceSpeed; +extern uint16_t g_usb1_host_SupportUsbDeviceSpeed; + +extern uint16_t g_usb1_host_SavReq; +extern uint16_t g_usb1_host_SavVal; +extern uint16_t g_usb1_host_SavIndx; +extern uint16_t g_usb1_host_SavLen; + +extern uint16_t g_usb1_host_pipecfg[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb1_host_pipebuf[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb1_host_pipemaxp[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb1_host_pipeperi[USB_HOST_MAX_PIPE_NO + 1]; + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +/* ==== common ==== */ +void usb1_host_dma_stop_d0(uint16_t pipe, uint32_t remain); +void usb1_host_dma_stop_d1(uint16_t pipe, uint32_t remain); +uint16_t usb1_host_is_hispeed(void); +uint16_t usb1_host_is_hispeed_enable(void); +uint16_t usb1_host_start_send_transfer(uint16_t pipe, uint32_t size, uint8_t *data); +uint16_t usb1_host_write_buffer(uint16_t pipe); +uint16_t usb1_host_write_buffer_c(uint16_t pipe); +uint16_t usb1_host_write_buffer_d0(uint16_t pipe); +uint16_t usb1_host_write_buffer_d1(uint16_t pipe); +void usb1_host_start_receive_transfer(uint16_t pipe, uint32_t size, uint8_t *data); +uint16_t usb1_host_read_buffer(uint16_t pipe); +uint16_t usb1_host_read_buffer_c(uint16_t pipe); +uint16_t usb1_host_read_buffer_d0(uint16_t pipe); +uint16_t usb1_host_read_buffer_d1(uint16_t pipe); +uint16_t usb1_host_change_fifo_port(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw); +void usb1_host_set_curpipe(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw); +void usb1_host_set_curpipe2(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw, uint16_t dfacc); +uint16_t usb1_host_get_mbw(uint32_t trncount, uint32_t dtptr); +uint16_t usb1_host_read_dma(uint16_t pipe); +void usb1_host_stop_transfer(uint16_t pipe); +void usb1_host_brdy_int(uint16_t status, uint16_t int_enb); +void usb1_host_nrdy_int(uint16_t status, uint16_t int_enb); +void usb1_host_bemp_int(uint16_t status, uint16_t int_enb); +void usb1_host_setting_interrupt(uint8_t level); +void usb1_host_reset_module(uint16_t clockmode); +uint16_t usb1_host_get_buf_size(uint16_t pipe); +uint16_t usb1_host_get_mxps(uint16_t pipe); +void usb1_host_enable_brdy_int(uint16_t pipe); +void usb1_host_disable_brdy_int(uint16_t pipe); +void usb1_host_clear_brdy_sts(uint16_t pipe); +void usb1_host_enable_bemp_int(uint16_t pipe); +void usb1_host_disable_bemp_int(uint16_t pipe); +void usb1_host_clear_bemp_sts(uint16_t pipe); +void usb1_host_enable_nrdy_int(uint16_t pipe); +void usb1_host_disable_nrdy_int(uint16_t pipe); +void usb1_host_clear_nrdy_sts(uint16_t pipe); +void usb1_host_set_pid_buf(uint16_t pipe); +void usb1_host_set_pid_nak(uint16_t pipe); +void usb1_host_set_pid_stall(uint16_t pipe); +void usb1_host_clear_pid_stall(uint16_t pipe); +uint16_t usb1_host_get_pid(uint16_t pipe); +void usb1_host_set_sqclr(uint16_t pipe); +void usb1_host_set_sqset(uint16_t pipe); +void usb1_host_set_csclr(uint16_t pipe); +void usb1_host_aclrm(uint16_t pipe); +void usb1_host_set_aclrm(uint16_t pipe); +void usb1_host_clr_aclrm(uint16_t pipe); +uint16_t usb1_host_get_sqmon(uint16_t pipe); +uint16_t usb1_host_get_inbuf(uint16_t pipe); + +/* ==== host ==== */ +void usb1_host_init_pipe_status(void); +int32_t usb1_host_CtrlTransStart(uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len, uint8_t *Buf); +void usb1_host_SetupStage(uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len); +void usb1_host_CtrlReadStart(uint32_t Bsize, uint8_t *Table); +uint16_t usb1_host_CtrlWriteStart(uint32_t Bsize, uint8_t *Table); +void usb1_host_StatusStage(void); +void usb1_host_get_devadd(uint16_t addr, uint16_t *devadd); +void usb1_host_set_devadd(uint16_t addr, uint16_t *devadd); +void usb1_host_InitModule(void); +uint16_t usb1_host_CheckAttach(void); +void usb1_host_UsbDetach(void); +void usb1_host_UsbDetach2(void); +void usb1_host_UsbAttach(void); +uint16_t usb1_host_UsbBusReset(void); +int32_t usb1_host_UsbResume(void); +int32_t usb1_host_UsbSuspend(void); +void usb1_host_Enable_DetachINT(void); +void usb1_host_Disable_DetachINT(void); +void usb1_host_UsbStateManager(void); + + +#endif /* USB1_HOST_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/inc/usb1_host_api.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,112 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_api.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB1_HOST_API_H +#define USB1_HOST_API_H + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Variable Externs +*******************************************************************************/ + + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +void usb1_host_interrupt(uint32_t int_sense); +void usb1_host_dma_interrupt_d0fifo(uint32_t int_sense); +void usb1_host_dma_interrupt_d1fifo(uint32_t int_sense); + +uint16_t usb1_api_host_init(uint8_t int_level, uint16_t mode, uint16_t clockmode); +int32_t usb1_api_host_enumeration(uint16_t devadr); +int32_t usb1_api_host_detach(void); +int32_t usb1_api_host_data_in(uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t usb1_api_host_data_out(uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t usb1_api_host_control_transfer(uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len, uint8_t *Buf); +int32_t usb1_api_host_set_endpoint(uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t *configdescriptor); +int32_t usb1_api_host_clear_endpoint(USB_HOST_CFG_PIPETBL_t *user_table); +int32_t usb1_api_host_clear_endpoint_pipe(uint16_t pipe_sel, USB_HOST_CFG_PIPETBL_t *user_table); +uint16_t usb1_api_host_SetEndpointTable(uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t *Table); +int32_t usb1_api_host_data_count(uint16_t pipe, uint32_t *data_count); + +int32_t usb1_api_host_GetDeviceDescriptor(uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t usb1_api_host_GetConfigDescriptor(uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t usb1_api_host_SetConfig(uint16_t devadr, uint16_t confignum); +int32_t usb1_api_host_SetInterface(uint16_t devadr, uint16_t interface_alt, uint16_t interface_index); +int32_t usb1_api_host_ClearStall(uint16_t devadr, uint16_t ep_dir); +uint16_t usb1_api_host_GetUsbDeviceState(void); + +void usb1_api_host_elt_4_4(void); +void usb1_api_host_elt_4_5(void); +void usb1_api_host_elt_4_6(void); +void usb1_api_host_elt_4_7(void); +void usb1_api_host_elt_4_8(void); +void usb1_api_host_elt_4_9(void); +void usb1_api_host_elt_get_desc(void); + +void usb1_host_EL_ModeInit(void); +void usb1_host_EL_SetUACT(void); +void usb1_host_EL_ClearUACT(void); +void usb1_host_EL_SetTESTMODE(uint16_t mode); +void usb1_host_EL_ClearNRDYSTS(uint16_t pipe); +uint16_t usb1_host_EL_GetINTSTS1(void); +void usb1_host_EL_UsbBusReset(void); +void usb1_host_EL_UsbAttach(void); +void usb1_host_EL_SetupStage(uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len); +void usb1_host_EL_StatusStage(void); +void usb1_host_EL_CtrlReadStart(uint32_t Bsize, uint8_t *Table); +int32_t usb1_host_EL_UsbSuspend(void); +int32_t usb1_host_EL_UsbResume(void); + +#if 0 /* prototype in devdrv_usb_host_api.h */ +uint16_t Userdef_USB_usb1_host_d0fifo_dmaintid(void); +uint16_t Userdef_USB_usb1_host_d1fifo_dmaintid(void); +void Userdef_USB_usb1_host_attach(void); +void Userdef_USB_usb1_host_detach(void); +void Userdef_USB_usb1_host_delay_1ms(void); +void Userdef_USB_usb1_host_delay_xms(uint32_t msec); +void Userdef_USB_usb1_host_delay_10us(uint32_t usec); +void Userdef_USB_usb1_host_delay_500ns(void); +void Userdef_USB_usb1_host_start_dma(USB_HOST_DMA_t *dma, uint16_t dfacc); +uint32_t Userdef_USB_usb1_host_stop_dma0(void); +uint32_t Userdef_USB_usb1_host_stop_dma1(void); +#endif + +#endif /* USB1_HOST_API_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/inc/usb1_host_dmacdrv.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,139 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_dmacdrv.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB1_HOST_DMACDRV_H +#define USB1_HOST_DMACDRV_H + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ +typedef struct dmac_transinfo +{ + uint32_t src_addr; /* Transfer source address */ + uint32_t dst_addr; /* Transfer destination address */ + uint32_t count; /* Transfer byte count */ + uint32_t src_size; /* Transfer source data size */ + uint32_t dst_size; /* Transfer destination data size */ + uint32_t saddr_dir; /* Transfer source address direction */ + uint32_t daddr_dir; /* Transfer destination address direction */ +} dmac_transinfo_t; + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +/* ==== Transfer specification of the sample program ==== */ +#define DMAC_SAMPLE_SINGLE (0) /* Single transfer */ +#define DMAC_SAMPLE_CONTINUATION (1) /* Continuous transfer (use REN bit) */ + +/* ==== DMA modes ==== */ +#define DMAC_MODE_REGISTER (0) /* Register mode */ +#define DMAC_MODE_LINK (1) /* Link mode */ + +/* ==== Transfer requests ==== */ +#define DMAC_REQ_MODE_EXT (0) /* External request */ +#define DMAC_REQ_MODE_PERI (1) /* On-chip peripheral module request */ +#define DMAC_REQ_MODE_SOFT (2) /* Auto-request (request by software) */ + +/* ==== DMAC transfer sizes ==== */ +#define DMAC_TRANS_SIZE_8 (0) /* 8 bits */ +#define DMAC_TRANS_SIZE_16 (1) /* 16 bits */ +#define DMAC_TRANS_SIZE_32 (2) /* 32 bits */ +#define DMAC_TRANS_SIZE_64 (3) /* 64 bits */ +#define DMAC_TRANS_SIZE_128 (4) /* 128 bits */ +#define DMAC_TRANS_SIZE_256 (5) /* 256 bits */ +#define DMAC_TRANS_SIZE_512 (6) /* 512 bits */ +#define DMAC_TRANS_SIZE_1024 (7) /* 1024 bits */ + +/* ==== Address increment for transferring ==== */ +#define DMAC_TRANS_ADR_NO_INC (1) /* Not increment */ +#define DMAC_TRANS_ADR_INC (0) /* Increment */ + +/* ==== Method for detecting DMA request ==== */ +#define DMAC_REQ_DET_FALL (0) /* Falling edge detection */ +#define DMAC_REQ_DET_RISE (1) /* Rising edge detection */ +#define DMAC_REQ_DET_LOW (2) /* Low level detection */ +#define DMAC_REQ_DET_HIGH (3) /* High level detection */ + +/* ==== Request Direction ==== */ +#define DMAC_REQ_DIR_SRC (0) /* DMAREQ is the source/ DMAACK is active when reading */ +#define DMAC_REQ_DIR_DST (1) /* DMAREQ is the destination/ DMAACK is active when writing */ + +/* ==== Descriptors ==== */ +#define DMAC_DESC_HEADER (0) /* Header */ +#define DMAC_DESC_SRC_ADDR (1) /* Source Address */ +#define DMAC_DESC_DST_ADDR (2) /* Destination Address */ +#define DMAC_DESC_COUNT (3) /* Transaction Byte */ +#define DMAC_DESC_CHCFG (4) /* Channel Confg */ +#define DMAC_DESC_CHITVL (5) /* Channel Interval */ +#define DMAC_DESC_CHEXT (6) /* Channel Extension */ +#define DMAC_DESC_LINK_ADDR (7) /* Link Address */ + +/* ==== On-chip peripheral module requests ===== */ +typedef enum dmac_request_factor +{ + DMAC_REQ_USB0_DMA0_TX, /* USB_0 channel 0 transmit FIFO empty */ + DMAC_REQ_USB0_DMA0_RX, /* USB_0 channel 0 receive FIFO full */ + DMAC_REQ_USB0_DMA1_TX, /* USB_0 channel 1 transmit FIFO empty */ + DMAC_REQ_USB0_DMA1_RX, /* USB_0 channel 1 receive FIFO full */ + DMAC_REQ_USB1_DMA0_TX, /* USB_1 channel 0 transmit FIFO empty */ + DMAC_REQ_USB1_DMA0_RX, /* USB_1 channel 0 receive FIFO full */ + DMAC_REQ_USB1_DMA1_TX, /* USB_1 channel 1 transmit FIFO empty */ + DMAC_REQ_USB1_DMA1_RX, /* USB_1 channel 1 receive FIFO full */ +} dmac_request_factor_t; + + +/******************************************************************************* +Variable Externs +*******************************************************************************/ + + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +void usb1_host_DMAC3_PeriReqInit(const dmac_transinfo_t *trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction); +int32_t usb1_host_DMAC3_Open(uint32_t req); +void usb1_host_DMAC3_Close(uint32_t *remain); +void usb1_host_DMAC3_Load_Set(uint32_t src_addr, uint32_t dst_addr, uint32_t count); + +void usb1_host_DMAC4_PeriReqInit(const dmac_transinfo_t *trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction); +int32_t usb1_host_DMAC4_Open(uint32_t req); +void usb1_host_DMAC4_Close(uint32_t *remain); +void usb1_host_DMAC4_Load_Set(uint32_t src_addr, uint32_t dst_addr, uint32_t count); + +#endif /* USB1_HOST_DMACDRV_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/src/common/usb1_host_dataio.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,2835 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_dataio.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +static uint16_t g_usb1_host_mbw[(USB_HOST_MAX_PIPE_NO + 1)]; + +static void usb1_host_start_receive_trns_c(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb1_host_start_receive_trns_d0(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb1_host_start_receive_trns_d1(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb1_host_start_receive_dma_d0(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb1_host_start_receive_dma_d1(uint16_t pipe, uint32_t size, uint8_t *data); +static uint16_t usb1_host_read_dma_d0(uint16_t pipe); +static uint16_t usb1_host_read_dma_d1(uint16_t pipe); +static uint16_t usb1_host_write_dma_d0(uint16_t pipe); +static uint16_t usb1_host_write_dma_d1(uint16_t pipe); + +static void usb1_host_read_c_fifo(uint16_t pipe, uint16_t count); +static void usb1_host_write_c_fifo(uint16_t Pipe, uint16_t count); +static void usb1_host_read_d0_fifo(uint16_t pipe, uint16_t count); +static void usb1_host_write_d0_fifo(uint16_t pipe, uint16_t count); +static void usb1_host_read_d1_fifo(uint16_t pipe, uint16_t count); +static void usb1_host_write_d1_fifo(uint16_t pipe, uint16_t count); + +static void usb1_host_clear_transaction_counter(uint16_t pipe); +static void usb1_host_set_transaction_counter(uint16_t pipe, uint32_t count); + +static uint32_t usb1_host_com_get_dmasize(uint32_t trncount, uint32_t dtptr); + +static uint16_t usb1_host_set_dfacc_d0(uint16_t mbw, uint32_t count); +static uint16_t usb1_host_set_dfacc_d1(uint16_t mbw, uint32_t count); + + +/******************************************************************************* +* Function Name: usb1_host_start_send_transfer +* Description : Starts the USB data communication using pipe specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data data Address +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_start_send_transfer (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t status; + uint16_t usefifo; + uint16_t mbw; + + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + usb1_host_clear_bemp_sts(pipe); + usb1_host_clear_brdy_sts(pipe); + usb1_host_clear_nrdy_sts(pipe); + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + + usefifo = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + case USB_HOST_D0FIFO_DMA: + usefifo = USB_HOST_D0USE; + break; + + case USB_HOST_D1FIFO_USE: + case USB_HOST_D1FIFO_DMA: + usefifo = USB_HOST_D1USE; + break; + + default: + usefifo = USB_HOST_CUSE; + break; + }; + + usb1_host_set_curpipe(USB_HOST_PIPE0, usefifo, USB_HOST_NO, mbw); + + usb1_host_clear_transaction_counter(pipe); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + status = usb1_host_write_buffer(pipe); + + if (status != USB_HOST_FIFOERROR) + { + usb1_host_set_pid_buf(pipe); + } + + return status; +} + +/******************************************************************************* +* Function Name: usb1_host_write_buffer +* Description : Writes data in the buffer allocated in the pipe specified by +* : the argument. The FIFO for using is set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_write_buffer (uint16_t pipe) +{ + uint16_t status; + uint16_t usefifo; + + g_usb1_host_PipeIgnore[pipe] = 0; + usefifo = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + status = usb1_host_write_buffer_d0(pipe); + break; + + case USB_HOST_D1FIFO_USE: + status = usb1_host_write_buffer_d1(pipe); + break; + + case USB_HOST_D0FIFO_DMA: + status = usb1_host_write_dma_d0(pipe); + break; + + case USB_HOST_D1FIFO_DMA: + status = usb1_host_write_dma_d1(pipe); + break; + + default: + status = usb1_host_write_buffer_c(pipe); + break; + }; + + switch (status) + { + case USB_HOST_WRITING: /* Continue of data write */ + usb1_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + usb1_host_enable_brdy_int(pipe); /* Enable Ready Interrupt */ + break; + + case USB_HOST_WRITEEND: /* End of data write */ + case USB_HOST_WRITESHRT: /* End of data write */ + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + + usb1_host_clear_nrdy_sts(pipe); + usb1_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + + /* for last transfer */ + usb1_host_enable_bemp_int(pipe); /* Enable Empty Interrupt */ + break; + + case USB_HOST_WRITEDMA: /* DMA write */ + usb1_host_clear_nrdy_sts(pipe); + usb1_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + usb1_host_disable_bemp_int(pipe); /* Disable Empty Interrupt */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_write_buffer_c +* Description : Writes data in the buffer allocated in the pipe specified in +* : the argument. Writes data by CPU transfer using CFIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_write_buffer_c (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + + if (pipe == USB_HOST_PIPE0) + { + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_CFIFO_WRITE, mbw); + } + else + { + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_NO, mbw); + } + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb1_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb1_host_write_c_fifo(pipe, (uint16_t)count); + + if (g_usb1_host_data_count[pipe] < (uint32_t)size) + { + g_usb1_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB201.CFIFOCTR, + USB_CFIFOCTR_BVAL_SHIFT, + USB_CFIFOCTR_BVAL) == 0) + { + USB201.CFIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb1_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_write_buffer_d0 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by CPU transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_write_buffer_d0 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D0USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb1_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb1_host_write_d0_fifo(pipe, (uint16_t)count); + + if (g_usb1_host_data_count[pipe] < (uint32_t)size) + { + g_usb1_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB201.D0FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + USB201.D0FIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb1_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_write_buffer_d1 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by CPU transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_write_buffer_d1 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D1USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb1_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb1_host_write_d1_fifo(pipe, (uint16_t)count); + + if (g_usb1_host_data_count[pipe] < (uint32_t)size) + { + g_usb1_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB201.D1FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + USB201.D1FIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb1_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_write_dma_d0 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by DMA transfer using D0FIFO. +* : The DMA-ch for using is specified by Userdef_USB_usb1_host_start_dma(). +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND : Write end +* : USB_HOST_WRITESHRT : short data +* : USB_HOST_WRITING : Continue of data write +* : USB_HOST_WRITEDMA : Write DMA +* : USB_HOST_FIFOERROR : FIFO status +*******************************************************************************/ +static uint16_t usb1_host_write_dma_d0 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + count = g_usb1_host_data_count[pipe]; + + if (count != 0) + { + g_usb1_host_DmaPipe[USB_HOST_D0FIFO] = pipe; + + if ((count % size) != 0) + { + g_usb1_host_DmaBval[USB_HOST_D0FIFO] = 1; + } + else + { + g_usb1_host_DmaBval[USB_HOST_D0FIFO] = 0; + } + + dfacc = usb1_host_set_dfacc_d0(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 0; /* 8bit transfer */ + } + + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].fifo = USB_HOST_D0FIFO_DMA; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].dir = USB_HOST_BUF2FIFO; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].buffer = (uint32_t)g_usb1_host_data_pointer[pipe]; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].bytes = count; + + Userdef_USB_usb1_host_start_dma(&g_usb1_host_DmaInfo[USB_HOST_D0FIFO], dfacc); + + usb1_host_set_curpipe2(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw, dfacc); + + RZA_IO_RegWrite_16(&USB201.D0FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + + g_usb1_host_data_count[pipe] = 0; + g_usb1_host_data_pointer[pipe] += count; + + status = USB_HOST_WRITEDMA; /* DMA write */ + } + else + { + if (RZA_IO_RegRead_16(&USB201.D0FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + RZA_IO_RegWrite_16(&USB201.D0FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); /* Short Packet */ + } + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_write_dma_d1 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by DMA transfer using D1FIFO. +* : The DMA-ch for using is specified by Userdef_USB_usb1_host_start_dma(). +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND : Write end +* : USB_HOST_WRITESHRT : short data +* : USB_HOST_WRITING : Continue of data write +* : USB_HOST_WRITEDMA : Write DMA +* : USB_HOST_FIFOERROR : FIFO status +*******************************************************************************/ +static uint16_t usb1_host_write_dma_d1 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + count = g_usb1_host_data_count[pipe]; + + if (count != 0) + { + g_usb1_host_DmaPipe[USB_HOST_D1FIFO] = pipe; + + if ((count % size) != 0) + { + g_usb1_host_DmaBval[USB_HOST_D1FIFO] = 1; + } + else + { + g_usb1_host_DmaBval[USB_HOST_D1FIFO] = 0; + } + + dfacc = usb1_host_set_dfacc_d1(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 0; /* 8bit transfer */ + } + + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].fifo = USB_HOST_D1FIFO_DMA; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].dir = USB_HOST_BUF2FIFO; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].buffer = (uint32_t)g_usb1_host_data_pointer[pipe]; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].bytes = count; + + Userdef_USB_usb1_host_start_dma(&g_usb1_host_DmaInfo[USB_HOST_D1FIFO], dfacc); + + usb1_host_set_curpipe2(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw , dfacc); + + RZA_IO_RegWrite_16(&USB201.D1FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + + g_usb1_host_data_count[pipe] = 0; + g_usb1_host_data_pointer[pipe] += count; + + status = USB_HOST_WRITEDMA; /* DMA write */ + } + else + { + if (RZA_IO_RegRead_16(&USB201.D1FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + RZA_IO_RegWrite_16(&USB201.D1FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); /* Short Packet */ + } + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_transfer +* Description : Starts USB data reception using the pipe specified in the argument. +* : The FIFO for using is set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +void usb1_host_start_receive_transfer (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t usefifo; + + usb1_host_clear_bemp_sts(pipe); + usb1_host_clear_brdy_sts(pipe); + usb1_host_clear_nrdy_sts(pipe); + + usefifo = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + usb1_host_start_receive_trns_d0(pipe, size, data); + break; + + case USB_HOST_D1FIFO_USE: + usb1_host_start_receive_trns_d1(pipe, size, data); + break; + + case USB_HOST_D0FIFO_DMA: + usb1_host_start_receive_dma_d0(pipe, size, data); + break; + + case USB_HOST_D1FIFO_DMA: + usb1_host_start_receive_dma_d1(pipe, size, data); + break; + + default: + usb1_host_start_receive_trns_c(pipe, size, data); + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_trns_c +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using CFIFO. +* : When storing data in the buffer allocated in the pipe specified in the +* : argument, BRDY interrupt is generated to read data +* : in the interrupt. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb1_host_start_receive_trns_c (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb1_host_set_pid_nak(pipe); + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_PipeIgnore[pipe] = 0; + + g_usb1_host_PipeDataSize[pipe] = size; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_CFIFO_READ, mbw); + USB201.CFIFOCTR = USB_HOST_BITBCLR; + + usb1_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + + usb1_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_trns_d0 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, BRDY interrupt is generated to read data in the +* : interrupt. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb1_host_start_receive_trns_d0 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb1_host_set_pid_nak(pipe); + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_PipeIgnore[pipe] = 0; + + g_usb1_host_PipeDataSize[pipe] = size; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, mbw); + + usb1_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + + usb1_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_trns_d1 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using D1FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, BRDY interrupt is generated to read data. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb1_host_start_receive_trns_d1 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb1_host_set_pid_nak(pipe); + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_PipeIgnore[pipe] = 0; + + g_usb1_host_PipeDataSize[pipe] = size; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, mbw); + + usb1_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + + usb1_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_dma_d0 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by DMA transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, delivered read request to DMAC to read data from +* : the buffer by DMAC. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb1_host_start_receive_dma_d0 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb1_host_set_pid_nak(pipe); + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_PipeIgnore[pipe] = 0; + + g_usb1_host_PipeDataSize[pipe] = 0; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, mbw); + + usb1_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + usb1_host_read_dma(pipe); + + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + } + else + { + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + } + + usb1_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_dma_d1 +* Description : Read data from the buffer allocated in the pipe specified in the argument. +* : Reads data by DMA transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, delivered read request to DMAC to read data from +* : the buffer by DMAC. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb1_host_start_receive_dma_d1 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb1_host_set_pid_nak(pipe); + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_PipeIgnore[pipe] = 0; + + g_usb1_host_PipeDataSize[pipe] = 0; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, mbw); + + usb1_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + usb1_host_read_dma(pipe); + + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + } + else + { + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + } + + usb1_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_read_buffer +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Uses FIF0 set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_read_buffer (uint16_t pipe) +{ + uint16_t status; + + g_usb1_host_PipeIgnore[pipe] = 0; + + if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_USE) + { + status = usb1_host_read_buffer_d0(pipe); + } + else if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_USE) + { + status = usb1_host_read_buffer_d1(pipe); + } + else + { + status = usb1_host_read_buffer_c(pipe); + } + + switch (status) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb1_host_disable_brdy_int(pipe); + g_usb1_host_PipeDataSize[pipe] -= g_usb1_host_data_count[pipe]; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + break; + + case USB_HOST_READOVER: /* buffer over */ + if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_USE) + { + USB201.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_USE) + { + USB201.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + USB201.CFIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#else + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; +#endif + g_usb1_host_PipeDataSize[pipe] -= g_usb1_host_data_count[pipe]; + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_buffer_c +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using CFIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_read_buffer_c (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb1_host_data_count[pipe]; + } + else if (g_usb1_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + } + + if (count == 0) /* 0 length packet */ + { + USB201.CFIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb1_host_read_c_fifo(pipe, (uint16_t)count); + } + + g_usb1_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_buffer_d0 +* Description : Reads data from the buffer allocated in the pipe specified in +* : the argument. +* : Reads data by CPU transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_read_buffer_d0 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t pipebuf_size; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D0USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb1_host_data_count[pipe]; + } + else if (g_usb1_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + else + { + pipebuf_size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + } + } + + if (count == 0) /* 0 length packet */ + { + USB201.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb1_host_read_d0_fifo(pipe, (uint16_t)count); + } + + g_usb1_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_buffer_d1 +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by CPU transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_read_buffer_d1 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t pipebuf_size; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D1USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb1_host_data_count[pipe]; + } + else if (g_usb1_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) !=0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + else + { + pipebuf_size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + } + } + + if (count == 0) /* 0 length packet */ + { + USB201.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb1_host_read_d1_fifo(pipe, (uint16_t)count); + } + + g_usb1_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_dma +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by DMA transfer using D0FIFO or D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_read_dma (uint16_t pipe) +{ + uint16_t status; + + g_usb1_host_PipeIgnore[pipe] = 0; + + if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_DMA) + { + status = usb1_host_read_dma_d0(pipe); + } + else + { + status = usb1_host_read_dma_d1(pipe); + } + + switch (status) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READZERO: /* End of data read */ + usb1_host_disable_brdy_int(pipe); + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb1_host_disable_brdy_int(pipe); + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + g_usb1_host_PipeDataSize[pipe] -= g_usb1_host_data_count[pipe]; + } + break; + + case USB_HOST_READOVER: /* buffer over */ + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + g_usb1_host_PipeDataSize[pipe] -= g_usb1_host_data_count[pipe]; + } +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#else + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; +#endif + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_dma_d0 +* Description : Writes data in the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by DMA transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +static uint16_t usb1_host_read_dma_d0 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + uint16_t pipebuf_size; + + g_usb1_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_READY; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + count = g_usb1_host_data_count[pipe]; + status = USB_HOST_READING; + } + else + { + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + count = g_usb1_host_data_count[pipe]; + } + else if (g_usb1_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + else + { + pipebuf_size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + } + } + + if (count == 0) /* 0 length packet */ + { + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + USB201.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + status = USB_HOST_READZERO; /* Null Packet receive */ + } + else + { + usb1_host_set_curpipe(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + /* transaction counter No set */ + /* FRDY = 1, DTLN = 0 -> BRDY */ + } + } + else + { + dfacc = usb1_host_set_dfacc_d0(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 0; /* 8bit transfer */ + } + + g_usb1_host_DmaPipe[USB_HOST_D0FIFO] = pipe; /* not use in read operation */ + g_usb1_host_DmaBval[USB_HOST_D0FIFO] = 0; /* not use in read operation */ + + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].fifo = USB_HOST_D0FIFO_DMA; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].dir = USB_HOST_FIFO2BUF; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].buffer = (uint32_t)g_usb1_host_data_pointer[pipe]; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].bytes = count; + + if (status == USB_HOST_READING) + { + g_usb1_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_BUSY; + } + else + { + g_usb1_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_BUSYEND; + } + + Userdef_USB_usb1_host_start_dma(&g_usb1_host_DmaInfo[USB_HOST_D0FIFO], dfacc); + + usb1_host_set_curpipe2(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw , dfacc); + + RZA_IO_RegWrite_16(&USB201.D0FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + g_usb1_host_data_count[pipe] -= count; + g_usb1_host_data_pointer[pipe] += count; + g_usb1_host_PipeDataSize[pipe] += count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_dma_d1 +* Description : Reads data from the buffer allocated in the pipe specified in +* : the argument. +* : Reads data by DMA transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +static uint16_t usb1_host_read_dma_d1 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + uint16_t pipebuf_size; + + g_usb1_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_READY; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + count = g_usb1_host_data_count[pipe]; + status = USB_HOST_READING; + } + else + { + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + count = g_usb1_host_data_count[pipe]; + } + else if (g_usb1_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + else + { + pipebuf_size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + } + } + + if (count == 0) /* 0 length packet */ + { + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + USB201.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + status = USB_HOST_READZERO; /* Null Packet receive */ + } + else + { + usb1_host_set_curpipe(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + /* transaction counter No set */ + /* FRDY = 1, DTLN = 0 -> BRDY */ + } + } + else + { + dfacc = usb1_host_set_dfacc_d1(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 0; /* 8bit transfer */ + } + + g_usb1_host_DmaPipe[USB_HOST_D1FIFO] = pipe; /* not use in read operation */ + g_usb1_host_DmaBval[USB_HOST_D1FIFO] = 0; /* not use in read operation */ + + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].fifo = USB_HOST_D1FIFO_DMA; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].dir = USB_HOST_FIFO2BUF; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].buffer = (uint32_t)g_usb1_host_data_pointer[pipe]; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].bytes = count; + + if (status == USB_HOST_READING) + { + g_usb1_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_BUSY; + } + else + { + g_usb1_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_BUSYEND; + } + + Userdef_USB_usb1_host_start_dma(&g_usb1_host_DmaInfo[USB_HOST_D1FIFO], dfacc); + + usb1_host_set_curpipe2(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw , dfacc); + + RZA_IO_RegWrite_16(&USB201.D1FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + g_usb1_host_data_count[pipe] -= count; + g_usb1_host_data_pointer[pipe] += count; + g_usb1_host_PipeDataSize[pipe] += count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_change_fifo_port +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument. After allocating FIF0, waits in the software +* : till the corresponding pipe becomes ready. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* Return Value : USB_HOST_FIFOERROR ; Error +* : Others ; CFIFOCTR/D0FIFOCTR/D1FIFOCTR Register Value +*******************************************************************************/ +uint16_t usb1_host_change_fifo_port (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw) +{ + uint16_t buffer; + uint32_t loop; + volatile uint32_t loop2; + + usb1_host_set_curpipe(pipe, fifosel, isel, mbw); + + for (loop = 0; loop < 4; loop++) + { + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB201.CFIFOCTR; + break; + + case USB_HOST_D0USE: + case USB_HOST_D0DMA: + buffer = USB201.D0FIFOCTR; + break; + + case USB_HOST_D1USE: + case USB_HOST_D1DMA: + buffer = USB201.D1FIFOCTR; + break; + + default: + buffer = 0; + break; + } + + if ((buffer & USB_HOST_BITFRDY) == USB_HOST_BITFRDY) + { + return buffer; + } + + loop2 = 25; + + while (loop2-- > 0) + { + /* wait */ + } + } + + return USB_HOST_FIFOERROR; +} + +/******************************************************************************* +* Function Name: usb1_host_set_curpipe +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* Return Value : none +*******************************************************************************/ +void usb1_host_set_curpipe (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw) +{ + uint16_t buffer; + uint32_t loop; + volatile uint32_t loop2; + + g_usb1_host_mbw[pipe] = mbw; + + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB201.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(~isel & USB_HOST_BITISEL); + USB201.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(isel | pipe | mbw); + USB201.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D0DMA: + case USB_HOST_D0USE: + buffer = USB201.D0FIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + USB201.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB201.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D1DMA: + case USB_HOST_D1USE: + buffer = USB201.D1FIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + USB201.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB201.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + default: + break; + } + + /* Cautions !!! + * Depending on the external bus speed of CPU, you may need to wait for 450ns here. + * For details, please look at the data sheet. */ + loop2 = 100; + + while (loop2-- > 0) + { + /* wait */ + } +} + +/******************************************************************************* +* Function Name: usb1_host_set_curpipe2 +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument.(DFACC) +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* : uint16_t dfacc ; DFACC Access mode +* Return Value : none +*******************************************************************************/ +void usb1_host_set_curpipe2 (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw, uint16_t dfacc) +{ + uint16_t buffer; + uint32_t loop; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + uint32_t dummy; +#endif + volatile uint32_t loop2; + + g_usb1_host_mbw[pipe] = mbw; + + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB201.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(~isel & USB_HOST_BITISEL); + USB201.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(isel | pipe | mbw); + USB201.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D0DMA: + case USB_HOST_D0USE: + buffer = USB201.D0FIFOSEL; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + + if (dfacc != 0) + { + buffer |= (uint16_t)(USB_HOST_BITMBW_32); + } +#else + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); +#endif + USB201.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + +#ifdef __USB_HOST_DF_ACC_ENABLE__ + if (dfacc != 0) + { + dummy = USB201.D0FIFO.UINT32; + } +#endif + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB201.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D1DMA: + case USB_HOST_D1USE: + buffer = USB201.D1FIFOSEL; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + + if (dfacc != 0) + { + buffer |= (uint16_t)(USB_HOST_BITMBW_32); + } +#else + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); +#endif + USB201.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + +#ifdef __USB_HOST_DF_ACC_ENABLE__ + if (dfacc != 0) + { + dummy = USB201.D1FIFO.UINT32; + loop = dummy; // avoid warning. + } +#endif + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB201.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + default: + break; + } + + /* Cautions !!! + * Depending on the external bus speed of CPU, you may need to wait for 450ns here. + * For details, please look at the data sheet. */ + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } +} + +/******************************************************************************* +* Function Name: usb1_host_write_c_fifo +* Description : Writes data in CFIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_write_c_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB201.CFIFO.UINT8[HH] = *g_usb1_host_data_pointer[pipe]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB201.CFIFO.UINT16[H] = *((uint16_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB201.CFIFO.UINT32 = *((uint32_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_read_c_fifo +* Description : Reads data from CFIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_read_c_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb1_host_data_pointer[pipe] = USB201.CFIFO.UINT8[HH]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb1_host_data_pointer[pipe]) = USB201.CFIFO.UINT16[H]; + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb1_host_data_pointer[pipe]) = USB201.CFIFO.UINT32; + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_write_d0_fifo +* Description : Writes data in D0FIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_write_d0_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB201.D0FIFO.UINT8[HH] = *g_usb1_host_data_pointer[pipe]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB201.D0FIFO.UINT16[H] = *((uint16_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB201.D0FIFO.UINT32 = *((uint32_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_read_d0_fifo +* Description : Reads data from D0FIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating DOFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t Pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_read_d0_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb1_host_data_pointer[pipe] = USB201.D0FIFO.UINT8[HH]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb1_host_data_pointer[pipe]) = USB201.D0FIFO.UINT16[H]; + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb1_host_data_pointer[pipe]) = USB201.D0FIFO.UINT32; + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_write_d1_fifo +* Description : Writes data in D1FIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating D1FIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_write_d1_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB201.D1FIFO.UINT8[HH] = *g_usb1_host_data_pointer[pipe]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB201.D1FIFO.UINT16[H] = *((uint16_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB201.D1FIFO.UINT32 = *((uint32_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_read_d1_fifo +* Description : Reads data from D1FIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating D1FIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_read_d1_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb1_host_data_pointer[pipe] = USB201.D1FIFO.UINT8[HH]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb1_host_data_pointer[pipe]) = USB201.D1FIFO.UINT16[H]; + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb1_host_data_pointer[pipe]) = USB201.D1FIFO.UINT32; + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_com_get_dmasize +* Description : Calculates access width of DMA transfer by the argument to + return as the Return Value. +* Arguments : uint32_t trncount : transfer byte +* : uint32_t dtptr : transfer data pointer +* Return Value : DMA transfer size : 0 8bit +* : : 1 16bit +* : : 2 32bit +*******************************************************************************/ +static uint32_t usb1_host_com_get_dmasize (uint32_t trncount, uint32_t dtptr) +{ + uint32_t size; + + if (((trncount & 0x0001) != 0) || ((dtptr & 0x00000001) != 0)) + { + /* When transfer byte count is odd */ + /* or transfer data area is 8-bit alignment */ + size = 0; /* 8bit */ + } + else if (((trncount & 0x0003) != 0) || ((dtptr & 0x00000003) != 0)) + { + /* When the transfer byte count is multiples of 2 */ + /* or the transfer data area is 16-bit alignment */ + size = 1; /* 16bit */ + } + else + { + /* When the transfer byte count is multiples of 4 */ + /* or the transfer data area is 32-bit alignment */ + size = 2; /* 32bit */ + } + + return size; +} + +/******************************************************************************* +* Function Name: usb1_host_get_mbw +* Description : Calculates access width of DMA to return the value set in MBW. +* Arguments : uint32_t trncount : transfer byte +* : uint32_t dtptr : transfer data pointer +* Return Value : FIFO transfer size : USB_HOST_BITMBW_8 8bit +* : : USB_HOST_BITMBW_16 16bit +* : : USB_HOST_BITMBW_32 32bit +*******************************************************************************/ +uint16_t usb1_host_get_mbw (uint32_t trncount, uint32_t dtptr) +{ + uint32_t size; + uint16_t mbw; + + size = usb1_host_com_get_dmasize(trncount, dtptr); + + if (size == 0) + { + /* 8bit */ + mbw = USB_HOST_BITMBW_8; + } + else if (size == 1) + { + /* 16bit */ + mbw = USB_HOST_BITMBW_16; + } + else + { + /* 32bit */ + mbw = USB_HOST_BITMBW_32; + } + + return mbw; +} + +/******************************************************************************* +* Function Name: usb1_host_set_transaction_counter +* Description : Sets transaction counter by the argument(PIPEnTRN). +* : Clears transaction before setting to enable transaction counter setting. +* Arguments : uint16_t pipe ; Pipe number +* : uint32_t bsize : Data transfer size +* Return Value : none +*******************************************************************************/ +static void usb1_host_set_transaction_counter (uint16_t pipe, uint32_t bsize) +{ + uint16_t mxps; + uint16_t cnt; + + if (bsize == 0) + { + return; + } + + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if ((bsize % mxps) == 0) + { + cnt = (uint16_t)(bsize / mxps); + } + else + { + cnt = (uint16_t)((bsize / mxps) + 1); + } + + switch (pipe) + { + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE1TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE1TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE2TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE2TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE3TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE3TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE4TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE4TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE5TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE5TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE9TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE9TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_clear_transaction_counter +* Description : Clears the transaction counter by the argument. +* : After executing this function, the transaction counter is invalid. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb1_host_clear_transaction_counter (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE1TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE2TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE3TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE4TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE5TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE9TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_stop_transfer +* Description : Stops the USB transfer in the pipe specified by the argument. +* : After stopping the USB transfer, clears the buffer allocated in +* : the pipe. +* : After executing this function, allocation in FIF0 becomes USB_HOST_PIPE0; +* : invalid. After executing this function, BRDY/NRDY/BEMP interrupt +* : in the corresponding pipe becomes invalid. Sequence bit is also +* : cleared. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_stop_transfer (uint16_t pipe) +{ + uint16_t usefifo; + uint32_t remain; + + usb1_host_set_pid_nak(pipe); + + usefifo = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + usb1_host_clear_transaction_counter(pipe); + USB201.D0FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D1FIFO_USE: + usb1_host_clear_transaction_counter(pipe); + USB201.D1FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D0FIFO_DMA: + remain = Userdef_USB_usb1_host_stop_dma0(); + usb1_host_dma_stop_d0(pipe, remain); + usb1_host_clear_transaction_counter(pipe); + USB201.D0FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D1FIFO_DMA: + remain = Userdef_USB_usb1_host_stop_dma1(); + usb1_host_dma_stop_d1(pipe, remain); + usb1_host_clear_transaction_counter(pipe); + USB201.D1FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + default: + usb1_host_clear_transaction_counter(pipe); + USB201.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + } + + /* Interrupt of pipe set is disabled */ + usb1_host_disable_brdy_int(pipe); + usb1_host_disable_nrdy_int(pipe); + usb1_host_disable_bemp_int(pipe); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + usb1_host_set_csclr(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_set_dfacc_d0 +* Description : Sets the DFACC setting value in D0FIFO using the transfer size. +* Arguments : uint16_t mbw ; MBW +* : uint16_t count ; data count +* Return Value : DFACC Access mode +*******************************************************************************/ +static uint16_t usb1_host_set_dfacc_d0 (uint16_t mbw, uint32_t count) +{ + uint16_t dfacc = 0; + +#ifndef __USB_HOST_DF_ACC_ENABLE__ + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; +#else + if (mbw == USB_HOST_BITMBW_32) + { + if ((count % 32) == 0) + { + /* 32byte transfer */ + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 2, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 2; + } + else if ((count % 16) == 0) + { + /* 16byte transfer */ + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 1, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 1; + } + else + { + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + } + else if (mbw == USB_HOST_BITMBW_16) + { + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + else + { + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } +#endif + + return dfacc; +} + +/******************************************************************************* +* Function Name: usb1_host_set_dfacc_d1 +* Description : Sets the DFACC setting value in D0FIFO using the transfer size. +* Arguments : uint16_t mbw ; MBW +* : uint16_t count ; data count +* Return Value : DFACC Access mode +*******************************************************************************/ +static uint16_t usb1_host_set_dfacc_d1 (uint16_t mbw, uint32_t count) +{ + uint16_t dfacc = 0; + +#ifndef __USB_HOST_DF_ACC_ENABLE__ + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; +#else + if (mbw == USB_HOST_BITMBW_32) + { + if ((count % 32) == 0) + { + /* 32byte transfer */ + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 2, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 2; + } + else if ((count % 16) == 0) + { + /* 16byte transfer */ + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 1, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 1; + } + else + { + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + } + else if (mbw == USB_HOST_BITMBW_16) + { + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + else + { + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } +#endif + + return dfacc; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/src/common/usb1_host_dma.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,355 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_dma.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +/* #include "usb1_host_dmacdrv.h" */ + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +static void usb1_host_dmaint(uint16_t fifo); +static void usb1_host_dmaint_buf2fifo(uint16_t pipe); +static void usb1_host_dmaint_fifo2buf(uint16_t pipe); + + +/******************************************************************************* +* Function Name: usb1_host_dma_stop_d0 +* Description : D0FIFO DMA stop +* Arguments : uint16_t pipe : pipe number +* : uint32_t remain : transfer byte +* Return Value : none +*******************************************************************************/ +void usb1_host_dma_stop_d0 (uint16_t pipe, uint32_t remain) +{ + uint16_t dtln; + uint16_t dfacc; + uint16_t buffer; + uint16_t sds_b = 1; + + dfacc = RZA_IO_RegRead_16(&USB201.D0FBCFG, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + if (dfacc == 2) + { + sds_b = 32; + } + else if (dfacc == 1) + { + sds_b = 16; + } + else + { + if (g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size == 2) + { + sds_b = 4; + } + else if (g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size == 1) + { + sds_b = 2; + } + else + { + sds_b = 1; + } + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + if (g_usb1_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + buffer = USB201.D0FIFOCTR; + dtln = (buffer & USB_HOST_BITDTLN); + + if ((dtln % sds_b) != 0) + { + remain += (sds_b - (dtln % sds_b)); + } + g_usb1_host_PipeDataSize[pipe] = (g_usb1_host_data_count[pipe] - remain); + g_usb1_host_data_count[pipe] = remain; + } + } + + RZA_IO_RegWrite_16(&USB201.D0FIFOSEL, + 0, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); +} + +/******************************************************************************* +* Function Name: usb1_host_dma_stop_d1 +* Description : D1FIFO DMA stop +* Arguments : uint16_t pipe : pipe number +* : uint32_t remain : transfer byte +* Return Value : none +*******************************************************************************/ +void usb1_host_dma_stop_d1 (uint16_t pipe, uint32_t remain) +{ + uint16_t dtln; + uint16_t dfacc; + uint16_t buffer; + uint16_t sds_b = 1; + + dfacc = RZA_IO_RegRead_16(&USB201.D1FBCFG, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + if (dfacc == 2) + { + sds_b = 32; + } + else if (dfacc == 1) + { + sds_b = 16; + } + else + { + if (g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size == 2) + { + sds_b = 4; + } + else if (g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size == 1) + { + sds_b = 2; + } + else + { + sds_b = 1; + } + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + if (g_usb1_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + buffer = USB201.D1FIFOCTR; + dtln = (buffer & USB_HOST_BITDTLN); + + if ((dtln % sds_b) != 0) + { + remain += (sds_b - (dtln % sds_b)); + } + g_usb1_host_PipeDataSize[pipe] = (g_usb1_host_data_count[pipe] - remain); + g_usb1_host_data_count[pipe] = remain; + } + } + + RZA_IO_RegWrite_16(&USB201.D1FIFOSEL, + 0, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); +} + +/******************************************************************************* +* Function Name: usb1_host_dma_interrupt_d0fifo +* Description : This function is DMA interrupt handler entry. +* : Execute usb1_host_dmaint() after disabling DMA interrupt in this function. +* : Disable DMA interrupt to DMAC executed when USB_HOST_D0FIFO_DMA is +* : specified by dma->fifo. +* : Register this function as DMA complete interrupt. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb1_host_dma_interrupt_d0fifo (uint32_t int_sense) +{ + usb1_host_dmaint(USB_HOST_D0FIFO); + g_usb1_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_READY; +} + +/******************************************************************************* +* Function Name: usb1_host_dma_interrupt_d1fifo +* Description : This function is DMA interrupt handler entry. +* : Execute usb0_host_dmaint() after disabling DMA interrupt in this function. +* : Disable DMA interrupt to DMAC executed when USB_HOST_D1FIFO_DMA is +* : specified by dma->fifo. +* : Register this function as DMA complete interrupt. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb1_host_dma_interrupt_d1fifo (uint32_t int_sense) +{ + usb1_host_dmaint(USB_HOST_D1FIFO); + g_usb1_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_READY; +} + +/******************************************************************************* +* Function Name: usb1_host_dmaint +* Description : This function is DMA transfer end interrupt +* Arguments : uint16_t fifo ; fifo number +* : ; USB_HOST_D0FIFO +* : ; USB_HOST_D1FIFO +* Return Value : none +*******************************************************************************/ +static void usb1_host_dmaint (uint16_t fifo) +{ + uint16_t pipe; + + pipe = g_usb1_host_DmaPipe[fifo]; + + if (g_usb1_host_DmaInfo[fifo].dir == USB_HOST_BUF2FIFO) + { + usb1_host_dmaint_buf2fifo(pipe); + } + else + { + usb1_host_dmaint_fifo2buf(pipe); + } +} + +/******************************************************************************* +* Function Name: usb1_host_dmaint_fifo2buf +* Description : Executes read completion from FIFO by DMAC. +* Arguments : uint16_t pipe : pipe number +* Return Value : none +*******************************************************************************/ +static void usb1_host_dmaint_fifo2buf (uint16_t pipe) +{ + uint32_t remain; + uint16_t useport; + + if (g_usb1_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + useport = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + if (useport == USB_HOST_D0FIFO_DMA) + { + remain = Userdef_USB_usb1_host_stop_dma0(); + usb1_host_dma_stop_d0(pipe, remain); + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + if (g_usb1_host_DmaStatus[USB_HOST_D0FIFO] == USB_HOST_DMA_BUSYEND) + { + USB201.D0FIFOCTR = USB_HOST_BITBCLR; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + else + { + usb1_host_enable_brdy_int(pipe); + } + } + } + else + { + remain = Userdef_USB_usb1_host_stop_dma1(); + usb1_host_dma_stop_d1(pipe, remain); + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + if (g_usb1_host_DmaStatus[USB_HOST_D1FIFO] == USB_HOST_DMA_BUSYEND) + { + USB201.D1FIFOCTR = USB_HOST_BITBCLR; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + else + { + usb1_host_enable_brdy_int(pipe); + } + } + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_dmaint_buf2fifo +* Description : Executes write completion in FIFO by DMAC. +* Arguments : uint16_t pipe : pipe number +* Return Value : none +*******************************************************************************/ +static void usb1_host_dmaint_buf2fifo (uint16_t pipe) +{ + uint16_t useport; + uint32_t remain; + + useport = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + if (useport == USB_HOST_D0FIFO_DMA) + { + remain = Userdef_USB_usb1_host_stop_dma0(); + usb1_host_dma_stop_d0(pipe, remain); + + if (g_usb1_host_DmaBval[USB_HOST_D0FIFO] != 0) + { + RZA_IO_RegWrite_16(&USB201.D0FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); + } + } + else + { + remain = Userdef_USB_usb1_host_stop_dma1(); + usb1_host_dma_stop_d1(pipe, remain); + + if (g_usb1_host_DmaBval[USB_HOST_D1FIFO] != 0) + { + RZA_IO_RegWrite_16(&USB201.D1FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); + } + } + + usb1_host_enable_bemp_int(pipe); +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/src/common/usb1_host_intrn.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,285 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_intrn.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#if(1) /* ohci_wrapp */ +#include "ohci_wrapp_RZ_A1_local.h" +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_brdy_int +* Description : Executes BRDY interrupt(USB_HOST_PIPE1-9). +* : According to the pipe that interrupt is generated in, +* : reads/writes buffer allocated in the pipe. +* : This function is executed in the BRDY interrupt handler. +* : This function clears BRDY interrupt status and BEMP interrupt +* : status. +* Arguments : uint16_t status ; BRDYSTS Register Value +* : uint16_t int_enb ; BRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_brdy_int (uint16_t status, uint16_t int_enb) +{ + uint32_t int_sense = 0; + uint16_t pipe; + uint16_t pipebit; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + pipebit = g_usb1_host_bit_set[pipe]; + + if ((status & pipebit) && (int_enb & pipebit)) + { + USB201.BRDYSTS = (uint16_t)~pipebit; + USB201.BEMPSTS = (uint16_t)~pipebit; + + if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_DMA) + { + if (g_usb1_host_DmaStatus[USB_HOST_D0FIFO] != USB_HOST_DMA_READY) + { + usb1_host_dma_interrupt_d0fifo(int_sense); + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + usb1_host_read_dma(pipe); + usb1_host_disable_brdy_int(pipe); + } + else + { + USB201.D0FIFOCTR = USB_HOST_BITBCLR; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + } + else if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_DMA) + { + if (g_usb1_host_DmaStatus[USB_HOST_D1FIFO] != USB_HOST_DMA_READY) + { + usb1_host_dma_interrupt_d1fifo(int_sense); + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + usb1_host_read_dma(pipe); + usb1_host_disable_brdy_int(pipe); + } + else + { + USB201.D1FIFOCTR = USB_HOST_BITBCLR; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + } + else + { + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 0) + { + usb1_host_read_buffer(pipe); + } + else + { + usb1_host_write_buffer(pipe); + } + } +#if(1) /* ohci_wrapp */ + switch (g_usb1_host_pipe_status[pipe]) + { + case USB_HOST_PIPE_DONE: + ohciwrapp_loc_TransEnd(pipe, TD_CC_NOERROR); + break; + case USB_HOST_PIPE_NORES: + case USB_HOST_PIPE_STALL: + case USB_HOST_PIPE_ERROR: + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); + break; + default: + /* Do Nothing */ + break; + } +#endif + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_nrdy_int +* Description : Executes NRDY interrupt(USB_HOST_PIPE1-9). +* : Checks NRDY interrupt cause by PID. When the cause if STALL, +* : regards the pipe state as STALL and ends the processing. +* : Then the cause is not STALL, increments the error count to +* : communicate again. When the error count is 3, determines +* : the pipe state as USB_HOST_PIPE_NORES and ends the processing. +* : This function is executed in the NRDY interrupt handler. +* : This function clears NRDY interrupt status. +* Arguments : uint16_t status ; NRDYSTS Register Value +* : uint16_t int_enb ; NRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_nrdy_int (uint16_t status, uint16_t int_enb) +{ + uint16_t pid; + uint16_t pipe; + uint16_t bitcheck; + + bitcheck = (uint16_t)(status & int_enb); + + USB201.NRDYSTS = (uint16_t)~status; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + if ((bitcheck&g_usb1_host_bit_set[pipe]) == g_usb1_host_bit_set[pipe]) + { + if (RZA_IO_RegRead_16(&USB201.SYSCFG0, + USB_SYSCFG_DCFM_SHIFT, + USB_SYSCFG_DCFM) == 1) + { + if (g_usb1_host_pipe_status[pipe] == USB_HOST_PIPE_WAIT) + { + pid = usb1_host_get_pid(pipe); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_STALL; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); +#endif + } + else + { +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_NORES; + ohciwrapp_loc_TransEnd(pipe, TD_CC_DEVICENOTRESPONDING); +#else + g_usb1_host_PipeIgnore[pipe]++; + + if (g_usb1_host_PipeIgnore[pipe] == 3) + { + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_NORES; + } + else + { + usb1_host_set_pid_buf(pipe); + } +#endif + } + } + } + else + { + /* USB Function */ + } + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_bemp_int +* Description : Executes BEMP interrupt(USB_HOST_PIPE1-9). +* Arguments : uint16_t status ; BEMPSTS Register Value +* : uint16_t int_enb ; BEMPENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_bemp_int (uint16_t status, uint16_t int_enb) +{ + uint16_t pid; + uint16_t pipe; + uint16_t bitcheck; + uint16_t inbuf; + + bitcheck = (uint16_t)(status & int_enb); + + USB201.BEMPSTS = (uint16_t)~status; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + if ((bitcheck&g_usb1_host_bit_set[pipe]) == g_usb1_host_bit_set[pipe]) + { + pid = usb1_host_get_pid(pipe); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_STALL; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); +#endif + } + else + { + inbuf = usb1_host_get_inbuf(pipe); + + if (inbuf == 0) + { + usb1_host_disable_bemp_int(pipe); + usb1_host_set_pid_nak(pipe); + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_NOERROR); +#endif + } + } + } + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/src/common/usb1_host_lib.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,1598 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_lib.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#if(1) /* ohci_wrapp */ +#include "MBRZA1H.h" /* INTC Driver Header */ +#else +#include "devdrv_intc.h" /* INTC Driver Header */ +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_enable_brdy_int +* Description : Enables BRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : BRDY. Enables BRDY interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_enable_brdy_int (uint16_t pipe) +{ + /* enable brdy interrupt */ + USB201.BRDYENB |= (uint16_t)g_usb1_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb1_host_disable_brdy_int +* Description : Disables BRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : BRDY. Enables BRDY interrupt in the pipe specified by the argument +* : in the disabled status. After disabling BRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_disable_brdy_int (uint16_t pipe) +{ + /* disable brdy interrupt */ + USB201.BRDYENB &= (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_clear_brdy_sts +* Description : Clear BRDY interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_clear_brdy_sts (uint16_t pipe) +{ + /* clear brdy status */ + USB201.BRDYSTS = (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_enable_bemp_int +* Description : Enables BEMP interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : BEMP. Enables BEMP interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BEMP, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_enable_bemp_int (uint16_t pipe) +{ + /* enable bemp interrupt */ + USB201.BEMPENB |= (uint16_t)g_usb1_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb1_host_disable_bemp_int +* Description : Disables BEMP interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : BEMP. Enables BEMP interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BEMP, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_disable_bemp_int (uint16_t pipe) +{ + /* disable bemp interrupt */ + USB201.BEMPENB &= (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_clear_bemp_sts +* Description : Clear BEMP interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_clear_bemp_sts (uint16_t pipe) +{ + /* clear bemp status */ + USB201.BEMPSTS = (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_enable_nrdy_int +* Description : Enables NRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : NRDY. Enables NRDY interrupt in the pipe specified by the argument +* : in the disabled status. After enabling NRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_enable_nrdy_int (uint16_t pipe) +{ + /* enable nrdy interrupt */ + USB201.NRDYENB |= (uint16_t)g_usb1_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb1_host_disable_nrdy_int +* Description : Disables NRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : NRDY. Disables NRDY interrupt in the pipe specified by the argument +* : in the disabled status. After disabling NRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_disable_nrdy_int (uint16_t pipe) +{ + /* disable nrdy interrupt */ + USB201.NRDYENB &= (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_clear_nrdy_sts +* Description : Clear NRDY interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_clear_nrdy_sts (uint16_t pipe) +{ + /* clear nrdy status */ + USB201.NRDYSTS = (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_is_hispeed +* Description : Returns the result of USB reset hand shake (RHST) as +* : return value. +* Arguments : none +* Return Value : USB_HOST_HIGH_SPEED ; Hi-Speed +* : USB_HOST_FULL_SPEED ; Full-Speed +* : USB_HOST_LOW_SPEED ; Low-Speed +* : USB_HOST_NON_SPEED ; error +*******************************************************************************/ +uint16_t usb1_host_is_hispeed (void) +{ + uint16_t rhst; + uint16_t speed; + + rhst = RZA_IO_RegRead_16(&USB201.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (rhst == USB_HOST_HSMODE) + { + speed = USB_HOST_HIGH_SPEED; + } + else if (rhst == USB_HOST_FSMODE) + { + speed = USB_HOST_FULL_SPEED; + } + else if (rhst == USB_HOST_LSMODE) + { + speed = USB_HOST_LOW_SPEED; + } + else + { + speed = USB_HOST_NON_SPEED; + } + + return speed; +} + +/******************************************************************************* +* Function Name: usb1_host_is_hispeed_enable +* Description : Returns the USB High-Speed connection enabled status as +* : return value. +* Arguments : none +* Return Value : USB_HOST_YES : Hi-Speed Enable +* : USB_HOST_NO : Hi-Speed Disable +*******************************************************************************/ +uint16_t usb1_host_is_hispeed_enable (void) +{ + uint16_t ret; + + ret = USB_HOST_NO; + + if (RZA_IO_RegRead_16(&USB201.SYSCFG0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE) == 1) + { + ret = USB_HOST_YES; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_host_set_pid_buf +* Description : Enables communicaqtion in the pipe specified by the argument +* : (BUF). +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_pid_buf (uint16_t pipe) +{ + uint16_t pid; + + pid = usb1_host_get_pid(pipe); + + if (pid == USB_HOST_PID_STALL2) + { + usb1_host_set_pid_nak(pipe); + } + + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + USB_HOST_PID_BUF, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_set_pid_nak +* Description : Disables communication (NAK) in the pipe specified by the argument. +* : When the pipe status was enabling communication (BUF) before +* : executing before executing this function, waits in the software +* : until the pipe becomes ready after setting disabled. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_pid_nak (uint16_t pipe) +{ + uint16_t pid; + uint16_t pbusy; + uint32_t loop; + + pid = usb1_host_get_pid(pipe); + + if (pid == USB_HOST_PID_STALL2) + { + usb1_host_set_pid_stall(pipe); + } + + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + USB_HOST_PID_NAK, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + + if (pid == USB_HOST_PID_BUF) + { + for (loop = 0; loop < 200; loop++) + { + switch (pipe) + { + case USB_HOST_PIPE0: + pbusy = RZA_IO_RegRead_16(&USB201.DCPCTR, + USB_DCPCTR_PBUSY_SHIFT, + USB_DCPCTR_PBUSY); + break; + + case USB_HOST_PIPE1: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE1CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE2: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE2CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE3: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE3CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE4: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE4CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE5: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE5CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE6: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE6CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE7: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE7CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE8: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE8CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE9: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE9CTR, + USB_PIPEnCTR_9_PBUSY_SHIFT, + USB_PIPEnCTR_9_PBUSY); + break; + + default: + pbusy = 1; + break; + } + + if (pbusy == 0) + { + break; + } + + Userdef_USB_usb1_host_delay_500ns(); + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_set_pid_stall +* Description : Disables communication (STALL) in the pipe specified by the +* : argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_pid_stall (uint16_t pipe) +{ + uint16_t pid; + + pid = usb1_host_get_pid(pipe); + + if (pid == USB_HOST_PID_BUF) + { + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + USB_HOST_PID_STALL2, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + } + else + { + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + USB_HOST_PID_STALL, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_clear_pid_stall +* Description : Disables communication (NAK) in the pipe specified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_clear_pid_stall (uint16_t pipe) +{ + usb1_host_set_pid_nak(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_get_pid +* Description : Returns the pipe state specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : PID +*******************************************************************************/ +uint16_t usb1_host_get_pid (uint16_t pipe) +{ + uint16_t pid; + + switch (pipe) + { + case USB_HOST_PIPE0: + pid = RZA_IO_RegRead_16(&USB201.DCPCTR, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + pid = RZA_IO_RegRead_16(&USB201.PIPE1CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + pid = RZA_IO_RegRead_16(&USB201.PIPE2CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + pid = RZA_IO_RegRead_16(&USB201.PIPE3CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + pid = RZA_IO_RegRead_16(&USB201.PIPE4CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + pid = RZA_IO_RegRead_16(&USB201.PIPE5CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + pid = RZA_IO_RegRead_16(&USB201.PIPE6CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + pid = RZA_IO_RegRead_16(&USB201.PIPE7CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + pid = RZA_IO_RegRead_16(&USB201.PIPE8CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + pid = RZA_IO_RegRead_16(&USB201.PIPE9CTR, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + pid = 0; + break; + } + + return pid; +} + +/******************************************************************************* +* Function Name: usb1_host_set_csclr +* Description : CSPLIT status clear setting of sprit transaction in specified +* : pipe is performed. +* : When SQSET bit or SQCLR bit, and SQSET bit or SQCLR bit +* : in DCPCTR register are continuously changed (when the sequence +* : toggle bit of data PID is continuously changed over two or more pipes), +* : the access cycle with 120 ns and more than 5 cycle bus clock is necessary. +* : Do not set both SQCLR bit and SQSET bit to 1 at the same time. +* : In addition, both bits should be operated after PID is set to NAK. +* : However, when it is set to the isochronous transfer as the transfer type +* : (TYPE=11), writing in SQSET bit is disabled. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_csclr (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + 1, + USB_DCPCTR_CSCLR_SHIFT, + USB_DCPCTR_CSCLR); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + 1, + USB_PIPEnCTR_9_CSCLR_SHIFT, + USB_PIPEnCTR_9_CSCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_set_sqclr +* Description : Sets the sequence bit of the pipe specified by the argument to +* : DATA0. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_sqclr (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + 1, + USB_DCPCTR_SQCLR_SHIFT, + USB_DCPCTR_SQCLR); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + 1, + USB_PIPEnCTR_9_SQCLR_SHIFT, + USB_PIPEnCTR_9_SQCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_set_sqset +* Description : Sets the sequence bit of the pipe specified by the argument to +* : DATA1. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_sqset (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + 1, + USB_DCPCTR_SQSET_SHIFT, + USB_DCPCTR_SQSET); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + 1, + USB_PIPEnCTR_9_SQSET_SHIFT, + USB_PIPEnCTR_9_SQSET); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_get_sqmon +* Description : Toggle bit of specified pipe is obtained +* Arguments : uint16_t pipe ; Pipe number +* Return Value : sqmon +*******************************************************************************/ +uint16_t usb1_host_get_sqmon (uint16_t pipe) +{ + uint16_t sqmon; + + switch (pipe) + { + case USB_HOST_PIPE0: + sqmon = RZA_IO_RegRead_16(&USB201.DCPCTR, + USB_DCPCTR_SQMON_SHIFT, + USB_DCPCTR_SQMON); + break; + + case USB_HOST_PIPE1: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE1CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE2: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE2CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE3: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE3CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE4: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE4CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE5: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE5CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE6: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE6CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE7: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE7CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE8: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE8CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE9: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE9CTR, + USB_PIPEnCTR_9_SQMON_SHIFT, + USB_PIPEnCTR_9_SQMON); + break; + + default: + sqmon = 0; + break; + } + + return sqmon; +} + +/******************************************************************************* +* Function Name: usb1_host_aclrm +* Description : The buffer of specified pipe is initialized +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb1_host_aclrm (uint16_t pipe) +{ + usb1_host_set_aclrm(pipe); + usb1_host_clr_aclrm(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_set_aclrm +* Description : The auto buffer clear mode of specified pipe is enabled +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb1_host_set_aclrm (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + 1, + USB_PIPEnCTR_9_ACLRM_SHIFT, + USB_PIPEnCTR_9_ACLRM); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_clr_aclrm +* Description : The auto buffer clear mode of specified pipe is enabled +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb1_host_clr_aclrm (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + 0, + USB_PIPEnCTR_9_ACLRM_SHIFT, + USB_PIPEnCTR_9_ACLRM); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_get_inbuf +* Description : Returns INBUFM of the pipe specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : inbuf +*******************************************************************************/ +uint16_t usb1_host_get_inbuf (uint16_t pipe) +{ + uint16_t inbuf; + + switch (pipe) + { + case USB_HOST_PIPE0: + inbuf = 0; + break; + + case USB_HOST_PIPE1: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE1CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE2: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE2CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE3: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE3CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE4: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE4CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE5: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE5CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE6: + inbuf = 0; + break; + + case USB_HOST_PIPE7: + inbuf = 0; + break; + + case USB_HOST_PIPE8: + inbuf = 0; + break; + + case USB_HOST_PIPE9: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE9CTR, + USB_PIPEnCTR_9_INBUFM_SHIFT, + USB_PIPEnCTR_9_INBUFM); + break; + + default: + inbuf = 0; + break; + } + + return inbuf; +} + +/******************************************************************************* +* Function Name: usb1_host_setting_interrupt +* Description : Sets the USB module interrupt level. +* Arguments : uint8_t level ; interrupt level +* Return Value : none +*******************************************************************************/ +void usb1_host_setting_interrupt (uint8_t level) +{ +#if(1) /* ohci_wrapp */ + IRQn_Type d0fifo_dmaintid; + IRQn_Type d1fifo_dmaintid; + + InterruptHandlerRegister(USBI1_IRQn, usb1_host_interrupt); + GIC_SetPriority(USBI1_IRQn, level); + GIC_EnableIRQ(USBI1_IRQn); + + d0fifo_dmaintid = (IRQn_Type)Userdef_USB_usb1_host_d0fifo_dmaintid(); + + if (d0fifo_dmaintid != 0xFFFF) + { + InterruptHandlerRegister(d0fifo_dmaintid, usb1_host_dma_interrupt_d0fifo); + GIC_SetPriority(d0fifo_dmaintid, level); + GIC_EnableIRQ(d0fifo_dmaintid); + } + + d1fifo_dmaintid = (IRQn_Type)Userdef_USB_usb1_host_d1fifo_dmaintid(); + + if (d1fifo_dmaintid != 0xFFFF) + { + InterruptHandlerRegister(d1fifo_dmaintid, usb1_host_dma_interrupt_d1fifo); + GIC_SetPriority(d1fifo_dmaintid, level); + GIC_EnableIRQ(d1fifo_dmaintid); + } +#else + uint16_t d0fifo_dmaintid; + uint16_t d1fifo_dmaintid; + + R_INTC_RegistIntFunc(INTC_ID_USBI1, usb1_host_interrupt); + R_INTC_SetPriority(INTC_ID_USBI1, level); + R_INTC_Enable(INTC_ID_USBI1); + + d0fifo_dmaintid = Userdef_USB_usb1_host_d0fifo_dmaintid(); + + if (d0fifo_dmaintid != 0xFFFF) + { + R_INTC_RegistIntFunc(d0fifo_dmaintid, usb1_host_dma_interrupt_d0fifo); + R_INTC_SetPriority(d0fifo_dmaintid, level); + R_INTC_Enable(d0fifo_dmaintid); + } + + d1fifo_dmaintid = Userdef_USB_usb1_host_d1fifo_dmaintid(); + + if (d1fifo_dmaintid != 0xFFFF) + { + R_INTC_RegistIntFunc(d1fifo_dmaintid, usb1_host_dma_interrupt_d1fifo); + R_INTC_SetPriority(d1fifo_dmaintid, level); + R_INTC_Enable(d1fifo_dmaintid); + } +#endif +} + +/******************************************************************************* +* Function Name: usb1_host_reset_module +* Description : Initializes the USB module. +* : Enables providing clock to the USB module. +* : Sets USB bus wait register. +* Arguments : uint16_t clockmode ; 48MHz ; USBHCLOCK_X1_48MHZ +* : ; 12MHz ; USBHCLOCK_EXTAL_12MHZ +* Return Value : none +*******************************************************************************/ +void usb1_host_reset_module (uint16_t clockmode) +{ + if (RZA_IO_RegRead_16(&USB200.SYSCFG0, + USB_SYSCFG_UPLLE_SHIFT, + USB_SYSCFG_UPLLE) == 1) + { + if ((USB200.SYSCFG0 & USB_HOST_BITUCKSEL) != clockmode) + { + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + USB201.SYSCFG0 = 0; + USB200.SYSCFG0 = 0; + USB200.SYSCFG0 = (USB_HOST_BITUPLLE | clockmode); + Userdef_USB_usb1_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + else + { + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + Userdef_USB_usb1_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + } + else + { + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + USB201.SYSCFG0 = 0; + USB200.SYSCFG0 = 0; + USB200.SYSCFG0 = (USB_HOST_BITUPLLE | clockmode); + Userdef_USB_usb1_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + + USB201.BUSWAIT = (uint16_t)(USB_HOST_BUSWAIT_05 & USB_HOST_BITBWAIT); +} + +/******************************************************************************* +* Function Name: usb1_host_get_buf_size +* Description : Obtains pipe buffer size specified by the argument and +* : maximum packet size of the USB device in use. +* : When USB_HOST_PIPE0 is specified by the argument, obtains the maximum +* : packet size of the USB device using the corresponding pipe. +* : For the case that USB_HOST_PIPE0 is not assigned by the argument, when the +* : corresponding pipe is in continuous transfer mode, +* : obtains the buffer size allocated in the corresponcing pipe, +* : when incontinuous transfer, obtains maximum packet size. +* Arguments : uint16_t ; pipe Number +* Return Value : Maximum packet size or buffer size +*******************************************************************************/ +uint16_t usb1_host_get_buf_size (uint16_t pipe) +{ + uint16_t size; + uint16_t bufsize; + + if (pipe == USB_HOST_PIPE0) + { + size = RZA_IO_RegRead_16(&USB201.DCPMAXP, + USB_DCPMAXP_MXPS_SHIFT, + USB_DCPMAXP_MXPS); + } + else + { + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_CNTMD_SHIFT, USB_PIPECFG_CNTMD) == 1) + { + bufsize = RZA_IO_RegRead_16(&g_usb1_host_pipebuf[pipe], USB_PIPEBUF_BUFSIZE_SHIFT, USB_PIPEBUF_BUFSIZE); + size = (uint16_t)((bufsize + 1) * USB_HOST_PIPExBUF); + } + else + { + size = RZA_IO_RegRead_16(&g_usb1_host_pipemaxp[pipe], USB_PIPEMAXP_MXPS_SHIFT, USB_PIPEMAXP_MXPS); + } + } + return size; +} + +/******************************************************************************* +* Function Name: usb1_host_get_mxps +* Description : Obtains maximum packet size of the USB device using the pipe +* : specified by the argument. +* Arguments : uint16_t ; Pipe Number +* Return Value : Max Packet Size +*******************************************************************************/ +uint16_t usb1_host_get_mxps (uint16_t pipe) +{ + uint16_t size; + + if (pipe == USB_HOST_PIPE0) + { + size = RZA_IO_RegRead_16(&USB201.DCPMAXP, + USB_DCPMAXP_MXPS_SHIFT, + USB_DCPMAXP_MXPS); + } + else + { + size = RZA_IO_RegRead_16(&g_usb1_host_pipemaxp[pipe], USB_PIPEMAXP_MXPS_SHIFT, USB_PIPEMAXP_MXPS); + } + + return size; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/src/host/usb1_host_controlrw.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,434 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_controlrw.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_CtrlTransStart +* Description : Executes USB control transfer. +* Arguments : uint16_t devadr ; device address +* : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* : uint8_t *Buf ; Data buffer +* Return Value : DEVDRV_SUCCESS ; SUCCESS +* : DEVDRV_ERROR ; ERROR +*******************************************************************************/ +int32_t usb1_host_CtrlTransStart (uint16_t devadr, uint16_t Req, uint16_t Val, + uint16_t Indx, uint16_t Len, uint8_t * Buf) +{ + if (g_usb1_host_UsbDeviceSpeed == USB_HOST_LOW_SPEED) + { + RZA_IO_RegWrite_16(&USB201.SOFCFG, + 1, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + else + { + RZA_IO_RegWrite_16(&USB201.SOFCFG, + 0, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + + USB201.DCPMAXP = (uint16_t)((uint16_t)(devadr << 12) + g_usb1_host_default_max_packet[devadr]); + + if (g_usb1_host_pipe_status[USB_HOST_PIPE0] == USB_HOST_PIPE_IDLE) + { + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_WAIT; + g_usb1_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + g_usb1_host_CmdStage = (USB_HOST_STAGE_SETUP | USB_HOST_CMD_IDLE); + + if (Len == 0) + { + g_usb1_host_CmdStage |= USB_HOST_MODE_NO_DATA; /* No-data Control */ + } + else + { + if ((Req & 0x0080) != 0) + { + g_usb1_host_CmdStage |= USB_HOST_MODE_READ; /* Control Read */ + } + else + { + g_usb1_host_CmdStage |= USB_HOST_MODE_WRITE; /* Control Write */ + } + } + + g_usb1_host_SavReq = Req; /* save request */ + g_usb1_host_SavVal = Val; + g_usb1_host_SavIndx = Indx; + g_usb1_host_SavLen = Len; + } + else + { + if ((g_usb1_host_SavReq != Req) || (g_usb1_host_SavVal != Val) + || (g_usb1_host_SavIndx != Indx) || (g_usb1_host_SavLen != Len)) + { + return DEVDRV_ERROR; + } + } + + switch ((g_usb1_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + /* --------------- SETUP STAGE --------------- */ + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_IDLE): + usb1_host_SetupStage(Req, Val, Indx, Len); + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_DONE): /* goto next stage */ + g_usb1_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + switch ((g_usb1_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_WRITE: + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_DATA; + break; + + case USB_HOST_MODE_READ: + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_DATA; + break; + + case USB_HOST_MODE_NO_DATA: + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_STATUS; + break; + + default: + break; + } + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_NORES): + if (g_usb1_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb1_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_IDLE; + } + break; + + /* --------------- DATA STAGE --------------- */ + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_IDLE): + switch ((g_usb1_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_WRITE: + usb1_host_CtrlWriteStart((uint32_t)Len, Buf); + break; + + case USB_HOST_MODE_READ: + usb1_host_CtrlReadStart((uint32_t)Len, Buf); + break; + + default: + break; + } + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DONE): /* goto next stage */ + g_usb1_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_STATUS; + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_NORES): + if (g_usb1_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb1_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DOING; + usb1_host_clear_pid_stall(USB_HOST_PIPE0); + usb1_host_set_pid_buf(USB_HOST_PIPE0); + } + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_STALL): + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + break; + + /* --------------- STATUS STAGE --------------- */ + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_IDLE): + usb1_host_StatusStage(); + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DONE): /* end of Control transfer */ + usb1_host_set_pid_nak(USB_HOST_PIPE0); + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_DONE; /* exit DONE */ + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_NORES): + if (g_usb1_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb1_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DOING; + usb1_host_clear_pid_stall(USB_HOST_PIPE0); + usb1_host_set_pid_buf(USB_HOST_PIPE0); + } + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_STALL): + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + break; + + default: + break; + } + + if (g_usb1_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_WAIT) + { + RZA_IO_RegWrite_16(&USB201.SOFCFG, + 0, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb1_host_SetupStage +* Description : Executes USB control transfer/set up stage. +* Arguments : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* Return Value : none +*******************************************************************************/ +void usb1_host_SetupStage (uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len) +{ + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DOING; + + USB201.INTSTS1 = (uint16_t)~(USB_HOST_BITSACK | USB_HOST_BITSIGN); /* Status Clear */ + USB201.USBREQ = Req; + USB201.USBVAL = Val; + USB201.USBINDX = Indx; + USB201.USBLENG = Len; + USB201.DCPCTR = USB_HOST_BITSUREQ; /* PID=NAK & Send Setup */ +} + +/******************************************************************************* +* Function Name: usb1_host_StatusStage +* Description : Executes USB control transfer/status stage. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_StatusStage (void) +{ + uint8_t Buf1[16]; + + switch ((g_usb1_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_READ: + usb1_host_CtrlWriteStart((uint32_t)0, (uint8_t*)&Buf1); + break; + + case USB_HOST_MODE_WRITE: + usb1_host_CtrlReadStart((uint32_t)0, (uint8_t*)&Buf1); + break; + + case USB_HOST_MODE_NO_DATA: + usb1_host_CtrlReadStart((uint32_t)0, (uint8_t*)&Buf1); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_CtrlWriteStart +* Description : Executes USB control transfer/data stage(write). +* Arguments : uint32_t Bsize ; Data Size +* : uint8_t *Table ; Data Table Address +* Return Value : USB_HOST_WRITESHRT ; End of data write +* : USB_HOST_WRITEEND ; End of data write (not null) +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_FIFOERROR ; FIFO access error +*******************************************************************************/ +uint16_t usb1_host_CtrlWriteStart (uint32_t Bsize, uint8_t * Table) +{ + uint16_t EndFlag_K; + uint16_t mbw; + + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DOING; + + usb1_host_set_pid_nak(USB_HOST_PIPE0); /* Set NAK */ + g_usb1_host_data_count[USB_HOST_PIPE0] = Bsize; /* Transfer size set */ + g_usb1_host_data_pointer[USB_HOST_PIPE0] = Table; /* Transfer address set */ + + USB201.DCPCTR = USB_HOST_BITSQSET; /* SQSET=1, PID=NAK */ +#if(1) /* ohci_wrapp */ + Userdef_USB_usb1_host_delay_10us(3); +#endif + RZA_IO_RegWrite_16(&USB201.DCPCFG, + 1, + USB_DCPCFG_DIR_SHIFT, + USB_DCPCFG_DIR); + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[USB_HOST_PIPE0], (uint32_t)g_usb1_host_data_pointer[USB_HOST_PIPE0]); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_BITISEL, mbw); + USB201.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + + usb1_host_clear_pid_stall(USB_HOST_PIPE0); + EndFlag_K = usb1_host_write_buffer_c(USB_HOST_PIPE0); + /* Host Control sequence */ + switch (EndFlag_K) + { + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_STATUS; + usb1_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb1_host_enable_bemp_int(USB_HOST_PIPE0); /* Enable Empty Interrupt */ + break; + + case USB_HOST_WRITEEND: /* End of data write (not null) */ + case USB_HOST_WRITING: /* Continue of data write */ + usb1_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb1_host_enable_bemp_int(USB_HOST_PIPE0); /* Enable Empty Interrupt */ + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + break; + + default: + break; + } + usb1_host_set_pid_buf(USB_HOST_PIPE0); /* Set BUF */ + return (EndFlag_K); /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_CtrlReadStart +* Description : Executes USB control transfer/data stage(read). +* Arguments : uint32_t Bsize ; Data Size +* : uint8_t *Table ; Data Table Address +* Return Value : none +*******************************************************************************/ +void usb1_host_CtrlReadStart (uint32_t Bsize, uint8_t * Table) +{ + uint16_t mbw; + + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DOING; + + usb1_host_set_pid_nak(USB_HOST_PIPE0); /* Set NAK */ + g_usb1_host_data_count[USB_HOST_PIPE0] = Bsize; /* Transfer size set */ + g_usb1_host_data_pointer[USB_HOST_PIPE0] = Table; /* Transfer address set */ + + USB201.DCPCTR = USB_HOST_BITSQSET; /* SQSET=1, PID=NAK */ +#if(1) /* ohci_wrapp */ + Userdef_USB_usb1_host_delay_10us(3); +#endif + RZA_IO_RegWrite_16(&USB201.DCPCFG, + 0, + USB_DCPCFG_DIR_SHIFT, + USB_DCPCFG_DIR); + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[USB_HOST_PIPE0], (uint32_t)g_usb1_host_data_pointer[USB_HOST_PIPE0]); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_NO, mbw); + USB201.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + + usb1_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb1_host_enable_brdy_int(USB_HOST_PIPE0); /* Ok */ + usb1_host_clear_pid_stall(USB_HOST_PIPE0); + usb1_host_set_pid_buf(USB_HOST_PIPE0); /* Set BUF */ +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/src/host/usb1_host_drv_api.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,889 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_drv_api.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb1_host_resetEP(USB_HOST_CFG_PIPETBL_t *tbl); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_api_host_init +* Description : Initializes USB module in the USB host mode. +* : USB connection is executed when executing this function in +* : the states that USB device isconnected to the USB port. +* Arguments : uint8_t int_level : USB Module interrupt level +* : USBU16 mode : USB_HOST_HIGH_SPEED +* : USB_HOST_FULL_SPEED +* : uint16_t clockmode : USB Clock mode +* Return Value : USB detach or attach +* : USB_HOST_ATTACH +* : USB_HOST_DETACH +*******************************************************************************/ +uint16_t usb1_api_host_init (uint8_t int_level, uint16_t mode, uint16_t clockmode) +{ + uint16_t connect; + volatile uint8_t dummy_buf; + + CPG.STBCR7 &= 0xfc; /*The clock of USB0/1 modules is permitted */ + dummy_buf = CPG.STBCR7; /* (Dummy read) */ + + g_usb1_host_SupportUsbDeviceSpeed = mode; + + usb1_host_setting_interrupt(int_level); + usb1_host_reset_module(clockmode); + + g_usb1_host_bchg_flag = USB_HOST_NO; + g_usb1_host_detach_flag = USB_HOST_NO; + g_usb1_host_attach_flag = USB_HOST_NO; + + g_usb1_host_driver_state = USB_HOST_DRV_DETACHED; + g_usb1_host_default_max_packet[USB_HOST_DEVICE_0] = 64; + + usb1_host_InitModule(); + + connect = usb1_host_CheckAttach(); + + if (connect == USB_HOST_ATTACH) + { + g_usb1_host_attach_flag = USB_HOST_YES; + } + else + { + usb1_host_UsbDetach2(); + } + + return connect; +} + +#if(1) /* ohci_wrapp */ +#else +/******************************************************************************* +* Function Name: usb1_api_host_enumeration +* Description : Initializes USB module in the USB host mode. +* : USB connection is executed when executing this function in +* : the states that USB device isconnected to the USB port. +* Arguments : uint16_t devadr : device address +* Return Value : DEVDRV_USBH_DETACH_ERR : device detach +* : DEVDRV_SUCCESS : device enumeration success +* : DEVDRV_ERROR : device enumeration error +*******************************************************************************/ +int32_t usb1_api_host_enumeration (uint16_t devadr) +{ + int32_t ret; + uint16_t driver_sts; + + g_usb1_host_setUsbAddress = devadr; + + while (1) + { + driver_sts = usb1_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + ret = DEVDRV_USBH_DETACH_ERR; + break; + } + else if (driver_sts == USB_HOST_DRV_CONFIGURED) + { + ret = DEVDRV_SUCCESS; + break; + } + else if (driver_sts == USB_HOST_DRV_STALL) + { + ret = DEVDRV_ERROR; + break; + } + else if (driver_sts == USB_HOST_DRV_NORES) + { + ret = DEVDRV_ERROR; + break; + } + else + { + /* Do Nothing */ + } + } + + if (driver_sts == USB_HOST_DRV_NORES) + { + while (1) + { + driver_sts = usb1_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + break; + } + } + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_api_host_detach +* Description : USB detach routine +* Arguments : none +* Return Value : USB_HOST_DETACH : USB detach +* : USB_HOST_ATTACH : USB attach +* : DEVDRV_ERROR : error +*******************************************************************************/ +int32_t usb1_api_host_detach (void) +{ + int32_t ret; + uint16_t driver_sts; + + while (1) + { + driver_sts = usb1_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + ret = USB_HOST_DETACH; + break; + } + else if (driver_sts == USB_HOST_DRV_CONFIGURED) + { + ret = USB_HOST_ATTACH; + break; + } + else if (driver_sts == USB_HOST_DRV_STALL) + { + ret = DEVDRV_ERROR; + break; + } + else if (driver_sts == USB_HOST_DRV_NORES) + { + ret = DEVDRV_ERROR; + break; + } + else + { + /* Do Nothing */ + } + } + + if (driver_sts == USB_HOST_DRV_NORES) + { + while (1) + { + driver_sts = usb1_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + break; + } + } + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_api_host_data_in +* Description : Executes USB transfer as data-in in the argument specified pipe. +* Arguments : uint16_t devadr ; device address +* : uint16_t Pipe ; Pipe Number +* : uint32_t Size ; Data Size +* : uint8_t *data_buf ; Data data_buf Address +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_data_in (uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t * data_buf) +{ + int32_t ret; + + if (Pipe == USB_HOST_PIPE0) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipemaxp[Pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL) != devadr) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[Pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 1) + { + return DEVDRV_ERROR; + } + + if (g_usb1_host_pipe_status[Pipe] == USB_HOST_PIPE_IDLE) + { + usb1_host_start_receive_transfer(Pipe, Size, data_buf); + } + else + { + return DEVDRV_ERROR; /* Now pipe is busy */ + } + + /* waiting for completing routine */ + do + { + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb1_host_pipe_status[Pipe] != USB_HOST_PIPE_IDLE) && (g_usb1_host_pipe_status[Pipe] != USB_HOST_PIPE_WAIT)) + { + break; + } + + } while (1); + + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb1_host_pipe_status[Pipe]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + usb1_host_stop_transfer(Pipe); + + g_usb1_host_pipe_status[Pipe] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_api_host_data_out +* Description : Executes USB transfer as data-out in the argument specified pipe. +* Arguments : uint16_t devadr ; device address +* : uint16_t Pipe ; Pipe Number +* : uint32_t Size ; Data Size +* : uint8_t *data_buf ; Data data_buf Address +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_data_out (uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t * data_buf) +{ + int32_t ret; + + if (Pipe == USB_HOST_PIPE0) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipemaxp[Pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL) != devadr) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[Pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 0) + { + return DEVDRV_ERROR; + } + + if (g_usb1_host_pipe_status[Pipe] == USB_HOST_PIPE_IDLE) + { + usb1_host_start_send_transfer(Pipe, Size, data_buf); + } + else + { + return DEVDRV_ERROR; /* Now pipe is busy */ + } + + /* waiting for completing routine */ + do + { + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb1_host_pipe_status[Pipe] != USB_HOST_PIPE_IDLE) && (g_usb1_host_pipe_status[Pipe] != USB_HOST_PIPE_WAIT)) + { + break; + } + + } while (1); + + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb1_host_pipe_status[Pipe]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + usb1_host_stop_transfer(Pipe); + + g_usb1_host_pipe_status[Pipe] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_api_host_control_transfer +* Description : Executes USB control transfer. +* Arguments : uint16_t devadr ; device address +* : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* : uint8_t *buf ; Buffer +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_USBH_DETACH_ERR ; device detach +* : DEVDRV_USBH_CTRL_COM_ERR ; device no response +* : DEVDRV_USBH_STALL ; STALL +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_control_transfer (uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, + uint16_t Len, uint8_t * Buf) +{ + int32_t ret; + + do + { + ret = usb1_host_CtrlTransStart(devadr, Req, Val, Indx, Len, Buf); + + if (ret == DEVDRV_SUCCESS) + { + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb1_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_IDLE) + && (g_usb1_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_WAIT)) + { + break; + } + } + else + { + return DEVDRV_ERROR; + } + } while (1); + + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb1_host_pipe_status[USB_HOST_PIPE0]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_CTRL_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_api_host_set_endpoint +* Description : Sets end point on the information specified in the argument. +* Arguments : uint16_t devadr ; device address +* : uint8_t *configdescriptor ; device configration descriptor +* : USB_HOST_CFG_PIPETBL_t *user_table ; pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_set_endpoint (uint16_t devadr, USB_HOST_CFG_PIPETBL_t * user_table, uint8_t * configdescriptor) +{ + uint16_t ret; + uint32_t end_point; + uint32_t offset; + uint32_t totalLength; + USB_HOST_CFG_PIPETBL_t * pipe_table; + + /* End Point Search */ + end_point = 0; + offset = configdescriptor[0]; + totalLength = (uint16_t)(configdescriptor[2] + ((uint16_t)configdescriptor[3] << 8)); + + do + { + if (configdescriptor[offset + 1] == USB_HOST_ENDPOINT_DESC) + { + pipe_table = &user_table[end_point]; + + if (pipe_table->pipe_number == 0xffff) + { + break; + } + + ret = usb1_api_host_SetEndpointTable(devadr, pipe_table, (uint8_t *)&configdescriptor[offset]); + + if ((ret != USB_HOST_PIPE_IN) && (ret != USB_HOST_PIPE_OUT)) + { + return DEVDRV_ERROR; + } + + ++end_point; + } + + /* Next End Point Search */ + offset += configdescriptor[offset]; + + } while (offset < totalLength); + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb1_api_host_clear_endpoint +* Description : Clears the pipe definition table specified in the argument. +* Arguments : uint16_t pipe_sel : Pipe Number +* : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_clear_endpoint (USB_HOST_CFG_PIPETBL_t * user_table) +{ + uint16_t pipe; + + for (pipe = USB_HOST_PIPE0; pipe <= USB_HOST_MAX_PIPE_NO; ++pipe) + { + if (user_table->pipe_number == 0xffff) + { + break; + } + user_table->pipe_cfg &= (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD); + user_table->pipe_max_pktsize = 0; + user_table->pipe_cycle = 0; + + user_table++; + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb1_api_host_clear_endpoint_pipe +* Description : Clears the pipe definition table specified in the argument. +* Arguments : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_clear_endpoint_pipe (uint16_t pipe_sel, USB_HOST_CFG_PIPETBL_t * user_table) +{ + uint16_t pipe; + + for (pipe = USB_HOST_PIPE0; pipe <= USB_HOST_MAX_PIPE_NO; ++pipe) + { + if (user_table->pipe_number == 0xffff) + { + break; + } + + if (user_table->pipe_number == pipe_sel) + { + user_table->pipe_cfg &= (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD); + user_table->pipe_max_pktsize = 0; + user_table->pipe_cycle = 0; + break; + } + + user_table++; + } + + return DEVDRV_SUCCESS; +} +#endif + +/******************************************************************************* +* Function Name: usb1_api_host_SetEndpointTable +* Description : Sets the end point on the information specified by the argument. +* Arguments : uint16_t devadr : device address +* : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* : uint8_t *Table : Endpoint descriptor +* Return Value : USB_HOST_DIR_H_IN ; IN endpoint +* : USB_HOST_DIR_H_OUT ; OUT endpoint +* : USB_END_POINT_ERROR ; error +*******************************************************************************/ +uint16_t usb1_api_host_SetEndpointTable (uint16_t devadr, USB_HOST_CFG_PIPETBL_t * user_table, uint8_t * Table) +{ + uint16_t PipeCfg; + uint16_t PipeMaxp; + uint16_t pipe_number; + uint16_t ret; + uint16_t ret_flag = 0; // avoid warning. + + pipe_number = user_table->pipe_number; + + if (Table[1] != USB_HOST_ENDPOINT_DESC) + { + return USB_END_POINT_ERROR; + } + + switch (Table[3] & USB_HOST_EP_TYPE) + { + case USB_HOST_EP_CNTRL: + ret_flag = USB_END_POINT_ERROR; + break; + + case USB_HOST_EP_ISO: + if ((pipe_number != USB_HOST_PIPE1) && (pipe_number != USB_HOST_PIPE2)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_ISO; + break; + + case USB_HOST_EP_BULK: + if ((pipe_number < USB_HOST_PIPE1) || (pipe_number > USB_HOST_PIPE5)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_BULK; + break; + + case USB_HOST_EP_INT: + if ((pipe_number < USB_HOST_PIPE6) || (pipe_number > USB_HOST_PIPE9)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_INTERRUPT; + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + + /* Set pipe configuration table */ + if ((Table[2] & USB_HOST_EP_DIR_MASK) == USB_HOST_EP_IN) /* IN(receive) */ + { + if (PipeCfg == USB_HOST_ISO) + { + /* Transfer Type is ISO*/ + PipeCfg |= USB_HOST_DIR_H_IN; + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + case USB_HOST_D0USE: + case USB_HOST_D1USE: + case USB_HOST_D0DMA: + case USB_HOST_D1DMA: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & USB_HOST_DBLBFIELD); + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + } + else + { + /* Transfer Type is BULK or INT */ + PipeCfg |= (USB_HOST_SHTNAKON | USB_HOST_DIR_H_IN); /* Compulsory SHTNAK */ + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + case USB_HOST_D0USE: + case USB_HOST_D1USE: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); + break; + + case USB_HOST_D0DMA: + case USB_HOST_D1DMA: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); +#ifdef __USB_DMA_BFRE_ENABLE__ + /* this routine cannnot be perfomred if read operation is executed in buffer size */ + PipeCfg |= USB_HOST_BFREON; +#endif + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + } + ret = USB_HOST_PIPE_IN; + } + else /* OUT(send) */ + { + if (PipeCfg == USB_HOST_ISO) + { + /* Transfer Type is ISO*/ + PipeCfg |= (uint16_t)(user_table->pipe_cfg & USB_HOST_DBLBFIELD); + } + else + { + /* Transfer Type is BULK or INT */ + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); + } + PipeCfg |= USB_HOST_DIR_H_OUT; + ret = USB_HOST_PIPE_OUT; + } + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + g_usb1_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_CFIFO_USE; + break; + + case USB_HOST_D0USE: + g_usb1_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D0FIFO_USE; + break; + + case USB_HOST_D1USE: + g_usb1_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D1FIFO_USE; + break; + + case USB_HOST_D0DMA: + g_usb1_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D0FIFO_DMA; + break; + + case USB_HOST_D1DMA: + g_usb1_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D1FIFO_DMA; + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + + /* Endpoint number set */ + PipeCfg |= (uint16_t)(Table[2] & USB_HOST_EP_NUM_MASK); + g_usb1_host_PipeTbl[pipe_number] |= (uint16_t)(Table[2] & USB_HOST_EP_NUM_MASK); + + /* Max packet size set */ + PipeMaxp = (uint16_t)((uint16_t)Table[4] | (uint16_t)((uint16_t)Table[5] << 8)); + + if (PipeMaxp == 0u) + { + return USB_END_POINT_ERROR; + } + + /* Set device address */ + PipeMaxp |= (uint16_t)(devadr << 12); + + user_table->pipe_cfg = PipeCfg; + user_table->pipe_max_pktsize = PipeMaxp; + + usb1_host_resetEP(user_table); + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_host_resetEP +* Description : Sets the end point on the information specified by the argument. +* Arguments : USB_HOST_CFG_PIPETBL_t *tbl : pipe table +* Return Value : none +*******************************************************************************/ +static void usb1_host_resetEP (USB_HOST_CFG_PIPETBL_t * tbl) +{ + + uint16_t pipe; + + /* Host pipe */ + /* The pipe number of pipe definition table is obtained */ + pipe = (uint16_t)(tbl->pipe_number & USB_HOST_BITCURPIPE); /* Pipe Number */ + + /* FIFO port access pipe is set to initial value */ + /* The connection with FIFO should be cut before setting the pipe */ + if (RZA_IO_RegRead_16(&USB201.CFIFOSEL, + USB_CFIFOSEL_CURPIPE_SHIFT, + USB_CFIFOSEL_CURPIPE) == pipe) + { + usb1_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + if (RZA_IO_RegRead_16(&USB201.D0FIFOSEL, + USB_DnFIFOSEL_CURPIPE_SHIFT, + USB_DnFIFOSEL_CURPIPE) == pipe) + { + usb1_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + if (RZA_IO_RegRead_16(&USB201.D1FIFOSEL, + USB_DnFIFOSEL_CURPIPE_SHIFT, + USB_DnFIFOSEL_CURPIPE) == pipe) + { + usb1_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + /* Interrupt of pipe set is disabled */ + usb1_host_disable_brdy_int(pipe); + usb1_host_disable_nrdy_int(pipe); + usb1_host_disable_bemp_int(pipe); + + /* Pipe to set is set to NAK */ + usb1_host_set_pid_nak(pipe); + + /* Pipe is set */ + USB201.PIPESEL = pipe; + + USB201.PIPECFG = tbl->pipe_cfg; + USB201.PIPEBUF = tbl->pipe_buf; + USB201.PIPEMAXP = tbl->pipe_max_pktsize; + USB201.PIPEPERI = tbl->pipe_cycle; + + g_usb1_host_pipecfg[pipe] = tbl->pipe_cfg; + g_usb1_host_pipebuf[pipe] = tbl->pipe_buf; + g_usb1_host_pipemaxp[pipe] = tbl->pipe_max_pktsize; + g_usb1_host_pipeperi[pipe] = tbl->pipe_cycle; + + /* Sequence bit clear */ + usb1_host_set_sqclr(pipe); + + usb1_host_aclrm(pipe); + usb1_host_set_csclr(pipe); + + /* Pipe window selection is set to unused */ + USB201.PIPESEL = USB_HOST_PIPE0; + +} + +#if(1) /* ohci_wrapp */ +#else +/******************************************************************************* +* Function Name: usb1_api_host_data_count +* Description : Get g_usb0_host_data_count[pipe] +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t *data_count ; return g_usb0_data_count[pipe] +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_data_count (uint16_t pipe, uint32_t * data_count) +{ + if (pipe > USB_HOST_MAX_PIPE_NO) + { + return DEVDRV_ERROR; + } + + *data_count = g_usb1_host_PipeDataSize[pipe]; + + return DEVDRV_SUCCESS; +} +#endif + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/src/host/usb1_host_global.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,137 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_global.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +const uint16_t g_usb1_host_bit_set[16] = +{ + 0x0001, 0x0002, 0x0004, 0x0008, + 0x0010, 0x0020, 0x0040, 0x0080, + 0x0100, 0x0200, 0x0400, 0x0800, + 0x1000, 0x2000, 0x4000, 0x8000 +}; + +uint32_t g_usb1_host_data_count[USB_HOST_MAX_PIPE_NO + 1]; +uint8_t * g_usb1_host_data_pointer[USB_HOST_MAX_PIPE_NO + 1]; + +uint16_t g_usb1_host_PipeIgnore[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb1_host_PipeTbl[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb1_host_pipe_status[USB_HOST_MAX_PIPE_NO + 1]; +uint32_t g_usb1_host_PipeDataSize[USB_HOST_MAX_PIPE_NO + 1]; + +USB_HOST_DMA_t g_usb1_host_DmaInfo[2]; + +uint16_t g_usb1_host_DmaPipe[2]; +uint16_t g_usb1_host_DmaBval[2]; +uint16_t g_usb1_host_DmaStatus[2]; + +uint16_t g_usb1_host_driver_state; +uint16_t g_usb1_host_ConfigNum; +uint16_t g_usb1_host_CmdStage; +uint16_t g_usb1_host_bchg_flag; +uint16_t g_usb1_host_detach_flag; +uint16_t g_usb1_host_attach_flag; + +uint16_t g_usb1_host_UsbAddress; +uint16_t g_usb1_host_setUsbAddress; +uint16_t g_usb1_host_default_max_packet[USB_HOST_MAX_DEVICE + 1]; +uint16_t g_usb1_host_UsbDeviceSpeed; +uint16_t g_usb1_host_SupportUsbDeviceSpeed; + +uint16_t g_usb1_host_SavReq; +uint16_t g_usb1_host_SavVal; +uint16_t g_usb1_host_SavIndx; +uint16_t g_usb1_host_SavLen; + +uint16_t g_usb1_host_pipecfg[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb1_host_pipebuf[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb1_host_pipemaxp[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb1_host_pipeperi[USB_HOST_MAX_PIPE_NO + 1]; + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_init_pipe_status +* Description : Initialize pipe status. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_init_pipe_status (void) +{ + uint16_t loop; + + g_usb1_host_ConfigNum = 0; + + for (loop = 0; loop < (USB_HOST_MAX_PIPE_NO + 1); ++loop) + { + g_usb1_host_pipe_status[loop] = USB_HOST_PIPE_IDLE; + g_usb1_host_PipeDataSize[loop] = 0; + + /* pipe configuration in usb1_host_resetEP() */ + g_usb1_host_pipecfg[loop] = 0; + g_usb1_host_pipebuf[loop] = 0; + g_usb1_host_pipemaxp[loop] = 0; + g_usb1_host_pipeperi[loop] = 0; + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/src/host/usb1_host_usbint.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,497 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_usbint.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#if(1) /* ohci_wrapp */ +#include "ohci_wrapp_RZ_A1_local.h" +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb1_host_interrupt1(void); +static void usb1_host_BRDYInterrupt(uint16_t Status, uint16_t Int_enbl); +static void usb1_host_NRDYInterrupt(uint16_t Status, uint16_t Int_enbl); +static void usb1_host_BEMPInterrupt(uint16_t Status, uint16_t Int_enbl); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_interrupt +* Description : Executes USB interrupt. +* : Register this function in the USB interrupt handler. +* : Set CFIF0 in the pipe set before the interrupt after executing +* : this function. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb1_host_interrupt (uint32_t int_sense) +{ + uint16_t savepipe1; + uint16_t savepipe2; + uint16_t buffer; + + savepipe1 = USB201.CFIFOSEL; + savepipe2 = USB201.PIPESEL; + usb1_host_interrupt1(); + + /* Control transmission changes ISEL within interruption processing. */ + /* For this reason, write return of ISEL cannot be performed. */ + buffer = USB201.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(savepipe1 & USB_HOST_BITCURPIPE); + USB201.CFIFOSEL = buffer; + USB201.PIPESEL = savepipe2; +} + +/******************************************************************************* +* Function Name: usb1_host_interrupt1 +* Description : Execue the USB interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_interrupt1 (void) +{ + uint16_t intsts0; + uint16_t intsts1; + uint16_t intenb0; + uint16_t intenb1; + uint16_t brdysts; + uint16_t nrdysts; + uint16_t bempsts; + uint16_t brdyenb; + uint16_t nrdyenb; + uint16_t bempenb; + volatile uint16_t dumy_sts; + + intsts0 = USB201.INTSTS0; + intsts1 = USB201.INTSTS1; + intenb0 = USB201.INTENB0; + intenb1 = USB201.INTENB1; + + if ((intsts1 & USB_HOST_BITBCHG) && (intenb1 & USB_HOST_BITBCHGE)) + { + USB201.INTSTS1 = (uint16_t)~USB_HOST_BITBCHG; + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); + g_usb1_host_bchg_flag = USB_HOST_YES; + } + else if ((intsts1 & USB_HOST_BITSACK) && (intenb1 & USB_HOST_BITSACKE)) + { + USB201.INTSTS1 = (uint16_t)~USB_HOST_BITSACK; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); +#else + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; +#endif + } + else if ((intsts1 & USB_HOST_BITSIGN) && (intenb1 & USB_HOST_BITSIGNE)) + { + USB201.INTSTS1 = (uint16_t)~USB_HOST_BITSIGN; +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#else + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_NORES; +#endif + } + else if (((intsts1 & USB_HOST_BITDTCH) == USB_HOST_BITDTCH) + && ((intenb1 & USB_HOST_BITDTCHE) == USB_HOST_BITDTCHE)) + { + USB201.INTSTS1 = (uint16_t)~USB_HOST_BITDTCH; + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); + g_usb1_host_detach_flag = USB_HOST_YES; + + Userdef_USB_usb1_host_detach(); + + usb1_host_UsbDetach2(); + } + else if (((intsts1 & USB_HOST_BITATTCH) == USB_HOST_BITATTCH) + && ((intenb1 & USB_HOST_BITATTCHE) == USB_HOST_BITATTCHE)) + { + USB201.INTSTS1 = (uint16_t)~USB_HOST_BITATTCH; + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); + g_usb1_host_attach_flag = USB_HOST_YES; + + Userdef_USB_usb1_host_attach(); + + usb1_host_UsbAttach(); + } + else if ((intsts0 & intenb0 & (USB_HOST_BITBEMP | USB_HOST_BITNRDY | USB_HOST_BITBRDY))) + { + brdysts = USB201.BRDYSTS; + nrdysts = USB201.NRDYSTS; + bempsts = USB201.BEMPSTS; + brdyenb = USB201.BRDYENB; + nrdyenb = USB201.NRDYENB; + bempenb = USB201.BEMPENB; + + if ((intsts0 & USB_HOST_BITBRDY) && (intenb0 & USB_HOST_BITBRDYE) && (brdysts & brdyenb)) + { + usb1_host_BRDYInterrupt(brdysts, brdyenb); + } + else if ((intsts0 & USB_HOST_BITBEMP) && (intenb0 & USB_HOST_BITBEMPE) && (bempsts & bempenb)) + { + usb1_host_BEMPInterrupt(bempsts, bempenb); + } + else if ((intsts0 & USB_HOST_BITNRDY) && (intenb0 & USB_HOST_BITNRDYE) && (nrdysts & nrdyenb)) + { + usb1_host_NRDYInterrupt(nrdysts, nrdyenb); + } + else + { + /* Do Nothing */ + } + } + else + { + /* Do Nothing */ + } + + /* Three dummy read for clearing interrupt requests */ + dumy_sts = USB201.INTSTS0; + dumy_sts = USB201.INTSTS1; + +} + +/******************************************************************************* +* Function Name: usb1_host_BRDYInterrupt +* Description : Executes USB BRDY interrupt. +* Arguments : uint16_t Status ; BRDYSTS Register Value +* : uint16_t Int_enbl ; BRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_BRDYInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t buffer; + volatile uint16_t dumy_sts; + + if ((Status & g_usb1_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb1_host_bit_set[USB_HOST_PIPE0])) + { + USB201.BRDYSTS = (uint16_t)~g_usb1_host_bit_set[USB_HOST_PIPE0]; + +#if(1) /* ohci_wrapp */ + switch ((g_usb1_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + buffer = usb1_host_read_buffer_c(USB_HOST_PIPE0); + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb1_host_read_buffer_c(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_READOVER: /* buffer over */ + USB201.CFIFOCTR = USB_HOST_BITBCLR; + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + break; + } +#else + switch ((g_usb1_host_CmdStage & (USB_HOST_MODE_FIELD | USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + case (USB_HOST_MODE_NO_DATA | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + buffer = usb1_host_read_buffer_c(USB_HOST_PIPE0); + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case (USB_HOST_MODE_READ | USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb1_host_read_buffer_c(USB_HOST_PIPE0); + + switch (buffer) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case USB_HOST_READOVER: /* buffer over */ + USB201.CFIFOCTR = USB_HOST_BITBCLR; + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + break; + } +#endif + } + else + { + usb1_host_brdy_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB201.BRDYSTS; +} + +/******************************************************************************* +* Function Name: usb1_host_NRDYInterrupt +* Description : Executes USB NRDY interrupt. +* Arguments : uint16_t Status ; NRDYSTS Register Value +* : uint16_t Int_enbl ; NRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_NRDYInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t pid; + volatile uint16_t dumy_sts; + + if ((Status & g_usb1_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb1_host_bit_set[USB_HOST_PIPE0])) + { + USB201.NRDYSTS = (uint16_t)~g_usb1_host_bit_set[USB_HOST_PIPE0]; + pid = usb1_host_get_pid(USB_HOST_PIPE0); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_STALL; +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + + } + else if (pid == USB_HOST_PID_NAK) + { + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_NORES; +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + } + else + { + /* Do Nothing */ + } + } + else + { + usb1_host_nrdy_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB201.NRDYSTS; +} + +/******************************************************************************* +* Function Name: usb1_host_BEMPInterrupt +* Description : Executes USB BEMP interrupt. +* Arguments : uint16_t Status ; BEMPSTS Register Value +* : uint16_t Int_enbl ; BEMPENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_BEMPInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t buffer; + uint16_t pid; + volatile uint16_t dumy_sts; + + if ((Status & g_usb1_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb1_host_bit_set[USB_HOST_PIPE0])) + { + USB201.BEMPSTS = (uint16_t)~g_usb1_host_bit_set[USB_HOST_PIPE0]; + pid = usb1_host_get_pid(USB_HOST_PIPE0); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_STALL; +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + } + else + { +#if(1) /* ohci_wrapp */ + switch ((g_usb1_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb1_host_write_buffer(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_WRITING: /* Continue of data write */ + case USB_HOST_WRITEEND: /* End of data write (zero-length) */ + break; + + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_STATUS; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + /* do nothing */ + break; + } +#else + switch ((g_usb1_host_CmdStage & (USB_HOST_MODE_FIELD | USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_MODE_READ | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb1_host_write_buffer(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_WRITING: /* Continue of data write */ + case USB_HOST_WRITEEND: /* End of data write (zero-length) */ + break; + + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_STATUS; + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + default: + /* do nothing */ + break; + } +#endif + } + } + else + { + usb1_host_bemp_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB201.BEMPSTS; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/src/host/usb1_host_usbsig.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,637 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_usbsig.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb1_host_EnableINT_Module(void); +static void usb1_host_Enable_AttachINT(void); +static void usb1_host_Disable_AttachINT(void); +static void usb1_host_Disable_BchgINT(void); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_InitModule +* Description : Initializes the USB module in USB host module. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_InitModule (void) +{ + uint16_t buf1; + uint16_t buf2; + uint16_t buf3; + + usb1_host_init_pipe_status(); + + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 1, + USB_SYSCFG_DCFM_SHIFT, + USB_SYSCFG_DCFM); /* HOST mode */ + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 1, + USB_SYSCFG_DRPD_SHIFT, + USB_SYSCFG_DRPD); /* PORT0 D+, D- setting */ + + do + { + buf1 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb1_host_delay_xms(50); + buf2 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb1_host_delay_xms(50); + buf3 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + + } while ((buf1 != buf2) || (buf1 != buf3)); + + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 1, + USB_SYSCFG_USBE_SHIFT, + USB_SYSCFG_USBE); + + USB201.CFIFOSEL = (uint16_t)(USB_HOST_BITRCNT | USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); + USB201.D0FIFOSEL = (uint16_t)( USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); + USB201.D1FIFOSEL = (uint16_t)( USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); +} + +/******************************************************************************* +* Function Name: usb1_host_CheckAttach +* Description : Returns the USB device connection state. +* Arguments : none +* Return Value : uint16_t ; USB_HOST_ATTACH : Attached +* : ; USB_HOST_DETACH : not Attached +*******************************************************************************/ +uint16_t usb1_host_CheckAttach (void) +{ + uint16_t buf1; + uint16_t buf2; + uint16_t buf3; + uint16_t rhst; + + do + { + buf1 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb1_host_delay_xms(50); + buf2 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb1_host_delay_xms(50); + buf3 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + + } while ((buf1 != buf2) || (buf1 != buf3)); + + rhst = RZA_IO_RegRead_16(&USB201.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (rhst == USB_HOST_UNDECID) + { + if (buf1 == USB_HOST_FS_JSTS) + { + if (g_usb1_host_SupportUsbDeviceSpeed == USB_HOST_HIGH_SPEED) + { + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 1, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + } + else + { + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + } + return USB_HOST_ATTACH; + } + else if (buf1 == USB_HOST_LS_JSTS) + { + /* Low Speed Device */ + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + return USB_HOST_ATTACH; + } + else + { + /* Do Nothing */ + } + } + else if ((rhst == USB_HOST_HSMODE) || (rhst == USB_HOST_FSMODE)) + { + return USB_HOST_ATTACH; + } + else if (rhst == USB_HOST_LSMODE) + { + return USB_HOST_ATTACH; + } + else + { + /* Do Nothing */ + } + + return USB_HOST_DETACH; +} + +/******************************************************************************* +* Function Name: usb1_host_UsbAttach +* Description : Connects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_UsbAttach (void) +{ + usb1_host_EnableINT_Module(); + usb1_host_Disable_BchgINT(); + usb1_host_Disable_AttachINT(); + usb1_host_Enable_DetachINT(); +} + +/******************************************************************************* +* Function Name: usb1_host_UsbDetach +* Description : Disconnects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_UsbDetach (void) +{ + uint16_t pipe; + uint16_t devadr; + + g_usb1_host_driver_state = USB_HOST_DRV_DETACHED; + + /* Terminate all the pipes in which communications on port */ + /* are currently carried out */ + for (pipe = 0; pipe < (USB_HOST_MAX_PIPE_NO + 1); ++pipe) + { + if (g_usb1_host_pipe_status[pipe] != USB_HOST_PIPE_IDLE) + { + if (pipe == USB_HOST_PIPE0) + { + devadr = RZA_IO_RegRead_16(&USB201.DCPMAXP, + USB_DCPMAXP_DEVSEL_SHIFT, + USB_DCPMAXP_DEVSEL); + } + else + { + devadr = RZA_IO_RegRead_16(&g_usb1_host_pipemaxp[pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL); + } + + if (devadr == g_usb1_host_UsbAddress) + { + usb1_host_stop_transfer(pipe); + } + + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_IDLE; + } + } + + g_usb1_host_ConfigNum = 0; + g_usb1_host_UsbAddress = 0; + g_usb1_host_default_max_packet[USB_HOST_DEVICE_0] = 64; + + usb1_host_UsbDetach2(); +} + +/******************************************************************************* +* Function Name: usb1_host_UsbDetach2 +* Description : Disconnects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_UsbDetach2 (void) +{ + usb1_host_Disable_DetachINT(); + usb1_host_Disable_BchgINT(); + usb1_host_Enable_AttachINT(); +} + +/******************************************************************************* +* Function Name: usb1_host_UsbBusReset +* Description : Issues the USB bus reset signal. +* Arguments : none +* Return Value : uint16_t ; RHST +*******************************************************************************/ +uint16_t usb1_host_UsbBusReset (void) +{ + uint16_t buffer; + uint16_t loop; + + RZA_IO_RegWrite_16(&USB201.DVSTCTR0, + 1, + USB_DVSTCTR0_USBRST_SHIFT, + USB_DVSTCTR0_USBRST); + RZA_IO_RegWrite_16(&USB201.DVSTCTR0, + 0, + USB_DVSTCTR0_UACT_SHIFT, + USB_DVSTCTR0_UACT); + + Userdef_USB_usb1_host_delay_xms(50); + + buffer = USB201.DVSTCTR0; + buffer &= (uint16_t)(~(USB_HOST_BITRST)); + buffer |= USB_HOST_BITUACT; + USB201.DVSTCTR0 = buffer; + + Userdef_USB_usb1_host_delay_xms(20); + + for (loop = 0, buffer = USB_HOST_HSPROC; loop < 3; ++loop) + { + buffer = RZA_IO_RegRead_16(&USB201.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (buffer == USB_HOST_HSPROC) + { + Userdef_USB_usb1_host_delay_xms(10); + } + else + { + break; + } + } + + return buffer; +} + +/******************************************************************************* +* Function Name: usb1_host_UsbResume +* Description : Issues the USB resume signal. +* Arguments : none +* Return Value : int32_t ; DEVDRV_SUCCESS +* : ; DEVDRV_ERROR +*******************************************************************************/ +int32_t usb1_host_UsbResume (void) +{ + uint16_t buf; + + if ((g_usb1_host_driver_state & USB_HOST_DRV_SUSPEND) == 0) + { + /* not SUSPEND */ + return DEVDRV_ERROR; + } + + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); + RZA_IO_RegWrite_16(&USB201.DVSTCTR0, + 1, + USB_DVSTCTR0_RESUME_SHIFT, + USB_DVSTCTR0_RESUME); + Userdef_USB_usb1_host_delay_xms(20); + + buf = USB201.DVSTCTR0; + buf &= (uint16_t)(~(USB_HOST_BITRESUME)); + buf |= USB_HOST_BITUACT; + USB201.DVSTCTR0 = buf; + + g_usb1_host_driver_state &= (uint16_t)~USB_HOST_DRV_SUSPEND; + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb1_host_UsbSuspend +* Description : Issues the USB suspend signal. +* Arguments : none +* Return Value : int32_t ; DEVDRV_SUCCESS :not SUSPEND +* : ; DEVDRV_ERROR :SUSPEND +*******************************************************************************/ +int32_t usb1_host_UsbSuspend (void) +{ + uint16_t buf; + + if ((g_usb1_host_driver_state & USB_HOST_DRV_SUSPEND) != 0) + { + /* SUSPEND */ + return DEVDRV_ERROR; + } + + RZA_IO_RegWrite_16(&USB201.DVSTCTR0, + 0, + USB_DVSTCTR0_UACT_SHIFT, + USB_DVSTCTR0_UACT); + + Userdef_USB_usb1_host_delay_xms(5); + + buf = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + if ((buf != USB_HOST_FS_JSTS) && (buf != USB_HOST_LS_JSTS)) + { + usb1_host_UsbDetach(); + } + else + { + g_usb1_host_driver_state |= USB_HOST_DRV_SUSPEND; + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb1_host_Enable_DetachINT +* Description : Enables the USB disconnection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_Enable_DetachINT (void) +{ + USB201.INTSTS1 = (uint16_t)(~(USB_HOST_BITDTCH)); + RZA_IO_RegWrite_16(&USB201.INTENB1, + 1, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); +} + +/******************************************************************************* +* Function Name: usb1_host_Disable_DetachINT +* Description : Disables the USB disconnection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_Disable_DetachINT (void) +{ + USB201.INTSTS1 = (uint16_t)(~(USB_HOST_BITDTCH)); + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); +} + +/******************************************************************************* +* Function Name: usb1_host_Enable_AttachINT +* Description : Enables the USB connection detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_Enable_AttachINT (void) +{ + USB201.INTSTS1 = (uint16_t)(~(USB_HOST_BITATTCH)); + RZA_IO_RegWrite_16(&USB201.INTENB1, + 1, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); +} + +/******************************************************************************* +* Function Name: usb1_host_Disable_AttachINT +* Description : Disables the USB connection detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_Disable_AttachINT (void) +{ + USB201.INTSTS1 = (uint16_t)(~(USB_HOST_BITATTCH)); + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); +} + +/******************************************************************************* +* Function Name: usb1_host_Disable_BchgINT +* Description : Disables the USB bus change detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_Disable_BchgINT (void) +{ + USB201.INTSTS1 = (uint16_t)(~(USB_HOST_BITBCHG)); + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); +} + +/******************************************************************************* +* Function Name: usb1_host_set_devadd +* Description : DEVADDn register is set by specified value +* Arguments : uint16_t addr : Device address +* : uint16_t *devadd : Set value +* Return Value : none +*******************************************************************************/ +void usb1_host_set_devadd (uint16_t addr, uint16_t * devadd) +{ + uint16_t * ptr; + uint16_t ret_flag = DEVDRV_FLAG_ON; // avoid warning. + + switch (addr) + { + case USB_HOST_DEVICE_0: + ptr = (uint16_t *)&USB201.DEVADD0; + break; + + case USB_HOST_DEVICE_1: + ptr = (uint16_t *)&USB201.DEVADD1; + break; + + case USB_HOST_DEVICE_2: + ptr = (uint16_t *)&USB201.DEVADD2; + break; + + case USB_HOST_DEVICE_3: + ptr = (uint16_t *)&USB201.DEVADD3; + break; + + case USB_HOST_DEVICE_4: + ptr = (uint16_t *)&USB201.DEVADD4; + break; + + case USB_HOST_DEVICE_5: + ptr = (uint16_t *)&USB201.DEVADD5; + break; + + case USB_HOST_DEVICE_6: + ptr = (uint16_t *)&USB201.DEVADD6; + break; + + case USB_HOST_DEVICE_7: + ptr = (uint16_t *)&USB201.DEVADD7; + break; + + case USB_HOST_DEVICE_8: + ptr = (uint16_t *)&USB201.DEVADD8; + break; + + case USB_HOST_DEVICE_9: + ptr = (uint16_t *)&USB201.DEVADD9; + break; + + case USB_HOST_DEVICE_10: + ptr = (uint16_t *)&USB201.DEVADDA; + break; + + default: + ret_flag = DEVDRV_FLAG_OFF; + break; + } + + if (ret_flag == DEVDRV_FLAG_ON) + { + *ptr = (uint16_t)(*devadd & USB_HOST_DEVADD_MASK); + } +} + +/******************************************************************************* +* Function Name: usb1_host_get_devadd +* Description : DEVADDn register is obtained +* Arguments : uint16_t addr : Device address +* : uint16_t *devadd : USB_HOST_DEVADD register value +* Return Value : none +*******************************************************************************/ +void usb1_host_get_devadd (uint16_t addr, uint16_t * devadd) +{ + uint16_t * ptr; + uint16_t ret_flag = DEVDRV_FLAG_ON; // avoid warning. + + switch (addr) + { + case USB_HOST_DEVICE_0: + ptr = (uint16_t *)&USB201.DEVADD0; + break; + + case USB_HOST_DEVICE_1: + ptr = (uint16_t *)&USB201.DEVADD1; + break; + + case USB_HOST_DEVICE_2: + ptr = (uint16_t *)&USB201.DEVADD2; + break; + + case USB_HOST_DEVICE_3: + ptr = (uint16_t *)&USB201.DEVADD3; + break; + + case USB_HOST_DEVICE_4: + ptr = (uint16_t *)&USB201.DEVADD4; + break; + + case USB_HOST_DEVICE_5: + ptr = (uint16_t *)&USB201.DEVADD5; + break; + + case USB_HOST_DEVICE_6: + ptr = (uint16_t *)&USB201.DEVADD6; + break; + + case USB_HOST_DEVICE_7: + ptr = (uint16_t *)&USB201.DEVADD7; + break; + + case USB_HOST_DEVICE_8: + ptr = (uint16_t *)&USB201.DEVADD8; + break; + + case USB_HOST_DEVICE_9: + ptr = (uint16_t *)&USB201.DEVADD9; + break; + + case USB_HOST_DEVICE_10: + ptr = (uint16_t *)&USB201.DEVADDA; + break; + + default: + ret_flag = DEVDRV_FLAG_OFF; + break; + } + + if (ret_flag == DEVDRV_FLAG_ON) + { + *devadd = *ptr; + } +} + +/******************************************************************************* +* Function Name: usb1_host_EnableINT_Module +* Description : Enables BEMP/NRDY/BRDY interrupt and SIGN/SACK interrupt. +* : Enables NRDY/BEMP interrupt in the pipe0. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_EnableINT_Module (void) +{ + uint16_t buf; + + buf = USB201.INTENB0; + buf |= (USB_HOST_BITBEMPE | USB_HOST_BITNRDYE | USB_HOST_BITBRDYE); + USB201.INTENB0 = buf; + + buf = USB201.INTENB1; + buf |= (USB_HOST_BITSIGNE | USB_HOST_BITSACKE); + USB201.INTENB1 = buf; + + usb1_host_enable_nrdy_int(USB_HOST_PIPE0); + usb1_host_enable_bemp_int(USB_HOST_PIPE0); +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/src/userdef/usb1_host_dmacdrv.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,698 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_dmacdrv.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "r_typedefs.h" +#include "iodefine.h" +#include "rza_io_regrw.h" +#include "usb1_host_dmacdrv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define DMAC_INDEFINE (255) /* Macro definition when REQD bit is not used */ + +/* ==== Request setting information for on-chip peripheral module ==== */ +typedef enum dmac_peri_req_reg_type +{ + DMAC_REQ_MID, + DMAC_REQ_RID, + DMAC_REQ_AM, + DMAC_REQ_LVL, + DMAC_REQ_REQD +} dmac_peri_req_reg_type_t; + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +/* ==== Prototype declaration ==== */ + +/* ==== Global variable ==== */ +/* On-chip peripheral module request setting table */ +static const uint8_t usb1_host_dmac_peri_req_init_table[8][5] = +{ + /* MID,RID, AM,LVL,REQD */ + { 32, 3, 2, 1, 1}, /* USB_0 channel 0 transmit FIFO empty */ + { 32, 3, 2, 1, 0}, /* USB_0 channel 0 receive FIFO full */ + { 33, 3, 2, 1, 1}, /* USB_0 channel 1 transmit FIFO empty */ + { 33, 3, 2, 1, 0}, /* USB_0 channel 1 receive FIFO full */ + { 34, 3, 2, 1, 1}, /* USB_1 channel 0 transmit FIFO empty */ + { 34, 3, 2, 1, 0}, /* USB_1 channel 0 receive FIFO full */ + { 35, 3, 2, 1, 1}, /* USB_1 channel 1 transmit FIFO empty */ + { 35, 3, 2, 1, 0}, /* USB_1 channel 1 receive FIFO full */ +}; + + +/******************************************************************************* +* Function Name: usb1_host_DMAC3_PeriReqInit +* Description : Sets the register mode for DMA mode and the on-chip peripheral +* : module request for transfer request for DMAC channel 3. +* : Executes DMAC initial setting using the DMA information +* : specified by the argument *trans_info and the enabled/disabled +* : continuous transfer specified by the argument continuation. +* : Registers DMAC channel 3 interrupt handler function and sets +* : the interrupt priority level. Then enables transfer completion +* : interrupt. +* Arguments : dmac_transinfo_t * trans_info : Setting information to DMAC +* : : register +* : uint32_t dmamode : DMA mode (only for DMAC_MODE_REGISTER) +* : uint32_t continuation : Set continuous transfer to be valid +* : : after DMA transfer has been completed +* : DMAC_SAMPLE_CONTINUATION : Execute continuous transfer +* : DMAC_SAMPLE_SINGLE : Do not execute continuous +* : : transfer +* : uint32_t request_factor : Factor for on-chip peripheral module +* : : request +* : DMAC_REQ_OSTM0TINT : OSTM_0 compare match +* : DMAC_REQ_OSTM1TINT : OSTM_1 compare match +* : DMAC_REQ_TGI0A : MTU2_0 input capture/compare match +* : : +* : uint32_t req_direction : Setting value of CHCFG_n register +* : : REQD bit +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC3_PeriReqInit (const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction) +{ + /* ==== Register mode ==== */ + if (DMAC_MODE_REGISTER == dmamode) + { + /* ==== Next0 register set ==== */ + DMAC3.N0SA_n = trans_info->src_addr; /* Start address of transfer source */ + DMAC3.N0DA_n = trans_info->dst_addr; /* Start address of transfer destination */ + DMAC3.N0TB_n = trans_info->count; /* Total transfer byte count */ + + /* DAD : Transfer destination address counting direction */ + /* SAD : Transfer source address counting direction */ + /* DDS : Transfer destination transfer size */ + /* SDS : Transfer source transfer size */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + trans_info->daddr_dir, + DMAC3_CHCFG_n_DAD_SHIFT, + DMAC3_CHCFG_n_DAD); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + trans_info->saddr_dir, + DMAC3_CHCFG_n_SAD_SHIFT, + DMAC3_CHCFG_n_SAD); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + trans_info->dst_size, + DMAC3_CHCFG_n_DDS_SHIFT, + DMAC3_CHCFG_n_DDS); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + trans_info->src_size, + DMAC3_CHCFG_n_SDS_SHIFT, + DMAC3_CHCFG_n_SDS); + + /* DMS : Register mode */ + /* RSEL : Select Next0 register set */ + /* SBE : No discharge of buffer data when aborted */ + /* DEM : No DMA interrupt mask */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_DMS_SHIFT, + DMAC3_CHCFG_n_DMS); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_RSEL_SHIFT, + DMAC3_CHCFG_n_RSEL); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_SBE_SHIFT, + DMAC3_CHCFG_n_SBE); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_DEM_SHIFT, + DMAC3_CHCFG_n_DEM); + + /* ---- Continuous transfer ---- */ + if (DMAC_SAMPLE_CONTINUATION == continuation) + { + /* REN : Execute continuous transfer */ + /* RSW : Change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 1, + DMAC3_CHCFG_n_REN_SHIFT, + DMAC3_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 1, + DMAC3_CHCFG_n_RSW_SHIFT, + DMAC3_CHCFG_n_RSW); + } + /* ---- Single transfer ---- */ + else + { + /* REN : Do not execute continuous transfer */ + /* RSW : Do not change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_REN_SHIFT, + DMAC3_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_RSW_SHIFT, + DMAC3_CHCFG_n_RSW); + } + + /* TM : Single transfer */ + /* SEL : Channel setting */ + /* HIEN, LOEN : On-chip peripheral module request */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_TM_SHIFT, + DMAC3_CHCFG_n_TM); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 3, + DMAC3_CHCFG_n_SEL_SHIFT, + DMAC3_CHCFG_n_SEL); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 1, + DMAC3_CHCFG_n_HIEN_SHIFT, + DMAC3_CHCFG_n_HIEN); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_LOEN_SHIFT, + DMAC3_CHCFG_n_LOEN); + + /* ---- Set factor by specified on-chip peripheral module request ---- */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_AM], + DMAC3_CHCFG_n_AM_SHIFT, + DMAC3_CHCFG_n_AM); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_LVL], + DMAC3_CHCFG_n_LVL_SHIFT, + DMAC3_CHCFG_n_LVL); + if (usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD] != DMAC_INDEFINE) + { + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD], + DMAC3_CHCFG_n_REQD_SHIFT, + DMAC3_CHCFG_n_REQD); + } + else + { + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + req_direction, + DMAC3_CHCFG_n_REQD_SHIFT, + DMAC3_CHCFG_n_REQD); + } + RZA_IO_RegWrite_32(&DMAC23.DMARS, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_RID], + DMAC23_DMARS_CH3_RID_SHIFT, + DMAC23_DMARS_CH3_RID); + RZA_IO_RegWrite_32(&DMAC23.DMARS, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_MID], + DMAC23_DMARS_CH3_MID_SHIFT, + DMAC23_DMARS_CH3_MID); + + /* PR : Round robin mode */ + RZA_IO_RegWrite_32(&DMAC07.DCTRL_0_7, + 1, + DMAC07_DCTRL_0_7_PR_SHIFT, + DMAC07_DCTRL_0_7_PR); + } +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC3_Open +* Description : Enables DMAC channel 3 transfer. +* Arguments : uint32_t req : DMAC request mode +* Return Value : 0 : Succeeded in enabling DMA transfer +* : -1 : Failed to enable DMA transfer (due to DMA operation) +*******************************************************************************/ +int32_t usb1_host_DMAC3_Open (uint32_t req) +{ + int32_t ret; + volatile uint8_t dummy; + + /* Transferable? */ + if ((0 == RZA_IO_RegRead_32(&DMAC3.CHSTAT_n, + DMAC3_CHSTAT_n_EN_SHIFT, + DMAC3_CHSTAT_n_EN)) && + (0 == RZA_IO_RegRead_32(&DMAC3.CHSTAT_n, + DMAC3_CHSTAT_n_TACT_SHIFT, + DMAC3_CHSTAT_n_TACT))) + { + /* Clear Channel Status Register */ + RZA_IO_RegWrite_32(&DMAC3.CHCTRL_n, + 1, + DMAC3_CHCTRL_n_SWRST_SHIFT, + DMAC3_CHCTRL_n_SWRST); + dummy = RZA_IO_RegRead_32(&DMAC3.CHCTRL_n, + DMAC3_CHCTRL_n_SWRST_SHIFT, + DMAC3_CHCTRL_n_SWRST); + /* Enable DMA transfer */ + RZA_IO_RegWrite_32(&DMAC3.CHCTRL_n, + 1, + DMAC3_CHCTRL_n_SETEN_SHIFT, + DMAC3_CHCTRL_n_SETEN); + + /* ---- Request by software ---- */ + if (DMAC_REQ_MODE_SOFT == req) + { + /* DMA transfer Request by software */ + RZA_IO_RegWrite_32(&DMAC3.CHCTRL_n, + 1, + DMAC3_CHCTRL_n_STG_SHIFT, + DMAC3_CHCTRL_n_STG); + } + + ret = 0; + } + else + { + ret = -1; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC3_Close +* Description : Aborts DMAC channel 3 transfer. Returns the remaining transfer +* : byte count at the time of DMA transfer abort to the argument +* : *remain. +* Arguments : uint32_t * remain : Remaining transfer byte count when +* : : DMA transfer is aborted +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC3_Close (uint32_t * remain) +{ + + /* ==== Abort transfer ==== */ + RZA_IO_RegWrite_32(&DMAC3.CHCTRL_n, + 1, + DMAC3_CHCTRL_n_CLREN_SHIFT, + DMAC3_CHCTRL_n_CLREN); + + while (1 == RZA_IO_RegRead_32(&DMAC3.CHSTAT_n, + DMAC3_CHSTAT_n_TACT_SHIFT, + DMAC3_CHSTAT_n_TACT)) + { + /* Loop until transfer is aborted */ + } + + while (1 == RZA_IO_RegRead_32(&DMAC3.CHSTAT_n, + DMAC3_CHSTAT_n_EN_SHIFT, + DMAC3_CHSTAT_n_EN)) + { + /* Loop until 0 is set in EN before checking the remaining transfer byte count */ + } + /* ==== Obtain remaining transfer byte count ==== */ + *remain = DMAC3.CRTB_n; +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC3_Load_Set +* Description : Sets the transfer source address, transfer destination +* : address, and total transfer byte count respectively +* : specified by the argument src_addr, dst_addr, and count to +* : DMAC channel 3 as DMA transfer information. +* : Sets the register set selected by the CHCFG_n register +* : RSEL bit from the Next0 or Next1 register set. +* : This function should be called when DMA transfer of DMAC +* : channel 3 is aboted. +* Arguments : uint32_t src_addr : Transfer source address +* : uint32_t dst_addr : Transfer destination address +* : uint32_t count : Total transfer byte count +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC3_Load_Set (uint32_t src_addr, uint32_t dst_addr, uint32_t count) +{ + uint8_t reg_set; + + /* Obtain register set in use */ + reg_set = RZA_IO_RegRead_32(&DMAC3.CHSTAT_n, + DMAC3_CHSTAT_n_SR_SHIFT, + DMAC3_CHSTAT_n_SR); + + /* ==== Load ==== */ + if (0 == reg_set) + { + /* ---- Next0 Register Set ---- */ + DMAC3.N0SA_n = src_addr; /* Start address of transfer source */ + DMAC3.N0DA_n = dst_addr; /* Start address of transfer destination */ + DMAC3.N0TB_n = count; /* Total transfer byte count */ + } + else + { + /* ---- Next1 Register Set ---- */ + DMAC3.N1SA_n = src_addr; /* Start address of transfer source */ + DMAC3.N1DA_n = dst_addr; /* Start address of transfer destination */ + DMAC3.N1TB_n = count; /* Total transfer byte count */ + } +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC4_PeriReqInit +* Description : Sets the register mode for DMA mode and the on-chip peripheral +* : module request for transfer request for DMAC channel 4. +* : Executes DMAC initial setting using the DMA information +* : specified by the argument *trans_info and the enabled/disabled +* : continuous transfer specified by the argument continuation. +* : Registers DMAC channel 4 interrupt handler function and sets +* : the interrupt priority level. Then enables transfer completion +* : interrupt. +* Arguments : dmac_transinfo_t * trans_info : Setting information to DMAC +* : : register +* : uint32_t dmamode : DMA mode (only for DMAC_MODE_REGISTER) +* : uint32_t continuation : Set continuous transfer to be valid +* : : after DMA transfer has been completed +* : DMAC_SAMPLE_CONTINUATION : Execute continuous transfer +* : DMAC_SAMPLE_SINGLE : Do not execute continuous +* : : transfer +* : uint32_t request_factor : Factor for on-chip peripheral module +* : : request +* : DMAC_REQ_OSTM0TINT : OSTM_0 compare match +* : DMAC_REQ_OSTM1TINT : OSTM_1 compare match +* : DMAC_REQ_TGI0A : MTU2_0 input capture/compare match +* : : +* : uint32_t req_direction : Setting value of CHCFG_n register +* : : REQD bit +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC4_PeriReqInit (const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction) +{ + /* ==== Register mode ==== */ + if (DMAC_MODE_REGISTER == dmamode) + { + /* ==== Next0 register set ==== */ + DMAC4.N0SA_n = trans_info->src_addr; /* Start address of transfer source */ + DMAC4.N0DA_n = trans_info->dst_addr; /* Start address of transfer destination */ + DMAC4.N0TB_n = trans_info->count; /* Total transfer byte count */ + + /* DAD : Transfer destination address counting direction */ + /* SAD : Transfer source address counting direction */ + /* DDS : Transfer destination transfer size */ + /* SDS : Transfer source transfer size */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + trans_info->daddr_dir, + DMAC4_CHCFG_n_DAD_SHIFT, + DMAC4_CHCFG_n_DAD); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + trans_info->saddr_dir, + DMAC4_CHCFG_n_SAD_SHIFT, + DMAC4_CHCFG_n_SAD); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + trans_info->dst_size, + DMAC4_CHCFG_n_DDS_SHIFT, + DMAC4_CHCFG_n_DDS); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + trans_info->src_size, + DMAC4_CHCFG_n_SDS_SHIFT, + DMAC4_CHCFG_n_SDS); + + /* DMS : Register mode */ + /* RSEL : Select Next0 register set */ + /* SBE : No discharge of buffer data when aborted */ + /* DEM : No DMA interrupt mask */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_DMS_SHIFT, + DMAC4_CHCFG_n_DMS); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_RSEL_SHIFT, + DMAC4_CHCFG_n_RSEL); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_SBE_SHIFT, + DMAC4_CHCFG_n_SBE); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_DEM_SHIFT, + DMAC4_CHCFG_n_DEM); + + /* ---- Continuous transfer ---- */ + if (DMAC_SAMPLE_CONTINUATION == continuation) + { + /* REN : Execute continuous transfer */ + /* RSW : Change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 1, + DMAC4_CHCFG_n_REN_SHIFT, + DMAC4_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 1, + DMAC4_CHCFG_n_RSW_SHIFT, + DMAC4_CHCFG_n_RSW); + } + /* ---- Single transfer ---- */ + else + { + /* REN : Do not execute continuous transfer */ + /* RSW : Do not change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_REN_SHIFT, + DMAC4_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_RSW_SHIFT, + DMAC4_CHCFG_n_RSW); + } + + /* TM : Single transfer */ + /* SEL : Channel setting */ + /* HIEN, LOEN : On-chip peripheral module request */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_TM_SHIFT, + DMAC4_CHCFG_n_TM); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 4, + DMAC4_CHCFG_n_SEL_SHIFT, + DMAC4_CHCFG_n_SEL); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 1, + DMAC4_CHCFG_n_HIEN_SHIFT, + DMAC4_CHCFG_n_HIEN); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_LOEN_SHIFT, + DMAC4_CHCFG_n_LOEN); + + /* ---- Set factor by specified on-chip peripheral module request ---- */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_AM], + DMAC4_CHCFG_n_AM_SHIFT, + DMAC4_CHCFG_n_AM); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_LVL], + DMAC4_CHCFG_n_LVL_SHIFT, + DMAC4_CHCFG_n_LVL); + if (usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD] != DMAC_INDEFINE) + { + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD], + DMAC4_CHCFG_n_REQD_SHIFT, + DMAC4_CHCFG_n_REQD); + } + else + { + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + req_direction, + DMAC4_CHCFG_n_REQD_SHIFT, + DMAC4_CHCFG_n_REQD); + } + RZA_IO_RegWrite_32(&DMAC45.DMARS, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_RID], + DMAC45_DMARS_CH4_RID_SHIFT, + DMAC45_DMARS_CH4_RID); + RZA_IO_RegWrite_32(&DMAC45.DMARS, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_MID], + DMAC45_DMARS_CH4_MID_SHIFT, + DMAC45_DMARS_CH4_MID); + + /* PR : Round robin mode */ + RZA_IO_RegWrite_32(&DMAC07.DCTRL_0_7, + 1, + DMAC07_DCTRL_0_7_PR_SHIFT, + DMAC07_DCTRL_0_7_PR); + } +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC4_Open +* Description : Enables DMAC channel 4 transfer. +* Arguments : uint32_t req : DMAC request mode +* Return Value : 0 : Succeeded in enabling DMA transfer +* : -1 : Failed to enable DMA transfer (due to DMA operation) +*******************************************************************************/ +int32_t usb1_host_DMAC4_Open (uint32_t req) +{ + int32_t ret; + volatile uint8_t dummy; + + /* Transferable? */ + if ((0 == RZA_IO_RegRead_32(&DMAC4.CHSTAT_n, + DMAC4_CHSTAT_n_EN_SHIFT, + DMAC4_CHSTAT_n_EN)) && + (0 == RZA_IO_RegRead_32(&DMAC4.CHSTAT_n, + DMAC4_CHSTAT_n_TACT_SHIFT, + DMAC4_CHSTAT_n_TACT))) + { + /* Clear Channel Status Register */ + RZA_IO_RegWrite_32(&DMAC4.CHCTRL_n, + 1, + DMAC4_CHCTRL_n_SWRST_SHIFT, + DMAC4_CHCTRL_n_SWRST); + dummy = RZA_IO_RegRead_32(&DMAC4.CHCTRL_n, + DMAC4_CHCTRL_n_SWRST_SHIFT, + DMAC4_CHCTRL_n_SWRST); + /* Enable DMA transfer */ + RZA_IO_RegWrite_32(&DMAC4.CHCTRL_n, + 1, + DMAC4_CHCTRL_n_SETEN_SHIFT, + DMAC4_CHCTRL_n_SETEN); + + /* ---- Request by software ---- */ + if (DMAC_REQ_MODE_SOFT == req) + { + /* DMA transfer Request by software */ + RZA_IO_RegWrite_32(&DMAC4.CHCTRL_n, + 1, + DMAC4_CHCTRL_n_STG_SHIFT, + DMAC4_CHCTRL_n_STG); + } + + ret = 0; + } + else + { + ret = -1; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC4_Close +* Description : Aborts DMAC channel 4 transfer. Returns the remaining transfer +* : byte count at the time of DMA transfer abort to the argument +* : *remain. +* Arguments : uint32_t * remain : Remaining transfer byte count when +* : : DMA transfer is aborted +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC4_Close (uint32_t * remain) +{ + + /* ==== Abort transfer ==== */ + RZA_IO_RegWrite_32(&DMAC4.CHCTRL_n, + 1, + DMAC4_CHCTRL_n_CLREN_SHIFT, + DMAC4_CHCTRL_n_CLREN); + + while (1 == RZA_IO_RegRead_32(&DMAC4.CHSTAT_n, + DMAC4_CHSTAT_n_TACT_SHIFT, + DMAC4_CHSTAT_n_TACT)) + { + /* Loop until transfer is aborted */ + } + + while (1 == RZA_IO_RegRead_32(&DMAC4.CHSTAT_n, + DMAC4_CHSTAT_n_EN_SHIFT, + DMAC4_CHSTAT_n_EN)) + { + /* Loop until 0 is set in EN before checking the remaining transfer byte count */ + } + /* ==== Obtain remaining transfer byte count ==== */ + *remain = DMAC4.CRTB_n; +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC4_Load_Set +* Description : Sets the transfer source address, transfer destination +* : address, and total transfer byte count respectively +* : specified by the argument src_addr, dst_addr, and count to +* : DMAC channel 4 as DMA transfer information. +* : Sets the register set selected by the CHCFG_n register +* : RSEL bit from the Next0 or Next1 register set. +* : This function should be called when DMA transfer of DMAC +* : channel 4 is aboted. +* Arguments : uint32_t src_addr : Transfer source address +* : uint32_t dst_addr : Transfer destination address +* : uint32_t count : Total transfer byte count +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC4_Load_Set (uint32_t src_addr, uint32_t dst_addr, uint32_t count) +{ + uint8_t reg_set; + + /* Obtain register set in use */ + reg_set = RZA_IO_RegRead_32(&DMAC4.CHSTAT_n, + DMAC4_CHSTAT_n_SR_SHIFT, + DMAC4_CHSTAT_n_SR); + + /* ==== Load ==== */ + if (0 == reg_set) + { + /* ---- Next0 Register Set ---- */ + DMAC4.N0SA_n = src_addr; /* Start address of transfer source */ + DMAC4.N0DA_n = dst_addr; /* Start address of transfer destination */ + DMAC4.N0TB_n = count; /* Total transfer byte count */ + } + else + { + /* ---- Next1 Register Set ---- */ + DMAC4.N1SA_n = src_addr; /* Start address of transfer source */ + DMAC4.N1DA_n = dst_addr; /* Start address of transfer destination */ + DMAC4.N1TB_n = count; /* Total transfer byte count */ + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb1/src/userdef/usb1_host_userdef.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,778 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_userdef.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include <stdio.h> +#include "cmsis_os.h" +#include "r_typedefs.h" +#include "iodefine.h" +#include "devdrv_usb_host_api.h" +#include "usb1_host.h" +#include "MBRZA1H.h" /* INTC Driver Header */ +#include "usb1_host_dmacdrv.h" +#include "ohci_wrapp_RZ_A1_local.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define DUMMY_ACCESS OSTM0CNT + +/* #define CACHE_WRITEBACK */ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +extern int32_t io_cwb(unsigned long start, unsigned long end); + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb1_host_enable_dmac0(uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc); +static void usb1_host_enable_dmac1(uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc); +static void Userdef_USB_usb1_host_delay_10us_2(void); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_d0fifo_dmaintid +* Description : get D0FIFO DMA Interrupt ID +* Arguments : none +* Return Value : D0FIFO DMA Interrupt ID +*******************************************************************************/ +uint16_t Userdef_USB_usb1_host_d0fifo_dmaintid (void) +{ +#if(1) /* ohci_wrapp */ + return 0xFFFF; +#else + return DMAINT1_IRQn; +#endif +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_d1fifo_dmaintid +* Description : get D1FIFO DMA Interrupt ID +* Arguments : none +* Return Value : D1FIFO DMA Interrupt ID +*******************************************************************************/ +uint16_t Userdef_USB_usb1_host_d1fifo_dmaintid (void) +{ +#if(1) /* ohci_wrapp */ + return 0xFFFF; +#else + return DMAINT2_IRQn; +#endif +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_attach +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_attach (void) +{ +// printf("\n"); +// printf("channel 1 attach device\n"); +// printf("\n"); + ohciwrapp_loc_Connect(1); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_detach +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_detach (void) +{ +// printf("\n"); +// printf("channel 1 detach device\n"); +// printf("\n"); + ohciwrapp_loc_Connect(0); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_delay_1ms +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_delay_1ms (void) +{ + osDelay(1); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_delay_xms +* Description : Wait for the software in the period of time specified by the +* : argument. +* : Alter this function according to the user's system. +* Arguments : uint32_t msec ; Wait Time (msec) +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_delay_xms (uint32_t msec) +{ + osDelay(msec); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_delay_10us +* Description : Waits for software for the period specified by the argument. +* : Alter this function according to the user's system. +* Arguments : uint32_t usec ; Wait Time(x 10usec) +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_delay_10us (uint32_t usec) +{ + volatile int i; + + /* Wait 10us (Please change for your MCU) */ + for (i = 0; i < usec; ++i) + { + Userdef_USB_usb1_host_delay_10us_2(); + } +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_delay_10us_2 +* Description : Waits for software for the period specified by the argument. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +static void Userdef_USB_usb1_host_delay_10us_2 (void) +{ + volatile int i; + volatile unsigned long tmp; + + /* Wait 1us (Please change for your MCU) */ + for (i = 0; i < 14; ++i) + { + tmp = DUMMY_ACCESS; + } +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_delay_500ns +* Description : Wait for software for 500ns. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_delay_500ns (void) +{ + volatile int i; + volatile unsigned long tmp; + + /* Wait 500ns (Please change for your MCU) */ + /* Wait 500ns I clock 266MHz */ + tmp = DUMMY_ACCESS; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_start_dma +* Description : Enables DMA transfer on the information specified by the argument. +* : Set DMAC register by this function to enable DMA transfer. +* : After executing this function, USB module is set to start DMA +* : transfer. DMA transfer should not wait for DMA transfer complete. +* Arguments : USB_HOST_DMA_t *dma : DMA parameter +* : typedef struct{ +* : uint32_t fifo; FIFO for using +* : uint32_t buffer; Start address of transfer source/destination +* : uint32_t bytes; Transfer size(Byte) +* : uint32_t dir; Transfer direction(0:Buffer->FIFO, 1:FIFO->Buffer) +* : uint32_t size; DMA transfer size +* : } USB_HOST_DMA_t; +* : uint16_t dfacc ; 0 : cycle steal mode +* : 1 : 16byte continuous mode +* : 2 : 32byte continuous mode +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_start_dma (USB_HOST_DMA_t * dma, uint16_t dfacc) +{ + uint32_t trncount; + uint32_t src; + uint32_t dst; + uint32_t size; + uint32_t dir; +#ifdef CACHE_WRITEBACK + uint32_t ptr; +#endif + + trncount = dma->bytes; + dir = dma->dir; + + if (dir == USB_HOST_FIFO2BUF) + { + /* DxFIFO determination */ + dst = dma->buffer; +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB201.D1FIFO.UINT32); + } + size = dma->size; + + if (size == 0) + { + src += 3; /* byte access */ + } + else if (size == 1) + { + src += 2; /* short access */ + } + else + { + /* Do Nothing */ + } +#else + size = dma->size; + + if (size == 2) + { + /* 32bit access */ + if (dfacc == 2) + { + /* 32byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFOB0); + } + else + { + src = (uint32_t)(&USB201.D1FIFOB0); + } + } + else if (dfacc == 1) + { + /* 16byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFOB0); + } + else + { + src = (uint32_t)(&USB201.D1FIFOB0); + } + } + else + { + /* normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB201.D1FIFO.UINT32); + } + } + } + else if (size == 1) + { + /* 16bit access */ + dfacc = 0; /* force normal access */ + + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB201.D1FIFO.UINT32); + } + src += 2; /* short access */ + } + else + { + /* 8bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB201.D1FIFO.UINT32); + } + src += 3; /* byte access */ + } +#endif + } + else + { + /* DxFIFO determination */ + src = dma->buffer; +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB201.D1FIFO.UINT32); + } + size = dma->size; + + if (size == 0) + { + dst += 3; /* byte access */ + } + else if (size == 1) + { + dst += 2; /* short access */ + } + else + { + /* Do Nothing */ + } +#else + size = dma->size; + if (size == 2) + { + /* 32bit access */ + if (dfacc == 2) + { + /* 32byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFOB0); + } + else + { + dst = (uint32_t)(&USB201.D1FIFOB0); + } + } + else if (dfacc == 1) + { + /* 16byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFOB0); + } + else + { + dst = (uint32_t)(&USB201.D1FIFOB0); + } + } + else + { + /* normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB201.D1FIFO.UINT32); + } + } + } + else if (size == 1) + { + /* 16bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB201.D1FIFO.UINT32); + } + dst += 2; /* short access */ + } + else + { + /* 8bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB201.D1FIFO.UINT32); + } + dst += 3; /* byte access */ + } +#endif + } + +#ifdef CACHE_WRITEBACK + ptr = (uint32_t)dma->buffer; + if ((ptr & 0x20000000ul) == 0) + { + io_cwb((uint32_t)ptr,(uint32_t)(ptr)+trncount); + } +#endif + + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + usb1_host_enable_dmac0(src, dst, trncount, size, dir, dma->fifo, dfacc); + } + else + { + usb1_host_enable_dmac1(src, dst, trncount, size, dir, dma->fifo, dfacc); + } +} + +/******************************************************************************* +* Function Name: usb1_host_enable_dmac0 +* Description : Enables DMA transfer on the information specified by the argument. +* Arguments : uint32_t src : src address +* : uint32_t dst : dst address +* : uint32_t count : transfer byte +* : uint32_t size : transfer size +* : uint32_t dir : direction +* : uint32_t fifo : FIFO(D0FIFO or D1FIFO) +* : uint16_t dfacc : 0 : normal access +* : : 1 : 16byte access +* : : 2 : 32byte access +* Return Value : none +*******************************************************************************/ +static void usb1_host_enable_dmac0 (uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc) +{ + dmac_transinfo_t trans_info; + uint32_t request_factor = 0; + int32_t ret; + + /* ==== Variable setting for DMAC initialization ==== */ + trans_info.src_addr = (uint32_t)src; /* Start address of transfer source */ + trans_info.dst_addr = (uint32_t)dst; /* Start address of transfer destination */ + trans_info.count = (uint32_t)count; /* Total byte count to be transferred */ +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } +#else + if (dfacc == 2) + { + /* 32byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_256; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_256; /* Transfer destination transfer size */ + } + else if (dfacc == 1) + { + /* 16byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_128; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_128; /* Transfer destination transfer size */ + } + else + { + /* normal access */ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } + } +#endif + + if (dir == USB_HOST_FIFO2BUF) + { + request_factor = DMAC_REQ_USB1_DMA0_RX; /* USB_0 channel 0 receive FIFO full */ + trans_info.saddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer destination address */ + } + else if (dir == USB_HOST_BUF2FIFO) + { + request_factor = DMAC_REQ_USB1_DMA0_TX; /* USB_0 channel 0 receive FIFO empty */ + trans_info.saddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer destination address */ + } + else + { + /* Do Nothing */ + } + + /* ==== DMAC initialization ==== */ + usb1_host_DMAC3_PeriReqInit((const dmac_transinfo_t *)&trans_info, + DMAC_MODE_REGISTER, + DMAC_SAMPLE_SINGLE, + request_factor, + 0); /* Don't care DMAC_REQ_REQD is setting in usb1_host_DMAC3_PeriReqInit() */ + + /* ==== DMAC startup ==== */ + ret = usb1_host_DMAC3_Open(DMAC_REQ_MODE_PERI); + + if (ret != 0) + { +// printf("DMAC3 Open error!!\n"); + } + + return; +} + +/******************************************************************************* +* Function Name: usb1_host_enable_dmac1 +* Description : Enables DMA transfer on the information specified by the argument. +* Arguments : uint32_t src : src address +* : uint32_t dst : dst address +* : uint32_t count : transfer byte +* : uint32_t size : transfer size +* : uint32_t dir : direction +* : uint32_t fifo : FIFO(D0FIFO or D1FIFO) +* : uint16_t dfacc : 0 : normal access +* : : 1 : 16byte access +* : : 2 : 32byte access +* Return Value : none +*******************************************************************************/ +static void usb1_host_enable_dmac1 (uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc) +{ + dmac_transinfo_t trans_info; + uint32_t request_factor = 0; + int32_t ret; + + /* ==== Variable setting for DMAC initialization ==== */ + trans_info.src_addr = (uint32_t)src; /* Start address of transfer source */ + trans_info.dst_addr = (uint32_t)dst; /* Start address of transfer destination */ + trans_info.count = (uint32_t)count; /* Total byte count to be transferred */ +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } +#else + if (dfacc == 2) + { + /* 32byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_256; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_256; /* Transfer destination transfer size */ + } + else if (dfacc == 1) + { + /* 16byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_128; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_128; /* Transfer destination transfer size */ + } + else + { + /* normal access */ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } + } +#endif + + if (dir == USB_HOST_FIFO2BUF) + { + request_factor =DMAC_REQ_USB1_DMA1_RX; /* USB_0 channel 0 receive FIFO full */ + trans_info.saddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer destination address */ + } + else if (dir == USB_HOST_BUF2FIFO) + { + request_factor =DMAC_REQ_USB1_DMA1_TX; /* USB_0 channel 0 receive FIFO empty */ + trans_info.saddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer destination address */ + } + else + { + /* Do Nothing */ + } + + /* ==== DMAC initialization ==== */ + usb1_host_DMAC4_PeriReqInit((const dmac_transinfo_t *)&trans_info, + DMAC_MODE_REGISTER, + DMAC_SAMPLE_SINGLE, + request_factor, + 0); /* Don't care DMAC_REQ_REQD is setting in usb1_host_DMAC4_PeriReqInit() */ + + /* ==== DMAC startup ==== */ + ret = usb1_host_DMAC4_Open(DMAC_REQ_MODE_PERI); + + if (ret != 0) + { +// printf("DMAC4 Open error!!\n"); + } + + return; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_stop_dma0 +* Description : Disables DMA transfer. +* Arguments : none +* Return Value : uint32_t return Transfer Counter register(DMATCRn) value +* : regarding to the bus width. +* Notice : This function should be executed to DMAC executed at the time +* : of specification of D0_FIF0_DMA in dma->fifo. +*******************************************************************************/ +uint32_t Userdef_USB_usb1_host_stop_dma0 (void) +{ + uint32_t remain; + + /* ==== DMAC release ==== */ + usb1_host_DMAC3_Close(&remain); + + return remain; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_stop_dma1 +* Description : Disables DMA transfer. +* : This function should be executed to DMAC executed at the time +* : of specification of D1_FIF0_DMA in dma->fifo. +* Arguments : none +* Return Value : uint32_t return Transfer Counter register(DMATCRn) value +* : regarding to the bus width. +*******************************************************************************/ +uint32_t Userdef_USB_usb1_host_stop_dma1 (void) +{ + uint32_t remain; + + /* ==== DMAC release ==== */ + usb1_host_DMAC4_Close(&remain); + + return remain; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_notice +* Description : Notice of USER +* Arguments : const char *format +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_notice (const char * format) +{ +// printf(format); + + return; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_user_rdy +* Description : This function notify a user and wait for trigger +* Arguments : const char *format +* : uint16_t data +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_user_rdy (const char * format, uint16_t data) +{ +// printf(format, data); + getchar(); + + return; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_RZ_A1H/usb_host_setting.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,100 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2014 - 2015 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ + +#ifndef USB_HOST_SETTING_H +#define USB_HOST_SETTING_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define USB_HOST_CH 0 +#define USB_HOST_HISPEED 1 + +#define INT_TRANS_MAX_NUM 4 /* min:1 max:4 */ +#define ISO_TRANS_MAX_NUM 0 /* min:0 max:2 */ + +#if (USB_HOST_CH == 0) +#include "usb0_host.h" +#define USB20X USB200 +#define USBIXUSBIX USBI0_IRQn +#define g_usbx_host_SupportUsbDeviceSpeed g_usb0_host_SupportUsbDeviceSpeed +#define g_usbx_host_UsbDeviceSpeed g_usb0_host_UsbDeviceSpeed +#define g_usbx_host_CmdStage g_usb0_host_CmdStage +#define g_usbx_host_pipe_status g_usb0_host_pipe_status +#define g_usbx_host_data_pointer g_usb0_host_data_pointer +#define g_usbx_host_data_count g_usb0_host_data_count +#define usbx_api_host_init usb0_api_host_init +#define usbx_host_UsbBusReset usb0_host_UsbBusReset +#define usbx_host_get_devadd usb0_host_get_devadd +#define usbx_host_set_devadd usb0_host_set_devadd +#define usbx_host_SetupStage usb0_host_SetupStage +#define usbx_host_CtrlWriteStart usb0_host_CtrlWriteStart +#define usbx_host_CtrlReadStart usb0_host_CtrlReadStart +#define usbx_api_host_SetEndpointTable usb0_api_host_SetEndpointTable +#define usbx_host_start_send_transfer usb0_host_start_send_transfer +#define usbx_host_start_receive_transfer usb0_host_start_receive_transfer +#define usbx_host_stop_transfer usb0_host_stop_transfer +#define usbx_host_set_sqclr usb0_host_set_sqclr +#define usbx_host_set_sqset usb0_host_set_sqset +#define usbx_host_CheckAttach usb0_host_CheckAttach +#define usbx_host_UsbDetach usb0_host_UsbDetach +#define usbx_host_UsbAttach usb0_host_UsbAttach +#define usbx_host_init_pipe_status usb0_host_init_pipe_status +#define usbx_host_get_sqmon usb0_host_get_sqmon +#else +#include "usb1_host.h" +#define USB20X USB201 +#define USBIXUSBIX USBI1_IRQn +#define g_usbx_host_SupportUsbDeviceSpeed g_usb1_host_SupportUsbDeviceSpeed +#define g_usbx_host_UsbDeviceSpeed g_usb1_host_UsbDeviceSpeed +#define g_usbx_host_CmdStage g_usb1_host_CmdStage +#define g_usbx_host_pipe_status g_usb1_host_pipe_status +#define g_usbx_host_data_pointer g_usb1_host_data_pointer +#define g_usbx_host_data_count g_usb1_host_data_count +#define usbx_api_host_init usb1_api_host_init +#define usbx_host_UsbBusReset usb1_host_UsbBusReset +#define usbx_host_get_devadd usb1_host_get_devadd +#define usbx_host_set_devadd usb1_host_set_devadd +#define usbx_host_SetupStage usb1_host_SetupStage +#define usbx_host_CtrlWriteStart usb1_host_CtrlWriteStart +#define usbx_host_CtrlReadStart usb1_host_CtrlReadStart +#define usbx_api_host_SetEndpointTable usb1_api_host_SetEndpointTable +#define usbx_host_start_send_transfer usb1_host_start_send_transfer +#define usbx_host_start_receive_transfer usb1_host_start_receive_transfer +#define usbx_host_stop_transfer usb1_host_stop_transfer +#define usbx_host_set_sqclr usb1_host_set_sqclr +#define usbx_host_set_sqset usb1_host_set_sqset +#define usbx_host_CheckAttach usb1_host_CheckAttach +#define usbx_host_UsbDetach usb1_host_UsbDetach +#define usbx_host_UsbAttach usb1_host_UsbAttach +#define usbx_host_init_pipe_status usb1_host_init_pipe_status +#define usbx_host_get_sqmon usb1_host_get_sqmon +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* USB_HOST_SETTING_H */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/inc/devdrv_usb_host_api.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,329 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : devdrv_usb_host_api.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB_HOST_API_H +#define USB_HOST_API_H + +#include "r_typedefs.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define USB_HOST_PORTNUM (2) + +#define USB_HOST_ELT_INTERRUPT_LEVEL (9) + +#define USBHCLOCK_X1_48MHZ (0x0000u) /* USB_X1_48MHz */ +#define USBHCLOCK_EXTAL_12MHZ (0x0004u) /* EXTAL_12MHz */ + +#define USB_HOST_MAX_DEVICE (10) + +#define USB_HOST_ON (1) +#define USB_HOST_OFF (0) +#define USB_HOST_YES (1) +#define USB_HOST_NO (0) + +#define USB_HOST_NON_SPEED (0) +#define USB_HOST_LOW_SPEED (1) +#define USB_HOST_FULL_SPEED (2) +#define USB_HOST_HIGH_SPEED (3) + +/* DEVDRV_SUCCESS(0) & DEVDRV_ERROR(-1) is dev_drv.h */ +#define DEVDRV_USBH_STALL (-2) +#define DEVDRV_USBH_TIMEOUT (-3) +#define DEVDRV_USBH_NAK_TIMEOUT (-4) +#define DEVDRV_USBH_DETACH_ERR (-5) +#define DEVDRV_USBH_SETUP_ERR (-6) +#define DEVDRV_USBH_CTRL_COM_ERR (-7) +#define DEVDRV_USBH_COM_ERR (-8) +#define DEVDRV_USBH_DEV_ADDR_ERR (-9) + +#define USB_HOST_ATTACH (1) +#define USB_HOST_DETACH (0) + +#define USB_HOST_MAX_PIPE_NO (9u) +#define USB_HOST_PIPE0 (0) +#define USB_HOST_PIPE1 (1) +#define USB_HOST_PIPE2 (2) +#define USB_HOST_PIPE3 (3) +#define USB_HOST_PIPE4 (4) +#define USB_HOST_PIPE5 (5) +#define USB_HOST_PIPE6 (6) +#define USB_HOST_PIPE7 (7) +#define USB_HOST_PIPE8 (8) +#define USB_HOST_PIPE9 (9) + +#define USB_HOST_ISO (0xc000u) +#define USB_HOST_INTERRUPT (0x8000u) +#define USB_HOST_BULK (0x4000u) + +#define USB_HOST_PIPE_IDLE (0x00) +#define USB_HOST_PIPE_WAIT (0x01) +#define USB_HOST_PIPE_DONE (0x02) +#define USB_HOST_PIPE_NORES (0x03) +#define USB_HOST_PIPE_STALL (0x04) +#define USB_HOST_PIPE_ERROR (0x05) + +#define USB_HOST_NONE (0x0000u) +#define USB_HOST_BFREFIELD (0x0400u) +#define USB_HOST_BFREON (0x0400u) +#define USB_HOST_BFREOFF (0x0000u) +#define USB_HOST_DBLBFIELD (0x0200u) +#define USB_HOST_DBLBON (0x0200u) +#define USB_HOST_DBLBOFF (0x0000u) +#define USB_HOST_CNTMDFIELD (0x0100u) +#define USB_HOST_CNTMDON (0x0100u) +#define USB_HOST_CNTMDOFF (0x0000u) +#define USB_HOST_SHTNAKON (0x0080u) +#define USB_HOST_SHTNAKOFF (0x0000u) +#define USB_HOST_DIRFIELD (0x0010u) +#define USB_HOST_DIR_H_OUT (0x0010u) +#define USB_HOST_DIR_H_IN (0x0000u) +#define USB_HOST_EPNUMFIELD (0x000fu) + +#define USB_HOST_CUSE (0) +#define USB_HOST_D0USE (1) +#define USB_HOST_D0DMA (2) +#define USB_HOST_D1USE (3) +#define USB_HOST_D1DMA (4) + +#define USB_HOST_CFIFO_USE (0x0000) +#define USB_HOST_D0FIFO_USE (0x1000) +#define USB_HOST_D1FIFO_USE (0x2000) +#define USB_HOST_D0FIFO_DMA (0x5000) +#define USB_HOST_D1FIFO_DMA (0x6000) + +#define USB_HOST_BUF2FIFO (0) +#define USB_HOST_FIFO2BUF (1) + +#define USB_HOST_DRV_DETACHED (0x0000) +#define USB_HOST_DRV_ATTACHED (0x0001) +#define USB_HOST_DRV_GET_DEVICE_DESC_64 (0x0002) +#define USB_HOST_DRV_POWERED (0x0003) +#define USB_HOST_DRV_DEFAULT (0x0004) +#define USB_HOST_DRV_SET_ADDRESS (0x0005) +#define USB_HOST_DRV_ADDRESSED (0x0006) +#define USB_HOST_DRV_GET_DEVICE_DESC_18 (0x0007) +#define USB_HOST_DRV_GET_CONGIG_DESC_9 (0x0008) +#define USB_HOST_DRV_GET_CONGIG_DESC (0x0009) +#define USB_HOST_DRV_SET_CONFIG (0x000a) +#define USB_HOST_DRV_CONFIGURED (0x000b) +#define USB_HOST_DRV_SUSPEND (0x1000) +#define USB_HOST_DRV_NORES (0x0100) +#define USB_HOST_DRV_STALL (0x0200) + +#define USB_HOST_TESTMODE_FORCE (0x000du) +#define USB_HOST_TESTMODE_TESTPACKET (0x000cu) +#define USB_HOST_TESTMODE_SE0_NAK (0x000bu) +#define USB_HOST_TESTMODE_K (0x000au) +#define USB_HOST_TESTMODE_J (0x0009u) +#define USB_HOST_TESTMODE_NORMAL (0x0000u) + +#define USB_HOST_DT_DEVICE (0x01) +#define USB_HOST_DT_CONFIGURATION (0x02) +#define USB_HOST_DT_STRING (0x03) +#define USB_HOST_DT_INTERFACE (0x04) +#define USB_HOST_DT_ENDPOINT (0x05) +#define USB_HOST_DT_DEVICE_QUALIFIER (0x06) +#define USB_HOST_DT_OTHER_SPEED_CONFIGURATION (0x07) +#define USB_HOST_DT_INTERFACE_POWER (0x08) + +#define USB_HOST_IF_CLS_NOT (0x00) +#define USB_HOST_IF_CLS_AUDIO (0x01) +#define USB_HOST_IF_CLS_CDC_CTRL (0x02) +#define USB_HOST_IF_CLS_HID (0x03) +#define USB_HOST_IF_CLS_PHYSICAL (0x05) +#define USB_HOST_IF_CLS_IMAGE (0x06) +#define USB_HOST_IF_CLS_PRINTER (0x07) +#define USB_HOST_IF_CLS_MASS (0x08) +#define USB_HOST_IF_CLS_HUB (0x09) +#define USB_HOST_IF_CLS_CDC_DATA (0x0a) +#define USB_HOST_IF_CLS_CRAD (0x0b) +#define USB_HOST_IF_CLS_CONTENT (0x0d) +#define USB_HOST_IF_CLS_VIDEO (0x0e) +#define USB_HOST_IF_CLS_DIAG (0xdc) +#define USB_HOST_IF_CLS_WIRELESS (0xe0) +#define USB_HOST_IF_CLS_APL (0xfe) +#define USB_HOST_IF_CLS_VENDOR (0xff) +#define USB_HOST_IF_CLS_HELE (0xaa) + +#define USB_HOST_EP_DIR_MASK (0x80) +#define USB_HOST_EP_OUT (0x00) +#define USB_HOST_EP_IN (0x80) +#define USB_HOST_EP_TYPE (0x03) +#define USB_HOST_EP_CNTRL (0x00) +#define USB_HOST_EP_ISO (0x01) +#define USB_HOST_EP_BULK (0x02) +#define USB_HOST_EP_INT (0x03) +#define USB_HOST_EP_NUM_MASK (0x0f) + +#define USB_HOST_PIPE_IN (0) +#define USB_HOST_PIPE_OUT (1) + +#define USB_END_POINT_ERROR (0xffff) + +#define USB_HOST_REQ_GET_STATUS (0x0000) +#define USB_HOST_REQ_CLEAR_FEATURE (0x0100) +#define USB_HOST_REQ_RESERVED2 (0x0200) +#define USB_HOST_REQ_SET_FEATURE (0x0300) +#define USB_HOST_REQ_RESERVED4 (0x0400) +#define USB_HOST_REQ_SET_ADDRESS (0x0500) +#define USB_HOST_REQ_GET_DESCRIPTOR (0x0600) +#define USB_HOST_REQ_SET_DESCRIPTOR (0x0700) +#define USB_HOST_REQ_GET_CONFIGURATION (0x0800) +#define USB_HOST_REQ_SET_CONFIGURATION (0x0900) +#define USB_HOST_REQ_GET_INTERFACE (0x0a00) +#define USB_HOST_REQ_SET_INTERFACE (0x0b00) +#define USB_HOST_REQ_SYNCH_FRAME (0x0c00) + +#define USB_HOST_REQTYPE_HOST_TO_DEVICE (0x0000) +#define USB_HOST_REQTYPE_DEVICE_TO_HOST (0x0080) +#define USB_HOST_REQTYPE_STANDARD (0x0020) +#define USB_HOST_REQTYPE_CLASS (0x0040) +#define USB_HOST_REQTYPE_VENDOR (0x0060) +#define USB_HOST_REQTYPE_DEVICE (0x0000) +#define USB_HOST_REQTYPE_INTERFACE (0x0001) +#define USB_HOST_REQTYPE_ENDPOINT (0x0002) +#define USB_HOST_REQTYPE_OTHER (0x0003) + +#define USB_HOST_DESCTYPE_DEVICE (0x0100) +#define USB_HOST_DESCTYPE_CONFIGURATION (0x0200) +#define USB_HOST_DESCTYPE_STRING (0x0300) +#define USB_HOST_DESCTYPE_INTERFACE (0x0400) +#define USB_HOST_DESCTYPE_ENDPOINT (0x0500) +#define USB_HOST_DESCTYPE_DEVICE_QUALIFIER (0x0600) +#define USB_HOST_DESCTYPE_OTHER_SPEED_CONFIGURATION (0x0700) +#define USB_HOST_DESCTYPE_INTERFACE_POWER (0x0800) + + +/******************************************************************************* +Variable Externs +*******************************************************************************/ +typedef struct +{ + uint16_t pipe_number; + uint16_t pipe_cfg; + uint16_t pipe_buf; + uint16_t pipe_max_pktsize; + uint16_t pipe_cycle; + uint16_t fifo_port; +} USB_HOST_CFG_PIPETBL_t; + +typedef struct +{ + uint32_t fifo; + uint32_t buffer; + uint32_t bytes; + uint32_t dir; + uint32_t size; +} USB_HOST_DMA_t; + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +uint16_t R_USB_api_host_init(uint16_t root, uint8_t int_level, uint16_t mode, uint16_t clockmode); +int32_t R_USB_api_host_enumeration(uint16_t root, uint16_t devadr); +int32_t R_USB_api_host_detach(uint16_t root); +int32_t R_USB_api_host_data_in(uint16_t root, uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t R_USB_api_host_data_in2(uint16_t root, uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf, uint32_t *bytes); +int32_t R_USB_api_host_data_out(uint16_t root, uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t R_USB_api_host_control_transfer(uint16_t root, uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len, uint8_t *Buf); +int32_t R_USB_api_host_set_endpoint(uint16_t root, uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t *configdescriptor); +int32_t R_USB_api_host_clear_endpoint(uint16_t root, USB_HOST_CFG_PIPETBL_t *user_table); +int32_t R_USB_api_host_clear_endpoint_pipe(uint16_t root, uint16_t pipe_sel, USB_HOST_CFG_PIPETBL_t *user_table); +uint16_t R_USB_api_host_SetEndpointTable(uint16_t root, uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t* Table); + +int32_t R_USB_api_host_GetDeviceDescriptor(uint16_t root, uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t R_USB_api_host_GetConfigDescriptor(uint16_t root, uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t R_USB_api_host_SetConfig(uint16_t root, uint16_t devadr, uint16_t confignum); +int32_t R_USB_api_host_SetInterface(uint16_t root, uint16_t devadr, uint16_t interface_alt, uint16_t interface_index); +int32_t R_USB_api_host_ClearStall(uint16_t root, uint16_t devadr, uint16_t ep_dir); +uint16_t R_USB_api_host_GetUsbDeviceState(uint16_t root); + +void R_USB_api_host_elt_clocksel(uint16_t clockmode); +void R_USB_api_host_elt_4_4(uint16_t root); +void R_USB_api_host_elt_4_5(uint16_t root); +void R_USB_api_host_elt_4_6(uint16_t root); +void R_USB_api_host_elt_4_7(uint16_t root); +void R_USB_api_host_elt_4_8(uint16_t root); +void R_USB_api_host_elt_4_9(uint16_t root); +void R_USB_api_host_elt_get_desc(uint16_t root); + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host_api.h" +#include "usb1_host_api.h" + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +#ifdef USB0_HOST_API_H +uint16_t Userdef_USB_usb0_host_d0fifo_dmaintid(void); +uint16_t Userdef_USB_usb0_host_d1fifo_dmaintid(void); +void Userdef_USB_usb0_host_attach(void); +void Userdef_USB_usb0_host_detach(void); +void Userdef_USB_usb0_host_delay_1ms(void); +void Userdef_USB_usb0_host_delay_xms(uint32_t msec); +void Userdef_USB_usb0_host_delay_10us(uint32_t usec); +void Userdef_USB_usb0_host_delay_500ns(void); +void Userdef_USB_usb0_host_start_dma(USB_HOST_DMA_t * dma, uint16_t dfacc); +uint32_t Userdef_USB_usb0_host_stop_dma0(void); +uint32_t Userdef_USB_usb0_host_stop_dma1(void); +void Userdef_USB_usb0_host_notice(const char * format); +void Userdef_USB_usb0_host_user_rdy(const char * format, uint16_t data); +#endif + +#ifdef USB1_HOST_API_H +uint16_t Userdef_USB_usb1_host_d0fifo_dmaintid(void); +uint16_t Userdef_USB_usb1_host_d1fifo_dmaintid(void); +void Userdef_USB_usb1_host_attach(void); +void Userdef_USB_usb1_host_detach(void); +void Userdef_USB_usb1_host_delay_1ms(void); +void Userdef_USB_usb1_host_delay_xms(uint32_t msec); +void Userdef_USB_usb1_host_delay_10us(uint32_t usec); +void Userdef_USB_usb1_host_delay_500ns(void); +void Userdef_USB_usb1_host_start_dma(USB_HOST_DMA_t * dma, uint16_t dfacc); +uint32_t Userdef_USB_usb1_host_stop_dma0(void); +uint32_t Userdef_USB_usb1_host_stop_dma1(void); +void Userdef_USB_usb1_host_notice(const char * format); +void Userdef_USB_usb1_host_user_rdy(const char * format, uint16_t data); +#endif + +#endif /* USB_HOST_API_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/inc/usb_host.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,201 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb_host.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB_HOST_H +#define USB_HOST_H + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "r_typedefs.h" +#include "iodefine.h" +#include "rza_io_regrw.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define USB_HOST_DEVICE_0 (0u) +#define USB_HOST_DEVICE_1 (1u) +#define USB_HOST_DEVICE_2 (2u) +#define USB_HOST_DEVICE_3 (3u) +#define USB_HOST_DEVICE_4 (4u) +#define USB_HOST_DEVICE_5 (5u) +#define USB_HOST_DEVICE_6 (6u) +#define USB_HOST_DEVICE_7 (7u) +#define USB_HOST_DEVICE_8 (8u) +#define USB_HOST_DEVICE_9 (9u) +#define USB_HOST_DEVICE_10 (10u) + +#define USB_HOST_ENDPOINT_DESC (0x05) + +#define USB_HOST_BITUPLLE (0x0002u) +#define USB_HOST_BITUCKSEL (0x0004u) +#define USB_HOST_BITBWAIT (0x003fu) + +#define USB_HOST_BUSWAIT_02 (0x0000u) +#define USB_HOST_BUSWAIT_03 (0x0001u) +#define USB_HOST_BUSWAIT_04 (0x0002u) +#define USB_HOST_BUSWAIT_05 (0x0003u) +#define USB_HOST_BUSWAIT_06 (0x0004u) +#define USB_HOST_BUSWAIT_07 (0x0005u) +#define USB_HOST_BUSWAIT_08 (0x0006u) +#define USB_HOST_BUSWAIT_09 (0x0007u) +#define USB_HOST_BUSWAIT_10 (0x0008u) +#define USB_HOST_BUSWAIT_11 (0x0009u) +#define USB_HOST_BUSWAIT_12 (0x000au) +#define USB_HOST_BUSWAIT_13 (0x000bu) +#define USB_HOST_BUSWAIT_14 (0x000cu) +#define USB_HOST_BUSWAIT_15 (0x000du) +#define USB_HOST_BUSWAIT_16 (0x000eu) +#define USB_HOST_BUSWAIT_17 (0x000fu) + +#define USB_HOST_FS_JSTS (0x0001u) +#define USB_HOST_LS_JSTS (0x0002u) + +#define USB_HOST_BITRST (0x0040u) +#define USB_HOST_BITRESUME (0x0020u) +#define USB_HOST_BITUACT (0x0010u) +#define USB_HOST_HSPROC (0x0004u) +#define USB_HOST_HSMODE (0x0003u) +#define USB_HOST_FSMODE (0x0002u) +#define USB_HOST_LSMODE (0x0001u) +#define USB_HOST_UNDECID (0x0000u) + +#define USB_HOST_BITRCNT (0x8000u) +#define USB_HOST_BITDREQE (0x1000u) +#define USB_HOST_BITMBW (0x0c00u) +#define USB_HOST_BITMBW_8 (0x0000u) +#define USB_HOST_BITMBW_16 (0x0400u) +#define USB_HOST_BITMBW_32 (0x0800u) +#define USB_HOST_BITBYTE_LITTLE (0x0000u) +#define USB_HOST_BITBYTE_BIG (0x0100u) +#define USB_HOST_BITISEL (0x0020u) +#define USB_HOST_BITCURPIPE (0x000fu) + +#define USB_HOST_CFIFO_READ (0x0000u) +#define USB_HOST_CFIFO_WRITE (0x0020u) + +#define USB_HOST_BITBVAL (0x8000u) +#define USB_HOST_BITBCLR (0x4000u) +#define USB_HOST_BITFRDY (0x2000u) +#define USB_HOST_BITDTLN (0x0fffu) + +#define USB_HOST_BITBEMPE (0x0400u) +#define USB_HOST_BITNRDYE (0x0200u) +#define USB_HOST_BITBRDYE (0x0100u) +#define USB_HOST_BITBEMP (0x0400u) +#define USB_HOST_BITNRDY (0x0200u) +#define USB_HOST_BITBRDY (0x0100u) + +#define USB_HOST_BITBCHGE (0x4000u) +#define USB_HOST_BITDTCHE (0x1000u) +#define USB_HOST_BITATTCHE (0x0800u) +#define USB_HOST_BITEOFERRE (0x0040u) +#define USB_HOST_BITBCHG (0x4000u) +#define USB_HOST_BITDTCH (0x1000u) +#define USB_HOST_BITATTCH (0x0800u) +#define USB_HOST_BITEOFERR (0x0040u) + +#define USB_HOST_BITSIGNE (0x0020u) +#define USB_HOST_BITSACKE (0x0010u) +#define USB_HOST_BITSIGN (0x0020u) +#define USB_HOST_BITSACK (0x0010u) + +#define USB_HOST_BITSUREQ (0x4000u) +#define USB_HOST_BITSQSET (0x0080u) +#define USB_HOST_PID_STALL2 (0x0003u) +#define USB_HOST_PID_STALL (0x0002u) +#define USB_HOST_PID_BUF (0x0001u) +#define USB_HOST_PID_NAK (0x0000u) + +#define USB_HOST_PIPExBUF (64u) + +#define USB_HOST_D0FIFO (0) +#define USB_HOST_D1FIFO (1) +#define USB_HOST_DMA_READY (0) +#define USB_HOST_DMA_BUSY (1) +#define USB_HOST_DMA_BUSYEND (2) + +#define USB_HOST_FIFO_USE (0x7000) + +#define USB_HOST_FIFOERROR (0xffff) +#define USB_HOST_WRITEEND (0) +#define USB_HOST_WRITESHRT (1) +#define USB_HOST_WRITING (2) +#define USB_HOST_WRITEDMA (3) +#define USB_HOST_READEND (0) +#define USB_HOST_READSHRT (1) +#define USB_HOST_READING (2) +#define USB_HOST_READOVER (3) +#define USB_HOST_READZERO (4) + +#define USB_HOST_CMD_IDLE (0x0000) +#define USB_HOST_CMD_DOING (0x0001) +#define USB_HOST_CMD_DONE (0x0002) +#define USB_HOST_CMD_NORES (0x0003) +#define USB_HOST_CMD_STALL (0x0004) +#define USB_HOST_CMD_FIELD (0x000f) + +#if 0 +#define USB_HOST_CHG_CMDFIELD( r, v ) do { r &= ( ~USB_HOST_CMD_FIELD ); \ + r |= v; } while(0) +#endif + +#define USB_HOST_MODE_WRITE (0x0100) +#define USB_HOST_MODE_READ (0x0200) +#define USB_HOST_MODE_NO_DATA (0x0300) +#define USB_HOST_MODE_FIELD (0x0f00) + +#define USB_HOST_STAGE_SETUP (0x0010) +#define USB_HOST_STAGE_DATA (0x0020) +#define USB_HOST_STAGE_STATUS (0x0030) +#define USB_HOST_STAGE_FIELD (0x00f0) + +#if 0 +#define USB_HOST_CHG_STAGEFIELD( r, v ) do { r &= ( ~USB_HOST_STAGE_FIELD ); \ + r |= v; } while(0) +#endif + +#define USB_HOST_DEVADD_MASK (0x7fc0) + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +extern uint16_t g_usb_host_elt_clockmode; + +#endif /* USB_HOST_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/inc/usb_host_version.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,32 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb_host_version.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ + +#define USB_HOST_LOCAL_Rev "VER080_140709" + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/ohci_wrapp_RZ_A1.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,1492 @@ +/* Copyright (c) 2010-2011 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#include <string.h> +#include "cmsis.h" +#include "cmsis_os.h" +#include "ohci_wrapp_RZ_A1.h" +#include "ohci_wrapp_RZ_A1_local.h" +#include "rza_io_regrw.h" +#include "usb_host_setting.h" + +/* ------------------ HcControl Register --------------------- */ +#define OR_CONTROL_PLE (0x00000004) +#define OR_CONTROL_IE (0x00000008) +#define OR_CONTROL_CLE (0x00000010) +#define OR_CONTROL_BLE (0x00000020) +/* ----------------- HcCommandStatus Register ----------------- */ +#define OR_CMD_STATUS_HCR (0x00000001) +#define OR_CMD_STATUS_CLF (0x00000002) +#define OR_CMD_STATUS_BLF (0x00000004) +#define OR_CMD_STATUS_OCR (0x00000008) +/* --------------- HcInterruptStatus Register ----------------- */ +#define OR_INTR_STATUS_WDH (0x00000002) +#define OR_INTR_STATUS_RHSC (0x00000040) +/* --------------- HcInterruptEnable Register ----------------- */ +#define OR_INTR_ENABLE_WDH (0x00000002) +#define OR_INTR_ENABLE_RHSC (0x00000040) +/* -------------- HcRhPortStatus[1:NDP] Register -------------- */ +#define OR_RH_PORT_CSC (0x00010000) +#define OR_RH_PORT_LSDA (0x00000200) +#define OR_RH_PORT_PRS (0x00000010) +#define OR_RH_PORT_POCI (0x00000008) +#define OR_RH_PORT_CCS (0x00000001) + +#define ED_FORMAT (0x00008000) /* Format */ +#define ED_SKIP (0x00004000) /* Skip this ep in queue */ +#define ED_TOGLE_CARRY (0x00000002) +#define ED_HALTED (0x00000001) + +#define TD_SETUP (0x00000000) /* Direction of Setup Packet */ +#define TD_OUT (0x00080000) /* Direction Out */ +#define TD_TOGGLE_0 (0x02000000) /* Toggle 0 */ +#define TD_TOGGLE_1 (0x03000000) /* Toggle 1 */ + +/* -------------- USB Standard Requests -------------- */ +#define GET_STATUS (0x00) +#define SET_FEATURE (0x03) +#define SET_ADDRESS (0x05) + +#define TD_CTL_MSK_DP (0x00180000) +#define TD_CTL_MSK_T (0x03000000) +#define TD_CTL_MSK_CC (0xF0000000) +#define TD_CTL_MSK_EC (0x0C000000) +#define TD_CTL_SHFT_CC (28) +#define TD_CTL_SHFT_EC (26) +#define TD_CTL_SHFT_T (24) +#define ED_SHFT_TOGLE_CARRY (1) +#define SIG_GEN_LIST_REQ (1) +#if (ISO_TRANS_MAX_NUM > 0) +#define TD_PSW_MSK_CC (0xF000) +#define TD_PSW_SHFT_CC (12) +#define TD_CTL_MSK_FC (0x07000000) +#define TD_CTL_SHFT_FC (24) +#endif + +#define CTL_TRANS_TIMEOUT (1000) +#define BLK_TRANS_TIMEOUT (5) +#define TOTAL_SEM_NUM (5 + (2 * INT_TRANS_MAX_NUM) + (2 * ISO_TRANS_MAX_NUM)) + +#define PORT_LOW_SPEED (0x00000200) +#define PORT_HIGH_SPEED (0x00000400) +#define PORT_NUM (16 + 1) /* num + root(1) */ + +typedef struct tag_hctd { + uint32_t control; /* Transfer descriptor control */ + uint8_t *currBufPtr; /* Physical address of current buffer pointer */ + struct tag_hctd *nextTD; /* Physical pointer to next Transfer Descriptor */ + uint8_t *bufEnd; /* Physical address of end of buffer */ +} hctd_t; + +#if (ISO_TRANS_MAX_NUM > 0) +#define PSW_NUM (8) +typedef struct tag_hcisotd { + uint32_t control; /* Transfer descriptor control */ + uint8_t *bufferPage0; /* Buffer Page 0 */ + struct tag_hcisotd *nextTD; /* Physical pointer to next Transfer Descriptor */ + uint8_t *bufEnd; /* Physical address of end of buffer */ + uint16_t offsetPSW[PSW_NUM]; /* Offset/PSW */ +} hcisotd_t; +#endif + +typedef struct tag_hced { + uint32_t control; /* Endpoint descriptor control */ + uint32_t tailTD; /* Physical address of tail in Transfer descriptor list */ + uint32_t headTD; /* Physcial address of head in Transfer descriptor list */ + struct tag_hced *nextED; /* Physical address of next Endpoint descriptor */ +} hced_t; + +typedef struct tag_hcca { + uint32_t IntTable[32]; /* Interrupt Table */ + uint32_t FrameNumber; /* Frame Number */ + uint32_t DoneHead; /* Done Head */ + volatile uint8_t Reserved[116]; /* Reserved for future use */ + volatile uint8_t Unknown[4]; /* Unused */ +} hcca_t; + +typedef struct tag_usb_ohci_reg { + volatile uint32_t HcRevision; + volatile uint32_t HcControl; + volatile uint32_t HcCommandStatus; + volatile uint32_t HcInterruptStatus; + volatile uint32_t HcInterruptEnable; + volatile uint32_t HcInterruptDisable; + volatile uint32_t HcHCCA; + volatile uint32_t HcPeriodCurrentED; + volatile uint32_t HcControlHeadED; + volatile uint32_t HcControlCurrentED; + volatile uint32_t HcBulkHeadED; + volatile uint32_t HcBulkCurrentED; + volatile uint32_t HcDoneHead; + volatile uint32_t HcFmInterval; + volatile uint32_t HcFmRemaining; + volatile uint32_t HcFmNumber; + volatile uint32_t HcPeriodicStart; + volatile uint32_t HcLSThreshold; + volatile uint32_t HcRhDescriptorA; + volatile uint32_t HcRhDescriptorB; + volatile uint32_t HcRhStatus; + volatile uint32_t HcRhPortStatus1; +} usb_ohci_reg_t; + +typedef struct tag_genelal_ed { + osThreadId tskid; + osSemaphoreId semid_wait; + osSemaphoreId semid_list; + void *p_curr_td; /* pointer of hctd_t or hcisotd_t */ + hced_t *p_curr_ed; + uint32_t pipe_no; + uint32_t trans_wait; + uint32_t cycle_time; + uint8_t *p_start_buf; +#if (ISO_TRANS_MAX_NUM > 0) + uint32_t psw_idx; +#endif +} genelal_ed_t; + +typedef struct tag_tdinfo { + uint32_t count; + uint32_t direction; + uint32_t msp; + uint16_t devadr; + uint16_t speed; /* 1:Speed = Low */ + uint8_t endpoint_no; +} tdinfo_t; + +typedef struct tag_split_trans { + uint16_t root_devadr; + uint16_t get_port; + uint16_t port_speed; + uint16_t reset_port; + uint32_t seq_cnt; + uint32_t port_sts_bits[PORT_NUM]; +} split_trans_t; + +static void callback_task(void const * argument); +static void control_ed_task(void const * argument); +static void bulk_ed_task(void const * argument); +static void int_ed_task(void const * argument); +static int32_t int_trans_doing(hced_t *p_ed, uint32_t index); +static int32_t chk_genelal_ed(genelal_ed_t *p_g_ed); +static void chk_genelal_td_done(genelal_ed_t *p_g_ed); +static void chk_split_trans_setting(genelal_ed_t *p_g_ed); +static void set_split_trans_setting(void); +static void control_trans(genelal_ed_t *p_g_ed); +static void bulk_trans(genelal_ed_t *p_g_ed); +static void int_trans_setting(genelal_ed_t *p_g_ed, uint32_t index); +static uint32_t chk_cycle(hced_t *p_ed); +static void int_trans(genelal_ed_t *p_g_ed); +static void get_td_info(genelal_ed_t *p_g_ed, tdinfo_t *p_td_info); +static void set_togle(uint32_t pipe, hctd_t *p_td, hced_t *p_ed); +#if (ISO_TRANS_MAX_NUM > 0) +static void iso_ed_task(void const * argument); +static int32_t iso_trans_doing(hced_t *p_ed, uint32_t index); +static void chk_iso_td_done(genelal_ed_t *p_g_ed); +static int32_t chk_iso_ed(genelal_ed_t *p_g_ed); +static void iso_trans_setting(genelal_ed_t *p_g_ed, uint32_t index); +static void iso_trans(genelal_ed_t *p_g_ed); +#endif +static void connect_check(void); + +extern USB_HOST_CFG_PIPETBL_t usb_host_blk_ep_tbl1[]; +extern USB_HOST_CFG_PIPETBL_t usb_host_int_ep_tbl1[]; +#if (ISO_TRANS_MAX_NUM > 0) +extern USB_HOST_CFG_PIPETBL_t usb_host_iso_ep_tbl1[]; +#endif + +static usb_ohci_reg_t usb_reg; +static usb_ohci_reg_t *p_usb_reg = &usb_reg; +static usbisr_fnc_t *p_usbisr_cb = NULL; +static osSemaphoreId semid_cb = NULL; +static uint32_t connect_change = 0xFFFFFFFF; +static uint32_t connect_status = 0; +static uint32_t init_end = 0; +static genelal_ed_t ctl_ed; +static genelal_ed_t blk_ed; +static genelal_ed_t int_ed[INT_TRANS_MAX_NUM]; +static split_trans_t split_ctl; + +#if (ISO_TRANS_MAX_NUM > 0) +static genelal_ed_t iso_ed[ISO_TRANS_MAX_NUM]; +#endif + +osSemaphoreDef(ohciwrapp_sem_01); +osSemaphoreDef(ohciwrapp_sem_02); +osSemaphoreDef(ohciwrapp_sem_03); +osSemaphoreDef(ohciwrapp_sem_04); +osSemaphoreDef(ohciwrapp_sem_05); +osSemaphoreDef(ohciwrapp_sem_06); +osSemaphoreDef(ohciwrapp_sem_07); +#if (INT_TRANS_MAX_NUM >= 2) +osSemaphoreDef(ohciwrapp_sem_08); +osSemaphoreDef(ohciwrapp_sem_09); +#endif +#if (INT_TRANS_MAX_NUM >= 3) +osSemaphoreDef(ohciwrapp_sem_10); +osSemaphoreDef(ohciwrapp_sem_11); +#endif +#if (INT_TRANS_MAX_NUM >= 4) +osSemaphoreDef(ohciwrapp_sem_12); +osSemaphoreDef(ohciwrapp_sem_13); +#endif +#if (ISO_TRANS_MAX_NUM >= 1) +osSemaphoreDef(ohciwrapp_sem_14); +osSemaphoreDef(ohciwrapp_sem_15); +#endif +#if (ISO_TRANS_MAX_NUM >= 2) +osSemaphoreDef(ohciwrapp_sem_16); +osSemaphoreDef(ohciwrapp_sem_17); +#endif + +osThreadDef(callback_task, osPriorityHigh, 512); +osThreadDef(control_ed_task, osPriorityNormal, 512); +osThreadDef(bulk_ed_task, osPriorityNormal, 512); +static void int_ed_task_1(void const * argument) { + int_ed_task(argument); +} +osThreadDef(int_ed_task_1, osPriorityNormal, 512); +#if (INT_TRANS_MAX_NUM >= 2) +static void int_ed_task_2(void const * argument) { + int_ed_task(argument); +} +osThreadDef(int_ed_task_2, osPriorityNormal, 512); +#endif +#if (INT_TRANS_MAX_NUM >= 3) +static void int_ed_task_3(void const * argument) { + int_ed_task(argument); +} +osThreadDef(int_ed_task_3, osPriorityNormal, 512); +#endif +#if (INT_TRANS_MAX_NUM >= 4) +static void int_ed_task_4(void const * argument) { + int_ed_task(argument); +} +osThreadDef(int_ed_task_4, osPriorityNormal, 512); +#endif + +#if (ISO_TRANS_MAX_NUM >= 1) +static void iso_ed_task_1(void const * argument) { + iso_ed_task(argument); +} +osThreadDef(iso_ed_task_1, osPriorityAboveNormal, 512); +#endif +#if (ISO_TRANS_MAX_NUM >= 2) +static void iso_ed_task_2(void const * argument) { + iso_ed_task(argument); +} +osThreadDef(iso_ed_task_2, osPriorityAboveNormal, 512); +#endif + +void ohciwrapp_init(usbisr_fnc_t *p_usbisr_fnc) { + static const osSemaphoreDef_t * const sem_def_tbl[TOTAL_SEM_NUM] = { + osSemaphore(ohciwrapp_sem_01), osSemaphore(ohciwrapp_sem_02), osSemaphore(ohciwrapp_sem_03) + , osSemaphore(ohciwrapp_sem_04), osSemaphore(ohciwrapp_sem_05), osSemaphore(ohciwrapp_sem_06) + , osSemaphore(ohciwrapp_sem_07) +#if (INT_TRANS_MAX_NUM >= 2) + , osSemaphore(ohciwrapp_sem_08), osSemaphore(ohciwrapp_sem_09) +#endif +#if (INT_TRANS_MAX_NUM >= 3) + , osSemaphore(ohciwrapp_sem_10), osSemaphore(ohciwrapp_sem_11) +#endif +#if (INT_TRANS_MAX_NUM >= 4) + , osSemaphore(ohciwrapp_sem_12), osSemaphore(ohciwrapp_sem_13) +#endif +#if (ISO_TRANS_MAX_NUM >= 1) + , osSemaphore(ohciwrapp_sem_14), osSemaphore(ohciwrapp_sem_15) +#endif +#if (ISO_TRANS_MAX_NUM >= 2) + , osSemaphore(ohciwrapp_sem_16), osSemaphore(ohciwrapp_sem_17) +#endif + }; + static const osThreadDef_t * const int_tsk_def_tbl[INT_TRANS_MAX_NUM] = { + osThread(int_ed_task_1) +#if (INT_TRANS_MAX_NUM >= 2) + , osThread(int_ed_task_2) +#endif +#if (INT_TRANS_MAX_NUM >= 3) + , osThread(int_ed_task_3) +#endif +#if (INT_TRANS_MAX_NUM >= 4) + , osThread(int_ed_task_4) +#endif + }; +#if (ISO_TRANS_MAX_NUM > 0) + static const osThreadDef_t * const iso_tsk_def_tbl[ISO_TRANS_MAX_NUM] = { + osThread(iso_ed_task_1) +#if (ISO_TRANS_MAX_NUM >= 2) + , osThread(iso_ed_task_2) +#endif + }; +#endif + + uint32_t cnt; + uint32_t index = 0; + + /* Disables interrupt for usb */ + GIC_DisableIRQ(USBIXUSBIX); + +#if (USB_HOST_CH == 0) + /* P4_1(USB0_EN) */ + GPIOP4 &= ~0x0002; /* Outputs low level */ + GPIOPMC4 &= ~0x0002; /* Port mode */ + GPIOPM4 &= ~0x0002; /* Output mode */ +#endif + + p_usbisr_cb = p_usbisr_fnc; +#if (USB_HOST_HISPEED == 0) + g_usbx_host_SupportUsbDeviceSpeed = USB_HOST_FULL_SPEED; +#else + g_usbx_host_SupportUsbDeviceSpeed = USB_HOST_HIGH_SPEED; +#endif + p_usb_reg->HcRevision = 0x00000010; + p_usb_reg->HcControl = 0x00000000; + p_usb_reg->HcCommandStatus = 0x00000000; + p_usb_reg->HcInterruptStatus = 0x00000000; + p_usb_reg->HcInterruptEnable = 0x00000000; + p_usb_reg->HcInterruptDisable = 0x00000000; + p_usb_reg->HcHCCA = 0x00000000; + p_usb_reg->HcPeriodCurrentED = 0x00000000; + p_usb_reg->HcControlHeadED = 0x00000000; + p_usb_reg->HcControlCurrentED = 0x00000000; + p_usb_reg->HcBulkHeadED = 0x00000000; + p_usb_reg->HcBulkCurrentED = 0x00000000; + p_usb_reg->HcDoneHead = 0x00000000; + p_usb_reg->HcFmInterval = 0x00002EDF; + p_usb_reg->HcFmRemaining = 0x00002EDF; + p_usb_reg->HcFmNumber = 0x00000000; + p_usb_reg->HcPeriodicStart = 0x00000000; + p_usb_reg->HcLSThreshold = 0x00000628; + p_usb_reg->HcRhDescriptorA = 0xFF000901; + p_usb_reg->HcRhDescriptorB = 0x00020000; + p_usb_reg->HcRhStatus = 0x00000000; + p_usb_reg->HcRhPortStatus1 = 0x00000000; + +#if (USB_HOST_CH == 0) + GPIOP4 |= 0x0002; /* P4_1 Outputs high level */ + osDelay(5); + GPIOP4 &= ~0x0002; /* P4_1 Outputs low level */ + osDelay(10); +#else + osDelay(15); +#endif + + if (init_end == 0) { + (void)memset(&ctl_ed, 0, sizeof(ctl_ed)); + (void)memset(&blk_ed, 0, sizeof(blk_ed)); + (void)memset(&int_ed[0], 0, sizeof(int_ed)); +#if (ISO_TRANS_MAX_NUM > 0) + (void)memset(&iso_ed[0], 0, sizeof(iso_ed)); +#endif + + /* callback */ + semid_cb = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + (void)osThreadCreate(osThread(callback_task), 0); + + /* control transfer */ + ctl_ed.semid_wait = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + ctl_ed.semid_list = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + ctl_ed.tskid = osThreadCreate(osThread(control_ed_task), 0); + + /* bulk transfer */ + blk_ed.semid_wait = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + blk_ed.semid_list = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + blk_ed.tskid = osThreadCreate(osThread(bulk_ed_task), 0); + + /* interrupt transfer */ + for (cnt = 0; cnt < INT_TRANS_MAX_NUM; cnt++) { + int_ed[cnt].semid_wait = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + int_ed[cnt].semid_list = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + int_ed[cnt].tskid = osThreadCreate(int_tsk_def_tbl[cnt], (void *)cnt); + } + +#if (ISO_TRANS_MAX_NUM > 0) + /* isochronous transfer */ + for (cnt = 0; cnt < ISO_TRANS_MAX_NUM; cnt++) { + iso_ed[cnt].semid_wait = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + iso_ed[cnt].semid_list = osSemaphoreCreate(sem_def_tbl[index], 0); + index++; + iso_ed[cnt].tskid = osThreadCreate(iso_tsk_def_tbl[cnt], (void *)cnt); + } +#endif + init_end = 1; + } +} + +uint32_t ohciwrapp_reg_r(uint32_t reg_ofs) { + if (init_end == 0) { + return 0; + } + + return *(uint32_t *)((uint8_t *)p_usb_reg + reg_ofs); +} + +void ohciwrapp_reg_w(uint32_t reg_ofs, uint32_t set_data) { + uint32_t cnt; + uint32_t last_data; + hcca_t *p_hcca; + + if (init_end == 0) { + return; + } + + switch (reg_ofs) { + case OHCI_REG_CONTROL: + last_data = p_usb_reg->HcControl; + p_usb_reg->HcControl = (set_data & 0x000007FF); + if ((last_data & OR_CONTROL_CLE) != (set_data & OR_CONTROL_CLE)) { + /* change CLE */ + if ((set_data & OR_CONTROL_CLE) != 0) { + (void)osSemaphoreRelease(ctl_ed.semid_list); + } else { + if (ctl_ed.trans_wait == 1) { + ctl_ed.trans_wait = 0; + (void)osSemaphoreRelease(ctl_ed.semid_wait); + } + (void)osSemaphoreWait(ctl_ed.semid_list, osWaitForever); + } + } + if ((last_data & OR_CONTROL_BLE) != (set_data & OR_CONTROL_BLE)) { + /* change BLE */ + if ((set_data & OR_CONTROL_BLE) != 0) { + (void)osSemaphoreRelease(blk_ed.semid_list); + } else { + if (blk_ed.trans_wait == 1) { + blk_ed.trans_wait = 0; + (void)osSemaphoreRelease(blk_ed.semid_wait); + } + (void)osSemaphoreWait(blk_ed.semid_list, osWaitForever); + } + } +#if (ISO_TRANS_MAX_NUM > 0) + if ((last_data & OR_CONTROL_IE) != (set_data & OR_CONTROL_IE)) { + /* change IE */ + for (cnt = 0; cnt < ISO_TRANS_MAX_NUM; cnt++) { + if ((set_data & OR_CONTROL_IE) != 0) { + (void)osSemaphoreRelease(iso_ed[cnt].semid_list); + } else { + if (iso_ed[cnt].trans_wait == 1) { + iso_ed[cnt].trans_wait = 0; + (void)osSemaphoreRelease(iso_ed[cnt].semid_wait); + } + (void)osSemaphoreWait(iso_ed[cnt].semid_list, osWaitForever); + } + } + } +#endif + if ((last_data & OR_CONTROL_PLE) != (set_data & OR_CONTROL_PLE)) { + /* change PLE */ + for (cnt = 0; cnt < INT_TRANS_MAX_NUM; cnt++) { + if ((set_data & OR_CONTROL_PLE) != 0) { + (void)osSemaphoreRelease(int_ed[cnt].semid_list); + } else { + if (int_ed[cnt].trans_wait == 1) { + int_ed[cnt].trans_wait = 0; + (void)osSemaphoreRelease(int_ed[cnt].semid_wait); + } + (void)osSemaphoreWait(int_ed[cnt].semid_list, osWaitForever); + } + } + } + break; + case OHCI_REG_COMMANDSTATUS: + if ((set_data & OR_CMD_STATUS_HCR) != 0) { /* HostController Reset */ + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_HCR; + if (usbx_api_host_init(16, g_usbx_host_SupportUsbDeviceSpeed, USBHCLOCK_X1_48MHZ) == USB_HOST_ATTACH) { + ohciwrapp_loc_Connect(1); + } + p_usb_reg->HcCommandStatus &= ~OR_CMD_STATUS_HCR; + } + if ((set_data & OR_CMD_STATUS_CLF) != 0) { + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_CLF; + osSignalSet(ctl_ed.tskid, SIG_GEN_LIST_REQ); + } + if ((set_data & OR_CMD_STATUS_BLF) != 0) { + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_BLF; + osSignalSet(blk_ed.tskid, SIG_GEN_LIST_REQ); + } + if ((set_data & OR_CMD_STATUS_OCR) != 0) { + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_OCR; + } else { + p_usb_reg->HcCommandStatus &= ~OR_CMD_STATUS_OCR; + } + break; + case OHCI_REG_INTERRUPTSTATUS: + if (((p_usb_reg->HcInterruptStatus & OR_INTR_STATUS_WDH) != 0) + && ((set_data & OR_INTR_STATUS_WDH) != 0)) { + if (p_usb_reg->HcDoneHead != 0x00000000) { + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + p_hcca->DoneHead = p_usb_reg->HcDoneHead; + p_usb_reg->HcDoneHead = 0x00000000; + p_usb_reg->HcInterruptStatus |= OR_INTR_STATUS_WDH; + (void)osSemaphoreRelease(semid_cb); + } else { + p_usb_reg->HcInterruptStatus &= ~OR_INTR_STATUS_WDH; + } + } + if ((set_data & OR_INTR_STATUS_RHSC) != 0) { + p_usb_reg->HcInterruptStatus &= ~OR_INTR_STATUS_RHSC; + } + break; + case OHCI_REG_INTERRUPTENABLE: + case OHCI_REG_INTERRUPTDISABLE: + case OHCI_REG_HCCA: + case OHCI_REG_CONTROLHEADED: + case OHCI_REG_CONTROLCURRENTED: + case OHCI_REG_BULKHEADED: + case OHCI_REG_BULKCURRENTED: + case OHCI_REG_FMINTERVAL: + case OHCI_REG_FMREMAINING: + case OHCI_REG_PERIODICSTART: + case OHCI_REG_LSTHRESHOLD: + case OHCI_REG_RHDESCRIPTORA: + case OHCI_REG_RHDESCRIPTORB: + case OHCI_REG_RHSTATUS: + *(uint32_t *)((uint8_t *)p_usb_reg + reg_ofs) = set_data; + break; + case OHCI_REG_RHPORTSTATUS1: + p_usb_reg->HcRhPortStatus1 &= ~(set_data & 0xFFFF0000); + if ((set_data & OR_RH_PORT_PRS) != 0) { /* Set Port Reset */ + p_usb_reg->HcRhPortStatus1 |= OR_RH_PORT_PRS; + usbx_host_UsbBusReset(); + p_usb_reg->HcRhPortStatus1 &= ~OR_RH_PORT_PRS; + } + break; + case OHCI_REG_REVISION: + case OHCI_REG_PERIODCURRENTED: + case OHCI_REG_DONEHEADED: + case OHCI_REG_FMNUMBER: + default: + /* Do Nothing */ + break; + } +} + +static void callback_task(void const * argument) { + usbisr_fnc_t *p_wk_cb = p_usbisr_cb; + + if (p_wk_cb == NULL) { + return; + } + + while (1) { + osSemaphoreWait(semid_cb, osWaitForever); + if (connect_change != 0xFFFFFFFF) { + connect_change = 0xFFFFFFFF; + connect_check(); + } + p_wk_cb(); + } +} + +static void control_ed_task(void const * argument) { + while (1) { + osSignalWait(SIG_GEN_LIST_REQ, osWaitForever); + (void)osSemaphoreWait(ctl_ed.semid_list, osWaitForever); + while ((p_usb_reg->HcControl & OR_CONTROL_CLE) != 0) { + if ((p_usb_reg->HcControlCurrentED == 0) + && ((p_usb_reg->HcCommandStatus & OR_CMD_STATUS_CLF) != 0)) { + p_usb_reg->HcControlCurrentED = p_usb_reg->HcControlHeadED; + p_usb_reg->HcCommandStatus &= ~OR_CMD_STATUS_CLF; + } + if (p_usb_reg->HcControlCurrentED != 0) { + ctl_ed.p_curr_ed = (hced_t *)p_usb_reg->HcControlCurrentED; + if (chk_genelal_ed(&ctl_ed) != 0) { + control_trans(&ctl_ed); + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_CLF; + } + p_usb_reg->HcControlCurrentED = (uint32_t)ctl_ed.p_curr_ed->nextED; + } else { + break; + } + } + if ((p_usb_reg->HcCommandStatus & OR_CMD_STATUS_CLF) != 0) { + osSignalSet(ctl_ed.tskid, SIG_GEN_LIST_REQ); + } + (void)osSemaphoreRelease(ctl_ed.semid_list); + } +} + +static void bulk_ed_task(void const * argument) { + while (1) { + osSignalWait(SIG_GEN_LIST_REQ, osWaitForever); + (void)osSemaphoreWait(blk_ed.semid_list, osWaitForever); + while ((p_usb_reg->HcControl & OR_CONTROL_BLE) != 0) { + if ((p_usb_reg->HcBulkCurrentED == 0) + && ((p_usb_reg->HcCommandStatus & OR_CMD_STATUS_BLF) != 0)) { + p_usb_reg->HcBulkCurrentED = p_usb_reg->HcBulkHeadED; + p_usb_reg->HcCommandStatus &= ~OR_CMD_STATUS_BLF; + } + if (p_usb_reg->HcBulkCurrentED != 0) { + blk_ed.p_curr_ed = (hced_t *)p_usb_reg->HcBulkCurrentED; + if (chk_genelal_ed(&blk_ed) != 0) { + bulk_trans(&blk_ed); + p_usb_reg->HcCommandStatus |= OR_CMD_STATUS_BLF; + } + p_usb_reg->HcBulkCurrentED = (uint32_t)blk_ed.p_curr_ed->nextED; + } else { + break; + } + } + if ((p_usb_reg->HcCommandStatus & OR_CMD_STATUS_BLF) != 0) { + osSignalSet(blk_ed.tskid, SIG_GEN_LIST_REQ); + } + (void)osSemaphoreRelease(blk_ed.semid_list); + } +} + +static void int_ed_task(void const * argument) { + genelal_ed_t *p_int_ed = &int_ed[(uint32_t)argument]; + uint32_t cnt; + uint32_t wait_cnt = 0; + hcca_t *p_hcca; + hced_t *p_ed; + + while (1) { + (void)osSemaphoreWait(p_int_ed->semid_list, osWaitForever); + if (p_int_ed->p_curr_ed == NULL) { + for (cnt = 0; (cnt < 32) && ((p_usb_reg->HcControl & OR_CONTROL_PLE) != 0) + && (p_int_ed->p_curr_ed == NULL); cnt++) { + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + p_ed = (hced_t *)p_hcca->IntTable[cnt]; + while ((p_ed != NULL) && ((p_usb_reg->HcControl & OR_CONTROL_PLE) != 0) + && (p_int_ed->p_curr_ed == NULL)) { + if (int_trans_doing(p_ed, (uint32_t)argument) == 0) { + p_int_ed->p_curr_ed = p_ed; + if (chk_genelal_ed(p_int_ed) != 0) { + int_trans_setting(p_int_ed, (uint32_t)argument); + } else { + p_int_ed->p_curr_ed = NULL; + } + } + p_ed = p_ed->nextED; + } + } + } + if (p_int_ed->p_curr_ed != NULL) { + while ((p_usb_reg->HcControl & OR_CONTROL_PLE) != 0) { + if (chk_genelal_ed(p_int_ed) != 0) { + int_trans(p_int_ed); + (void)osSemaphoreWait(p_int_ed->semid_wait, osWaitForever); + usbx_host_stop_transfer(p_int_ed->pipe_no); + wait_cnt = p_int_ed->cycle_time; + } else { + if (wait_cnt > 0) { + wait_cnt--; + } else { + p_int_ed->p_curr_ed = NULL; + } + break; + } + } + } + (void)osSemaphoreRelease(p_int_ed->semid_list); + if (p_int_ed->p_curr_ed == NULL) { + osDelay(10); + } else { + osDelay(1); + } + } +} + +static int32_t int_trans_doing(hced_t *p_ed, uint32_t index) { + uint32_t cnt; + int32_t ret = 0; + + for (cnt = 0; cnt < INT_TRANS_MAX_NUM; cnt++) { + if ((index != cnt) && (int_ed[cnt].p_curr_ed == p_ed)) { + ret = 1; + } + } + + return ret; +} + +static int32_t chk_genelal_ed(genelal_ed_t *p_g_ed){ + int32_t ret = 0; + hced_t *p_ed = p_g_ed->p_curr_ed; + + if (((p_ed->control & ED_SKIP) != 0) + || ((p_ed->control & ED_FORMAT) != 0) + || ((p_ed->headTD & ED_HALTED) != 0) + || ((p_ed->tailTD & 0xFFFFFFF0) == (p_ed->headTD & 0xFFFFFFF0))) { + /* Do Nothing */ + } else if ((p_ed->control & 0x0000007F) > 10) { + p_ed->headTD |= ED_HALTED; + } else { + p_g_ed->p_curr_td = (void *)(p_ed->headTD & 0xFFFFFFF0); + if (p_g_ed->p_curr_td == NULL) { + p_ed->headTD |= ED_HALTED; + } else { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + + p_g_ed->p_start_buf = p_td->currBufPtr; + ret = 1; + } + } + + return ret; +} + +static void chk_genelal_td_done(genelal_ed_t *p_g_ed) { + hcca_t *p_hcca; + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + uint32_t ConditionCode = RZA_IO_RegRead_32(&p_td->control, TD_CTL_SHFT_CC, TD_CTL_MSK_CC); + + if ((ConditionCode != TD_CC_NOT_ACCESSED_1) && (ConditionCode != TD_CC_NOT_ACCESSED_2)) { + p_g_ed->p_curr_ed->headTD = ((uint32_t)p_td->nextTD & 0xFFFFFFF0) + | (p_g_ed->p_curr_ed->headTD & 0x0000000F); + p_td->nextTD = (hctd_t *)p_usb_reg->HcDoneHead; + p_usb_reg->HcDoneHead = (uint32_t)p_g_ed->p_curr_td; + if ((p_usb_reg->HcInterruptStatus & OR_INTR_STATUS_WDH) == 0) { + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + p_hcca->DoneHead = p_usb_reg->HcDoneHead; + p_usb_reg->HcDoneHead = 0x00000000; + p_usb_reg->HcInterruptStatus |= OR_INTR_STATUS_WDH; + (void)osSemaphoreRelease(semid_cb); + } + } +} + +static void chk_split_trans_setting(genelal_ed_t *p_g_ed) { + uint8_t *p_buf; + tdinfo_t td_info; + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + + /* Hi-Speed mode only */ + if (g_usbx_host_UsbDeviceSpeed != USB_HOST_HIGH_SPEED) { + return; + } + + if (RZA_IO_RegRead_32(&p_td->control, TD_CTL_SHFT_CC, TD_CTL_MSK_CC) != TD_CC_NOERROR) { + return; + } + + get_td_info(p_g_ed, &td_info); + p_buf = p_g_ed->p_start_buf; + + if (td_info.direction == 0) { + uint8_t bRequest = p_buf[1]; + uint16_t wValue = (p_buf[3] << 8) + p_buf[2]; + uint16_t wIndx = (p_buf[5] << 8) + p_buf[4]; + uint16_t devadd; + + if ((td_info.devadr == 0) && (bRequest == SET_ADDRESS)) { + /* SET_ADDRESS */ + usbx_host_get_devadd(USB_HOST_DEVICE_0, &devadd); + usbx_host_set_devadd(wValue, &devadd); + if (split_ctl.root_devadr == 0) { + split_ctl.root_devadr = wValue; /* New Address */ + } + } else if ((td_info.devadr == split_ctl.root_devadr) && (bRequest == SET_FEATURE) + && (wValue == 0x0004) && (split_ctl.root_devadr != 0)) { + /* SET_FEATURE PORT_RESET */ + split_ctl.reset_port = (wIndx & 0x00FF); + } else if ((td_info.devadr == split_ctl.root_devadr) && (bRequest == GET_STATUS)) { + /* GET_STATUS */ + split_ctl.get_port = wIndx; + split_ctl.seq_cnt = 1; + } else { + /* Do Nothing */ + } + } else if (td_info.direction == 2) { + if ((td_info.devadr == split_ctl.root_devadr) && (split_ctl.seq_cnt == 1)) { + if (split_ctl.get_port < PORT_NUM) { + split_ctl.port_sts_bits[split_ctl.get_port] = (p_buf[1] << 8) + p_buf[0]; + } + split_ctl.seq_cnt = 0; + } + } else { + /* Do Nothing */ + } +} + +static void set_split_trans_setting(void) { + uint16_t port_speed; + uint16_t devadd; + + if ((split_ctl.root_devadr != 0) && (split_ctl.reset_port != 0) && (split_ctl.reset_port < PORT_NUM)) { + usbx_host_get_devadd(USB_HOST_DEVICE_0, &devadd); + RZA_IO_RegWrite_16(&devadd, split_ctl.root_devadr, USB_DEVADDn_UPPHUB_SHIFT, USB_DEVADDn_UPPHUB); + RZA_IO_RegWrite_16(&devadd, split_ctl.reset_port, USB_DEVADDn_HUBPORT_SHIFT, USB_DEVADDn_HUBPORT); + if ((split_ctl.port_sts_bits[split_ctl.reset_port] & PORT_HIGH_SPEED) != 0) { + port_speed = USB_HOST_HIGH_SPEED; + } else if ((split_ctl.port_sts_bits[split_ctl.reset_port] & PORT_LOW_SPEED) != 0) { + port_speed = USB_HOST_LOW_SPEED; + } else { + port_speed = USB_HOST_FULL_SPEED; + } + RZA_IO_RegWrite_16(&devadd, port_speed, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD); + usbx_host_set_devadd(USB_HOST_DEVICE_0, &devadd); + split_ctl.reset_port = 0; + } +} + +static void control_trans(genelal_ed_t *p_g_ed) { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + tdinfo_t td_info; + uint16_t devadd; + + get_td_info(p_g_ed, &td_info); + + if (g_usbx_host_UsbDeviceSpeed == USB_HOST_HIGH_SPEED) { + if (td_info.devadr == 0) { + set_split_trans_setting(); + } + } else { + /* When a non-Hi-Speed, the communication speed is determined from the TD. */ + usbx_host_get_devadd(USB_HOST_DEVICE_0, &devadd); + if (td_info.speed == 1) { + RZA_IO_RegWrite_16(&devadd, USB_HOST_LOW_SPEED, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD); + } else { + RZA_IO_RegWrite_16(&devadd, USB_HOST_FULL_SPEED, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD); + } + usbx_host_set_devadd(td_info.devadr, &devadd); + } + + USB20X.DCPMAXP = (td_info.devadr << 12) + td_info.msp; + if (td_info.direction == 0) { + g_usbx_host_CmdStage = (USB_HOST_STAGE_SETUP | USB_HOST_CMD_IDLE); + } else if (td_info.count != 0) { + g_usbx_host_CmdStage = (USB_HOST_STAGE_DATA | USB_HOST_CMD_IDLE); + } else { + g_usbx_host_CmdStage = (USB_HOST_STAGE_STATUS | USB_HOST_CMD_IDLE); + } + g_usbx_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_WAIT; + p_g_ed->pipe_no = USB_HOST_PIPE0; + + p_g_ed->trans_wait = 1; + if (connect_status == 0) { + ohciwrapp_loc_TransEnd(p_g_ed->pipe_no, TD_CC_DEVICENOTRESPONDING); + } else { + if (td_info.direction == 0) { + uint16_t Req = (p_td->currBufPtr[1] << 8) + p_td->currBufPtr[0]; + uint16_t Val = (p_td->currBufPtr[3] << 8) + p_td->currBufPtr[2]; + uint16_t Indx = (p_td->currBufPtr[5] << 8) + p_td->currBufPtr[4]; + uint16_t Len = (p_td->currBufPtr[7] << 8) + p_td->currBufPtr[6]; + + g_usbx_host_data_pointer[USB_HOST_PIPE0] = p_td->bufEnd; + usbx_host_SetupStage(Req, Val, Indx, Len); + } else if (td_info.direction == 1) { + usbx_host_CtrlWriteStart(td_info.count, p_td->currBufPtr); + } else { + usbx_host_CtrlReadStart(td_info.count, p_td->currBufPtr); + } + + (void)osSemaphoreWait(p_g_ed->semid_wait, CTL_TRANS_TIMEOUT); + if (p_g_ed->trans_wait == 1) { + p_g_ed->trans_wait = 0; + RZA_IO_RegWrite_32(&p_td->control, TD_CC_DEVICENOTRESPONDING, TD_CTL_SHFT_CC, TD_CTL_MSK_CC); + } + } + + g_usbx_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usbx_host_CmdStage |= USB_HOST_CMD_IDLE; + g_usbx_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_IDLE; +} + +static void bulk_trans(genelal_ed_t *p_g_ed) { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + hced_t *p_ed = p_g_ed->p_curr_ed; + tdinfo_t td_info; + USB_HOST_CFG_PIPETBL_t *user_table = &usb_host_blk_ep_tbl1[0]; + uint8_t wk_table[6]; + + get_td_info(p_g_ed, &td_info); + + wk_table[0] = 0; + wk_table[1] = USB_HOST_ENDPOINT_DESC; + wk_table[2] = td_info.endpoint_no; + if (td_info.direction == 2) { + wk_table[2] |= USB_HOST_EP_IN; + } + wk_table[3] = USB_HOST_EP_BULK; + wk_table[4] = (uint8_t)td_info.msp; + wk_table[5] = (uint8_t)(td_info.msp >> 8); + p_g_ed->pipe_no = user_table->pipe_number; + usbx_api_host_SetEndpointTable(td_info.devadr, user_table, wk_table); + + set_togle(p_g_ed->pipe_no, p_td, p_ed); + + p_g_ed->trans_wait = 1; + if (connect_status == 0) { + ohciwrapp_loc_TransEnd(p_g_ed->pipe_no, TD_CC_DEVICENOTRESPONDING); + } else { + if (td_info.direction == 1) { + usbx_host_start_send_transfer(p_g_ed->pipe_no, td_info.count, p_td->currBufPtr); + } else { + usbx_host_start_receive_transfer(p_g_ed->pipe_no, td_info.count, p_td->currBufPtr); + } + + (void)osSemaphoreWait(p_g_ed->semid_wait, BLK_TRANS_TIMEOUT); + usbx_host_stop_transfer(p_g_ed->pipe_no); + } +} + +static void int_trans_setting(genelal_ed_t *p_g_ed, uint32_t index) { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + hced_t *p_ed = p_g_ed->p_curr_ed; + tdinfo_t td_info; + USB_HOST_CFG_PIPETBL_t *user_table = &usb_host_int_ep_tbl1[index]; + uint8_t wk_table[6]; + uint32_t cycle_time; + uint16_t devadd; + + get_td_info(p_g_ed, &td_info); + + wk_table[0] = 0; + wk_table[1] = USB_HOST_ENDPOINT_DESC; + wk_table[2] = td_info.endpoint_no; + if (td_info.direction == 2) { + wk_table[2] |= USB_HOST_EP_IN; + } + wk_table[3] = USB_HOST_EP_INT; + wk_table[4] = (uint8_t)td_info.msp; + wk_table[5] = (uint8_t)(td_info.msp >> 8); + cycle_time = chk_cycle(p_ed); + p_g_ed->cycle_time = cycle_time; + user_table->pipe_cycle = 0; + while (cycle_time > 1) { + cycle_time >>= 1; + user_table->pipe_cycle++; + } + if (g_usbx_host_UsbDeviceSpeed == USB_HOST_HIGH_SPEED) { + usbx_host_get_devadd(td_info.devadr, &devadd); + if (RZA_IO_RegRead_16(&devadd, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD) == USB_HOST_HIGH_SPEED) { + user_table->pipe_cycle += 3; + if (user_table->pipe_cycle > 7) { + user_table->pipe_cycle = 7; + } + } + } + + p_g_ed->pipe_no = user_table->pipe_number; + usbx_api_host_SetEndpointTable(td_info.devadr, user_table, wk_table); + + set_togle(p_g_ed->pipe_no, p_td, p_ed); +} + +static uint32_t chk_cycle(hced_t *p_ed) { + uint32_t cnt; + uint32_t hit_cnt = 0; + uint32_t cycle_time = 1; + hcca_t *p_hcca; + hced_t *p_wk_ed; + + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + + for (cnt = 0; cnt < 32; cnt++) { + p_wk_ed = (hced_t *)p_hcca->IntTable[cnt]; + while (p_wk_ed != NULL) { + if (p_wk_ed == p_ed) { + hit_cnt++; + break; + } + p_wk_ed = p_wk_ed->nextED; + } + } + if (hit_cnt < 2) { + cycle_time = 32; + } else if (hit_cnt < 4) { + cycle_time = 16; + } else if (hit_cnt < 8) { + cycle_time = 8; + } else if (hit_cnt < 16) { + cycle_time = 4; + } else if (hit_cnt < 32) { + cycle_time = 2; + } else{ + cycle_time = 1; + } + + return cycle_time; +} + +static void int_trans(genelal_ed_t *p_g_ed) { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + tdinfo_t td_info; + + get_td_info(p_g_ed, &td_info); + p_g_ed->trans_wait = 1; + if (connect_status == 0) { + ohciwrapp_loc_TransEnd(p_g_ed->pipe_no, TD_CC_DEVICENOTRESPONDING); + } else { + if (td_info.direction == 1) { + usbx_host_start_send_transfer(p_g_ed->pipe_no, td_info.count, p_td->currBufPtr); + } else { + usbx_host_start_receive_transfer(p_g_ed->pipe_no, td_info.count, p_td->currBufPtr); + } + } +} + +static void get_td_info(genelal_ed_t *p_g_ed, tdinfo_t *p_td_info) { + hced_t *p_ed = p_g_ed->p_curr_ed; + + p_td_info->endpoint_no = (uint8_t)((p_ed->control >> 7) & 0x0000000F); + p_td_info->msp = (p_ed->control >> 16) & 0x000007FF; + p_td_info->devadr = p_ed->control & 0x0000000F; + p_td_info->speed = (p_ed->control >> 13) & 0x00000001; + p_td_info->direction = (p_ed->control >> 11) & 0x00000003; + + if ((p_ed->control & ED_FORMAT) == 0) { + hctd_t *p_td = (hctd_t *)p_g_ed->p_curr_td; + + if ((p_td_info->direction == 0) || (p_td_info->direction == 3)) { + if ((p_td->control & TD_CTL_MSK_DP) == TD_SETUP) { + p_td_info->direction = 0; + } else if ((p_td->control & TD_CTL_MSK_DP) == TD_OUT) { + p_td_info->direction = 1; + } else { + p_td_info->direction = 2; + } + } + if (p_td->currBufPtr != NULL) { + p_td_info->count = (uint32_t)p_td->bufEnd - (uint32_t)p_td->currBufPtr + 1; + } else { + p_td_info->count = 0; + } + } else { +#if (ISO_TRANS_MAX_NUM > 0) + hcisotd_t *p_isotd = (hcisotd_t *)p_g_ed->p_curr_td; + + if ((p_td_info->direction == 0) || (p_td_info->direction == 3)) { + if ((p_isotd->control & TD_CTL_MSK_DP) == TD_SETUP) { + p_td_info->direction = 0; + } else if ((p_isotd->control & TD_CTL_MSK_DP) == TD_OUT) { + p_td_info->direction = 1; + } else { + p_td_info->direction = 2; + } + } +#endif + } +} + +static void set_togle(uint32_t pipe, hctd_t *p_td, hced_t *p_ed) { + if ((p_td->control & TD_CTL_MSK_T) == TD_TOGGLE_0) { + usbx_host_set_sqclr(pipe); + } else if ((p_td->control & TD_CTL_MSK_T) == TD_TOGGLE_1) { + usbx_host_set_sqset(pipe); + } else if ((p_ed->headTD & ED_TOGLE_CARRY) == 0) { + usbx_host_set_sqclr(pipe); + } else { + usbx_host_set_sqset(pipe); + } +} + +#if (ISO_TRANS_MAX_NUM > 0) +static void iso_ed_task(void const * argument) { + genelal_ed_t *p_iso_ed = &iso_ed[(uint32_t)argument]; + uint32_t wait_cnt = 0; + hcca_t *p_hcca; + hced_t *p_ed; + + while (1) { + (void)osSemaphoreWait(p_iso_ed->semid_list, osWaitForever); + if (p_iso_ed->p_curr_ed == NULL) { + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + p_ed = (hced_t *)p_hcca->IntTable[0]; + while ((p_ed != NULL) && ((p_usb_reg->HcControl & OR_CONTROL_IE) != 0) + && (p_iso_ed->p_curr_ed == NULL)) { + if (iso_trans_doing(p_ed, (uint32_t)argument) == 0) { + p_iso_ed->p_curr_ed = p_ed; + if (chk_iso_ed(p_iso_ed) != 0) { + iso_trans_setting(p_iso_ed, (uint32_t)argument); + } else { + p_iso_ed->p_curr_ed = NULL; + } + } + p_ed = p_ed->nextED; + } + p_iso_ed->psw_idx = 0; + } + if (p_iso_ed->p_curr_ed != NULL) { + while ((p_usb_reg->HcControl & OR_CONTROL_IE) != 0) { + if (chk_iso_ed(p_iso_ed) != 0) { + hcisotd_t *p_isotd = (hcisotd_t *)p_iso_ed->p_curr_td; + uint32_t starting_frame = p_isotd->control & 0x0000FFFF; + uint32_t wait_time = 0; + uint32_t wk_HcFmNumber = p_usb_reg->HcFmNumber; + + if (starting_frame > wk_HcFmNumber) { + wait_time = starting_frame - wk_HcFmNumber; + } else { + wait_time = (0xFFFF - wk_HcFmNumber) + starting_frame; + } + if ((wait_time >= 2) && (wait_time <= 1000)) { + for (int cnt = 0; cnt < (wait_time - 1); cnt++) { + osDelay(1); + p_usb_reg->HcFmNumber = (wk_HcFmNumber + cnt) & 0x0000FFFF; + } + } + p_iso_ed->psw_idx = 0; + iso_trans(p_iso_ed); + (void)osSemaphoreWait(p_iso_ed->semid_wait, osWaitForever); + wait_cnt = 8; + } else { + if (wait_cnt > 0) { + wait_cnt--; + } else { + p_iso_ed->p_curr_ed = NULL; + } + break; + } + } + } + (void)osSemaphoreRelease(p_iso_ed->semid_list); + if (p_iso_ed->p_curr_ed == NULL) { + osDelay(10); + } else { + osDelay(1); + } + } +} + +static int32_t iso_trans_doing(hced_t *p_ed, uint32_t index) { + uint32_t cnt; + int32_t ret = 0; + + for (cnt = 0; cnt < ISO_TRANS_MAX_NUM; cnt++) { + if ((index != cnt) && (iso_ed[cnt].p_curr_ed == p_ed)) { + ret = 1; + } + } + + return ret; +} + +static void chk_iso_td_done(genelal_ed_t *p_g_ed) { + hcca_t *p_hcca; + hcisotd_t *p_isotd = (hcisotd_t *)p_g_ed->p_curr_td; + uint32_t ConditionCode = RZA_IO_RegRead_32(&p_isotd->control, TD_CTL_SHFT_CC, TD_CTL_MSK_CC); + + if ((ConditionCode != TD_CC_NOT_ACCESSED_1) && (ConditionCode != TD_CC_NOT_ACCESSED_2)) { + p_g_ed->p_curr_ed->headTD = ((uint32_t)p_isotd->nextTD & 0xFFFFFFF0) + | (p_g_ed->p_curr_ed->headTD & 0x0000000F); + p_isotd->nextTD = (hcisotd_t *)p_usb_reg->HcDoneHead; + p_usb_reg->HcDoneHead = (uint32_t)p_g_ed->p_curr_td; + if ((p_usb_reg->HcInterruptStatus & OR_INTR_STATUS_WDH) == 0) { + p_hcca = (hcca_t *)p_usb_reg->HcHCCA; + p_hcca->DoneHead = p_usb_reg->HcDoneHead; + p_usb_reg->HcDoneHead = 0x00000000; + p_usb_reg->HcInterruptStatus |= OR_INTR_STATUS_WDH; + (void)osSemaphoreRelease(semid_cb); + } + } +} + +static int32_t chk_iso_ed(genelal_ed_t *p_g_ed){ + int32_t ret = 0; + hced_t *p_ed = p_g_ed->p_curr_ed; + + if (((p_ed->control & ED_SKIP) != 0) + || ((p_ed->control & ED_FORMAT) == 0) + || ((p_ed->headTD & ED_HALTED) != 0) + || ((p_ed->tailTD & 0xFFFFFFF0) == (p_ed->headTD & 0xFFFFFFF0))) { + /* Do Nothing */ + } else if ((p_ed->control & 0x0000007F) > 10) { + p_ed->headTD |= ED_HALTED; + } else { + p_g_ed->p_curr_td = (void *)(p_ed->headTD & 0xFFFFFFF0); + if (p_g_ed->p_curr_td == NULL) { + p_ed->headTD |= ED_HALTED; + } else { + hcisotd_t *p_isotd = (hcisotd_t *)p_g_ed->p_curr_td; + + p_g_ed->p_start_buf = p_isotd->bufferPage0; + ret = 1; + } + } + + return ret; +} + +static void iso_trans_setting(genelal_ed_t *p_g_ed, uint32_t index) { + tdinfo_t td_info; + USB_HOST_CFG_PIPETBL_t *user_table = &usb_host_iso_ep_tbl1[index]; + uint8_t wk_table[6]; + uint16_t devadd; + + get_td_info(p_g_ed, &td_info); + + wk_table[0] = 0; + wk_table[1] = USB_HOST_ENDPOINT_DESC; + wk_table[2] = td_info.endpoint_no; + if (td_info.direction == 2) { + wk_table[2] |= USB_HOST_EP_IN; + } + wk_table[3] = USB_HOST_EP_ISO; + wk_table[4] = (uint8_t)td_info.msp; + wk_table[5] = (uint8_t)(td_info.msp >> 8); + p_g_ed->cycle_time = 1; + user_table->pipe_cycle = 0; + if (g_usbx_host_UsbDeviceSpeed == USB_HOST_HIGH_SPEED) { + usbx_host_get_devadd(td_info.devadr, &devadd); + if (RZA_IO_RegRead_16(&devadd, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD) == USB_HOST_HIGH_SPEED) { + user_table->pipe_cycle += 3; + } + } + + p_g_ed->pipe_no = user_table->pipe_number; + usbx_api_host_SetEndpointTable(td_info.devadr, user_table, wk_table); +} + +static void iso_trans(genelal_ed_t *p_g_ed) { + hcisotd_t *p_isotd = (hcisotd_t *)p_g_ed->p_curr_td; + tdinfo_t td_info; + uint32_t buff_addr; + uint32_t data_size; + + if (((uint32_t)p_isotd->offsetPSW[p_g_ed->psw_idx] & 0x00001000) == 0) { + buff_addr = (uint32_t)p_isotd->bufferPage0 & 0xFFFFF000; + } else { + buff_addr = (uint32_t)p_isotd->bufEnd & 0xFFFFF000; + } + buff_addr |= (uint32_t)p_isotd->offsetPSW[p_g_ed->psw_idx] & 0x00000FFF; + + if (p_g_ed->psw_idx < RZA_IO_RegRead_32(&p_isotd->control, TD_CTL_SHFT_FC, TD_CTL_MSK_FC)) { + data_size = p_isotd->offsetPSW[p_g_ed->psw_idx + 1] - p_isotd->offsetPSW[p_g_ed->psw_idx]; + } else { + data_size = (uint32_t)p_isotd->bufEnd - buff_addr + 1; + } + p_isotd->offsetPSW[p_g_ed->psw_idx] = (uint16_t)data_size; + + get_td_info(p_g_ed, &td_info); + p_g_ed->trans_wait = 1; + if (connect_status == 0) { + ohciwrapp_loc_TransEnd(p_g_ed->pipe_no, TD_CC_DEVICENOTRESPONDING); + } else { + if (td_info.direction == 1) { + usbx_host_start_send_transfer(p_g_ed->pipe_no, data_size, (uint8_t *)buff_addr); + } else { + usbx_host_start_receive_transfer(p_g_ed->pipe_no, data_size, (uint8_t *)buff_addr); + } + } +} +#endif + +static void connect_check(void) { + uint32_t type = 0; + uint16_t stat; + uint16_t devadd = 0; + uint32_t wk_HcRhPortStatus1 = p_usb_reg->HcRhPortStatus1; + + if (usbx_host_CheckAttach() == USB_HOST_ATTACH) { + type = 1; + } + + if ((((wk_HcRhPortStatus1 & OR_RH_PORT_CCS) == 0) && (type == 0)) + || (((wk_HcRhPortStatus1 & OR_RH_PORT_CCS) != 0) && (type != 0))) { + return; + } + + if (type == 0) { + usbx_host_UsbDetach(); + wk_HcRhPortStatus1 &= ~OR_RH_PORT_CCS; + } else { + usbx_host_UsbAttach(); + stat = usbx_host_UsbBusReset(); + RZA_IO_RegWrite_16(&devadd, 0, USB_DEVADDn_UPPHUB_SHIFT, USB_DEVADDn_UPPHUB); + RZA_IO_RegWrite_16(&devadd, 0, USB_DEVADDn_HUBPORT_SHIFT, USB_DEVADDn_HUBPORT); + if (stat == USB_HOST_HSMODE) { + wk_HcRhPortStatus1 &= ~OR_RH_PORT_LSDA; + RZA_IO_RegWrite_16(&USB20X.SOFCFG, 0, USB_SOFCFG_TRNENSEL_SHIFT, USB_SOFCFG_TRNENSEL); + g_usbx_host_UsbDeviceSpeed = USB_HOST_HIGH_SPEED; + } else if (stat == USB_HOST_FSMODE) { + wk_HcRhPortStatus1 &= ~OR_RH_PORT_LSDA; + RZA_IO_RegWrite_16(&USB20X.SOFCFG, 0, USB_SOFCFG_TRNENSEL_SHIFT, USB_SOFCFG_TRNENSEL); + g_usbx_host_UsbDeviceSpeed = USB_HOST_FULL_SPEED; + } else { + wk_HcRhPortStatus1 |= OR_RH_PORT_LSDA; + RZA_IO_RegWrite_16(&USB20X.SOFCFG, 1, USB_SOFCFG_TRNENSEL_SHIFT, USB_SOFCFG_TRNENSEL); + g_usbx_host_UsbDeviceSpeed = USB_HOST_LOW_SPEED; + } + RZA_IO_RegWrite_16(&devadd, g_usbx_host_UsbDeviceSpeed, USB_DEVADDn_USBSPD_SHIFT, USB_DEVADDn_USBSPD); + usbx_host_init_pipe_status(); + usbx_host_set_devadd(USB_HOST_DEVICE_0, &devadd); + wk_HcRhPortStatus1 |= OR_RH_PORT_CCS; + } + wk_HcRhPortStatus1 |= OR_RH_PORT_CSC; + p_usb_reg->HcRhPortStatus1 = wk_HcRhPortStatus1; + p_usb_reg->HcInterruptStatus |= OR_INTR_STATUS_RHSC; + (void)memset(&split_ctl, 0, sizeof(split_ctl)); +} + +void ohciwrapp_loc_Connect(uint32_t type) { + uint32_t cnt; + + connect_status = type; + connect_change = type; + if (type == 0) { + if (ctl_ed.trans_wait == 1) { + ohciwrapp_loc_TransEnd(ctl_ed.pipe_no, TD_CC_DEVICENOTRESPONDING); + } + if (blk_ed.trans_wait == 1) { + ohciwrapp_loc_TransEnd(blk_ed.pipe_no, TD_CC_DEVICENOTRESPONDING); + } + for (cnt = 0; cnt< INT_TRANS_MAX_NUM; cnt++) { + if (int_ed[cnt].trans_wait == 1) { + ohciwrapp_loc_TransEnd(int_ed[cnt].pipe_no, TD_CC_DEVICENOTRESPONDING); + } + } +#if (ISO_TRANS_MAX_NUM > 0) + for (cnt = 0; cnt< ISO_TRANS_MAX_NUM; cnt++) { + if (iso_ed[cnt].trans_wait == 1) { + hced_t *p_ed = iso_ed[cnt].p_curr_ed; + + p_ed->headTD |= ED_HALTED; + ohciwrapp_loc_TransEnd(iso_ed[cnt].pipe_no, TD_CC_DEVICENOTRESPONDING); + } + } +#endif + } + (void)osSemaphoreRelease(semid_cb); +} + +void ohciwrapp_loc_TransEnd(uint32_t pipe, uint32_t ConditionCode) { + uint32_t periodic = 0; + uint32_t cnt; + uint32_t sqmon; + hced_t *p_ed; + genelal_ed_t *p_wait_ed = NULL; + + if (ctl_ed.pipe_no == pipe) { + p_wait_ed = &ctl_ed; + } else if (blk_ed.pipe_no == pipe) { + p_wait_ed = &blk_ed; + } else { +#if (ISO_TRANS_MAX_NUM > 0) + if (p_wait_ed == NULL) { + for (cnt = 0; cnt< ISO_TRANS_MAX_NUM; cnt++) { + if (iso_ed[cnt].pipe_no == pipe) { + p_wait_ed = &iso_ed[cnt]; + break; + } + } + } +#endif + if (p_wait_ed == NULL) { + for (cnt = 0; cnt< INT_TRANS_MAX_NUM; cnt++) { + if (int_ed[cnt].pipe_no == pipe) { + p_wait_ed = &int_ed[cnt]; + periodic = 1; + break; + } + } + } + } + + if (p_wait_ed == NULL) { + return; + } + p_ed = p_wait_ed->p_curr_ed; + if (p_ed == NULL) { + return; + } + + if ((p_ed->control & ED_FORMAT) == 0) { + hctd_t *p_td = (hctd_t *)p_wait_ed->p_curr_td; + + if (p_td != NULL) { + if (ConditionCode == TD_CC_NOERROR) { + /* ErrorCount */ + RZA_IO_RegWrite_32(&p_td->control, 0, TD_CTL_SHFT_EC, TD_CTL_MSK_EC); + + /* CurrentBufferPointer */ + p_td->currBufPtr += ((uint32_t)p_td->bufEnd - (uint32_t)p_td->currBufPtr + 1) - g_usbx_host_data_count[pipe]; + } else { + /* ErrorCount */ + RZA_IO_RegWrite_32(&p_td->control, 3, TD_CTL_SHFT_EC, TD_CTL_MSK_EC); + } + + /* DataToggle */ + sqmon = usbx_host_get_sqmon(pipe); + RZA_IO_RegWrite_32(&p_td->control, sqmon, TD_CTL_SHFT_T, TD_CTL_MSK_T); + if (sqmon == 0) { + p_ed->headTD &= ~ED_TOGLE_CARRY; + } else { + p_ed->headTD |= ED_TOGLE_CARRY; + } + + /* ConditionCode */ + RZA_IO_RegWrite_32(&p_td->control, ConditionCode, TD_CTL_SHFT_CC, TD_CTL_MSK_CC); + + if (p_wait_ed == &ctl_ed) { + chk_split_trans_setting(&ctl_ed); + } + chk_genelal_td_done(p_wait_ed); + + if (periodic != 0) { + if (chk_genelal_ed(p_wait_ed) != 0) { + int_trans(p_wait_ed); + } else { + p_wait_ed->trans_wait = 0; + (void)osSemaphoreRelease(p_wait_ed->semid_wait); + } + } else { + p_wait_ed->trans_wait = 0; + (void)osSemaphoreRelease(p_wait_ed->semid_wait); + } + } + } else { +#if (ISO_TRANS_MAX_NUM > 0) + hcisotd_t *p_isotd = (hcisotd_t *)p_wait_ed->p_curr_td; + uint32_t next_trans = 0; + + if (p_isotd != NULL) { + usbx_host_stop_transfer(pipe); + p_usb_reg->HcFmNumber = ((p_isotd->control & 0x0000FFFF) + p_wait_ed->psw_idx) & 0x0000FFFF; + + /* Size of packet */ + p_isotd->offsetPSW[p_wait_ed->psw_idx] -= g_usbx_host_data_count[pipe]; + + /* ConditionCode */ + RZA_IO_RegWrite_32(&p_isotd->control, ConditionCode, TD_CTL_SHFT_CC, TD_CTL_MSK_CC); + RZA_IO_RegWrite_16(&p_isotd->offsetPSW[p_wait_ed->psw_idx], + (uint16_t)ConditionCode, TD_PSW_SHFT_CC, TD_PSW_MSK_CC); + + if (usbx_host_CheckAttach() != USB_HOST_ATTACH) { + p_ed->headTD |= ED_HALTED; + } + if (p_wait_ed->psw_idx >= RZA_IO_RegRead_32(&p_isotd->control, TD_CTL_SHFT_FC, TD_CTL_MSK_FC)) { + p_wait_ed->psw_idx = 0; + chk_iso_td_done(p_wait_ed); + } else { + p_wait_ed->psw_idx++; + } + if (chk_iso_ed(p_wait_ed) != 0) { + iso_trans(p_wait_ed); + next_trans = 1; + } + if (next_trans == 0) { + p_wait_ed->trans_wait = 0; + (void)osSemaphoreRelease(p_wait_ed->semid_wait); + } + } +#endif + } + +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/ohci_wrapp_RZ_A1.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,60 @@ +/* Copyright (c) 2010-2011 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef OHCI_WRAPP_RZ_A1_H +#define OHCI_WRAPP_RZ_A1_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define OHCI_REG_REVISION (0x00) /* HcRevision */ +#define OHCI_REG_CONTROL (0x04) /* HcControl */ +#define OHCI_REG_COMMANDSTATUS (0x08) /* HcCommandStatus */ +#define OHCI_REG_INTERRUPTSTATUS (0x0C) /* HcInterruptStatus */ +#define OHCI_REG_INTERRUPTENABLE (0x10) /* HcInterruptEnable */ +#define OHCI_REG_INTERRUPTDISABLE (0x14) /* HcInterruptDisable */ +#define OHCI_REG_HCCA (0x18) /* HcHCCA */ +#define OHCI_REG_PERIODCURRENTED (0x1C) /* HcPeriodCurrentED */ +#define OHCI_REG_CONTROLHEADED (0x20) /* HcControlHeadED */ +#define OHCI_REG_CONTROLCURRENTED (0x24) /* HcControlCurrentED */ +#define OHCI_REG_BULKHEADED (0x28) /* HcBulkHeadED */ +#define OHCI_REG_BULKCURRENTED (0x2C) /* HcBulkCurrentED */ +#define OHCI_REG_DONEHEADED (0x30) /* HcDoneHead */ +#define OHCI_REG_FMINTERVAL (0x34) /* HcFmInterval */ +#define OHCI_REG_FMREMAINING (0x38) /* HcFmRemaining */ +#define OHCI_REG_FMNUMBER (0x3C) /* HcFmNumber */ +#define OHCI_REG_PERIODICSTART (0x40) /* HcPeriodicStart */ +#define OHCI_REG_LSTHRESHOLD (0x44) /* HcLSThreshold */ +#define OHCI_REG_RHDESCRIPTORA (0x48) /* HcRhDescriptorA */ +#define OHCI_REG_RHDESCRIPTORB (0x4C) /* HcRhDescriptorB */ +#define OHCI_REG_RHSTATUS (0x50) /* HcRhStatus */ +#define OHCI_REG_RHPORTSTATUS1 (0x54) /* HcRhPortStatus1 */ + +typedef void (usbisr_fnc_t)(void); + +extern void ohciwrapp_init(usbisr_fnc_t *p_usbisr_fnc); +extern uint32_t ohciwrapp_reg_r(uint32_t reg_ofs); +extern void ohciwrapp_reg_w(uint32_t reg_ofs, uint32_t set_data); +extern void ohciwrapp_interrupt(uint32_t int_sense); + +#ifdef __cplusplus +} +#endif + +#endif /* OHCI_WRAPP_RZ_A1_H */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/ohci_wrapp_RZ_A1_local.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,49 @@ +/* Copyright (c) 2010-2011 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef OHCI_WRAPP_RZ_A1_LOCAL_H +#define OHCI_WRAPP_RZ_A1_LOCAL_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* ConditionCode */ +#define TD_CC_NOERROR (0) +#define TD_CC_CRC (1) +#define TD_CC_BITSTUFFING (2) +#define TD_CC_DATATOGGLEMISMATCH (3) +#define TD_CC_STALL (4) +#define TD_CC_DEVICENOTRESPONDING (5) +#define TD_CC_PIDCHECKFAILURE (6) +#define TD_CC_UNEXPECTEDPID (7) +#define TD_CC_DATAOVERRUN (8) +#define TD_CC_DATAUNDERRUN (9) +#define TD_CC_BUFFEROVERRUN (12) +#define TD_CC_BUFFERUNDERRUN (13) +#define TD_CC_NOT_ACCESSED_1 (14) +#define TD_CC_NOT_ACCESSED_2 (15) + +extern void ohciwrapp_loc_Connect(uint32_t type); +extern void ohciwrapp_loc_TransEnd(uint32_t pipe, uint32_t ConditionCode); + +#ifdef __cplusplus +} +#endif + +#endif /* OHCI_WRAPP_RZ_A1_LOCAL_H */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/ohci_wrapp_pipe.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,189 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "devdrv_usb_host_api.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/********************************************************************************************************/ +/* Endpoint Configuration Data Format */ +/********************************************************************************************************/ +/* LINE1: Pipe Window Select Register */ +/* CPU Access PIPE : USB_HOST_PIPE1 to USB_HOST_PIPE9 [ ### SET ### ] */ +/* LINE2: Pipe Configuration Register */ +/* Transfer Type : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* Buffer Ready interrupt : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* Double Buffer Mode : USB_HOST_DBLBON / USB_HOST_DBLBOFF [ ### SET ### ] */ +/* Continuous Transmit: : USB_HOST_CNTMDON / USB_HOST_CNTMDOFF [ ### SET ### ] */ +/* Short NAK : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* Transfer Direction : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* Endpoint Number : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* LINE3: Pipe Buffer Configuration Register */ +/* Buffer Size : (uint16_t)((uint16_t)(((x) / 64) - 1) << 10) */ +/* [ ### SET ### ] */ +/* Buffer Top Number : (uint16_t)(x) [ ### SET ### ] */ +/* LINE4: Pipe Maxpacket Size Register */ +/* Max Packet Size : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* LINE5: Pipe Cycle Configuration Register (0x6C) */ +/* ISO Buffer Flush Mode : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* ISO Interval Value : USB_HOST_NONE [ USB_HOST_NONE ] */ +/* LINE6: use FIFO port */ +/* : USB_HOST_CUSE [ ### SET ### ] */ +/* : USB_HOST_D0USE / USB_HOST_D1USE */ +/* : USB_HOST_D0DMA / USB_HOST_D0DMA */ +/********************************************************************************************************/ + +/* Device Address 1 */ +USB_HOST_CFG_PIPETBL_t usb_host_blk_ep_tbl1[ ] = +{ + { + USB_HOST_PIPE3, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBON | USB_HOST_CNTMDON | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((1024) / 64) - 1) << 10) | (uint16_t)(8), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D0USE + }, + + { + /* Pipe end */ + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF + } +}; + +USB_HOST_CFG_PIPETBL_t usb_host_int_ep_tbl1[ ] = +{ + { + USB_HOST_PIPE6, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBOFF | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((64) / 64) - 1) << 10) | (uint16_t)(40), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + USB_HOST_PIPE7, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBOFF | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((64) / 64) - 1) << 10) | (uint16_t)(41), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + USB_HOST_PIPE8, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBOFF | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((64) / 64) - 1) << 10) | (uint16_t)(42), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + USB_HOST_PIPE9, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBOFF | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((64) / 64) - 1) << 10) | (uint16_t)(43), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + /* Pipe end */ + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF + } +}; + +USB_HOST_CFG_PIPETBL_t usb_host_iso_ep_tbl1[ ] = +{ + { + USB_HOST_PIPE1, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBON | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((1024) / 64) - 1) << 10) | (uint16_t)(44), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + USB_HOST_PIPE2, + /* TYPE / BFRE / DBLB / CNTMD / SHTNAK / DIR / EPNUM */ + USB_HOST_NONE | USB_HOST_NONE | USB_HOST_DBLBON | USB_HOST_CNTMDOFF | USB_HOST_NONE | USB_HOST_NONE | USB_HOST_NONE, + (uint16_t)((uint16_t)(((1024) / 64) - 1) << 10) | (uint16_t)(76), + USB_HOST_NONE, + USB_HOST_NONE, + USB_HOST_D1USE + }, + + { + /* Pipe end */ + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF, + 0xFFFF + } +}; + + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/inc/usb0_host.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,156 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB0_HOST_H +#define USB0_HOST_H + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "devdrv_usb_host_api.h" +#include "usb_host.h" + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +extern const uint16_t g_usb0_host_bit_set[]; +extern uint32_t g_usb0_host_data_count[USB_HOST_MAX_PIPE_NO + 1]; +extern uint8_t *g_usb0_host_data_pointer[USB_HOST_MAX_PIPE_NO + 1]; + +extern uint16_t g_usb0_host_PipeIgnore[]; +extern uint16_t g_usb0_host_PipeTbl[]; +extern uint16_t g_usb0_host_pipe_status[]; +extern uint32_t g_usb0_host_PipeDataSize[]; + +extern USB_HOST_DMA_t g_usb0_host_DmaInfo[]; +extern uint16_t g_usb0_host_DmaPipe[]; +extern uint16_t g_usb0_host_DmaBval[]; +extern uint16_t g_usb0_host_DmaStatus[]; + +extern uint16_t g_usb0_host_driver_state; +extern uint16_t g_usb0_host_ConfigNum; +extern uint16_t g_usb0_host_CmdStage; +extern uint16_t g_usb0_host_bchg_flag; +extern uint16_t g_usb0_host_detach_flag; +extern uint16_t g_usb0_host_attach_flag; + +extern uint16_t g_usb0_host_UsbAddress; +extern uint16_t g_usb0_host_setUsbAddress; +extern uint16_t g_usb0_host_default_max_packet[USB_HOST_MAX_DEVICE + 1]; +extern uint16_t g_usb0_host_UsbDeviceSpeed; +extern uint16_t g_usb0_host_SupportUsbDeviceSpeed; + +extern uint16_t g_usb0_host_SavReq; +extern uint16_t g_usb0_host_SavVal; +extern uint16_t g_usb0_host_SavIndx; +extern uint16_t g_usb0_host_SavLen; + +extern uint16_t g_usb0_host_pipecfg[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb0_host_pipebuf[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb0_host_pipemaxp[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb0_host_pipeperi[USB_HOST_MAX_PIPE_NO + 1]; + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +/* ==== common ==== */ +void usb0_host_dma_stop_d0(uint16_t pipe, uint32_t remain); +void usb0_host_dma_stop_d1(uint16_t pipe, uint32_t remain); +uint16_t usb0_host_is_hispeed(void); +uint16_t usb0_host_is_hispeed_enable(void); +uint16_t usb0_host_start_send_transfer(uint16_t pipe, uint32_t size, uint8_t *data); +uint16_t usb0_host_write_buffer(uint16_t pipe); +uint16_t usb0_host_write_buffer_c(uint16_t pipe); +uint16_t usb0_host_write_buffer_d0(uint16_t pipe); +uint16_t usb0_host_write_buffer_d1(uint16_t pipe); +void usb0_host_start_receive_transfer(uint16_t pipe, uint32_t size, uint8_t *data); +uint16_t usb0_host_read_buffer(uint16_t pipe); +uint16_t usb0_host_read_buffer_c(uint16_t pipe); +uint16_t usb0_host_read_buffer_d0(uint16_t pipe); +uint16_t usb0_host_read_buffer_d1(uint16_t pipe); +uint16_t usb0_host_change_fifo_port(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw); +void usb0_host_set_curpipe(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw); +void usb0_host_set_curpipe2(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw, uint16_t dfacc); +uint16_t usb0_host_get_mbw(uint32_t trncount, uint32_t dtptr); +uint16_t usb0_host_read_dma(uint16_t pipe); +void usb0_host_stop_transfer(uint16_t pipe); +void usb0_host_brdy_int(uint16_t status, uint16_t int_enb); +void usb0_host_nrdy_int(uint16_t status, uint16_t int_enb); +void usb0_host_bemp_int(uint16_t status, uint16_t int_enb); +void usb0_host_setting_interrupt(uint8_t level); +void usb0_host_reset_module(uint16_t clockmode); +uint16_t usb0_host_get_buf_size(uint16_t pipe); +uint16_t usb0_host_get_mxps(uint16_t pipe); +void usb0_host_enable_brdy_int(uint16_t pipe); +void usb0_host_disable_brdy_int(uint16_t pipe); +void usb0_host_clear_brdy_sts(uint16_t pipe); +void usb0_host_enable_bemp_int(uint16_t pipe); +void usb0_host_disable_bemp_int(uint16_t pipe); +void usb0_host_clear_bemp_sts(uint16_t pipe); +void usb0_host_enable_nrdy_int(uint16_t pipe); +void usb0_host_disable_nrdy_int(uint16_t pipe); +void usb0_host_clear_nrdy_sts(uint16_t pipe); +void usb0_host_set_pid_buf(uint16_t pipe); +void usb0_host_set_pid_nak(uint16_t pipe); +void usb0_host_set_pid_stall(uint16_t pipe); +void usb0_host_clear_pid_stall(uint16_t pipe); +uint16_t usb0_host_get_pid(uint16_t pipe); +void usb0_host_set_sqclr(uint16_t pipe); +void usb0_host_set_sqset(uint16_t pipe); +void usb0_host_set_csclr(uint16_t pipe); +void usb0_host_aclrm(uint16_t pipe); +void usb0_host_set_aclrm(uint16_t pipe); +void usb0_host_clr_aclrm(uint16_t pipe); +uint16_t usb0_host_get_sqmon(uint16_t pipe); +uint16_t usb0_host_get_inbuf(uint16_t pipe); + +/* ==== host ==== */ +void usb0_host_init_pipe_status(void); +int32_t usb0_host_CtrlTransStart(uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len, uint8_t *Buf); +void usb0_host_SetupStage(uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len); +void usb0_host_CtrlReadStart(uint32_t Bsize, uint8_t *Table); +uint16_t usb0_host_CtrlWriteStart(uint32_t Bsize, uint8_t *Table); +void usb0_host_StatusStage(void); +void usb0_host_get_devadd(uint16_t addr, uint16_t *devadd); +void usb0_host_set_devadd(uint16_t addr, uint16_t *devadd); +void usb0_host_InitModule(void); +uint16_t usb0_host_CheckAttach(void); +void usb0_host_UsbDetach(void); +void usb0_host_UsbDetach2(void); +void usb0_host_UsbAttach(void); +uint16_t usb0_host_UsbBusReset(void); +int32_t usb0_host_UsbResume(void); +int32_t usb0_host_UsbSuspend(void); +void usb0_host_Enable_DetachINT(void); +void usb0_host_Disable_DetachINT(void); +void usb0_host_UsbStateManager(void); + + +#endif /* USB0_HOST_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/inc/usb0_host_api.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,112 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_api.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB0_HOST_API_H +#define USB0_HOST_API_H + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Variable Externs +*******************************************************************************/ + + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +void usb0_host_interrupt(uint32_t int_sense); +void usb0_host_dma_interrupt_d0fifo(uint32_t int_sense); +void usb0_host_dma_interrupt_d1fifo(uint32_t int_sense); + +uint16_t usb0_api_host_init(uint8_t int_level, uint16_t mode, uint16_t clockmode); +int32_t usb0_api_host_enumeration(uint16_t devadr); +int32_t usb0_api_host_detach(void); +int32_t usb0_api_host_data_in(uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t usb0_api_host_data_out(uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t usb0_api_host_control_transfer(uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len, uint8_t *Buf); +int32_t usb0_api_host_set_endpoint(uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t *configdescriptor); +int32_t usb0_api_host_clear_endpoint(USB_HOST_CFG_PIPETBL_t *user_table); +int32_t usb0_api_host_clear_endpoint_pipe(uint16_t pipe_sel, USB_HOST_CFG_PIPETBL_t *user_table); +uint16_t usb0_api_host_SetEndpointTable(uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t* Table); +int32_t usb0_api_host_data_count(uint16_t pipe, uint32_t *data_count); + +int32_t usb0_api_host_GetDeviceDescriptor(uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t usb0_api_host_GetConfigDescriptor(uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t usb0_api_host_SetConfig(uint16_t devadr, uint16_t confignum); +int32_t usb0_api_host_SetInterface(uint16_t devadr, uint16_t interface_alt, uint16_t interface_index); +int32_t usb0_api_host_ClearStall(uint16_t devadr, uint16_t ep_dir); +uint16_t usb0_api_host_GetUsbDeviceState(void); + +void usb0_api_host_elt_4_4(void); +void usb0_api_host_elt_4_5(void); +void usb0_api_host_elt_4_6(void); +void usb0_api_host_elt_4_7(void); +void usb0_api_host_elt_4_8(void); +void usb0_api_host_elt_4_9(void); +void usb0_api_host_elt_get_desc(void); + +void usb0_host_EL_ModeInit(void); +void usb0_host_EL_SetUACT(void); +void usb0_host_EL_ClearUACT(void); +void usb0_host_EL_SetTESTMODE(uint16_t mode); +void usb0_host_EL_ClearNRDYSTS(uint16_t pipe); +uint16_t usb0_host_EL_GetINTSTS1(void); +void usb0_host_EL_UsbBusReset(void); +void usb0_host_EL_UsbAttach(void); +void usb0_host_EL_SetupStage(uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len); +void usb0_host_EL_StatusStage(void); +void usb0_host_EL_CtrlReadStart(uint32_t Bsize, uint8_t *Table); +int32_t usb0_host_EL_UsbSuspend(void); +int32_t usb0_host_EL_UsbResume(void); + +#if 0 /* prototype in devdrv_usb_host_api.h */ +uint16_t Userdef_USB_usb0_host_d0fifo_dmaintid(void); +uint16_t Userdef_USB_usb0_host_d1fifo_dmaintid(void); +void Userdef_USB_usb0_host_attach(void); +void Userdef_USB_usb0_host_detach(void); +void Userdef_USB_usb0_host_delay_1ms(void); +void Userdef_USB_usb0_host_delay_xms(uint32_t msec); +void Userdef_USB_usb0_host_delay_10us(uint32_t usec); +void Userdef_USB_usb0_host_delay_500ns(void); +void Userdef_USB_usb0_host_start_dma(USB_HOST_DMA_t *dma, uint16_t dfacc); +uint32_t Userdef_USB_usb0_host_stop_dma0(void); +uint32_t Userdef_USB_usb0_host_stop_dma1(void); +#endif + +#endif /* USB0_HOST_API_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/inc/usb0_host_dmacdrv.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,139 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_dmacdrv.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB0_HOST_DMACDRV_H +#define USB0_HOST_DMACDRV_H + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ +typedef struct dmac_transinfo +{ + uint32_t src_addr; /* Transfer source address */ + uint32_t dst_addr; /* Transfer destination address */ + uint32_t count; /* Transfer byte count */ + uint32_t src_size; /* Transfer source data size */ + uint32_t dst_size; /* Transfer destination data size */ + uint32_t saddr_dir; /* Transfer source address direction */ + uint32_t daddr_dir; /* Transfer destination address direction */ +} dmac_transinfo_t; + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +/* ==== Transfer specification of the sample program ==== */ +#define DMAC_SAMPLE_SINGLE (0) /* Single transfer */ +#define DMAC_SAMPLE_CONTINUATION (1) /* Continuous transfer (use REN bit) */ + +/* ==== DMA modes ==== */ +#define DMAC_MODE_REGISTER (0) /* Register mode */ +#define DMAC_MODE_LINK (1) /* Link mode */ + +/* ==== Transfer requests ==== */ +#define DMAC_REQ_MODE_EXT (0) /* External request */ +#define DMAC_REQ_MODE_PERI (1) /* On-chip peripheral module request */ +#define DMAC_REQ_MODE_SOFT (2) /* Auto-request (request by software) */ + +/* ==== DMAC transfer sizes ==== */ +#define DMAC_TRANS_SIZE_8 (0) /* 8 bits */ +#define DMAC_TRANS_SIZE_16 (1) /* 16 bits */ +#define DMAC_TRANS_SIZE_32 (2) /* 32 bits */ +#define DMAC_TRANS_SIZE_64 (3) /* 64 bits */ +#define DMAC_TRANS_SIZE_128 (4) /* 128 bits */ +#define DMAC_TRANS_SIZE_256 (5) /* 256 bits */ +#define DMAC_TRANS_SIZE_512 (6) /* 512 bits */ +#define DMAC_TRANS_SIZE_1024 (7) /* 1024 bits */ + +/* ==== Address increment for transferring ==== */ +#define DMAC_TRANS_ADR_NO_INC (1) /* Not increment */ +#define DMAC_TRANS_ADR_INC (0) /* Increment */ + +/* ==== Method for detecting DMA request ==== */ +#define DMAC_REQ_DET_FALL (0) /* Falling edge detection */ +#define DMAC_REQ_DET_RISE (1) /* Rising edge detection */ +#define DMAC_REQ_DET_LOW (2) /* Low level detection */ +#define DMAC_REQ_DET_HIGH (3) /* High level detection */ + +/* ==== Request Direction ==== */ +#define DMAC_REQ_DIR_SRC (0) /* DMAREQ is the source/ DMAACK is active when reading */ +#define DMAC_REQ_DIR_DST (1) /* DMAREQ is the destination/ DMAACK is active when writing */ + +/* ==== Descriptors ==== */ +#define DMAC_DESC_HEADER (0) /* Header */ +#define DMAC_DESC_SRC_ADDR (1) /* Source Address */ +#define DMAC_DESC_DST_ADDR (2) /* Destination Address */ +#define DMAC_DESC_COUNT (3) /* Transaction Byte */ +#define DMAC_DESC_CHCFG (4) /* Channel Confg */ +#define DMAC_DESC_CHITVL (5) /* Channel Interval */ +#define DMAC_DESC_CHEXT (6) /* Channel Extension */ +#define DMAC_DESC_LINK_ADDR (7) /* Link Address */ + +/* ==== On-chip peripheral module requests ===== */ +typedef enum dmac_request_factor +{ + DMAC_REQ_USB0_DMA0_TX, /* USB_0 channel 0 transmit FIFO empty */ + DMAC_REQ_USB0_DMA0_RX, /* USB_0 channel 0 receive FIFO full */ + DMAC_REQ_USB0_DMA1_TX, /* USB_0 channel 1 transmit FIFO empty */ + DMAC_REQ_USB0_DMA1_RX, /* USB_0 channel 1 receive FIFO full */ + DMAC_REQ_USB1_DMA0_TX, /* USB_1 channel 0 transmit FIFO empty */ + DMAC_REQ_USB1_DMA0_RX, /* USB_1 channel 0 receive FIFO full */ + DMAC_REQ_USB1_DMA1_TX, /* USB_1 channel 1 transmit FIFO empty */ + DMAC_REQ_USB1_DMA1_RX, /* USB_1 channel 1 receive FIFO full */ +} dmac_request_factor_t; + + +/******************************************************************************* +Variable Externs +*******************************************************************************/ + + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +void usb0_host_DMAC1_PeriReqInit(const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction); +int32_t usb0_host_DMAC1_Open(uint32_t req); +void usb0_host_DMAC1_Close(uint32_t * remain); +void usb0_host_DMAC1_Load_Set(uint32_t src_addr, uint32_t dst_addr, uint32_t count); + +void usb0_host_DMAC2_PeriReqInit(const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction); +int32_t usb0_host_DMAC2_Open(uint32_t req); +void usb0_host_DMAC2_Close(uint32_t * remain); +void usb0_host_DMAC2_Load_Set(uint32_t src_addr, uint32_t dst_addr, uint32_t count); + +#endif /* USB0_HOST_DMACDRV_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/common/usb0_host_dataio.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,2835 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_dataio.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +static uint16_t g_usb0_host_mbw[(USB_HOST_MAX_PIPE_NO + 1)]; + +static void usb0_host_start_receive_trns_c(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb0_host_start_receive_trns_d0(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb0_host_start_receive_trns_d1(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb0_host_start_receive_dma_d0(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb0_host_start_receive_dma_d1(uint16_t pipe, uint32_t size, uint8_t *data); +static uint16_t usb0_host_read_dma_d0(uint16_t pipe); +static uint16_t usb0_host_read_dma_d1(uint16_t pipe); +static uint16_t usb0_host_write_dma_d0(uint16_t pipe); +static uint16_t usb0_host_write_dma_d1(uint16_t pipe); + +static void usb0_host_read_c_fifo(uint16_t pipe, uint16_t count); +static void usb0_host_write_c_fifo(uint16_t Pipe, uint16_t count); +static void usb0_host_read_d0_fifo(uint16_t pipe, uint16_t count); +static void usb0_host_write_d0_fifo(uint16_t pipe, uint16_t count); +static void usb0_host_read_d1_fifo(uint16_t pipe, uint16_t count); +static void usb0_host_write_d1_fifo(uint16_t pipe, uint16_t count); + +static void usb0_host_clear_transaction_counter(uint16_t pipe); +static void usb0_host_set_transaction_counter(uint16_t pipe, uint32_t count); + +static uint32_t usb0_host_com_get_dmasize(uint32_t trncount, uint32_t dtptr); + +static uint16_t usb0_host_set_dfacc_d0(uint16_t mbw, uint32_t count); +static uint16_t usb0_host_set_dfacc_d1(uint16_t mbw, uint32_t count); + + +/******************************************************************************* +* Function Name: usb0_host_start_send_transfer +* Description : Starts the USB data communication using pipe specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data data Address +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_start_send_transfer (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t status; + uint16_t usefifo; + uint16_t mbw; + + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + usb0_host_clear_bemp_sts(pipe); + usb0_host_clear_brdy_sts(pipe); + usb0_host_clear_nrdy_sts(pipe); + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + + usefifo = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + case USB_HOST_D0FIFO_DMA: + usefifo = USB_HOST_D0USE; + break; + + case USB_HOST_D1FIFO_USE: + case USB_HOST_D1FIFO_DMA: + usefifo = USB_HOST_D1USE; + break; + + default: + usefifo = USB_HOST_CUSE; + break; + }; + + usb0_host_set_curpipe(USB_HOST_PIPE0, usefifo, USB_HOST_NO, mbw); + + usb0_host_clear_transaction_counter(pipe); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + status = usb0_host_write_buffer(pipe); + + if (status != USB_HOST_FIFOERROR) + { + usb0_host_set_pid_buf(pipe); + } + + return status; +} + +/******************************************************************************* +* Function Name: usb0_host_write_buffer +* Description : Writes data in the buffer allocated in the pipe specified by +* : the argument. The FIFO for using is set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_write_buffer (uint16_t pipe) +{ + uint16_t status; + uint16_t usefifo; + + g_usb0_host_PipeIgnore[pipe] = 0; + usefifo = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + status = usb0_host_write_buffer_d0(pipe); + break; + + case USB_HOST_D1FIFO_USE: + status = usb0_host_write_buffer_d1(pipe); + break; + + case USB_HOST_D0FIFO_DMA: + status = usb0_host_write_dma_d0(pipe); + break; + + case USB_HOST_D1FIFO_DMA: + status = usb0_host_write_dma_d1(pipe); + break; + + default: + status = usb0_host_write_buffer_c(pipe); + break; + }; + + switch (status) + { + case USB_HOST_WRITING: /* Continue of data write */ + usb0_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + usb0_host_enable_brdy_int(pipe); /* Enable Ready Interrupt */ + break; + + case USB_HOST_WRITEEND: /* End of data write */ + case USB_HOST_WRITESHRT: /* End of data write */ + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + + usb0_host_clear_nrdy_sts(pipe); + usb0_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + + /* for last transfer */ + usb0_host_enable_bemp_int(pipe); /* Enable Empty Interrupt */ + break; + + case USB_HOST_WRITEDMA: /* DMA write */ + usb0_host_clear_nrdy_sts(pipe); + usb0_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + usb0_host_disable_bemp_int(pipe); /* Disable Empty Interrupt */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_write_buffer_c +* Description : Writes data in the buffer allocated in the pipe specified in +* : the argument. Writes data by CPU transfer using CFIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_write_buffer_c (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + + if (pipe == USB_HOST_PIPE0) + { + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_CFIFO_WRITE, mbw); + } + else + { + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_NO, mbw); + } + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb0_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb0_host_write_c_fifo(pipe, (uint16_t)count); + + if (g_usb0_host_data_count[pipe] < (uint32_t)size) + { + g_usb0_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB200.CFIFOCTR, + USB_CFIFOCTR_BVAL_SHIFT, + USB_CFIFOCTR_BVAL) == 0) + { + USB200.CFIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb0_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_write_buffer_d0 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by CPU transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_write_buffer_d0 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D0USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb0_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb0_host_write_d0_fifo(pipe, (uint16_t)count); + + if (g_usb0_host_data_count[pipe] < (uint32_t)size) + { + g_usb0_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB200.D0FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + USB200.D0FIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb0_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_write_buffer_d1 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by CPU transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_write_buffer_d1 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D1USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb0_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb0_host_write_d1_fifo(pipe, (uint16_t)count); + + if (g_usb0_host_data_count[pipe] < (uint32_t)size) + { + g_usb0_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB200.D1FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + USB200.D1FIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb0_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_write_dma_d0 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by DMA transfer using D0FIFO. +* : The DMA-ch for using is specified by Userdef_USB_usb0_host_start_dma(). +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND : Write end +* : USB_HOST_WRITESHRT : short data +* : USB_HOST_WRITING : Continue of data write +* : USB_HOST_WRITEDMA : Write DMA +* : USB_HOST_FIFOERROR : FIFO status +*******************************************************************************/ +static uint16_t usb0_host_write_dma_d0 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + count = g_usb0_host_data_count[pipe]; + + if (count != 0) + { + g_usb0_host_DmaPipe[USB_HOST_D0FIFO] = pipe; + + if ((count % size) != 0) + { + g_usb0_host_DmaBval[USB_HOST_D0FIFO] = 1; + } + else + { + g_usb0_host_DmaBval[USB_HOST_D0FIFO] = 0; + } + + dfacc = usb0_host_set_dfacc_d0(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 0; /* 8bit transfer */ + } + + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].fifo = USB_HOST_D0FIFO_DMA; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].dir = USB_HOST_BUF2FIFO; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].buffer = (uint32_t)g_usb0_host_data_pointer[pipe]; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].bytes = count; + + Userdef_USB_usb0_host_start_dma(&g_usb0_host_DmaInfo[USB_HOST_D0FIFO], dfacc); + + usb0_host_set_curpipe2(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw, dfacc); + + RZA_IO_RegWrite_16(&USB200.D0FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + + g_usb0_host_data_count[pipe] = 0; + g_usb0_host_data_pointer[pipe] += count; + + status = USB_HOST_WRITEDMA; /* DMA write */ + } + else + { + if (RZA_IO_RegRead_16(&USB200.D0FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + RZA_IO_RegWrite_16(&USB200.D0FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); /* Short Packet */ + } + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_write_dma_d1 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by DMA transfer using D1FIFO. +* : The DMA-ch for using is specified by Userdef_USB_usb0_host_start_dma(). +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND : Write end +* : USB_HOST_WRITESHRT : short data +* : USB_HOST_WRITING : Continue of data write +* : USB_HOST_WRITEDMA : Write DMA +* : USB_HOST_FIFOERROR : FIFO status +*******************************************************************************/ +static uint16_t usb0_host_write_dma_d1 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + count = g_usb0_host_data_count[pipe]; + + if (count != 0) + { + g_usb0_host_DmaPipe[USB_HOST_D1FIFO] = pipe; + + if ((count % size) != 0) + { + g_usb0_host_DmaBval[USB_HOST_D1FIFO] = 1; + } + else + { + g_usb0_host_DmaBval[USB_HOST_D1FIFO] = 0; + } + + dfacc = usb0_host_set_dfacc_d1(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 0; /* 8bit transfer */ + } + + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].fifo = USB_HOST_D1FIFO_DMA; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].dir = USB_HOST_BUF2FIFO; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].buffer = (uint32_t)g_usb0_host_data_pointer[pipe]; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].bytes = count; + + Userdef_USB_usb0_host_start_dma(&g_usb0_host_DmaInfo[USB_HOST_D1FIFO], dfacc); + + usb0_host_set_curpipe2(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw, dfacc); + + RZA_IO_RegWrite_16(&USB200.D1FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + + g_usb0_host_data_count[pipe] = 0; + g_usb0_host_data_pointer[pipe] += count; + + status = USB_HOST_WRITEDMA; /* DMA write */ + } + else + { + if (RZA_IO_RegRead_16(&USB200.D1FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + RZA_IO_RegWrite_16(&USB200.D1FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); /* Short Packet */ + } + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_transfer +* Description : Starts USB data reception using the pipe specified in the argument. +* : The FIFO for using is set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +void usb0_host_start_receive_transfer (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t usefifo; + + usb0_host_clear_bemp_sts(pipe); + usb0_host_clear_brdy_sts(pipe); + usb0_host_clear_nrdy_sts(pipe); + + usefifo = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + usb0_host_start_receive_trns_d0(pipe, size, data); + break; + + case USB_HOST_D1FIFO_USE: + usb0_host_start_receive_trns_d1(pipe, size, data); + break; + + case USB_HOST_D0FIFO_DMA: + usb0_host_start_receive_dma_d0(pipe, size, data); + break; + + case USB_HOST_D1FIFO_DMA: + usb0_host_start_receive_dma_d1(pipe, size, data); + break; + + default: + usb0_host_start_receive_trns_c(pipe, size, data); + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_trns_c +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using CFIFO. +* : When storing data in the buffer allocated in the pipe specified in the +* : argument, BRDY interrupt is generated to read data +* : in the interrupt. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb0_host_start_receive_trns_c (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb0_host_set_pid_nak(pipe); + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_PipeIgnore[pipe] = 0; + + g_usb0_host_PipeDataSize[pipe] = size; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_CFIFO_READ, mbw); + USB200.CFIFOCTR = USB_HOST_BITBCLR; + + usb0_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + + usb0_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_trns_d0 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, BRDY interrupt is generated to read data in the +* : interrupt. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb0_host_start_receive_trns_d0 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb0_host_set_pid_nak(pipe); + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_PipeIgnore[pipe] = 0; + + g_usb0_host_PipeDataSize[pipe] = size; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, mbw); + + usb0_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + + usb0_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_trns_d1 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using D1FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, BRDY interrupt is generated to read data. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb0_host_start_receive_trns_d1 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb0_host_set_pid_nak(pipe); + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_PipeIgnore[pipe] = 0; + + g_usb0_host_PipeDataSize[pipe] = size; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, mbw); + + usb0_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + + usb0_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_dma_d0 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by DMA transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, delivered read request to DMAC to read data from +* : the buffer by DMAC. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb0_host_start_receive_dma_d0 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb0_host_set_pid_nak(pipe); + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_PipeIgnore[pipe] = 0; + + g_usb0_host_PipeDataSize[pipe] = 0; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, mbw); + + usb0_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + usb0_host_read_dma(pipe); + + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + } + else + { + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + } + + usb0_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_start_receive_dma_d1 +* Description : Read data from the buffer allocated in the pipe specified in the argument. +* : Reads data by DMA transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, delivered read request to DMAC to read data from +* : the buffer by DMAC. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb0_host_start_receive_dma_d1 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb0_host_set_pid_nak(pipe); + g_usb0_host_data_count[pipe] = size; + g_usb0_host_data_pointer[pipe] = (uint8_t *)data; + g_usb0_host_PipeIgnore[pipe] = 0; + + g_usb0_host_PipeDataSize[pipe] = 0; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb0_host_get_mbw(size, (uint32_t)data); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, mbw); + + usb0_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + usb0_host_read_dma(pipe); + + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + } + else + { + usb0_host_enable_nrdy_int(pipe); + usb0_host_enable_brdy_int(pipe); + } + + usb0_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_read_buffer +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Uses FIF0 set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_read_buffer (uint16_t pipe) +{ + uint16_t status; + + g_usb0_host_PipeIgnore[pipe] = 0; + + if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_USE) + { + status = usb0_host_read_buffer_d0(pipe); + } + else if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_USE) + { + status = usb0_host_read_buffer_d1(pipe); + } + else + { + status = usb0_host_read_buffer_c(pipe); + } + + switch (status) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb0_host_disable_brdy_int(pipe); + g_usb0_host_PipeDataSize[pipe] -= g_usb0_host_data_count[pipe]; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + break; + + case USB_HOST_READOVER: /* buffer over */ + if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_USE) + { + USB200.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_USE) + { + USB200.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + USB200.CFIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#else + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; +#endif + g_usb0_host_PipeDataSize[pipe] -= g_usb0_host_data_count[pipe]; + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_buffer_c +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using CFIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_read_buffer_c (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb0_host_data_count[pipe]; + } + else if (g_usb0_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + } + + if (count == 0) /* 0 length packet */ + { + USB200.CFIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb0_host_read_c_fifo(pipe, (uint16_t)count); + } + + g_usb0_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_buffer_d0 +* Description : Reads data from the buffer allocated in the pipe specified in +* : the argument. +* : Reads data by CPU transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_read_buffer_d0 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t pipebuf_size; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D0USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb0_host_data_count[pipe]; + } + else if (g_usb0_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + else + { + pipebuf_size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + } + } + + if (count == 0) /* 0 length packet */ + { + USB200.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb0_host_read_d0_fifo(pipe, (uint16_t)count); + } + + g_usb0_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_buffer_d1 +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by CPU transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_read_buffer_d1 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t pipebuf_size; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D1USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb0_host_data_count[pipe]; + } + else if (g_usb0_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb0_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) !=0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + else + { + pipebuf_size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb0_host_set_pid_nak(pipe); /* Set NAK */ + } + } + } + + if (count == 0) /* 0 length packet */ + { + USB200.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb0_host_read_d1_fifo(pipe, (uint16_t)count); + } + + g_usb0_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_dma +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by DMA transfer using D0FIFO or D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb0_host_read_dma (uint16_t pipe) +{ + uint16_t status; + + g_usb0_host_PipeIgnore[pipe] = 0; + + if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_DMA) + { + status = usb0_host_read_dma_d0(pipe); + } + else + { + status = usb0_host_read_dma_d1(pipe); + } + + switch (status) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READZERO: /* End of data read */ + usb0_host_disable_brdy_int(pipe); + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb0_host_disable_brdy_int(pipe); + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + g_usb0_host_PipeDataSize[pipe] -= g_usb0_host_data_count[pipe]; + } + break; + + case USB_HOST_READOVER: /* buffer over */ + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + g_usb0_host_PipeDataSize[pipe] -= g_usb0_host_data_count[pipe]; + } +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#else + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; +#endif + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb0_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_dma_d0 +* Description : Writes data in the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by DMA transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +static uint16_t usb0_host_read_dma_d0 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + uint16_t pipebuf_size; + + g_usb0_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_READY; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + count = g_usb0_host_data_count[pipe]; + status = USB_HOST_READING; + } + else + { + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + count = g_usb0_host_data_count[pipe]; + } + else if (g_usb0_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + else + { + pipebuf_size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + } + } + + if (count == 0) /* 0 length packet */ + { + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + USB200.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear B_CLR */ + status = USB_HOST_READZERO; /* Null Packet receive */ + } + else + { + usb0_host_set_curpipe(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + /* transaction counter No set */ + /* FRDY = 1, DTLN = 0 -> BRDY */ + } + } + else + { + dfacc = usb0_host_set_dfacc_d0(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size = 0; /* 8bit transfer */ + } + + g_usb0_host_DmaPipe[USB_HOST_D0FIFO] = pipe; /* not use in read operation */ + g_usb0_host_DmaBval[USB_HOST_D0FIFO] = 0; /* not use in read operation */ + + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].fifo = USB_HOST_D0FIFO_DMA; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].dir = USB_HOST_FIFO2BUF; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].buffer = (uint32_t)g_usb0_host_data_pointer[pipe]; + g_usb0_host_DmaInfo[USB_HOST_D0FIFO].bytes = count; + + if (status == USB_HOST_READING) + { + g_usb0_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_BUSY; + } + else + { + g_usb0_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_BUSYEND; + } + + Userdef_USB_usb0_host_start_dma(&g_usb0_host_DmaInfo[USB_HOST_D0FIFO], dfacc); + + usb0_host_set_curpipe2(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw, dfacc); + + RZA_IO_RegWrite_16(&USB200.D0FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + g_usb0_host_data_count[pipe] -= count; + g_usb0_host_data_pointer[pipe] += count; + g_usb0_host_PipeDataSize[pipe] += count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_read_dma_d1 +* Description : Reads data from the buffer allocated in the pipe specified in +* : the argument. +* : Reads data by DMA transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +static uint16_t usb0_host_read_dma_d1 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + uint16_t pipebuf_size; + + g_usb0_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_READY; + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[pipe], (uint32_t)g_usb0_host_data_pointer[pipe]); + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + count = g_usb0_host_data_count[pipe]; + status = USB_HOST_READING; + } + else + { + buffer = usb0_host_change_fifo_port(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb0_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + count = g_usb0_host_data_count[pipe]; + } + else if (g_usb0_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + else + { + pipebuf_size = usb0_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + } + } + + if (count == 0) /* 0 length packet */ + { + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + USB200.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + status = USB_HOST_READZERO; /* Null Packet receive */ + } + else + { + usb0_host_set_curpipe(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + /* transaction counter No set */ + /* FRDY = 1, DTLN = 0 -> BRDY */ + } + } + else + { + dfacc = usb0_host_set_dfacc_d1(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size = 0; /* 8bit transfer */ + } + + g_usb0_host_DmaPipe[USB_HOST_D1FIFO] = pipe; /* not use in read operation */ + g_usb0_host_DmaBval[USB_HOST_D1FIFO] = 0; /* not use in read operation */ + + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].fifo = USB_HOST_D1FIFO_DMA; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].dir = USB_HOST_FIFO2BUF; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].buffer = (uint32_t)g_usb0_host_data_pointer[pipe]; + g_usb0_host_DmaInfo[USB_HOST_D1FIFO].bytes = count; + + if (status == USB_HOST_READING) + { + g_usb0_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_BUSY; + } + else + { + g_usb0_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_BUSYEND; + } + + Userdef_USB_usb0_host_start_dma(&g_usb0_host_DmaInfo[USB_HOST_D1FIFO], dfacc); + + usb0_host_set_curpipe2(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw, dfacc); + + RZA_IO_RegWrite_16(&USB200.D1FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + g_usb0_host_data_count[pipe] -= count; + g_usb0_host_data_pointer[pipe] += count; + g_usb0_host_PipeDataSize[pipe] += count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_change_fifo_port +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument. After allocating FIF0, waits in the software +* : till the corresponding pipe becomes ready. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* Return Value : USB_HOST_FIFOERROR ; Error +* : Others ; CFIFOCTR/D0FIFOCTR/D1FIFOCTR Register Value +*******************************************************************************/ +uint16_t usb0_host_change_fifo_port (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw) +{ + uint16_t buffer; + uint32_t loop; + volatile uint32_t loop2; + + usb0_host_set_curpipe(pipe, fifosel, isel, mbw); + + for (loop = 0; loop < 4; loop++) + { + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB200.CFIFOCTR; + break; + + case USB_HOST_D0USE: + case USB_HOST_D0DMA: + buffer = USB200.D0FIFOCTR; + break; + + case USB_HOST_D1USE: + case USB_HOST_D1DMA: + buffer = USB200.D1FIFOCTR; + break; + + default: + buffer = 0; + break; + } + + if ((buffer & USB_HOST_BITFRDY) == USB_HOST_BITFRDY) + { + return buffer; + } + + loop2 = 25; + + while (loop2-- > 0) + { + /* wait */ + } + } + + return USB_HOST_FIFOERROR; +} + +/******************************************************************************* +* Function Name: usb0_host_set_curpipe +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* Return Value : none +*******************************************************************************/ +void usb0_host_set_curpipe (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw) +{ + uint16_t buffer; + uint32_t loop; + volatile uint32_t loop2; + + g_usb0_host_mbw[pipe] = mbw; + + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB200.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(~isel & USB_HOST_BITISEL); + USB200.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(isel | pipe | mbw); + USB200.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D0DMA: + case USB_HOST_D0USE: + buffer = USB200.D0FIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + USB200.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB200.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D1DMA: + case USB_HOST_D1USE: + buffer = USB200.D1FIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + USB200.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB200.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + default: + break; + } + + /* Cautions !!! + * Depending on the external bus speed of CPU, you may need to wait for 450ns here. + * For details, please look at the data sheet. */ + loop2 = 100; + + while (loop2-- > 0) + { + /* wait */ + } +} + +/******************************************************************************* +* Function Name: usb0_host_set_curpipe2 +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument.(DFACC) +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* : uint16_t dfacc ; DFACC Access mode +* Return Value : none +*******************************************************************************/ +void usb0_host_set_curpipe2 (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw, uint16_t dfacc) +{ + uint16_t buffer; + uint32_t loop; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + uint32_t dummy; +#endif + volatile uint32_t loop2; + + g_usb0_host_mbw[pipe] = mbw; + + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB200.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(~isel & USB_HOST_BITISEL); + USB200.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(isel | pipe | mbw); + USB200.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D0DMA: + case USB_HOST_D0USE: + buffer = USB200.D0FIFOSEL; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + + if (dfacc != 0) + { + buffer |= (uint16_t)(USB_HOST_BITMBW_32); + } +#else + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); +#endif + USB200.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + +#ifdef __USB_HOST_DF_ACC_ENABLE__ + if (dfacc != 0) + { + dummy = USB200.D0FIFO.UINT32; + } +#endif + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB200.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D1DMA: + case USB_HOST_D1USE: + buffer = USB200.D1FIFOSEL; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + + if (dfacc != 0) + { + buffer |= (uint16_t)(USB_HOST_BITMBW_32); + } +#else + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); +#endif + USB200.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + +#ifdef __USB_HOST_DF_ACC_ENABLE__ + if (dfacc != 0) + { + dummy = USB200.D1FIFO.UINT32; + loop = dummy; // avoid warning. + } +#endif + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB200.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB200.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + default: + break; + } + + /* Cautions !!! + * Depending on the external bus speed of CPU, you may need to wait for 450ns here. + * For details, please look at the data sheet. */ + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } +} + +/******************************************************************************* +* Function Name: usb0_host_write_c_fifo +* Description : Writes data in CFIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_write_c_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB200.CFIFO.UINT8[HH] = *g_usb0_host_data_pointer[pipe]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB200.CFIFO.UINT16[H] = *((uint16_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB200.CFIFO.UINT32 = *((uint32_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_read_c_fifo +* Description : Reads data from CFIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_read_c_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb0_host_data_pointer[pipe] = USB200.CFIFO.UINT8[HH]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb0_host_data_pointer[pipe]) = USB200.CFIFO.UINT16[H]; + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb0_host_data_pointer[pipe]) = USB200.CFIFO.UINT32; + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_write_d0_fifo +* Description : Writes data in D0FIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_write_d0_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB200.D0FIFO.UINT8[HH] = *g_usb0_host_data_pointer[pipe]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB200.D0FIFO.UINT16[H] = *((uint16_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB200.D0FIFO.UINT32 = *((uint32_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_read_d0_fifo +* Description : Reads data from D0FIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating DOFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t Pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_read_d0_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb0_host_data_pointer[pipe] = USB200.D0FIFO.UINT8[HH]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb0_host_data_pointer[pipe]) = USB200.D0FIFO.UINT16[H]; + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb0_host_data_pointer[pipe]) = USB200.D0FIFO.UINT32; + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_write_d1_fifo +* Description : Writes data in D1FIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating D1FIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_write_d1_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB200.D1FIFO.UINT8[HH] = *g_usb0_host_data_pointer[pipe]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB200.D1FIFO.UINT16[H] = *((uint16_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB200.D1FIFO.UINT32 = *((uint32_t *)g_usb0_host_data_pointer[pipe]); + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_read_d1_fifo +* Description : Reads data from D1FIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating D1FIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb0_host_read_d1_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb0_host_data_pointer[pipe] = USB200.D1FIFO.UINT8[HH]; + g_usb0_host_data_pointer[pipe] += 1; + } + } + else if (g_usb0_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb0_host_data_pointer[pipe]) = USB200.D1FIFO.UINT16[H]; + g_usb0_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb0_host_data_pointer[pipe]) = USB200.D1FIFO.UINT32; + g_usb0_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_com_get_dmasize +* Description : Calculates access width of DMA transfer by the argument to + return as the Return Value. +* Arguments : uint32_t trncount : transfer byte +* : uint32_t dtptr : transfer data pointer +* Return Value : DMA transfer size : 0 8bit +* : : 1 16bit +* : : 2 32bit +*******************************************************************************/ +static uint32_t usb0_host_com_get_dmasize (uint32_t trncount, uint32_t dtptr) +{ + uint32_t size; + + if (((trncount & 0x0001) != 0) || ((dtptr & 0x00000001) != 0)) + { + /* When transfer byte count is odd */ + /* or transfer data area is 8-bit alignment */ + size = 0; /* 8bit */ + } + else if (((trncount & 0x0003) != 0) || ((dtptr & 0x00000003) != 0)) + { + /* When the transfer byte count is multiples of 2 */ + /* or the transfer data area is 16-bit alignment */ + size = 1; /* 16bit */ + } + else + { + /* When the transfer byte count is multiples of 4 */ + /* or the transfer data area is 32-bit alignment */ + size = 2; /* 32bit */ + } + + return size; +} + +/******************************************************************************* +* Function Name: usb0_host_get_mbw +* Description : Calculates access width of DMA to return the value set in MBW. +* Arguments : uint32_t trncount : transfer byte +* : uint32_t dtptr : transfer data pointer +* Return Value : FIFO transfer size : USB_HOST_BITMBW_8 8bit +* : : USB_HOST_BITMBW_16 16bit +* : : USB_HOST_BITMBW_32 32bit +*******************************************************************************/ +uint16_t usb0_host_get_mbw (uint32_t trncount, uint32_t dtptr) +{ + uint32_t size; + uint16_t mbw; + + size = usb0_host_com_get_dmasize(trncount, dtptr); + + if (size == 0) + { + /* 8bit */ + mbw = USB_HOST_BITMBW_8; + } + else if (size == 1) + { + /* 16bit */ + mbw = USB_HOST_BITMBW_16; + } + else + { + /* 32bit */ + mbw = USB_HOST_BITMBW_32; + } + + return mbw; +} + +/******************************************************************************* +* Function Name: usb0_host_set_transaction_counter +* Description : Sets transaction counter by the argument(PIPEnTRN). +* : Clears transaction before setting to enable transaction counter setting. +* Arguments : uint16_t pipe ; Pipe number +* : uint32_t bsize : Data transfer size +* Return Value : none +*******************************************************************************/ +static void usb0_host_set_transaction_counter (uint16_t pipe, uint32_t bsize) +{ + uint16_t mxps; + uint16_t cnt; + + if (bsize == 0) + { + return; + } + + mxps = usb0_host_get_mxps(pipe); /* Max Packet Size */ + + if ((bsize % mxps) == 0) + { + cnt = (uint16_t)(bsize / mxps); + } + else + { + cnt = (uint16_t)((bsize / mxps) + 1); + } + + switch (pipe) + { + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE1TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE1TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE2TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE2TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE3TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE3TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE4TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE4TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE5TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE5TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB200.PIPE9TRN = cnt; + RZA_IO_RegWrite_16(&USB200.PIPE9TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_clear_transaction_counter +* Description : Clears the transaction counter by the argument. +* : After executing this function, the transaction counter is invalid. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb0_host_clear_transaction_counter (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE1TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE2TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE3TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE4TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE5TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB200.PIPE9TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_stop_transfer +* Description : Stops the USB transfer in the pipe specified by the argument. +* : After stopping the USB transfer, clears the buffer allocated in +* : the pipe. +* : After executing this function, allocation in FIF0 becomes USB_HOST_PIPE0; +* : invalid. After executing this function, BRDY/NRDY/BEMP interrupt +* : in the corresponding pipe becomes invalid. Sequence bit is also +* : cleared. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_stop_transfer (uint16_t pipe) +{ + uint16_t usefifo; + uint32_t remain; + + usb0_host_set_pid_nak(pipe); + + usefifo = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + usb0_host_clear_transaction_counter(pipe); + USB200.D0FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D1FIFO_USE: + usb0_host_clear_transaction_counter(pipe); + USB200.D1FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D0FIFO_DMA: + remain = Userdef_USB_usb0_host_stop_dma0(); + usb0_host_dma_stop_d0(pipe, remain); + usb0_host_clear_transaction_counter(pipe); + USB200.D0FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D1FIFO_DMA: + remain = Userdef_USB_usb0_host_stop_dma1(); + usb0_host_dma_stop_d1(pipe, remain); + usb0_host_clear_transaction_counter(pipe); + USB200.D1FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + default: + usb0_host_clear_transaction_counter(pipe); + USB200.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + } + + /* Interrupt of pipe set is disabled */ + usb0_host_disable_brdy_int(pipe); + usb0_host_disable_nrdy_int(pipe); + usb0_host_disable_bemp_int(pipe); + +#if(1) /* ohci_wrapp */ +#else + usb0_host_aclrm(pipe); +#endif + usb0_host_set_csclr(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_set_dfacc_d0 +* Description : Sets the DFACC setting value in D0FIFO using the transfer size. +* Arguments : uint16_t mbw ; MBW +* : uint16_t count ; data count +* Return Value : DFACC Access mode +*******************************************************************************/ +static uint16_t usb0_host_set_dfacc_d0 (uint16_t mbw, uint32_t count) +{ + uint16_t dfacc = 0; + +#ifndef __USB_HOST_DF_ACC_ENABLE__ + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; +#else + if (mbw == USB_HOST_BITMBW_32) + { + if ((count % 32) == 0) + { + /* 32byte transfer */ + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 2, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 2; + } + else if ((count % 16) == 0) + { + /* 16byte transfer */ + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 1, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 1; + } + else + { + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + } + else if (mbw == USB_HOST_BITMBW_16) + { + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + else + { + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } +#endif + + return dfacc; +} + +/******************************************************************************* +* Function Name: usb0_host_set_dfacc_d1 +* Description : Sets the DFACC setting value in D1FIFO using the transfer size. +* Arguments : uint16_t mbw ; MBW +* : uint16_t count ; data count +* Return Value : DFACC Access mode +*******************************************************************************/ +static uint16_t usb0_host_set_dfacc_d1 (uint16_t mbw, uint32_t count) +{ + uint16_t dfacc = 0; + +#ifndef __USB_HOST_DF_ACC_ENABLE__ + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; +#else + if (mbw == USB_HOST_BITMBW_32) + { + if ((count % 32) == 0) + { + /* 32byte transfer */ + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 2, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 2; + } + else if ((count % 16) == 0) + { + /* 16byte transfer */ + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 1, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 1; + } + else + { + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + } + else if (mbw == USB_HOST_BITMBW_16) + { + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + else + { + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB200.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } +#endif + + return dfacc; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/common/usb0_host_dma.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,355 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_dma.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +/* #include "usb0_host_dmacdrv.h" */ + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +static void usb0_host_dmaint(uint16_t fifo); +static void usb0_host_dmaint_buf2fifo(uint16_t pipe); +static void usb0_host_dmaint_fifo2buf(uint16_t pipe); + + +/******************************************************************************* +* Function Name: usb0_host_dma_stop_d0 +* Description : D0FIFO DMA stop +* Arguments : uint16_t pipe : pipe number +* : uint32_t remain : transfer byte +* Return Value : none +*******************************************************************************/ +void usb0_host_dma_stop_d0 (uint16_t pipe, uint32_t remain) +{ + uint16_t dtln; + uint16_t dfacc; + uint16_t buffer; + uint16_t sds_b = 1; + + dfacc = RZA_IO_RegRead_16(&USB200.D0FBCFG, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + if (dfacc == 2) + { + sds_b = 32; + } + else if (dfacc == 1) + { + sds_b = 16; + } + else + { + if (g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size == 2) + { + sds_b = 4; + } + else if (g_usb0_host_DmaInfo[USB_HOST_D0FIFO].size == 1) + { + sds_b = 2; + } + else + { + sds_b = 1; + } + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + if (g_usb0_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + buffer = USB200.D0FIFOCTR; + dtln = (buffer & USB_HOST_BITDTLN); + + if ((dtln % sds_b) != 0) + { + remain += (sds_b - (dtln % sds_b)); + } + g_usb0_host_PipeDataSize[pipe] = (g_usb0_host_data_count[pipe] - remain); + g_usb0_host_data_count[pipe] = remain; + } + } + + RZA_IO_RegWrite_16(&USB200.D0FIFOSEL, + 0, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); +} + +/******************************************************************************* +* Function Name: usb0_host_dma_stop_d1 +* Description : D1FIFO DMA stop +* Arguments : uint16_t pipe : pipe number +* : uint32_t remain : transfer byte +* Return Value : none +*******************************************************************************/ +void usb0_host_dma_stop_d1 (uint16_t pipe, uint32_t remain) +{ + uint16_t dtln; + uint16_t dfacc; + uint16_t buffer; + uint16_t sds_b = 1; + + dfacc = RZA_IO_RegRead_16(&USB200.D1FBCFG, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + if (dfacc == 2) + { + sds_b = 32; + } + else if (dfacc == 1) + { + sds_b = 16; + } + else + { + if (g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size == 2) + { + sds_b = 4; + } + else if (g_usb0_host_DmaInfo[USB_HOST_D1FIFO].size == 1) + { + sds_b = 2; + } + else + { + sds_b = 1; + } + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + if (g_usb0_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + buffer = USB200.D1FIFOCTR; + dtln = (buffer & USB_HOST_BITDTLN); + + if ((dtln % sds_b) != 0) + { + remain += (sds_b - (dtln % sds_b)); + } + g_usb0_host_PipeDataSize[pipe] = (g_usb0_host_data_count[pipe] - remain); + g_usb0_host_data_count[pipe] = remain; + } + } + + RZA_IO_RegWrite_16(&USB200.D1FIFOSEL, + 0, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); +} + +/******************************************************************************* +* Function Name: usb0_host_dma_interrupt_d0fifo +* Description : This function is DMA interrupt handler entry. +* : Execute usb1_host_dmaint() after disabling DMA interrupt in this function. +* : Disable DMA interrupt to DMAC executed when USB_HOST_D0FIFO_DMA is +* : specified by dma->fifo. +* : Register this function as DMA complete interrupt. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb0_host_dma_interrupt_d0fifo (uint32_t int_sense) +{ + usb0_host_dmaint(USB_HOST_D0FIFO); + g_usb0_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_READY; +} + +/******************************************************************************* +* Function Name: usb0_host_dma_interrupt_d1fifo +* Description : This function is DMA interrupt handler entry. +* : Execute usb0_host_dmaint() after disabling DMA interrupt in this function. +* : Disable DMA interrupt to DMAC executed when USB_HOST_D1FIFO_DMA is +* : specified by dma->fifo. +* : Register this function as DMA complete interrupt. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb0_host_dma_interrupt_d1fifo (uint32_t int_sense) +{ + usb0_host_dmaint(USB_HOST_D1FIFO); + g_usb0_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_READY; +} + +/******************************************************************************* +* Function Name: usb0_host_dmaint +* Description : This function is DMA transfer end interrupt +* Arguments : uint16_t fifo ; fifo number +* : ; USB_HOST_D0FIFO +* : ; USB_HOST_D1FIFO +* Return Value : none +*******************************************************************************/ +static void usb0_host_dmaint (uint16_t fifo) +{ + uint16_t pipe; + + pipe = g_usb0_host_DmaPipe[fifo]; + + if (g_usb0_host_DmaInfo[fifo].dir == USB_HOST_BUF2FIFO) + { + usb0_host_dmaint_buf2fifo(pipe); + } + else + { + usb0_host_dmaint_fifo2buf(pipe); + } +} + +/******************************************************************************* +* Function Name: usb0_host_dmaint_fifo2buf +* Description : Executes read completion from FIFO by DMAC. +* Arguments : uint16_t pipe : pipe number +* Return Value : none +*******************************************************************************/ +static void usb0_host_dmaint_fifo2buf (uint16_t pipe) +{ + uint32_t remain; + uint16_t useport; + + if (g_usb0_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + useport = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + if (useport == USB_HOST_D0FIFO_DMA) + { + remain = Userdef_USB_usb0_host_stop_dma0(); + usb0_host_dma_stop_d0(pipe, remain); + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + if (g_usb0_host_DmaStatus[USB_HOST_D0FIFO] == USB_HOST_DMA_BUSYEND) + { + USB200.D0FIFOCTR = USB_HOST_BITBCLR; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + else + { + usb0_host_enable_brdy_int(pipe); + } + } + } + else + { + remain = Userdef_USB_usb0_host_stop_dma1(); + usb0_host_dma_stop_d1(pipe, remain); + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + if (g_usb0_host_DmaStatus[USB_HOST_D1FIFO] == USB_HOST_DMA_BUSYEND) + { + USB200.D1FIFOCTR = USB_HOST_BITBCLR; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + else + { + usb0_host_enable_brdy_int(pipe); + } + } + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_dmaint_buf2fifo +* Description : Executes write completion in FIFO by DMAC. +* Arguments : uint16_t pipe : pipe number +* Return Value : none +*******************************************************************************/ +static void usb0_host_dmaint_buf2fifo (uint16_t pipe) +{ + uint16_t useport; + uint32_t remain; + + useport = (uint16_t)(g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + if (useport == USB_HOST_D0FIFO_DMA) + { + remain = Userdef_USB_usb0_host_stop_dma0(); + usb0_host_dma_stop_d0(pipe, remain); + + if (g_usb0_host_DmaBval[USB_HOST_D0FIFO] != 0) + { + RZA_IO_RegWrite_16(&USB200.D0FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); + } + } + else + { + remain = Userdef_USB_usb0_host_stop_dma1(); + usb0_host_dma_stop_d1(pipe, remain); + + if (g_usb0_host_DmaBval[USB_HOST_D1FIFO] != 0) + { + RZA_IO_RegWrite_16(&USB200.D1FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); + } + } + + usb0_host_enable_bemp_int(pipe); +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/common/usb0_host_intrn.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,285 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_intrn.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#if(1) /* ohci_wrapp */ +#include "ohci_wrapp_RZ_A1_local.h" +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_brdy_int +* Description : Executes BRDY interrupt(USB_HOST_PIPE1-9). +* : According to the pipe that interrupt is generated in, +* : reads/writes buffer allocated in the pipe. +* : This function is executed in the BRDY interrupt handler. +* : This function clears BRDY interrupt status and BEMP interrupt +* : status. +* Arguments : uint16_t status ; BRDYSTS Register Value +* : uint16_t int_enb ; BRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_brdy_int (uint16_t status, uint16_t int_enb) +{ + uint32_t int_sense = 0; + uint16_t pipe; + uint16_t pipebit; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + pipebit = g_usb0_host_bit_set[pipe]; + + if ((status & pipebit) && (int_enb & pipebit)) + { + USB200.BRDYSTS = (uint16_t)~pipebit; + USB200.BEMPSTS = (uint16_t)~pipebit; + + if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_DMA) + { + if (g_usb0_host_DmaStatus[USB_HOST_D0FIFO] != USB_HOST_DMA_READY) + { + usb0_host_dma_interrupt_d0fifo(int_sense); + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + usb0_host_read_dma(pipe); + usb0_host_disable_brdy_int(pipe); + } + else + { + USB200.D0FIFOCTR = USB_HOST_BITBCLR; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + } + else if ((g_usb0_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_DMA) + { + if (g_usb0_host_DmaStatus[USB_HOST_D1FIFO] != USB_HOST_DMA_READY) + { + usb0_host_dma_interrupt_d1fifo(int_sense); + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + usb0_host_read_dma(pipe); + usb0_host_disable_brdy_int(pipe); + } + else + { + USB200.D1FIFOCTR = USB_HOST_BITBCLR; + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + } + else + { + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 0) + { + usb0_host_read_buffer(pipe); + } + else + { + usb0_host_write_buffer(pipe); + } + } +#if(1) /* ohci_wrapp */ + switch (g_usb0_host_pipe_status[pipe]) + { + case USB_HOST_PIPE_DONE: + ohciwrapp_loc_TransEnd(pipe, TD_CC_NOERROR); + break; + case USB_HOST_PIPE_NORES: + case USB_HOST_PIPE_STALL: + case USB_HOST_PIPE_ERROR: + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); + break; + default: + /* Do Nothing */ + break; + } +#endif + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_nrdy_int +* Description : Executes NRDY interrupt(USB_HOST_PIPE1-9). +* : Checks NRDY interrupt cause by PID. When the cause if STALL, +* : regards the pipe state as STALL and ends the processing. +* : Then the cause is not STALL, increments the error count to +* : communicate again. When the error count is 3, determines +* : the pipe state as USB_HOST_PIPE_NORES and ends the processing. +* : This function is executed in the NRDY interrupt handler. +* : This function clears NRDY interrupt status. +* Arguments : uint16_t status ; NRDYSTS Register Value +* : uint16_t int_enb ; NRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_nrdy_int (uint16_t status, uint16_t int_enb) +{ + uint16_t pid; + uint16_t pipe; + uint16_t bitcheck; + + bitcheck = (uint16_t)(status & int_enb); + + USB200.NRDYSTS = (uint16_t)~status; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + if ((bitcheck&g_usb0_host_bit_set[pipe]) == g_usb0_host_bit_set[pipe]) + { + if (RZA_IO_RegRead_16(&USB200.SYSCFG0, + USB_SYSCFG_DCFM_SHIFT, + USB_SYSCFG_DCFM) == 1) + { + if (g_usb0_host_pipe_status[pipe] == USB_HOST_PIPE_WAIT) + { + pid = usb0_host_get_pid(pipe); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_STALL; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); +#endif + } + else + { +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_NORES; + ohciwrapp_loc_TransEnd(pipe, TD_CC_DEVICENOTRESPONDING); +#else + g_usb0_host_PipeIgnore[pipe]++; + + if (g_usb0_host_PipeIgnore[pipe] == 3) + { + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_NORES; + } + else + { + usb0_host_set_pid_buf(pipe); + } +#endif + } + } + } + else + { + /* USB Function */ + } + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_bemp_int +* Description : Executes BEMP interrupt(USB_HOST_PIPE1-9). +* Arguments : uint16_t status ; BEMPSTS Register Value +* : uint16_t int_enb ; BEMPENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_bemp_int (uint16_t status, uint16_t int_enb) +{ + uint16_t pid; + uint16_t pipe; + uint16_t bitcheck; + uint16_t inbuf; + + bitcheck = (uint16_t)(status & int_enb); + + USB200.BEMPSTS = (uint16_t)~status; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + if ((bitcheck&g_usb0_host_bit_set[pipe]) == g_usb0_host_bit_set[pipe]) + { + pid = usb0_host_get_pid(pipe); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_STALL; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); +#endif + } + else + { + inbuf = usb0_host_get_inbuf(pipe); + + if (inbuf == 0) + { + usb0_host_disable_bemp_int(pipe); + usb0_host_set_pid_nak(pipe); + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_NOERROR); +#endif + } + } + } + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/common/usb0_host_lib.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,1580 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_lib.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#if(1) /* ohci_wrapp */ +#include "VKRZA1H.h" /* INTC Driver Header */ +#else +#include "devdrv_intc.h" /* INTC Driver Header */ +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_enable_brdy_int +* Description : Enables BRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : BRDY. Enables BRDY interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_enable_brdy_int (uint16_t pipe) +{ + /* enable brdy interrupt */ + USB200.BRDYENB |= (uint16_t)g_usb0_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb0_host_disable_brdy_int +* Description : Disables BRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : BRDY. Enables BRDY interrupt in the pipe specified by the argument +* : in the disabled status. After disabling BRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_disable_brdy_int (uint16_t pipe) +{ + /* disable brdy interrupt */ + USB200.BRDYENB &= (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_clear_brdy_sts +* Description : Clear BRDY interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_clear_brdy_sts (uint16_t pipe) +{ + /* clear brdy status */ + USB200.BRDYSTS = (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_enable_bemp_int +* Description : Enables BEMP interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : BEMP. Enables BEMP interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BEMP, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_enable_bemp_int (uint16_t pipe) +{ + /* enable bemp interrupt */ + USB200.BEMPENB |= (uint16_t)g_usb0_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb0_host_disable_bemp_int +* Description : Disables BEMP interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : BEMP. Enables BEMP interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BEMP, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_disable_bemp_int (uint16_t pipe) +{ + /* disable bemp interrupt */ + USB200.BEMPENB &= (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_clear_bemp_sts +* Description : Clear BEMP interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_clear_bemp_sts (uint16_t pipe) +{ + /* clear bemp status */ + USB200.BEMPSTS = (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_enable_nrdy_int +* Description : Enables NRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : NRDY. Enables NRDY interrupt in the pipe specified by the argument +* : in the disabled status. After enabling NRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_enable_nrdy_int (uint16_t pipe) +{ + /* enable nrdy interrupt */ + USB200.NRDYENB |= (uint16_t)g_usb0_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb0_host_disable_nrdy_int +* Description : Disables NRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : NRDY. Disables NRDY interrupt in the pipe specified by the argument +* : in the disabled status. After disabling NRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_disable_nrdy_int (uint16_t pipe) +{ + /* disable nrdy interrupt */ + USB200.NRDYENB &= (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_clear_nrdy_sts +* Description : Clear NRDY interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_clear_nrdy_sts (uint16_t pipe) +{ + /* clear nrdy status */ + USB200.NRDYSTS = (uint16_t)~(g_usb0_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb0_host_is_hispeed +* Description : Returns the result of USB reset hand shake (RHST) as +* : return value. +* Arguments : none +* Return Value : USB_HOST_HIGH_SPEED ; Hi-Speed +* : USB_HOST_FULL_SPEED ; Full-Speed +* : USB_HOST_LOW_SPEED ; Low-Speed +* : USB_HOST_NON_SPEED ; error +*******************************************************************************/ +uint16_t usb0_host_is_hispeed (void) +{ + uint16_t rhst; + uint16_t speed; + + rhst = RZA_IO_RegRead_16(&USB200.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (rhst == USB_HOST_HSMODE) + { + speed = USB_HOST_HIGH_SPEED; + } + else if (rhst == USB_HOST_FSMODE) + { + speed = USB_HOST_FULL_SPEED; + } + else if (rhst == USB_HOST_LSMODE) + { + speed = USB_HOST_LOW_SPEED; + } + else + { + speed = USB_HOST_NON_SPEED; + } + + return speed; +} + +/******************************************************************************* +* Function Name: usb0_host_is_hispeed_enable +* Description : Returns the USB High-Speed connection enabled status as +* : return value. +* Arguments : none +* Return Value : USB_HOST_YES : Hi-Speed Enable +* : USB_HOST_NO : Hi-Speed Disable +*******************************************************************************/ +uint16_t usb0_host_is_hispeed_enable (void) +{ + uint16_t ret; + + ret = USB_HOST_NO; + + if (RZA_IO_RegRead_16(&USB200.SYSCFG0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE) == 1) + { + ret = USB_HOST_YES; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_host_set_pid_buf +* Description : Enables communicaqtion in the pipe specified by the argument +* : (BUF). +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_pid_buf (uint16_t pipe) +{ + uint16_t pid; + + pid = usb0_host_get_pid(pipe); + + if (pid == USB_HOST_PID_STALL2) + { + usb0_host_set_pid_nak(pipe); + } + + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + USB_HOST_PID_BUF, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_set_pid_nak +* Description : Disables communication (NAK) in the pipe specified by the argument. +* : When the pipe status was enabling communication (BUF) before +* : executing before executing this function, waits in the software +* : until the pipe becomes ready after setting disabled. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_pid_nak (uint16_t pipe) +{ + uint16_t pid; + uint16_t pbusy; + uint32_t loop; + + pid = usb0_host_get_pid(pipe); + + if (pid == USB_HOST_PID_STALL2) + { + usb0_host_set_pid_stall(pipe); + } + + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + USB_HOST_PID_NAK, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + + if (pid == USB_HOST_PID_BUF) + { + for (loop = 0; loop < 200; loop++) + { + switch (pipe) + { + case USB_HOST_PIPE0: + pbusy = RZA_IO_RegRead_16(&USB200.DCPCTR, + USB_DCPCTR_PBUSY_SHIFT, + USB_DCPCTR_PBUSY); + break; + + case USB_HOST_PIPE1: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE1CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE2: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE2CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE3: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE3CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE4: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE4CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE5: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE5CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE6: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE6CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE7: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE7CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE8: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE8CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE9: + pbusy = RZA_IO_RegRead_16(&USB200.PIPE9CTR, + USB_PIPEnCTR_9_PBUSY_SHIFT, + USB_PIPEnCTR_9_PBUSY); + break; + + default: + pbusy = 1; + break; + } + + if (pbusy == 0) + { + break; + } + + Userdef_USB_usb0_host_delay_500ns(); + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_set_pid_stall +* Description : Disables communication (STALL) in the pipe specified by the +* : argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_pid_stall (uint16_t pipe) +{ + uint16_t pid; + + pid = usb0_host_get_pid(pipe); + + if (pid == USB_HOST_PID_BUF) + { + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + USB_HOST_PID_STALL2, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + } + else + { + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + USB_HOST_PID_STALL, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + } +} + +/******************************************************************************* +* Function Name: usb0_host_clear_pid_stall +* Description : Disables communication (NAK) in the pipe specified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_clear_pid_stall (uint16_t pipe) +{ + usb0_host_set_pid_nak(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_get_pid +* Description : Returns the pipe state specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : PID +*******************************************************************************/ +uint16_t usb0_host_get_pid (uint16_t pipe) +{ + uint16_t pid; + + switch (pipe) + { + case USB_HOST_PIPE0: + pid = RZA_IO_RegRead_16(&USB200.DCPCTR, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + pid = RZA_IO_RegRead_16(&USB200.PIPE1CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + pid = RZA_IO_RegRead_16(&USB200.PIPE2CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + pid = RZA_IO_RegRead_16(&USB200.PIPE3CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + pid = RZA_IO_RegRead_16(&USB200.PIPE4CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + pid = RZA_IO_RegRead_16(&USB200.PIPE5CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + pid = RZA_IO_RegRead_16(&USB200.PIPE6CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + pid = RZA_IO_RegRead_16(&USB200.PIPE7CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + pid = RZA_IO_RegRead_16(&USB200.PIPE8CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + pid = RZA_IO_RegRead_16(&USB200.PIPE9CTR, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + pid = 0; + break; + } + + return pid; +} + +/******************************************************************************* +* Function Name: usb0_host_set_csclr +* Description : CSPLIT status clear setting of sprit transaction in specified +* : pipe is performed. +* : When SQSET bit or SQCLR bit, and SQSET bit or SQCLR bit +* : in DCPCTR register are continuously changed (when the sequence +* : toggle bit of data PID is continuously changed over two or more pipes), +* : the access cycle with 120 ns and more than 5 cycle bus clock is necessary. +* : Do not set both SQCLR bit and SQSET bit to 1 at the same time. +* : In addition, both bits should be operated after PID is set to NAK. +* : However, when it is set to the isochronous transfer as the transfer type +* : (TYPE=11), writing in SQSET bit is disabled. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_csclr (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + 1, + USB_DCPCTR_CSCLR_SHIFT, + USB_DCPCTR_CSCLR); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + 1, + USB_PIPEnCTR_9_CSCLR_SHIFT, + USB_PIPEnCTR_9_CSCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_set_sqclr +* Description : Sets the sequence bit of the pipe specified by the argument to +* : DATA0. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_sqclr (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + 1, + USB_DCPCTR_SQCLR_SHIFT, + USB_DCPCTR_SQCLR); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + 1, + USB_PIPEnCTR_9_SQCLR_SHIFT, + USB_PIPEnCTR_9_SQCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_set_sqset +* Description : Sets the sequence bit of the pipe specified by the argument to +* : DATA1. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb0_host_set_sqset (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB200.DCPCTR, + 1, + USB_DCPCTR_SQSET_SHIFT, + USB_DCPCTR_SQSET); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + 1, + USB_PIPEnCTR_9_SQSET_SHIFT, + USB_PIPEnCTR_9_SQSET); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_get_sqmon +* Description : Toggle bit of specified pipe is obtained +* Arguments : uint16_t pipe ; Pipe number +* Return Value : sqmon +*******************************************************************************/ +uint16_t usb0_host_get_sqmon (uint16_t pipe) +{ + uint16_t sqmon; + + switch (pipe) + { + case USB_HOST_PIPE0: + sqmon = RZA_IO_RegRead_16(&USB200.DCPCTR, + USB_DCPCTR_SQMON_SHIFT, + USB_DCPCTR_SQMON); + break; + + case USB_HOST_PIPE1: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE1CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE2: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE2CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE3: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE3CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE4: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE4CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE5: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE5CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE6: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE6CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE7: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE7CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE8: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE8CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE9: + sqmon = RZA_IO_RegRead_16(&USB200.PIPE9CTR, + USB_PIPEnCTR_9_SQMON_SHIFT, + USB_PIPEnCTR_9_SQMON); + break; + + default: + sqmon = 0; + break; + } + + return sqmon; +} + +/******************************************************************************* +* Function Name: usb0_host_aclrm +* Description : The buffer of specified pipe is initialized +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb0_host_aclrm (uint16_t pipe) +{ + usb0_host_set_aclrm(pipe); + usb0_host_clr_aclrm(pipe); +} + +/******************************************************************************* +* Function Name: usb0_host_set_aclrm +* Description : The auto buffer clear mode of specified pipe is enabled +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb0_host_set_aclrm (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + 1, + USB_PIPEnCTR_9_ACLRM_SHIFT, + USB_PIPEnCTR_9_ACLRM); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_clr_aclrm +* Description : The auto buffer clear mode of specified pipe is enabled +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb0_host_clr_aclrm (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB200.PIPE1CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB200.PIPE2CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB200.PIPE3CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB200.PIPE4CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB200.PIPE5CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB200.PIPE6CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB200.PIPE7CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB200.PIPE8CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB200.PIPE9CTR, + 0, + USB_PIPEnCTR_9_ACLRM_SHIFT, + USB_PIPEnCTR_9_ACLRM); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_get_inbuf +* Description : Returns INBUFM of the pipe specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : inbuf +*******************************************************************************/ +uint16_t usb0_host_get_inbuf (uint16_t pipe) +{ + uint16_t inbuf; + + switch (pipe) + { + case USB_HOST_PIPE0: + inbuf = 0; + break; + + case USB_HOST_PIPE1: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE1CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE2: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE2CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE3: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE3CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE4: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE4CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE5: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE5CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE6: + inbuf = 0; + break; + + case USB_HOST_PIPE7: + inbuf = 0; + break; + + case USB_HOST_PIPE8: + inbuf = 0; + break; + + case USB_HOST_PIPE9: + inbuf = RZA_IO_RegRead_16(&USB200.PIPE9CTR, + USB_PIPEnCTR_9_INBUFM_SHIFT, + USB_PIPEnCTR_9_INBUFM); + break; + + default: + inbuf = 0; + break; + } + + return inbuf; +} + +/******************************************************************************* +* Function Name: usb0_host_setting_interrupt +* Description : Sets the USB module interrupt level. +* Arguments : uint8_t level ; interrupt level +* Return Value : none +*******************************************************************************/ +void usb0_host_setting_interrupt (uint8_t level) +{ +#if(1) /* ohci_wrapp */ + IRQn_Type d0fifo_dmaintid; + IRQn_Type d1fifo_dmaintid; + + InterruptHandlerRegister(USBI0_IRQn, usb0_host_interrupt); + GIC_SetPriority(USBI0_IRQn, level); + GIC_EnableIRQ(USBI0_IRQn); + + d0fifo_dmaintid = (IRQn_Type)Userdef_USB_usb0_host_d0fifo_dmaintid(); + + if (d0fifo_dmaintid != 0xFFFF) + { + InterruptHandlerRegister(d0fifo_dmaintid, usb0_host_dma_interrupt_d0fifo); + GIC_SetPriority(d0fifo_dmaintid, level); + GIC_EnableIRQ(d0fifo_dmaintid); + } + + d1fifo_dmaintid = (IRQn_Type)Userdef_USB_usb0_host_d1fifo_dmaintid(); + + if (d1fifo_dmaintid != 0xFFFF) + { + InterruptHandlerRegister(d1fifo_dmaintid, usb0_host_dma_interrupt_d1fifo); + GIC_SetPriority(d1fifo_dmaintid, level); + GIC_EnableIRQ(d1fifo_dmaintid); + } +#else + uint16_t d0fifo_dmaintid; + uint16_t d1fifo_dmaintid; + + R_INTC_RegistIntFunc(INTC_ID_USBI0, usb0_host_interrupt); + R_INTC_SetPriority(INTC_ID_USBI0, level); + R_INTC_Enable(INTC_ID_USBI0); + + d0fifo_dmaintid = Userdef_USB_usb0_host_d0fifo_dmaintid(); + + if (d0fifo_dmaintid != 0xFFFF) + { + R_INTC_RegistIntFunc(d0fifo_dmaintid, usb0_host_dma_interrupt_d0fifo); + R_INTC_SetPriority(d0fifo_dmaintid, level); + R_INTC_Enable(d0fifo_dmaintid); + } + + d1fifo_dmaintid = Userdef_USB_usb0_host_d1fifo_dmaintid(); + + if (d1fifo_dmaintid != 0xFFFF) + { + R_INTC_RegistIntFunc(d1fifo_dmaintid, usb0_host_dma_interrupt_d1fifo); + R_INTC_SetPriority(d1fifo_dmaintid, level); + R_INTC_Enable(d1fifo_dmaintid); + } +#endif +} + +/******************************************************************************* +* Function Name: usb0_host_reset_module +* Description : Initializes the USB module. +* : Enables providing clock to the USB module. +* : Sets USB bus wait register. +* Arguments : uint16_t clockmode ; 48MHz ; USBHCLOCK_X1_48MHZ +* : ; 12MHz ; USBHCLOCK_EXTAL_12MHZ +* Return Value : none +*******************************************************************************/ +void usb0_host_reset_module (uint16_t clockmode) +{ + if (RZA_IO_RegRead_16(&USB200.SYSCFG0, + USB_SYSCFG_UPLLE_SHIFT, + USB_SYSCFG_UPLLE) == 1) + { + if ((USB200.SYSCFG0 & USB_HOST_BITUCKSEL) != clockmode) + { + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + USB200.SYSCFG0 = 0; + USB200.SYSCFG0 = (USB_HOST_BITUPLLE | clockmode); + Userdef_USB_usb0_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + else + { + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + Userdef_USB_usb0_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + } + else + { + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + USB200.SYSCFG0 = 0; + USB200.SYSCFG0 = (USB_HOST_BITUPLLE | clockmode); + Userdef_USB_usb0_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + + USB200.BUSWAIT = (uint16_t)(USB_HOST_BUSWAIT_05 & USB_HOST_BITBWAIT); +} + +/******************************************************************************* +* Function Name: usb0_host_get_buf_size +* Description : Obtains pipe buffer size specified by the argument and +* : maximum packet size of the USB device in use. +* : When USB_HOST_PIPE0 is specified by the argument, obtains the maximum +* : packet size of the USB device using the corresponding pipe. +* : For the case that USB_HOST_PIPE0 is not assigned by the argument, when the +* : corresponding pipe is in continuous transfer mode, +* : obtains the buffer size allocated in the corresponcing pipe, +* : when incontinuous transfer, obtains maximum packet size. +* Arguments : uint16_t ; pipe Number +* Return Value : Maximum packet size or buffer size +*******************************************************************************/ +uint16_t usb0_host_get_buf_size (uint16_t pipe) +{ + uint16_t size; + uint16_t bufsize; + + if (pipe == USB_HOST_PIPE0) + { + size = RZA_IO_RegRead_16(&USB200.DCPMAXP, + USB_DCPMAXP_MXPS_SHIFT, + USB_DCPMAXP_MXPS); + } + else + { + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[pipe], USB_PIPECFG_CNTMD_SHIFT, USB_PIPECFG_CNTMD) == 1) + { + bufsize = RZA_IO_RegRead_16(&g_usb0_host_pipebuf[pipe], USB_PIPEBUF_BUFSIZE_SHIFT, USB_PIPEBUF_BUFSIZE); + size = (uint16_t)((bufsize + 1) * USB_HOST_PIPExBUF); + } + else + { + size = RZA_IO_RegRead_16(&g_usb0_host_pipemaxp[pipe], USB_PIPEMAXP_MXPS_SHIFT, USB_PIPEMAXP_MXPS); + } + } + return size; +} + +/******************************************************************************* +* Function Name: usb0_host_get_mxps +* Description : Obtains maximum packet size of the USB device using the pipe +* : specified by the argument. +* Arguments : uint16_t ; Pipe Number +* Return Value : Max Packet Size +*******************************************************************************/ +uint16_t usb0_host_get_mxps (uint16_t pipe) +{ + uint16_t size; + + if (pipe == USB_HOST_PIPE0) + { + size = RZA_IO_RegRead_16(&USB200.DCPMAXP, + USB_DCPMAXP_MXPS_SHIFT, + USB_DCPMAXP_MXPS); + } + else + { + size = RZA_IO_RegRead_16(&g_usb0_host_pipemaxp[pipe], USB_PIPEMAXP_MXPS_SHIFT, USB_PIPEMAXP_MXPS); + } + + return size; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/host/usb0_host_controlrw.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,434 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_controlrw.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_CtrlTransStart +* Description : Executes USB control transfer. +* Arguments : uint16_t devadr ; device address +* : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* : uint8_t *Buf ; Data buffer +* Return Value : DEVDRV_SUCCESS ; SUCCESS +* : DEVDRV_ERROR ; ERROR +*******************************************************************************/ +int32_t usb0_host_CtrlTransStart (uint16_t devadr, uint16_t Req, uint16_t Val, + uint16_t Indx, uint16_t Len, uint8_t * Buf) +{ + if (g_usb0_host_UsbDeviceSpeed == USB_HOST_LOW_SPEED) + { + RZA_IO_RegWrite_16(&USB200.SOFCFG, + 1, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + else + { + RZA_IO_RegWrite_16(&USB200.SOFCFG, + 0, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + + USB200.DCPMAXP = (uint16_t)((uint16_t)(devadr << 12) + g_usb0_host_default_max_packet[devadr]); + + if (g_usb0_host_pipe_status[USB_HOST_PIPE0] == USB_HOST_PIPE_IDLE) + { + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_WAIT; + g_usb0_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + g_usb0_host_CmdStage = (USB_HOST_STAGE_SETUP | USB_HOST_CMD_IDLE); + + if (Len == 0) + { + g_usb0_host_CmdStage |= USB_HOST_MODE_NO_DATA; /* No-data Control */ + } + else + { + if ((Req & 0x0080) != 0) + { + g_usb0_host_CmdStage |= USB_HOST_MODE_READ; /* Control Read */ + } + else + { + g_usb0_host_CmdStage |= USB_HOST_MODE_WRITE; /* Control Write */ + } + } + + g_usb0_host_SavReq = Req; /* save request */ + g_usb0_host_SavVal = Val; + g_usb0_host_SavIndx = Indx; + g_usb0_host_SavLen = Len; + } + else + { + if ((g_usb0_host_SavReq != Req) || (g_usb0_host_SavVal != Val) + || (g_usb0_host_SavIndx != Indx) || (g_usb0_host_SavLen != Len)) + { + return DEVDRV_ERROR; + } + } + + switch ((g_usb0_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + /* --------------- SETUP STAGE --------------- */ + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_IDLE): + usb0_host_SetupStage(Req, Val, Indx, Len); + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_DONE): /* goto next stage */ + g_usb0_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + switch ((g_usb0_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_WRITE: + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_DATA; + break; + + case USB_HOST_MODE_READ: + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_DATA; + break; + + case USB_HOST_MODE_NO_DATA: + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_STATUS; + break; + + default: + break; + } + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_NORES): + if (g_usb0_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb0_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_IDLE; + } + break; + + /* --------------- DATA STAGE --------------- */ + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_IDLE): + switch ((g_usb0_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_WRITE: + usb0_host_CtrlWriteStart((uint32_t)Len, Buf); + break; + + case USB_HOST_MODE_READ: + usb0_host_CtrlReadStart((uint32_t)Len, Buf); + break; + + default: + break; + } + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DONE): /* goto next stage */ + g_usb0_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_STATUS; + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_NORES): + if (g_usb0_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb0_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DOING; + usb0_host_clear_pid_stall(USB_HOST_PIPE0); + usb0_host_set_pid_buf(USB_HOST_PIPE0); + } + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_STALL): + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + break; + + /* --------------- STATUS STAGE --------------- */ + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_IDLE): + usb0_host_StatusStage(); + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DONE): /* end of Control transfer */ + usb0_host_set_pid_nak(USB_HOST_PIPE0); + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_DONE; /* exit DONE */ + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_NORES): + if (g_usb0_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb0_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DOING; + usb0_host_clear_pid_stall(USB_HOST_PIPE0); + usb0_host_set_pid_buf(USB_HOST_PIPE0); + } + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_STALL): + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + break; + + default: + break; + } + + if (g_usb0_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_WAIT) + { + RZA_IO_RegWrite_16(&USB200.SOFCFG, + 0, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb0_host_SetupStage +* Description : Executes USB control transfer/set up stage. +* Arguments : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* Return Value : none +*******************************************************************************/ +void usb0_host_SetupStage (uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len) +{ + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DOING; + + USB200.INTSTS1 = (uint16_t)~(USB_HOST_BITSACK | USB_HOST_BITSIGN); /* Status Clear */ + USB200.USBREQ = Req; + USB200.USBVAL = Val; + USB200.USBINDX = Indx; + USB200.USBLENG = Len; + USB200.DCPCTR = USB_HOST_BITSUREQ; /* PID=NAK & Send Setup */ +} + +/******************************************************************************* +* Function Name: usb0_host_StatusStage +* Description : Executes USB control transfer/status stage. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_StatusStage (void) +{ + uint8_t Buf1[16]; + + switch ((g_usb0_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_READ: + usb0_host_CtrlWriteStart((uint32_t)0, (uint8_t *)&Buf1); + break; + + case USB_HOST_MODE_WRITE: + usb0_host_CtrlReadStart((uint32_t)0, (uint8_t *)&Buf1); + break; + + case USB_HOST_MODE_NO_DATA: + usb0_host_CtrlReadStart((uint32_t)0, (uint8_t *)&Buf1); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb0_host_CtrlWriteStart +* Description : Executes USB control transfer/data stage(write). +* Arguments : uint32_t Bsize ; Data Size +* : uint8_t *Table ; Data Table Address +* Return Value : USB_HOST_WRITESHRT ; End of data write +* : USB_HOST_WRITEEND ; End of data write (not null) +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_FIFOERROR ; FIFO access error +*******************************************************************************/ +uint16_t usb0_host_CtrlWriteStart (uint32_t Bsize, uint8_t * Table) +{ + uint16_t EndFlag_K; + uint16_t mbw; + + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DOING; + + usb0_host_set_pid_nak(USB_HOST_PIPE0); /* Set NAK */ + g_usb0_host_data_count[USB_HOST_PIPE0] = Bsize; /* Transfer size set */ + g_usb0_host_data_pointer[USB_HOST_PIPE0] = Table; /* Transfer address set */ + + USB200.DCPCTR = USB_HOST_BITSQSET; /* SQSET=1, PID=NAK */ +#if(1) /* ohci_wrapp */ + Userdef_USB_usb0_host_delay_10us(3); +#endif + RZA_IO_RegWrite_16(&USB200.DCPCFG, + 1, + USB_DCPCFG_DIR_SHIFT, + USB_DCPCFG_DIR); + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[USB_HOST_PIPE0], (uint32_t)g_usb0_host_data_pointer[USB_HOST_PIPE0]); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_BITISEL, mbw); + USB200.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + + usb0_host_clear_pid_stall(USB_HOST_PIPE0); + EndFlag_K = usb0_host_write_buffer_c(USB_HOST_PIPE0); + /* Host Control sequence */ + switch (EndFlag_K) + { + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_STATUS; + usb0_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb0_host_enable_bemp_int(USB_HOST_PIPE0); /* Enable Empty Interrupt */ + break; + + case USB_HOST_WRITEEND: /* End of data write (not null) */ + case USB_HOST_WRITING: /* Continue of data write */ + usb0_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb0_host_enable_bemp_int(USB_HOST_PIPE0); /* Enable Empty Interrupt */ + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + break; + + default: + break; + } + usb0_host_set_pid_buf(USB_HOST_PIPE0); /* Set BUF */ + return (EndFlag_K); /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb0_host_CtrlReadStart +* Description : Executes USB control transfer/data stage(read). +* Arguments : uint32_t Bsize ; Data Size +* : uint8_t *Table ; Data Table Address +* Return Value : none +*******************************************************************************/ +void usb0_host_CtrlReadStart (uint32_t Bsize, uint8_t * Table) +{ + uint16_t mbw; + + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DOING; + + usb0_host_set_pid_nak(USB_HOST_PIPE0); /* Set NAK */ + g_usb0_host_data_count[USB_HOST_PIPE0] = Bsize; /* Transfer size set */ + g_usb0_host_data_pointer[USB_HOST_PIPE0] = Table; /* Transfer address set */ + + USB200.DCPCTR = USB_HOST_BITSQSET; /* SQSET=1, PID=NAK */ +#if(1) /* ohci_wrapp */ + Userdef_USB_usb0_host_delay_10us(3); +#endif + RZA_IO_RegWrite_16(&USB200.DCPCFG, + 0, + USB_DCPCFG_DIR_SHIFT, + USB_DCPCFG_DIR); + + mbw = usb0_host_get_mbw(g_usb0_host_data_count[USB_HOST_PIPE0], (uint32_t)g_usb0_host_data_pointer[USB_HOST_PIPE0]); + usb0_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_NO, mbw); + USB200.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + + usb0_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb0_host_enable_brdy_int(USB_HOST_PIPE0); /* Ok */ + usb0_host_clear_pid_stall(USB_HOST_PIPE0); + usb0_host_set_pid_buf(USB_HOST_PIPE0); /* Set BUF */ +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/host/usb0_host_drv_api.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,889 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_drv_api.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb0_host_resetEP(USB_HOST_CFG_PIPETBL_t *tbl); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_api_host_init +* Description : Initializes USB module in the USB host mode. +* : USB connection is executed when executing this function in +* : the states that USB device isconnected to the USB port. +* Arguments : uint8_t int_level : USB Module interrupt level +* : USBU16 mode : USB_HOST_HIGH_SPEED +* : USB_HOST_FULL_SPEED +* : uint16_t clockmode : USB Clock mode +* Return Value : USB detach or attach +* : USB_HOST_ATTACH +* : USB_HOST_DETACH +*******************************************************************************/ +uint16_t usb0_api_host_init (uint8_t int_level, uint16_t mode, uint16_t clockmode) +{ + uint16_t connect; + volatile uint8_t dummy_buf; + + CPG.STBCR7 &= 0xfd; /*The clock of USB0 modules is permitted */ + dummy_buf = CPG.STBCR7; /* (Dummy read) */ + + g_usb0_host_SupportUsbDeviceSpeed = mode; + + usb0_host_setting_interrupt(int_level); + usb0_host_reset_module(clockmode); + + g_usb0_host_bchg_flag = USB_HOST_NO; + g_usb0_host_detach_flag = USB_HOST_NO; + g_usb0_host_attach_flag = USB_HOST_NO; + + g_usb0_host_driver_state = USB_HOST_DRV_DETACHED; + g_usb0_host_default_max_packet[USB_HOST_DEVICE_0] = 64; + + usb0_host_InitModule(); + + connect = usb0_host_CheckAttach(); + + if (connect == USB_HOST_ATTACH) + { + g_usb0_host_attach_flag = USB_HOST_YES; + } + else + { + usb0_host_UsbDetach2(); + } + + return connect; +} + +#if(1) /* ohci_wrapp */ +#else +/******************************************************************************* +* Function Name: usb0_api_host_enumeration +* Description : Initializes USB module in the USB host mode. +* : USB connection is executed when executing this function in +* : the states that USB device isconnected to the USB port. +* Arguments : uint16_t devadr : device address +* Return Value : DEVDRV_USBH_DETACH_ERR : device detach +* : DEVDRV_SUCCESS : device enumeration success +* : DEVDRV_ERROR : device enumeration error +*******************************************************************************/ +int32_t usb0_api_host_enumeration (uint16_t devadr) +{ + int32_t ret; + uint16_t driver_sts; + + g_usb0_host_setUsbAddress = devadr; + + while (1) + { + driver_sts = usb0_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + ret = DEVDRV_USBH_DETACH_ERR; + break; + } + else if (driver_sts == USB_HOST_DRV_CONFIGURED) + { + ret = DEVDRV_SUCCESS; + break; + } + else if (driver_sts == USB_HOST_DRV_STALL) + { + ret = DEVDRV_ERROR; + break; + } + else if (driver_sts == USB_HOST_DRV_NORES) + { + ret = DEVDRV_ERROR; + break; + } + else + { + /* Do Nothing */ + } + } + + if (driver_sts == USB_HOST_DRV_NORES) + { + while (1) + { + driver_sts = usb0_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + break; + } + } + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_api_host_detach +* Description : USB detach routine +* Arguments : none +* Return Value : USB_HOST_DETACH : USB detach +* : USB_HOST_ATTACH : USB attach +* : DEVDRV_ERROR : error +*******************************************************************************/ +int32_t usb0_api_host_detach (void) +{ + int32_t ret; + uint16_t driver_sts; + + while (1) + { + driver_sts = usb0_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + ret = USB_HOST_DETACH; + break; + } + else if (driver_sts == USB_HOST_DRV_CONFIGURED) + { + ret = USB_HOST_ATTACH; + break; + } + else if (driver_sts == USB_HOST_DRV_STALL) + { + ret = DEVDRV_ERROR; + break; + } + else if (driver_sts == USB_HOST_DRV_NORES) + { + ret = DEVDRV_ERROR; + break; + } + else + { + /* Do Nothing */ + } + } + + if (driver_sts == USB_HOST_DRV_NORES) + { + while (1) + { + driver_sts = usb0_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + break; + } + } + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_api_host_data_in +* Description : Executes USB transfer as data-in in the argument specified pipe. +* Arguments : uint16_t devadr ; device address +* : uint16_t Pipe ; Pipe Number +* : uint32_t Size ; Data Size +* : uint8_t *data_buf ; Data data_buf Address +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_data_in (uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t * data_buf) +{ + int32_t ret; + + if (Pipe == USB_HOST_PIPE0) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipemaxp[Pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL) != devadr) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[Pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 1) + { + return DEVDRV_ERROR; + } + + if (g_usb0_host_pipe_status[Pipe] == USB_HOST_PIPE_IDLE) + { + usb0_host_start_receive_transfer(Pipe, Size, data_buf); + } + else + { + return DEVDRV_ERROR; /* Now pipe is busy */ + } + + /* waiting for completing routine */ + do + { + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb0_host_pipe_status[Pipe] != USB_HOST_PIPE_IDLE) && (g_usb0_host_pipe_status[Pipe] != USB_HOST_PIPE_WAIT)) + { + break; + } + + } while (1); + + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb0_host_pipe_status[Pipe]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + usb0_host_stop_transfer(Pipe); + + g_usb0_host_pipe_status[Pipe] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_api_host_data_out +* Description : Executes USB transfer as data-out in the argument specified pipe. +* Arguments : uint16_t devadr ; device address +* : uint16_t Pipe ; Pipe Number +* : uint32_t Size ; Data Size +* : uint8_t *data_buf ; Data data_buf Address +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_data_out (uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t * data_buf) +{ + int32_t ret; + + if (Pipe == USB_HOST_PIPE0) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipemaxp[Pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL) != devadr) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb0_host_pipecfg[Pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 0) + { + return DEVDRV_ERROR; + } + + if (g_usb0_host_pipe_status[Pipe] == USB_HOST_PIPE_IDLE) + { + usb0_host_start_send_transfer(Pipe, Size, data_buf); + } + else + { + return DEVDRV_ERROR; /* Now pipe is busy */ + } + + /* waiting for completing routine */ + do + { + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb0_host_pipe_status[Pipe] != USB_HOST_PIPE_IDLE) && (g_usb0_host_pipe_status[Pipe] != USB_HOST_PIPE_WAIT)) + { + break; + } + + } while (1); + + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb0_host_pipe_status[Pipe]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + usb0_host_stop_transfer(Pipe); + + g_usb0_host_pipe_status[Pipe] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_api_host_control_transfer +* Description : Executes USB control transfer. +* Arguments : uint16_t devadr ; device address +* : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* : uint8_t *buf ; Buffer +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_USBH_DETACH_ERR ; device detach +* : DEVDRV_USBH_CTRL_COM_ERR ; device no response +* : DEVDRV_USBH_STALL ; STALL +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_control_transfer (uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, + uint16_t Len, uint8_t * Buf) +{ + int32_t ret; + + do + { + ret = usb0_host_CtrlTransStart(devadr, Req, Val, Indx, Len, Buf); + + if (ret == DEVDRV_SUCCESS) + { + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb0_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_IDLE) + && (g_usb0_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_WAIT)) + { + break; + } + } + else + { + return DEVDRV_ERROR; + } + } while (1); + + if (g_usb0_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb0_host_pipe_status[USB_HOST_PIPE0]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_CTRL_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_api_host_set_endpoint +* Description : Sets end point on the information specified in the argument. +* Arguments : uint16_t devadr ; device address +* : uint8_t *configdescriptor ; device configration descriptor +* : USB_HOST_CFG_PIPETBL_t *user_table ; pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_set_endpoint (uint16_t devadr, USB_HOST_CFG_PIPETBL_t * user_table, uint8_t * configdescriptor) +{ + uint16_t ret; + uint32_t end_point; + uint32_t offset; + uint32_t totalLength; + USB_HOST_CFG_PIPETBL_t * pipe_table; + + /* End Point Search */ + end_point = 0; + offset = configdescriptor[0]; + totalLength = (uint16_t)(configdescriptor[2] + ((uint16_t)configdescriptor[3] << 8)); + + do + { + if (configdescriptor[offset + 1] == USB_HOST_ENDPOINT_DESC) + { + pipe_table = &user_table[end_point]; + + if (pipe_table->pipe_number == 0xffff) + { + break; + } + + ret = usb0_api_host_SetEndpointTable(devadr, pipe_table, (uint8_t *)&configdescriptor[offset]); + + if ((ret != USB_HOST_PIPE_IN) && (ret != USB_HOST_PIPE_OUT)) + { + return DEVDRV_ERROR; + } + + ++end_point; + } + + /* Next End Point Search */ + offset += configdescriptor[offset]; + + } while (offset < totalLength); + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb0_api_host_clear_endpoint +* Description : Clears the pipe definition table specified in the argument. +* Arguments : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_clear_endpoint (USB_HOST_CFG_PIPETBL_t * user_table) +{ + uint16_t pipe; + + for (pipe = USB_HOST_PIPE0; pipe <= USB_HOST_MAX_PIPE_NO; ++pipe) + { + if (user_table->pipe_number == 0xffff) + { + break; + } + user_table->pipe_cfg &= (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD); + user_table->pipe_max_pktsize = 0; + user_table->pipe_cycle = 0; + + user_table++; + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb0_api_host_clear_endpoint_pipe +* Description : Clears the pipe definition table specified in the argument. +* Arguments : uint16_t pipe_sel : Pipe Number +* : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_clear_endpoint_pipe (uint16_t pipe_sel, USB_HOST_CFG_PIPETBL_t * user_table) +{ + uint16_t pipe; + + for (pipe = USB_HOST_PIPE0; pipe <= USB_HOST_MAX_PIPE_NO; ++pipe) + { + if (user_table->pipe_number == 0xffff) + { + break; + } + + if (user_table->pipe_number == pipe_sel) + { + user_table->pipe_cfg &= (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD); + user_table->pipe_max_pktsize = 0; + user_table->pipe_cycle = 0; + break; + } + + user_table++; + } + + return DEVDRV_SUCCESS; +} +#endif + +/******************************************************************************* +* Function Name: usb0_api_host_SetEndpointTable +* Description : Sets the end point on the information specified by the argument. +* Arguments : uint16_t devadr : device address +* : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* : uint8_t *Table : Endpoint descriptor +* Return Value : USB_HOST_DIR_H_IN ; IN endpoint +* : USB_HOST_DIR_H_OUT ; OUT endpoint +* : USB_END_POINT_ERROR ; error +*******************************************************************************/ +uint16_t usb0_api_host_SetEndpointTable (uint16_t devadr, USB_HOST_CFG_PIPETBL_t * user_table, uint8_t * Table) +{ + uint16_t PipeCfg; + uint16_t PipeMaxp; + uint16_t pipe_number; + uint16_t ret; + uint16_t ret_flag = 0; // avoid warning. + + pipe_number = user_table->pipe_number; + + if (Table[1] != USB_HOST_ENDPOINT_DESC) + { + return USB_END_POINT_ERROR; + } + + switch (Table[3] & USB_HOST_EP_TYPE) + { + case USB_HOST_EP_CNTRL: + ret_flag = USB_END_POINT_ERROR; + break; + + case USB_HOST_EP_ISO: + if ((pipe_number != USB_HOST_PIPE1) && (pipe_number != USB_HOST_PIPE2)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_ISO; + break; + + case USB_HOST_EP_BULK: + if ((pipe_number < USB_HOST_PIPE1) || (pipe_number > USB_HOST_PIPE5)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_BULK; + break; + + case USB_HOST_EP_INT: + if ((pipe_number < USB_HOST_PIPE6) || (pipe_number > USB_HOST_PIPE9)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_INTERRUPT; + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + + /* Set pipe configuration table */ + if ((Table[2] & USB_HOST_EP_DIR_MASK) == USB_HOST_EP_IN) /* IN(receive) */ + { + if (PipeCfg == USB_HOST_ISO) + { + /* Transfer Type is ISO*/ + PipeCfg |= USB_HOST_DIR_H_IN; + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + case USB_HOST_D0USE: + case USB_HOST_D1USE: + case USB_HOST_D0DMA: + case USB_HOST_D1DMA: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & USB_HOST_DBLBFIELD); + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + } + else + { + /* Transfer Type is BULK or INT */ + PipeCfg |= (USB_HOST_SHTNAKON | USB_HOST_DIR_H_IN); /* Compulsory SHTNAK */ + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + case USB_HOST_D0USE: + case USB_HOST_D1USE: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); + break; + + case USB_HOST_D0DMA: + case USB_HOST_D1DMA: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); +#ifdef __USB_DMA_BFRE_ENABLE__ + /* this routine cannnot be perfomred if read operation is executed in buffer size */ + PipeCfg |= USB_HOST_BFREON; +#endif + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + } + ret = USB_HOST_PIPE_IN; + } + else /* OUT(send) */ + { + if (PipeCfg == USB_HOST_ISO) + { + /* Transfer Type is ISO*/ + PipeCfg |= (uint16_t)(user_table->pipe_cfg & USB_HOST_DBLBFIELD); + } + else + { + /* Transfer Type is BULK or INT */ + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); + } + PipeCfg |= USB_HOST_DIR_H_OUT; + ret = USB_HOST_PIPE_OUT; + } + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + g_usb0_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_CFIFO_USE; + break; + + case USB_HOST_D0USE: + g_usb0_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D0FIFO_USE; + break; + + case USB_HOST_D1USE: + g_usb0_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D1FIFO_USE; + break; + + case USB_HOST_D0DMA: + g_usb0_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D0FIFO_DMA; + break; + + case USB_HOST_D1DMA: + g_usb0_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D1FIFO_DMA; + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + + /* Endpoint number set */ + PipeCfg |= (uint16_t)(Table[2] & USB_HOST_EP_NUM_MASK); + g_usb0_host_PipeTbl[pipe_number] |= (uint16_t)(Table[2] & USB_HOST_EP_NUM_MASK); + + /* Max packet size set */ + PipeMaxp = (uint16_t)((uint16_t)Table[4] | (uint16_t)((uint16_t)Table[5] << 8)); + + if (PipeMaxp == 0u) + { + return USB_END_POINT_ERROR; + } + + /* Set device address */ + PipeMaxp |= (uint16_t)(devadr << 12); + + user_table->pipe_cfg = PipeCfg; + user_table->pipe_max_pktsize = PipeMaxp; + + usb0_host_resetEP(user_table); + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_host_resetEP +* Description : Sets the end point on the information specified by the argument. +* Arguments : USB_HOST_CFG_PIPETBL_t *tbl : pipe table +* Return Value : none +*******************************************************************************/ +static void usb0_host_resetEP (USB_HOST_CFG_PIPETBL_t * tbl) +{ + + uint16_t pipe; + + /* Host pipe */ + /* The pipe number of pipe definition table is obtained */ + pipe = (uint16_t)(tbl->pipe_number & USB_HOST_BITCURPIPE); /* Pipe Number */ + + /* FIFO port access pipe is set to initial value */ + /* The connection with FIFO should be cut before setting the pipe */ + if (RZA_IO_RegRead_16(&USB200.CFIFOSEL, + USB_CFIFOSEL_CURPIPE_SHIFT, + USB_CFIFOSEL_CURPIPE) == pipe) + { + usb0_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + if (RZA_IO_RegRead_16(&USB200.D0FIFOSEL, + USB_DnFIFOSEL_CURPIPE_SHIFT, + USB_DnFIFOSEL_CURPIPE) == pipe) + { + usb0_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + if (RZA_IO_RegRead_16(&USB200.D1FIFOSEL, + USB_DnFIFOSEL_CURPIPE_SHIFT, + USB_DnFIFOSEL_CURPIPE) == pipe) + { + usb0_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + /* Interrupt of pipe set is disabled */ + usb0_host_disable_brdy_int(pipe); + usb0_host_disable_nrdy_int(pipe); + usb0_host_disable_bemp_int(pipe); + + /* Pipe to set is set to NAK */ + usb0_host_set_pid_nak(pipe); + + /* Pipe is set */ + USB200.PIPESEL = pipe; + + USB200.PIPECFG = tbl->pipe_cfg; + USB200.PIPEBUF = tbl->pipe_buf; + USB200.PIPEMAXP = tbl->pipe_max_pktsize; + USB200.PIPEPERI = tbl->pipe_cycle; + + g_usb0_host_pipecfg[pipe] = tbl->pipe_cfg; + g_usb0_host_pipebuf[pipe] = tbl->pipe_buf; + g_usb0_host_pipemaxp[pipe] = tbl->pipe_max_pktsize; + g_usb0_host_pipeperi[pipe] = tbl->pipe_cycle; + + /* Sequence bit clear */ + usb0_host_set_sqclr(pipe); + + usb0_host_aclrm(pipe); + usb0_host_set_csclr(pipe); + + /* Pipe window selection is set to unused */ + USB200.PIPESEL = USB_HOST_PIPE0; + +} + +#if(1) /* ohci_wrapp */ +#else +/******************************************************************************* +* Function Name: usb0_api_host_data_count +* Description : Get g_usb0_host_data_count[pipe] +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t *data_count ; return g_usb0_data_count[pipe] +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb0_api_host_data_count (uint16_t pipe, uint32_t * data_count) +{ + if (pipe > USB_HOST_MAX_PIPE_NO) + { + return DEVDRV_ERROR; + } + + *data_count = g_usb0_host_PipeDataSize[pipe]; + + return DEVDRV_SUCCESS; +} +#endif + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/host/usb0_host_global.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,137 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_global.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +const uint16_t g_usb0_host_bit_set[16] = +{ + 0x0001, 0x0002, 0x0004, 0x0008, + 0x0010, 0x0020, 0x0040, 0x0080, + 0x0100, 0x0200, 0x0400, 0x0800, + 0x1000, 0x2000, 0x4000, 0x8000 +}; + +uint32_t g_usb0_host_data_count[USB_HOST_MAX_PIPE_NO + 1]; +uint8_t * g_usb0_host_data_pointer[USB_HOST_MAX_PIPE_NO + 1]; + +uint16_t g_usb0_host_PipeIgnore[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb0_host_PipeTbl[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb0_host_pipe_status[USB_HOST_MAX_PIPE_NO + 1]; +uint32_t g_usb0_host_PipeDataSize[USB_HOST_MAX_PIPE_NO + 1]; + +USB_HOST_DMA_t g_usb0_host_DmaInfo[2]; + +uint16_t g_usb0_host_DmaPipe[2]; +uint16_t g_usb0_host_DmaBval[2]; +uint16_t g_usb0_host_DmaStatus[2]; + +uint16_t g_usb0_host_driver_state; +uint16_t g_usb0_host_ConfigNum; +uint16_t g_usb0_host_CmdStage; +uint16_t g_usb0_host_bchg_flag; +uint16_t g_usb0_host_detach_flag; +uint16_t g_usb0_host_attach_flag; + +uint16_t g_usb0_host_UsbAddress; +uint16_t g_usb0_host_setUsbAddress; +uint16_t g_usb0_host_default_max_packet[USB_HOST_MAX_DEVICE + 1]; +uint16_t g_usb0_host_UsbDeviceSpeed; +uint16_t g_usb0_host_SupportUsbDeviceSpeed; + +uint16_t g_usb0_host_SavReq; +uint16_t g_usb0_host_SavVal; +uint16_t g_usb0_host_SavIndx; +uint16_t g_usb0_host_SavLen; + +uint16_t g_usb0_host_pipecfg[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb0_host_pipebuf[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb0_host_pipemaxp[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb0_host_pipeperi[USB_HOST_MAX_PIPE_NO + 1]; + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_init_pipe_status +* Description : Initialize pipe status. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_init_pipe_status (void) +{ + uint16_t loop; + + g_usb0_host_ConfigNum = 0; + + for (loop = 0; loop < (USB_HOST_MAX_PIPE_NO + 1); ++loop) + { + g_usb0_host_pipe_status[loop] = USB_HOST_PIPE_IDLE; + g_usb0_host_PipeDataSize[loop] = 0; + + /* pipe configuration in usb0_host_resetEP() */ + g_usb0_host_pipecfg[loop] = 0; + g_usb0_host_pipebuf[loop] = 0; + g_usb0_host_pipemaxp[loop] = 0; + g_usb0_host_pipeperi[loop] = 0; + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/host/usb0_host_usbint.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,496 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_usbint.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#if(1) /* ohci_wrapp */ +#include "ohci_wrapp_RZ_A1_local.h" +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb0_host_interrupt1(void); +static void usb0_host_BRDYInterrupt(uint16_t Status, uint16_t Int_enbl); +static void usb0_host_NRDYInterrupt(uint16_t Status, uint16_t Int_enbl); +static void usb0_host_BEMPInterrupt(uint16_t Status, uint16_t Int_enbl); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_interrupt +* Description : Executes USB interrupt. +* : Register this function in the USB interrupt handler. +* : Set CFIF0 in the pipe set before the interrupt after executing +* : this function. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb0_host_interrupt (uint32_t int_sense) +{ + uint16_t savepipe1; + uint16_t savepipe2; + uint16_t buffer; + + savepipe1 = USB200.CFIFOSEL; + savepipe2 = USB200.PIPESEL; + usb0_host_interrupt1(); + + /* Control transmission changes ISEL within interruption processing. */ + /* For this reason, write return of ISEL cannot be performed. */ + buffer = USB200.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(savepipe1 & USB_HOST_BITCURPIPE); + USB200.CFIFOSEL = buffer; + USB200.PIPESEL = savepipe2; +} + +/******************************************************************************* +* Function Name: usb0_host_interrupt1 +* Description : Execue the USB interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_interrupt1 (void) +{ + uint16_t intsts0; + uint16_t intsts1; + uint16_t intenb0; + uint16_t intenb1; + uint16_t brdysts; + uint16_t nrdysts; + uint16_t bempsts; + uint16_t brdyenb; + uint16_t nrdyenb; + uint16_t bempenb; + volatile uint16_t dumy_sts; + + intsts0 = USB200.INTSTS0; + intsts1 = USB200.INTSTS1; + intenb0 = USB200.INTENB0; + intenb1 = USB200.INTENB1; + + if ((intsts1 & USB_HOST_BITBCHG) && (intenb1 & USB_HOST_BITBCHGE)) + { + USB200.INTSTS1 = (uint16_t)~USB_HOST_BITBCHG; + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); + g_usb0_host_bchg_flag = USB_HOST_YES; + } + else if ((intsts1 & USB_HOST_BITSACK) && (intenb1 & USB_HOST_BITSACKE)) + { + USB200.INTSTS1 = (uint16_t)~USB_HOST_BITSACK; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); +#else + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; +#endif + } + else if ((intsts1 & USB_HOST_BITSIGN) && (intenb1 & USB_HOST_BITSIGNE)) + { + USB200.INTSTS1 = (uint16_t)~USB_HOST_BITSIGN; +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#else + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_NORES; +#endif + } + else if (((intsts1 & USB_HOST_BITDTCH) == USB_HOST_BITDTCH) + && ((intenb1 & USB_HOST_BITDTCHE) == USB_HOST_BITDTCHE)) + { + USB200.INTSTS1 = (uint16_t)~USB_HOST_BITDTCH; + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); + g_usb0_host_detach_flag = USB_HOST_YES; + + Userdef_USB_usb0_host_detach(); + + usb0_host_UsbDetach2(); + } + else if (((intsts1 & USB_HOST_BITATTCH) == USB_HOST_BITATTCH) + && ((intenb1 & USB_HOST_BITATTCHE) == USB_HOST_BITATTCHE)) + { + USB200.INTSTS1 = (uint16_t)~USB_HOST_BITATTCH; + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); + g_usb0_host_attach_flag = USB_HOST_YES; + + Userdef_USB_usb0_host_attach(); + + usb0_host_UsbAttach(); + } + else if ((intsts0 & intenb0 & (USB_HOST_BITBEMP | USB_HOST_BITNRDY | USB_HOST_BITBRDY))) + { + brdysts = USB200.BRDYSTS; + nrdysts = USB200.NRDYSTS; + bempsts = USB200.BEMPSTS; + brdyenb = USB200.BRDYENB; + nrdyenb = USB200.NRDYENB; + bempenb = USB200.BEMPENB; + + if ((intsts0 & USB_HOST_BITBRDY) && (intenb0 & USB_HOST_BITBRDYE) && (brdysts & brdyenb)) + { + usb0_host_BRDYInterrupt(brdysts, brdyenb); + } + else if ((intsts0 & USB_HOST_BITBEMP) && (intenb0 & USB_HOST_BITBEMPE) && (bempsts & bempenb)) + { + usb0_host_BEMPInterrupt(bempsts, bempenb); + } + else if ((intsts0 & USB_HOST_BITNRDY) && (intenb0 & USB_HOST_BITNRDYE) && (nrdysts & nrdyenb)) + { + usb0_host_NRDYInterrupt(nrdysts, nrdyenb); + } + else + { + /* Do Nothing */ + } + } + else + { + /* Do Nothing */ + } + + /* Three dummy read for clearing interrupt requests */ + dumy_sts = USB200.INTSTS0; + dumy_sts = USB200.INTSTS1; + +} + +/******************************************************************************* +* Function Name: usb0_host_BRDYInterrupt +* Description : Executes USB BRDY interrupt. +* Arguments : uint16_t Status ; BRDYSTS Register Value +* : uint16_t Int_enbl ; BRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_BRDYInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t buffer; + volatile uint16_t dumy_sts; + + if ((Status & g_usb0_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb0_host_bit_set[USB_HOST_PIPE0])) + { + USB200.BRDYSTS = (uint16_t)~g_usb0_host_bit_set[USB_HOST_PIPE0]; + +#if(1) /* ohci_wrapp */ + switch ((g_usb0_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + buffer = usb0_host_read_buffer_c(USB_HOST_PIPE0); + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb0_host_read_buffer_c(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_READOVER: /* buffer over */ + USB200.CFIFOCTR = USB_HOST_BITBCLR; + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + break; + } +#else + switch ((g_usb0_host_CmdStage & (USB_HOST_MODE_FIELD | USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + case (USB_HOST_MODE_NO_DATA | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + buffer = usb0_host_read_buffer_c(USB_HOST_PIPE0); + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case (USB_HOST_MODE_READ | USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb0_host_read_buffer_c(USB_HOST_PIPE0); + + switch (buffer) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case USB_HOST_READOVER: /* buffer over */ + USB200.CFIFOCTR = USB_HOST_BITBCLR; + usb0_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + break; + } +#endif + } + else + { + usb0_host_brdy_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB200.BRDYSTS; +} + +/******************************************************************************* +* Function Name: usb0_host_NRDYInterrupt +* Description : Executes USB NRDY interrupt. +* Arguments : uint16_t Status ; NRDYSTS Register Value +* : uint16_t Int_enbl ; NRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_NRDYInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t pid; + volatile uint16_t dumy_sts; + + if ((Status & g_usb0_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb0_host_bit_set[USB_HOST_PIPE0])) + { + USB200.NRDYSTS = (uint16_t)~g_usb0_host_bit_set[USB_HOST_PIPE0]; + pid = usb0_host_get_pid(USB_HOST_PIPE0); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_STALL; +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + } + else if (pid == USB_HOST_PID_NAK) + { + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_NORES; +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + } + else + { + /* Do Nothing */ + } + } + else + { + usb0_host_nrdy_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB200.NRDYSTS; +} + +/******************************************************************************* +* Function Name: usb0_host_BEMPInterrupt +* Description : Executes USB BEMP interrupt. +* Arguments : uint16_t Status ; BEMPSTS Register Value +* : uint16_t Int_enbl ; BEMPENB Register Value +* Return Value : none +*******************************************************************************/ +void usb0_host_BEMPInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t buffer; + uint16_t pid; + volatile uint16_t dumy_sts; + + if ((Status & g_usb0_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb0_host_bit_set[USB_HOST_PIPE0])) + { + USB200.BEMPSTS = (uint16_t)~g_usb0_host_bit_set[USB_HOST_PIPE0]; + pid = usb0_host_get_pid(USB_HOST_PIPE0); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_STALL; +#if(1) /* ohci_wrapp */ + g_usb0_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + } + else + { +#if(1) /* ohci_wrapp */ + switch ((g_usb0_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb0_host_write_buffer(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_WRITING: /* Continue of data write */ + case USB_HOST_WRITEEND: /* End of data write (zero-length) */ + break; + + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_STATUS; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + /* do nothing */ + break; + } +#else + switch ((g_usb0_host_CmdStage & (USB_HOST_MODE_FIELD | USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_MODE_READ | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb0_host_write_buffer(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_WRITING: /* Continue of data write */ + case USB_HOST_WRITEEND: /* End of data write (zero-length) */ + break; + + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb0_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb0_host_CmdStage |= USB_HOST_STAGE_STATUS; + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb0_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb0_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + default: + /* do nothing */ + break; + } +#endif + } + } + else + { + usb0_host_bemp_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB200.BEMPSTS; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/host/usb0_host_usbsig.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,637 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_usbsig.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb0_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb0_host_EnableINT_Module(void); +static void usb0_host_Enable_AttachINT(void); +static void usb0_host_Disable_AttachINT(void); +static void usb0_host_Disable_BchgINT(void); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb0_host_InitModule +* Description : Initializes the USB module in USB host module. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_InitModule (void) +{ + uint16_t buf1; + uint16_t buf2; + uint16_t buf3; + + usb0_host_init_pipe_status(); + + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 1, + USB_SYSCFG_DCFM_SHIFT, + USB_SYSCFG_DCFM); /* HOST mode */ + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 1, + USB_SYSCFG_DRPD_SHIFT, + USB_SYSCFG_DRPD); /* PORT0 D+, D- setting */ + + do + { + buf1 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb0_host_delay_xms(50); + buf2 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb0_host_delay_xms(50); + buf3 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + + } while ((buf1 != buf2) || (buf1 != buf3)); + + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 1, + USB_SYSCFG_USBE_SHIFT, + USB_SYSCFG_USBE); + + USB200.CFIFOSEL = (uint16_t)(USB_HOST_BITRCNT | USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); + USB200.D0FIFOSEL = (uint16_t)( USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); + USB200.D1FIFOSEL = (uint16_t)( USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); +} + +/******************************************************************************* +* Function Name: usb0_host_CheckAttach +* Description : Returns the USB device connection state. +* Arguments : none +* Return Value : uint16_t ; USB_HOST_ATTACH : Attached +* : ; USB_HOST_DETACH : not Attached +*******************************************************************************/ +uint16_t usb0_host_CheckAttach (void) +{ + uint16_t buf1; + uint16_t buf2; + uint16_t buf3; + uint16_t rhst; + + do + { + buf1 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb0_host_delay_xms(50); + buf2 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb0_host_delay_xms(50); + buf3 = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + + } while ((buf1 != buf2) || (buf1 != buf3)); + + rhst = RZA_IO_RegRead_16(&USB200.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (rhst == USB_HOST_UNDECID) + { + if (buf1 == USB_HOST_FS_JSTS) + { + if (g_usb0_host_SupportUsbDeviceSpeed == USB_HOST_HIGH_SPEED) + { + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 1, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + } + else + { + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + } + return USB_HOST_ATTACH; + } + else if (buf1 == USB_HOST_LS_JSTS) + { + /* Low Speed Device */ + RZA_IO_RegWrite_16(&USB200.SYSCFG0, + 0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + return USB_HOST_ATTACH; + } + else + { + /* Do Nothing */ + } + } + else if ((rhst == USB_HOST_HSMODE) || (rhst == USB_HOST_FSMODE)) + { + return USB_HOST_ATTACH; + } + else if (rhst == USB_HOST_LSMODE) + { + return USB_HOST_ATTACH; + } + else + { + /* Do Nothing */ + } + + return USB_HOST_DETACH; +} + +/******************************************************************************* +* Function Name: usb0_host_UsbAttach +* Description : Connects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_UsbAttach (void) +{ + usb0_host_EnableINT_Module(); + usb0_host_Disable_BchgINT(); + usb0_host_Disable_AttachINT(); + usb0_host_Enable_DetachINT(); +} + +/******************************************************************************* +* Function Name: usb0_host_UsbDetach +* Description : Disconnects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_UsbDetach (void) +{ + uint16_t pipe; + uint16_t devadr; + + g_usb0_host_driver_state = USB_HOST_DRV_DETACHED; + + /* Terminate all the pipes in which communications on port */ + /* are currently carried out */ + for (pipe = 0; pipe < (USB_HOST_MAX_PIPE_NO + 1); ++pipe) + { + if (g_usb0_host_pipe_status[pipe] != USB_HOST_PIPE_IDLE) + { + if (pipe == USB_HOST_PIPE0) + { + devadr = RZA_IO_RegRead_16(&USB200.DCPMAXP, + USB_DCPMAXP_DEVSEL_SHIFT, + USB_DCPMAXP_DEVSEL); + } + else + { + devadr = RZA_IO_RegRead_16(&g_usb0_host_pipemaxp[pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL); + } + + if (devadr == g_usb0_host_UsbAddress) + { + usb0_host_stop_transfer(pipe); + } + + g_usb0_host_pipe_status[pipe] = USB_HOST_PIPE_IDLE; + } + } + + g_usb0_host_ConfigNum = 0; + g_usb0_host_UsbAddress = 0; + g_usb0_host_default_max_packet[USB_HOST_DEVICE_0] = 64; + + usb0_host_UsbDetach2(); +} + +/******************************************************************************* +* Function Name: usb0_host_UsbDetach2 +* Description : Disconnects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_UsbDetach2 (void) +{ + usb0_host_Disable_DetachINT(); + usb0_host_Disable_BchgINT(); + usb0_host_Enable_AttachINT(); +} + +/******************************************************************************* +* Function Name: usb0_host_UsbBusReset +* Description : Issues the USB bus reset signal. +* Arguments : none +* Return Value : uint16_t ; RHST +*******************************************************************************/ +uint16_t usb0_host_UsbBusReset (void) +{ + uint16_t buffer; + uint16_t loop; + + RZA_IO_RegWrite_16(&USB200.DVSTCTR0, + 1, + USB_DVSTCTR0_USBRST_SHIFT, + USB_DVSTCTR0_USBRST); + RZA_IO_RegWrite_16(&USB200.DVSTCTR0, + 0, + USB_DVSTCTR0_UACT_SHIFT, + USB_DVSTCTR0_UACT); + + Userdef_USB_usb0_host_delay_xms(50); + + buffer = USB200.DVSTCTR0; + buffer &= (uint16_t)(~(USB_HOST_BITRST)); + buffer |= USB_HOST_BITUACT; + USB200.DVSTCTR0 = buffer; + + Userdef_USB_usb0_host_delay_xms(20); + + for (loop = 0, buffer = USB_HOST_HSPROC; loop < 3; ++loop) + { + buffer = RZA_IO_RegRead_16(&USB200.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (buffer == USB_HOST_HSPROC) + { + Userdef_USB_usb0_host_delay_xms(10); + } + else + { + break; + } + } + + return buffer; +} + +/******************************************************************************* +* Function Name: usb0_host_UsbResume +* Description : Issues the USB resume signal. +* Arguments : none +* Return Value : int32_t ; DEVDRV_SUCCESS +* : ; DEVDRV_ERROR +*******************************************************************************/ +int32_t usb0_host_UsbResume (void) +{ + uint16_t buf; + + if ((g_usb0_host_driver_state & USB_HOST_DRV_SUSPEND) == 0) + { + /* not SUSPEND */ + return DEVDRV_ERROR; + } + + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); + RZA_IO_RegWrite_16(&USB200.DVSTCTR0, + 1, + USB_DVSTCTR0_RESUME_SHIFT, + USB_DVSTCTR0_RESUME); + Userdef_USB_usb0_host_delay_xms(20); + + buf = USB200.DVSTCTR0; + buf &= (uint16_t)(~(USB_HOST_BITRESUME)); + buf |= USB_HOST_BITUACT; + USB200.DVSTCTR0 = buf; + + g_usb0_host_driver_state &= (uint16_t)~USB_HOST_DRV_SUSPEND; + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb0_host_UsbSuspend +* Description : Issues the USB suspend signal. +* Arguments : none +* Return Value : int32_t ; DEVDRV_SUCCESS :not SUSPEND +* : ; DEVDRV_ERROR :SUSPEND +*******************************************************************************/ +int32_t usb0_host_UsbSuspend (void) +{ + uint16_t buf; + + if ((g_usb0_host_driver_state & USB_HOST_DRV_SUSPEND) != 0) + { + /* SUSPEND */ + return DEVDRV_ERROR; + } + + RZA_IO_RegWrite_16(&USB200.DVSTCTR0, + 0, + USB_DVSTCTR0_UACT_SHIFT, + USB_DVSTCTR0_UACT); + + Userdef_USB_usb0_host_delay_xms(5); + + buf = RZA_IO_RegRead_16(&USB200.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + if ((buf != USB_HOST_FS_JSTS) && (buf != USB_HOST_LS_JSTS)) + { + usb0_host_UsbDetach(); + } + else + { + g_usb0_host_driver_state |= USB_HOST_DRV_SUSPEND; + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb0_host_Enable_DetachINT +* Description : Enables the USB disconnection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_Enable_DetachINT (void) +{ + USB200.INTSTS1 = (uint16_t)(~(USB_HOST_BITDTCH)); + RZA_IO_RegWrite_16(&USB200.INTENB1, + 1, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); +} + +/******************************************************************************* +* Function Name: usb0_host_Disable_DetachINT +* Description : Disables the USB disconnection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_Disable_DetachINT (void) +{ + USB200.INTSTS1 = (uint16_t)(~(USB_HOST_BITDTCH)); + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); +} + +/******************************************************************************* +* Function Name: usb0_host_Enable_AttachINT +* Description : Enables the USB connection detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_Enable_AttachINT (void) +{ + USB200.INTSTS1 = (uint16_t)(~(USB_HOST_BITATTCH)); + RZA_IO_RegWrite_16(&USB200.INTENB1, + 1, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); +} + +/******************************************************************************* +* Function Name: usb0_host_Disable_AttachINT +* Description : Disables the USB connection detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_Disable_AttachINT (void) +{ + USB200.INTSTS1 = (uint16_t)(~(USB_HOST_BITATTCH)); + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); +} + +/******************************************************************************* +* Function Name: usb0_host_Disable_BchgINT +* Description : Disables the USB bus change detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_Disable_BchgINT (void) +{ + USB200.INTSTS1 = (uint16_t)(~(USB_HOST_BITBCHG)); + RZA_IO_RegWrite_16(&USB200.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); +} + +/******************************************************************************* +* Function Name: usb0_host_set_devadd +* Description : DEVADDn register is set by specified value +* Arguments : uint16_t addr : Device address +* : uint16_t *devadd : Set value +* Return Value : none +*******************************************************************************/ +void usb0_host_set_devadd (uint16_t addr, uint16_t * devadd) +{ + uint16_t * ptr; + uint16_t ret_flag = DEVDRV_FLAG_ON; // avoid warning. + + switch (addr) + { + case USB_HOST_DEVICE_0: + ptr = (uint16_t *)&USB200.DEVADD0; + break; + + case USB_HOST_DEVICE_1: + ptr = (uint16_t *)&USB200.DEVADD1; + break; + + case USB_HOST_DEVICE_2: + ptr = (uint16_t *)&USB200.DEVADD2; + break; + + case USB_HOST_DEVICE_3: + ptr = (uint16_t *)&USB200.DEVADD3; + break; + + case USB_HOST_DEVICE_4: + ptr = (uint16_t *)&USB200.DEVADD4; + break; + + case USB_HOST_DEVICE_5: + ptr = (uint16_t *)&USB200.DEVADD5; + break; + + case USB_HOST_DEVICE_6: + ptr = (uint16_t *)&USB200.DEVADD6; + break; + + case USB_HOST_DEVICE_7: + ptr = (uint16_t *)&USB200.DEVADD7; + break; + + case USB_HOST_DEVICE_8: + ptr = (uint16_t *)&USB200.DEVADD8; + break; + + case USB_HOST_DEVICE_9: + ptr = (uint16_t *)&USB200.DEVADD9; + break; + + case USB_HOST_DEVICE_10: + ptr = (uint16_t *)&USB200.DEVADDA; + break; + + default: + ret_flag = DEVDRV_FLAG_OFF; + break; + } + + if (ret_flag == DEVDRV_FLAG_ON) + { + *ptr = (uint16_t)(*devadd & USB_HOST_DEVADD_MASK); + } +} + +/******************************************************************************* +* Function Name: usb0_host_get_devadd +* Description : DEVADDn register is obtained +* Arguments : uint16_t addr : Device address +* : uint16_t *devadd : USB_HOST_DEVADD register value +* Return Value : none +*******************************************************************************/ +void usb0_host_get_devadd (uint16_t addr, uint16_t * devadd) +{ + uint16_t * ptr; + uint16_t ret_flag = DEVDRV_FLAG_ON; // avoid warning. + + switch (addr) + { + case USB_HOST_DEVICE_0: + ptr = (uint16_t *)&USB200.DEVADD0; + break; + + case USB_HOST_DEVICE_1: + ptr = (uint16_t *)&USB200.DEVADD1; + break; + + case USB_HOST_DEVICE_2: + ptr = (uint16_t *)&USB200.DEVADD2; + break; + + case USB_HOST_DEVICE_3: + ptr = (uint16_t *)&USB200.DEVADD3; + break; + + case USB_HOST_DEVICE_4: + ptr = (uint16_t *)&USB200.DEVADD4; + break; + + case USB_HOST_DEVICE_5: + ptr = (uint16_t *)&USB200.DEVADD5; + break; + + case USB_HOST_DEVICE_6: + ptr = (uint16_t *)&USB200.DEVADD6; + break; + + case USB_HOST_DEVICE_7: + ptr = (uint16_t *)&USB200.DEVADD7; + break; + + case USB_HOST_DEVICE_8: + ptr = (uint16_t *)&USB200.DEVADD8; + break; + + case USB_HOST_DEVICE_9: + ptr = (uint16_t *)&USB200.DEVADD9; + break; + + case USB_HOST_DEVICE_10: + ptr = (uint16_t *)&USB200.DEVADDA; + break; + + default: + ret_flag = DEVDRV_FLAG_OFF; + break; + } + + if (ret_flag == DEVDRV_FLAG_ON) + { + *devadd = *ptr; + } +} + +/******************************************************************************* +* Function Name: usb0_host_EnableINT_Module +* Description : Enables BEMP/NRDY/BRDY interrupt and SIGN/SACK interrupt. +* : Enables NRDY/BEMP interrupt in the pipe0. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb0_host_EnableINT_Module (void) +{ + uint16_t buf; + + buf = USB200.INTENB0; + buf |= (USB_HOST_BITBEMPE | USB_HOST_BITNRDYE | USB_HOST_BITBRDYE); + USB200.INTENB0 = buf; + + buf = USB200.INTENB1; + buf |= (USB_HOST_BITSIGNE | USB_HOST_BITSACKE); + USB200.INTENB1 = buf; + + usb0_host_enable_nrdy_int(USB_HOST_PIPE0); + usb0_host_enable_bemp_int(USB_HOST_PIPE0); +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/userdef/usb0_host_dmacdrv.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,698 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_dmacdrv.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "r_typedefs.h" +#include "iodefine.h" +#include "rza_io_regrw.h" +#include "usb0_host_dmacdrv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define DMAC_INDEFINE (255) /* Macro definition when REQD bit is not used */ + +/* ==== Request setting information for on-chip peripheral module ==== */ +typedef enum dmac_peri_req_reg_type +{ + DMAC_REQ_MID, + DMAC_REQ_RID, + DMAC_REQ_AM, + DMAC_REQ_LVL, + DMAC_REQ_REQD +} dmac_peri_req_reg_type_t; + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +/* ==== Prototype declaration ==== */ + +/* ==== Global variable ==== */ +/* On-chip peripheral module request setting table */ +static const uint8_t usb0_host_dmac_peri_req_init_table[8][5] = +{ + /* MID,RID, AM,LVL,REQD */ + { 32, 3, 2, 1, 1}, /* USB_0 channel 0 transmit FIFO empty */ + { 32, 3, 2, 1, 0}, /* USB_0 channel 0 receive FIFO full */ + { 33, 3, 2, 1, 1}, /* USB_0 channel 1 transmit FIFO empty */ + { 33, 3, 2, 1, 0}, /* USB_0 channel 1 receive FIFO full */ + { 34, 3, 2, 1, 1}, /* USB_1 channel 0 transmit FIFO empty */ + { 34, 3, 2, 1, 0}, /* USB_1 channel 0 receive FIFO full */ + { 35, 3, 2, 1, 1}, /* USB_1 channel 1 transmit FIFO empty */ + { 35, 3, 2, 1, 0}, /* USB_1 channel 1 receive FIFO full */ +}; + + +/******************************************************************************* +* Function Name: usb0_host_DMAC1_PeriReqInit +* Description : Sets the register mode for DMA mode and the on-chip peripheral +* : module request for transfer request for DMAC channel 1. +* : Executes DMAC initial setting using the DMA information +* : specified by the argument *trans_info and the enabled/disabled +* : continuous transfer specified by the argument continuation. +* : Registers DMAC channel 1 interrupt handler function and sets +* : the interrupt priority level. Then enables transfer completion +* : interrupt. +* Arguments : dmac_transinfo_t * trans_info : Setting information to DMAC +* : : register +* : uint32_t dmamode : DMA mode (only for DMAC_MODE_REGISTER) +* : uint32_t continuation : Set continuous transfer to be valid +* : : after DMA transfer has been completed +* : DMAC_SAMPLE_CONTINUATION : Execute continuous transfer +* : DMAC_SAMPLE_SINGLE : Do not execute continuous +* : : transfer +* : uint32_t request_factor : Factor for on-chip peripheral module +* : : request +* : DMAC_REQ_OSTM0TINT : OSTM_0 compare match +* : DMAC_REQ_OSTM1TINT : OSTM_1 compare match +* : DMAC_REQ_TGI0A : MTU2_0 input capture/compare match +* : : +* : uint32_t req_direction : Setting value of CHCFG_n register +* : : REQD bit +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC1_PeriReqInit (const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction) +{ + /* ==== Register mode ==== */ + if (DMAC_MODE_REGISTER == dmamode) + { + /* ==== Next0 register set ==== */ + DMAC1.N0SA_n = trans_info->src_addr; /* Start address of transfer source */ + DMAC1.N0DA_n = trans_info->dst_addr; /* Start address of transfer destination */ + DMAC1.N0TB_n = trans_info->count; /* Total transfer byte count */ + + /* DAD : Transfer destination address counting direction */ + /* SAD : Transfer source address counting direction */ + /* DDS : Transfer destination transfer size */ + /* SDS : Transfer source transfer size */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + trans_info->daddr_dir, + DMAC1_CHCFG_n_DAD_SHIFT, + DMAC1_CHCFG_n_DAD); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + trans_info->saddr_dir, + DMAC1_CHCFG_n_SAD_SHIFT, + DMAC1_CHCFG_n_SAD); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + trans_info->dst_size, + DMAC1_CHCFG_n_DDS_SHIFT, + DMAC1_CHCFG_n_DDS); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + trans_info->src_size, + DMAC1_CHCFG_n_SDS_SHIFT, + DMAC1_CHCFG_n_SDS); + + /* DMS : Register mode */ + /* RSEL : Select Next0 register set */ + /* SBE : No discharge of buffer data when aborted */ + /* DEM : No DMA interrupt mask */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_DMS_SHIFT, + DMAC1_CHCFG_n_DMS); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_RSEL_SHIFT, + DMAC1_CHCFG_n_RSEL); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_SBE_SHIFT, + DMAC1_CHCFG_n_SBE); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_DEM_SHIFT, + DMAC1_CHCFG_n_DEM); + + /* ---- Continuous transfer ---- */ + if (DMAC_SAMPLE_CONTINUATION == continuation) + { + /* REN : Execute continuous transfer */ + /* RSW : Change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 1, + DMAC1_CHCFG_n_REN_SHIFT, + DMAC1_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 1, + DMAC1_CHCFG_n_RSW_SHIFT, + DMAC1_CHCFG_n_RSW); + } + /* ---- Single transfer ---- */ + else + { + /* REN : Do not execute continuous transfer */ + /* RSW : Do not change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_REN_SHIFT, + DMAC1_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_RSW_SHIFT, + DMAC1_CHCFG_n_RSW); + } + + /* TM : Single transfer */ + /* SEL : Channel setting */ + /* HIEN, LOEN : On-chip peripheral module request */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_TM_SHIFT, + DMAC1_CHCFG_n_TM); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 1, + DMAC1_CHCFG_n_SEL_SHIFT, + DMAC1_CHCFG_n_SEL); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 1, + DMAC1_CHCFG_n_HIEN_SHIFT, + DMAC1_CHCFG_n_HIEN); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + 0, + DMAC1_CHCFG_n_LOEN_SHIFT, + DMAC1_CHCFG_n_LOEN); + + /* ---- Set factor by specified on-chip peripheral module request ---- */ + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_AM], + DMAC1_CHCFG_n_AM_SHIFT, + DMAC1_CHCFG_n_AM); + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_LVL], + DMAC1_CHCFG_n_LVL_SHIFT, + DMAC1_CHCFG_n_LVL); + if (usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD] != DMAC_INDEFINE) + { + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD], + DMAC1_CHCFG_n_REQD_SHIFT, + DMAC1_CHCFG_n_REQD); + } + else + { + RZA_IO_RegWrite_32(&DMAC1.CHCFG_n, + req_direction, + DMAC1_CHCFG_n_REQD_SHIFT, + DMAC1_CHCFG_n_REQD); + } + RZA_IO_RegWrite_32(&DMAC01.DMARS, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_RID], + DMAC01_DMARS_CH1_RID_SHIFT, + DMAC01_DMARS_CH1_RID); + RZA_IO_RegWrite_32(&DMAC01.DMARS, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_MID], + DMAC01_DMARS_CH1_MID_SHIFT, + DMAC01_DMARS_CH1_MID); + + /* PR : Round robin mode */ + RZA_IO_RegWrite_32(&DMAC07.DCTRL_0_7, + 1, + DMAC07_DCTRL_0_7_PR_SHIFT, + DMAC07_DCTRL_0_7_PR); + } +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC1_Open +* Description : Enables DMAC channel 1 transfer. +* Arguments : uint32_t req : DMAC request mode +* Return Value : 0 : Succeeded in enabling DMA transfer +* : -1 : Failed to enable DMA transfer (due to DMA operation) +*******************************************************************************/ +int32_t usb0_host_DMAC1_Open (uint32_t req) +{ + int32_t ret; + volatile uint8_t dummy; + + /* Transferable? */ + if ((0 == RZA_IO_RegRead_32(&DMAC1.CHSTAT_n, + DMAC1_CHSTAT_n_EN_SHIFT, + DMAC1_CHSTAT_n_EN)) && + (0 == RZA_IO_RegRead_32(&DMAC1.CHSTAT_n, + DMAC1_CHSTAT_n_TACT_SHIFT, + DMAC1_CHSTAT_n_TACT))) + { + /* Clear Channel Status Register */ + RZA_IO_RegWrite_32(&DMAC1.CHCTRL_n, + 1, + DMAC1_CHCTRL_n_SWRST_SHIFT, + DMAC1_CHCTRL_n_SWRST); + dummy = RZA_IO_RegRead_32(&DMAC1.CHCTRL_n, + DMAC1_CHCTRL_n_SWRST_SHIFT, + DMAC1_CHCTRL_n_SWRST); + /* Enable DMA transfer */ + RZA_IO_RegWrite_32(&DMAC1.CHCTRL_n, + 1, + DMAC1_CHCTRL_n_SETEN_SHIFT, + DMAC1_CHCTRL_n_SETEN); + + /* ---- Request by software ---- */ + if (DMAC_REQ_MODE_SOFT == req) + { + /* DMA transfer Request by software */ + RZA_IO_RegWrite_32(&DMAC1.CHCTRL_n, + 1, + DMAC1_CHCTRL_n_STG_SHIFT, + DMAC1_CHCTRL_n_STG); + } + + ret = 0; + } + else + { + ret = -1; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC1_Close +* Description : Aborts DMAC channel 1 transfer. Returns the remaining transfer +* : byte count at the time of DMA transfer abort to the argument +* : *remain. +* Arguments : uint32_t * remain : Remaining transfer byte count when +* : : DMA transfer is aborted +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC1_Close (uint32_t * remain) +{ + + /* ==== Abort transfer ==== */ + RZA_IO_RegWrite_32(&DMAC1.CHCTRL_n, + 1, + DMAC1_CHCTRL_n_CLREN_SHIFT, + DMAC1_CHCTRL_n_CLREN); + + while (1 == RZA_IO_RegRead_32(&DMAC1.CHSTAT_n, + DMAC1_CHSTAT_n_TACT_SHIFT, + DMAC1_CHSTAT_n_TACT)) + { + /* Loop until transfer is aborted */ + } + + while (1 == RZA_IO_RegRead_32(&DMAC1.CHSTAT_n, + DMAC1_CHSTAT_n_EN_SHIFT, + DMAC1_CHSTAT_n_EN)) + { + /* Loop until 0 is set in EN before checking the remaining transfer byte count */ + } + /* ==== Obtain remaining transfer byte count ==== */ + *remain = DMAC1.CRTB_n; +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC1_Load_Set +* Description : Sets the transfer source address, transfer destination +* : address, and total transfer byte count respectively +* : specified by the argument src_addr, dst_addr, and count to +* : DMAC channel 1 as DMA transfer information. +* : Sets the register set selected by the CHCFG_n register +* : RSEL bit from the Next0 or Next1 register set. +* : This function should be called when DMA transfer of DMAC +* : channel 1 is aboted. +* Arguments : uint32_t src_addr : Transfer source address +* : uint32_t dst_addr : Transfer destination address +* : uint32_t count : Total transfer byte count +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC1_Load_Set (uint32_t src_addr, uint32_t dst_addr, uint32_t count) +{ + uint8_t reg_set; + + /* Obtain register set in use */ + reg_set = RZA_IO_RegRead_32(&DMAC1.CHSTAT_n, + DMAC1_CHSTAT_n_SR_SHIFT, + DMAC1_CHSTAT_n_SR); + + /* ==== Load ==== */ + if (0 == reg_set) + { + /* ---- Next0 Register Set ---- */ + DMAC1.N0SA_n = src_addr; /* Start address of transfer source */ + DMAC1.N0DA_n = dst_addr; /* Start address of transfer destination */ + DMAC1.N0TB_n = count; /* Total transfer byte count */ + } + else + { + /* ---- Next1 Register Set ---- */ + DMAC1.N1SA_n = src_addr; /* Start address of transfer source */ + DMAC1.N1DA_n = dst_addr; /* Start address of transfer destination */ + DMAC1.N1TB_n = count; /* Total transfer byte count */ + } +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC2_PeriReqInit +* Description : Sets the register mode for DMA mode and the on-chip peripheral +* : module request for transfer request for DMAC channel 2. +* : Executes DMAC initial setting using the DMA information +* : specified by the argument *trans_info and the enabled/disabled +* : continuous transfer specified by the argument continuation. +* : Registers DMAC channel 2 interrupt handler function and sets +* : the interrupt priority level. Then enables transfer completion +* : interrupt. +* Arguments : dmac_transinfo_t * trans_info : Setting information to DMAC +* : : register +* : uint32_t dmamode : DMA mode (only for DMAC_MODE_REGISTER) +* : uint32_t continuation : Set continuous transfer to be valid +* : : after DMA transfer has been completed +* : DMAC_SAMPLE_CONTINUATION : Execute continuous transfer +* : DMAC_SAMPLE_SINGLE : Do not execute continuous +* : : transfer +* : uint32_t request_factor : Factor for on-chip peripheral module +* : : request +* : DMAC_REQ_OSTM0TINT : OSTM_0 compare match +* : DMAC_REQ_OSTM1TINT : OSTM_1 compare match +* : DMAC_REQ_TGI0A : MTU2_0 input capture/compare match +* : : +* : uint32_t req_direction : Setting value of CHCFG_n register +* : : REQD bit +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC2_PeriReqInit (const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction) +{ + /* ==== Register mode ==== */ + if (DMAC_MODE_REGISTER == dmamode) + { + /* ==== Next0 register set ==== */ + DMAC2.N0SA_n = trans_info->src_addr; /* Start address of transfer source */ + DMAC2.N0DA_n = trans_info->dst_addr; /* Start address of transfer destination */ + DMAC2.N0TB_n = trans_info->count; /* Total transfer byte count */ + + /* DAD : Transfer destination address counting direction */ + /* SAD : Transfer source address counting direction */ + /* DDS : Transfer destination transfer size */ + /* SDS : Transfer source transfer size */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + trans_info->daddr_dir, + DMAC2_CHCFG_n_DAD_SHIFT, + DMAC2_CHCFG_n_DAD); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + trans_info->saddr_dir, + DMAC2_CHCFG_n_SAD_SHIFT, + DMAC2_CHCFG_n_SAD); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + trans_info->dst_size, + DMAC2_CHCFG_n_DDS_SHIFT, + DMAC2_CHCFG_n_DDS); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + trans_info->src_size, + DMAC2_CHCFG_n_SDS_SHIFT, + DMAC2_CHCFG_n_SDS); + + /* DMS : Register mode */ + /* RSEL : Select Next0 register set */ + /* SBE : No discharge of buffer data when aborted */ + /* DEM : No DMA interrupt mask */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_DMS_SHIFT, + DMAC2_CHCFG_n_DMS); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_RSEL_SHIFT, + DMAC2_CHCFG_n_RSEL); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_SBE_SHIFT, + DMAC2_CHCFG_n_SBE); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_DEM_SHIFT, + DMAC2_CHCFG_n_DEM); + + /* ---- Continuous transfer ---- */ + if (DMAC_SAMPLE_CONTINUATION == continuation) + { + /* REN : Execute continuous transfer */ + /* RSW : Change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 1, + DMAC2_CHCFG_n_REN_SHIFT, + DMAC2_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 1, + DMAC2_CHCFG_n_RSW_SHIFT, + DMAC2_CHCFG_n_RSW); + } + /* ---- Single transfer ---- */ + else + { + /* REN : Do not execute continuous transfer */ + /* RSW : Do not change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_REN_SHIFT, + DMAC2_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_RSW_SHIFT, + DMAC2_CHCFG_n_RSW); + } + + /* TM : Single transfer */ + /* SEL : Channel setting */ + /* HIEN, LOEN : On-chip peripheral module request */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_TM_SHIFT, + DMAC2_CHCFG_n_TM); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 2, + DMAC2_CHCFG_n_SEL_SHIFT, + DMAC2_CHCFG_n_SEL); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 1, + DMAC2_CHCFG_n_HIEN_SHIFT, + DMAC2_CHCFG_n_HIEN); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + 0, + DMAC2_CHCFG_n_LOEN_SHIFT, + DMAC2_CHCFG_n_LOEN); + + /* ---- Set factor by specified on-chip peripheral module request ---- */ + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_AM], + DMAC2_CHCFG_n_AM_SHIFT, + DMAC2_CHCFG_n_AM); + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_LVL], + DMAC2_CHCFG_n_LVL_SHIFT, + DMAC2_CHCFG_n_LVL); + if (usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD] != DMAC_INDEFINE) + { + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD], + DMAC2_CHCFG_n_REQD_SHIFT, + DMAC2_CHCFG_n_REQD); + } + else + { + RZA_IO_RegWrite_32(&DMAC2.CHCFG_n, + req_direction, + DMAC2_CHCFG_n_REQD_SHIFT, + DMAC2_CHCFG_n_REQD); + } + RZA_IO_RegWrite_32(&DMAC23.DMARS, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_RID], + DMAC23_DMARS_CH2_RID_SHIFT, + DMAC23_DMARS_CH2_RID); + RZA_IO_RegWrite_32(&DMAC23.DMARS, + usb0_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_MID], + DMAC23_DMARS_CH2_MID_SHIFT, + DMAC23_DMARS_CH2_MID); + + /* PR : Round robin mode */ + RZA_IO_RegWrite_32(&DMAC07.DCTRL_0_7, + 1, + DMAC07_DCTRL_0_7_PR_SHIFT, + DMAC07_DCTRL_0_7_PR); + } +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC2_Open +* Description : Enables DMAC channel 2 transfer. +* Arguments : uint32_t req : DMAC request mode +* Return Value : 0 : Succeeded in enabling DMA transfer +* : -1 : Failed to enable DMA transfer (due to DMA operation) +*******************************************************************************/ +int32_t usb0_host_DMAC2_Open (uint32_t req) +{ + int32_t ret; + volatile uint8_t dummy; + + /* Transferable? */ + if ((0 == RZA_IO_RegRead_32(&DMAC2.CHSTAT_n, + DMAC2_CHSTAT_n_EN_SHIFT, + DMAC2_CHSTAT_n_EN)) && + (0 == RZA_IO_RegRead_32(&DMAC2.CHSTAT_n, + DMAC2_CHSTAT_n_TACT_SHIFT, + DMAC2_CHSTAT_n_TACT))) + { + /* Clear Channel Status Register */ + RZA_IO_RegWrite_32(&DMAC2.CHCTRL_n, + 1, + DMAC2_CHCTRL_n_SWRST_SHIFT, + DMAC2_CHCTRL_n_SWRST); + dummy = RZA_IO_RegRead_32(&DMAC2.CHCTRL_n, + DMAC2_CHCTRL_n_SWRST_SHIFT, + DMAC2_CHCTRL_n_SWRST); + /* Enable DMA transfer */ + RZA_IO_RegWrite_32(&DMAC2.CHCTRL_n, + 1, + DMAC2_CHCTRL_n_SETEN_SHIFT, + DMAC2_CHCTRL_n_SETEN); + + /* ---- Request by software ---- */ + if (DMAC_REQ_MODE_SOFT == req) + { + /* DMA transfer Request by software */ + RZA_IO_RegWrite_32(&DMAC2.CHCTRL_n, + 1, + DMAC2_CHCTRL_n_STG_SHIFT, + DMAC2_CHCTRL_n_STG); + } + + ret = 0; + } + else + { + ret = -1; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC2_Close +* Description : Aborts DMAC channel 2 transfer. Returns the remaining transfer +* : byte count at the time of DMA transfer abort to the argument +* : *remain. +* Arguments : uint32_t * remain : Remaining transfer byte count when +* : : DMA transfer is aborted +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC2_Close (uint32_t * remain) +{ + + /* ==== Abort transfer ==== */ + RZA_IO_RegWrite_32(&DMAC2.CHCTRL_n, + 1, + DMAC2_CHCTRL_n_CLREN_SHIFT, + DMAC2_CHCTRL_n_CLREN); + + while (1 == RZA_IO_RegRead_32(&DMAC2.CHSTAT_n, + DMAC2_CHSTAT_n_TACT_SHIFT, + DMAC2_CHSTAT_n_TACT)) + { + /* Loop until transfer is aborted */ + } + + while (1 == RZA_IO_RegRead_32(&DMAC2.CHSTAT_n, + DMAC2_CHSTAT_n_EN_SHIFT, + DMAC2_CHSTAT_n_EN)) + { + /* Loop until 0 is set in EN before checking the remaining transfer byte count */ + } + /* ==== Obtain remaining transfer byte count ==== */ + *remain = DMAC2.CRTB_n; +} + +/******************************************************************************* +* Function Name: usb0_host_DMAC2_Load_Set +* Description : Sets the transfer source address, transfer destination +* : address, and total transfer byte count respectively +* : specified by the argument src_addr, dst_addr, and count to +* : DMAC channel 2 as DMA transfer information. +* : Sets the register set selected by the CHCFG_n register +* : RSEL bit from the Next0 or Next1 register set. +* : This function should be called when DMA transfer of DMAC +* : channel 2 is aboted. +* Arguments : uint32_t src_addr : Transfer source address +* : uint32_t dst_addr : Transfer destination address +* : uint32_t count : Total transfer byte count +* Return Value : none +*******************************************************************************/ +void usb0_host_DMAC2_Load_Set (uint32_t src_addr, uint32_t dst_addr, uint32_t count) +{ + uint8_t reg_set; + + /* Obtain register set in use */ + reg_set = RZA_IO_RegRead_32(&DMAC2.CHSTAT_n, + DMAC2_CHSTAT_n_SR_SHIFT, + DMAC2_CHSTAT_n_SR); + + /* ==== Load ==== */ + if (0 == reg_set) + { + /* ---- Next0 Register Set ---- */ + DMAC2.N0SA_n = src_addr; /* Start address of transfer source */ + DMAC2.N0DA_n = dst_addr; /* Start address of transfer destination */ + DMAC2.N0TB_n = count; /* Total transfer byte count */ + } + else + { + /* ---- Next1 Register Set ---- */ + DMAC2.N1SA_n = src_addr; /* Start address of transfer source */ + DMAC2.N1DA_n = dst_addr; /* Start address of transfer destination */ + DMAC2.N1TB_n = count; /* Total transfer byte count */ + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb0/src/userdef/usb0_host_userdef.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,778 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb0_host_userdef.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include <stdio.h> +#include "cmsis_os.h" +#include "r_typedefs.h" +#include "iodefine.h" +#include "devdrv_usb_host_api.h" +#include "usb0_host.h" +#include "VKRZA1H.h" /* INTC Driver Header */ +#include "usb0_host_dmacdrv.h" +#include "ohci_wrapp_RZ_A1_local.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define DUMMY_ACCESS OSTM0CNT + +/* #define CACHE_WRITEBACK */ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +extern int32_t io_cwb(unsigned long start, unsigned long end); + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb0_host_enable_dmac0(uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc); +static void usb0_host_enable_dmac1(uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc); +static void Userdef_USB_usb0_host_delay_10us_2(void); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_d0fifo_dmaintid +* Description : get D0FIFO DMA Interrupt ID +* Arguments : none +* Return Value : D0FIFO DMA Interrupt ID +*******************************************************************************/ +uint16_t Userdef_USB_usb0_host_d0fifo_dmaintid (void) +{ +#if(1) /* ohci_wrapp */ + return 0xFFFF; +#else + return DMAINT1_IRQn; +#endif +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_d1fifo_dmaintid +* Description : get D1FIFO DMA Interrupt ID +* Arguments : none +* Return Value : D1FIFO DMA Interrupt ID +*******************************************************************************/ +uint16_t Userdef_USB_usb0_host_d1fifo_dmaintid (void) +{ +#if(1) /* ohci_wrapp */ + return 0xFFFF; +#else + return DMAINT2_IRQn; +#endif +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_attach +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_attach (void) +{ +// printf("\n"); +// printf("channel 0 attach device\n"); +// printf("\n"); + ohciwrapp_loc_Connect(1); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_detach +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_detach (void) +{ +// printf("\n"); +// printf("channel 0 detach device\n"); +// printf("\n"); + ohciwrapp_loc_Connect(0); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_delay_1ms +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_delay_1ms (void) +{ + osDelay(1); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_delay_xms +* Description : Wait for the software in the period of time specified by the +* : argument. +* : Alter this function according to the user's system. +* Arguments : uint32_t msec ; Wait Time (msec) +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_delay_xms (uint32_t msec) +{ + osDelay(msec); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_delay_10us +* Description : Waits for software for the period specified by the argument. +* : Alter this function according to the user's system. +* Arguments : uint32_t usec ; Wait Time(x 10usec) +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_delay_10us (uint32_t usec) +{ + volatile int i; + + /* Wait 10us (Please change for your MCU) */ + for (i = 0; i < usec; ++i) + { + Userdef_USB_usb0_host_delay_10us_2(); + } +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_delay_10us_2 +* Description : Waits for software for the period specified by the argument. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +static void Userdef_USB_usb0_host_delay_10us_2 (void) +{ + volatile int i; + volatile unsigned long tmp; + + /* Wait 1us (Please change for your MCU) */ + for (i = 0; i < 14; ++i) + { + tmp = DUMMY_ACCESS; + } +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_delay_500ns +* Description : Wait for software for 500ns. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_delay_500ns (void) +{ + volatile int i; + volatile unsigned long tmp; + + /* Wait 500ns (Please change for your MCU) */ + /* Wait 500ns I clock 266MHz */ + tmp = DUMMY_ACCESS; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_start_dma +* Description : Enables DMA transfer on the information specified by the argument. +* : Set DMAC register by this function to enable DMA transfer. +* : After executing this function, USB module is set to start DMA +* : transfer. DMA transfer should not wait for DMA transfer complete. +* Arguments : USB_HOST_DMA_t *dma : DMA parameter +* : typedef struct{ +* : uint32_t fifo; FIFO for using +* : uint32_t buffer; Start address of transfer source/destination +* : uint32_t bytes; Transfer size(Byte) +* : uint32_t dir; Transfer direction(0:Buffer->FIFO, 1:FIFO->Buffer) +* : uint32_t size; DMA transfer size +* : } USB_HOST_DMA_t; +* : uint16_t dfacc ; 0 : cycle steal mode +* : 1 : 16byte continuous mode +* : 2 : 32byte continuous mode +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_start_dma (USB_HOST_DMA_t * dma, uint16_t dfacc) +{ + uint32_t trncount; + uint32_t src; + uint32_t dst; + uint32_t size; + uint32_t dir; +#ifdef CACHE_WRITEBACK + uint32_t ptr; +#endif + + trncount = dma->bytes; + dir = dma->dir; + + if (dir == USB_HOST_FIFO2BUF) + { + /* DxFIFO determination */ + dst = dma->buffer; +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB200.D1FIFO.UINT32); + } + size = dma->size; + + if (size == 0) + { + src += 3; /* byte access */ + } + else if (size == 1) + { + src += 2; /* short access */ + } + else + { + /* Do Nothing */ + } +#else + size = dma->size; + + if (size == 2) + { + /* 32bit access */ + if (dfacc == 2) + { + /* 32byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFOB0); + } + else + { + src = (uint32_t)(&USB200.D1FIFOB0); + } + } + else if (dfacc == 1) + { + /* 16byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFOB0); + } + else + { + src = (uint32_t)(&USB200.D1FIFOB0); + } + } + else + { + /* normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB200.D1FIFO.UINT32); + } + } + } + else if (size == 1) + { + /* 16bit access */ + dfacc = 0; /* force normal access */ + + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB200.D1FIFO.UINT32); + } + src += 2; /* short access */ + } + else + { + /* 8bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB200.D1FIFO.UINT32); + } + src += 3; /* byte access */ + } +#endif + } + else + { + /* DxFIFO determination */ + src = dma->buffer; +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB200.D1FIFO.UINT32); + } + size = dma->size; + + if (size == 0) + { + dst += 3; /* byte access */ + } + else if (size == 1) + { + dst += 2; /* short access */ + } + else + { + /* Do Nothing */ + } +#else + size = dma->size; + if (size == 2) + { + /* 32bit access */ + if (dfacc == 2) + { + /* 32byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFOB0); + } + else + { + dst = (uint32_t)(&USB200.D1FIFOB0); + } + } + else if (dfacc == 1) + { + /* 16byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFOB0); + } + else + { + dst = (uint32_t)(&USB200.D1FIFOB0); + } + } + else + { + /* normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB200.D1FIFO.UINT32); + } + } + } + else if (size == 1) + { + /* 16bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB200.D1FIFO.UINT32); + } + dst += 2; /* short access */ + } + else + { + /* 8bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB200.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB200.D1FIFO.UINT32); + } + dst += 3; /* byte access */ + } +#endif + } + +#ifdef CACHE_WRITEBACK + ptr = (uint32_t)dma->buffer; + if ((ptr & 0x20000000ul) == 0) + { + io_cwb((uint32_t)ptr,(uint32_t)(ptr)+trncount); + } +#endif + + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + usb0_host_enable_dmac0(src, dst, trncount, size, dir, dma->fifo, dfacc); + } + else + { + usb0_host_enable_dmac1(src, dst, trncount, size, dir, dma->fifo, dfacc); + } +} + +/******************************************************************************* +* Function Name: usb0_host_enable_dmac0 +* Description : Enables DMA transfer on the information specified by the argument. +* Arguments : uint32_t src : src address +* : uint32_t dst : dst address +* : uint32_t count : transfer byte +* : uint32_t size : transfer size +* : uint32_t dir : direction +* : uint32_t fifo : FIFO(D0FIFO or D1FIFO) +* : uint16_t dfacc : 0 : normal access +* : : 1 : 16byte access +* : : 2 : 32byte access +* Return Value : none +*******************************************************************************/ +static void usb0_host_enable_dmac0 (uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc) +{ + dmac_transinfo_t trans_info; + uint32_t request_factor = 0; + int32_t ret; + + /* ==== Variable setting for DMAC initialization ==== */ + trans_info.src_addr = (uint32_t)src; /* Start address of transfer source */ + trans_info.dst_addr = (uint32_t)dst; /* Start address of transfer destination */ + trans_info.count = (uint32_t)count; /* Total byte count to be transferred */ +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } +#else + if (dfacc == 2) + { + /* 32byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_256; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_256; /* Transfer destination transfer size */ + } + else if (dfacc == 1) + { + /* 16byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_128; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_128; /* Transfer destination transfer size */ + } + else + { + /* normal access */ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } + } +#endif + + if (dir == USB_HOST_FIFO2BUF) + { + request_factor = DMAC_REQ_USB0_DMA0_RX; /* USB_0 channel 0 receive FIFO full */ + trans_info.saddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer destination address */ + } + else if (dir == USB_HOST_BUF2FIFO) + { + request_factor = DMAC_REQ_USB0_DMA0_TX; /* USB_0 channel 0 receive FIFO empty */ + trans_info.saddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer destination address */ + } + else + { + /* Do Nothing */ + } + + /* ==== DMAC initialization ==== */ + usb0_host_DMAC1_PeriReqInit((const dmac_transinfo_t *)&trans_info, + DMAC_MODE_REGISTER, + DMAC_SAMPLE_SINGLE, + request_factor, + 0); /* Don't care DMAC_REQ_REQD is setting in usb0_host_DMAC1_PeriReqInit() */ + + /* ==== DMAC startup ==== */ + ret = usb0_host_DMAC1_Open(DMAC_REQ_MODE_PERI); + + if (ret != 0) + { +// printf("DMAC1 Open error!!\n"); + } + + return; +} + +/******************************************************************************* +* Function Name: usb0_host_enable_dmac1 +* Description : Enables DMA transfer on the information specified by the argument. +* Arguments : uint32_t src : src address +* : uint32_t dst : dst address +* : uint32_t count : transfer byte +* : uint32_t size : transfer size +* : uint32_t dir : direction +* : uint32_t fifo : FIFO(D0FIFO or D1FIFO) +* : uint16_t dfacc : 0 : normal access +* : : 1 : 16byte access +* : : 2 : 32byte access +* Return Value : none +*******************************************************************************/ +static void usb0_host_enable_dmac1 (uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc) +{ + dmac_transinfo_t trans_info; + uint32_t request_factor = 0; + int32_t ret; + + /* ==== Variable setting for DMAC initialization ==== */ + trans_info.src_addr = (uint32_t)src; /* Start address of transfer source */ + trans_info.dst_addr = (uint32_t)dst; /* Start address of transfer destination */ + trans_info.count = (uint32_t)count; /* Total byte count to be transferred */ +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } +#else + if (dfacc == 2) + { + /* 32byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_256; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_256; /* Transfer destination transfer size */ + } + else if (dfacc == 1) + { + /* 16byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_128; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_128; /* Transfer destination transfer size */ + } + else + { + /* normal access */ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } + } +#endif + + if (dir == USB_HOST_FIFO2BUF) + { + request_factor =DMAC_REQ_USB0_DMA1_RX; /* USB_0 channel 0 receive FIFO full */ + trans_info.saddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer destination address */ + } + else if (dir == USB_HOST_BUF2FIFO) + { + request_factor =DMAC_REQ_USB0_DMA1_TX; /* USB_0 channel 0 receive FIFO empty */ + trans_info.saddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer destination address */ + } + else + { + /* Do Nothing */ + } + + /* ==== DMAC initialization ==== */ + usb0_host_DMAC2_PeriReqInit((const dmac_transinfo_t *)&trans_info, + DMAC_MODE_REGISTER, + DMAC_SAMPLE_SINGLE, + request_factor, + 0); /* Don't care DMAC_REQ_REQD is setting in usb0_host_DMAC2_PeriReqInit() */ + + /* ==== DMAC startup ==== */ + ret = usb0_host_DMAC2_Open(DMAC_REQ_MODE_PERI); + + if (ret != 0) + { +// printf("DMAC2 Open error!!\n"); + } + + return; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_stop_dma0 +* Description : Disables DMA transfer. +* Arguments : none +* Return Value : uint32_t return Transfer Counter register(DMATCRn) value +* : regarding to the bus width. +* Notice : This function should be executed to DMAC executed at the time +* : of specification of D0_FIF0_DMA in dma->fifo. +*******************************************************************************/ +uint32_t Userdef_USB_usb0_host_stop_dma0 (void) +{ + uint32_t remain; + + /* ==== DMAC release ==== */ + usb0_host_DMAC1_Close(&remain); + + return remain; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_stop_dma1 +* Description : Disables DMA transfer. +* : This function should be executed to DMAC executed at the time +* : of specification of D1_FIF0_DMA in dma->fifo. +* Arguments : none +* Return Value : uint32_t return Transfer Counter register(DMATCRn) value +* : regarding to the bus width. +*******************************************************************************/ +uint32_t Userdef_USB_usb0_host_stop_dma1 (void) +{ + uint32_t remain; + + /* ==== DMAC release ==== */ + usb0_host_DMAC2_Close(&remain); + + return remain; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_notice +* Description : Notice of USER +* Arguments : const char *format +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_notice (const char * format) +{ +// printf(format); + + return; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb0_host_user_rdy +* Description : This function notify a user and wait for trigger +* Arguments : const char *format +* : uint16_t data +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb0_host_user_rdy (const char * format, uint16_t data) +{ +// printf(format, data); + getchar(); + + return; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/inc/usb1_host.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,156 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB1_HOST_H +#define USB1_HOST_H + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "devdrv_usb_host_api.h" +#include "usb_host.h" + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +extern const uint16_t g_usb1_host_bit_set[]; +extern uint32_t g_usb1_host_data_count[USB_HOST_MAX_PIPE_NO + 1]; +extern uint8_t *g_usb1_host_data_pointer[USB_HOST_MAX_PIPE_NO + 1]; + +extern uint16_t g_usb1_host_PipeIgnore[]; +extern uint16_t g_usb1_host_PipeTbl[]; +extern uint16_t g_usb1_host_pipe_status[]; +extern uint32_t g_usb1_host_PipeDataSize[]; + +extern USB_HOST_DMA_t g_usb1_host_DmaInfo[]; +extern uint16_t g_usb1_host_DmaPipe[]; +extern uint16_t g_usb1_host_DmaBval[]; +extern uint16_t g_usb1_host_DmaStatus[]; + +extern uint16_t g_usb1_host_driver_state; +extern uint16_t g_usb1_host_ConfigNum; +extern uint16_t g_usb1_host_CmdStage; +extern uint16_t g_usb1_host_bchg_flag; +extern uint16_t g_usb1_host_detach_flag; +extern uint16_t g_usb1_host_attach_flag; + +extern uint16_t g_usb1_host_UsbAddress; +extern uint16_t g_usb1_host_setUsbAddress; +extern uint16_t g_usb1_host_default_max_packet[USB_HOST_MAX_DEVICE + 1]; +extern uint16_t g_usb1_host_UsbDeviceSpeed; +extern uint16_t g_usb1_host_SupportUsbDeviceSpeed; + +extern uint16_t g_usb1_host_SavReq; +extern uint16_t g_usb1_host_SavVal; +extern uint16_t g_usb1_host_SavIndx; +extern uint16_t g_usb1_host_SavLen; + +extern uint16_t g_usb1_host_pipecfg[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb1_host_pipebuf[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb1_host_pipemaxp[USB_HOST_MAX_PIPE_NO + 1]; +extern uint16_t g_usb1_host_pipeperi[USB_HOST_MAX_PIPE_NO + 1]; + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +/* ==== common ==== */ +void usb1_host_dma_stop_d0(uint16_t pipe, uint32_t remain); +void usb1_host_dma_stop_d1(uint16_t pipe, uint32_t remain); +uint16_t usb1_host_is_hispeed(void); +uint16_t usb1_host_is_hispeed_enable(void); +uint16_t usb1_host_start_send_transfer(uint16_t pipe, uint32_t size, uint8_t *data); +uint16_t usb1_host_write_buffer(uint16_t pipe); +uint16_t usb1_host_write_buffer_c(uint16_t pipe); +uint16_t usb1_host_write_buffer_d0(uint16_t pipe); +uint16_t usb1_host_write_buffer_d1(uint16_t pipe); +void usb1_host_start_receive_transfer(uint16_t pipe, uint32_t size, uint8_t *data); +uint16_t usb1_host_read_buffer(uint16_t pipe); +uint16_t usb1_host_read_buffer_c(uint16_t pipe); +uint16_t usb1_host_read_buffer_d0(uint16_t pipe); +uint16_t usb1_host_read_buffer_d1(uint16_t pipe); +uint16_t usb1_host_change_fifo_port(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw); +void usb1_host_set_curpipe(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw); +void usb1_host_set_curpipe2(uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw, uint16_t dfacc); +uint16_t usb1_host_get_mbw(uint32_t trncount, uint32_t dtptr); +uint16_t usb1_host_read_dma(uint16_t pipe); +void usb1_host_stop_transfer(uint16_t pipe); +void usb1_host_brdy_int(uint16_t status, uint16_t int_enb); +void usb1_host_nrdy_int(uint16_t status, uint16_t int_enb); +void usb1_host_bemp_int(uint16_t status, uint16_t int_enb); +void usb1_host_setting_interrupt(uint8_t level); +void usb1_host_reset_module(uint16_t clockmode); +uint16_t usb1_host_get_buf_size(uint16_t pipe); +uint16_t usb1_host_get_mxps(uint16_t pipe); +void usb1_host_enable_brdy_int(uint16_t pipe); +void usb1_host_disable_brdy_int(uint16_t pipe); +void usb1_host_clear_brdy_sts(uint16_t pipe); +void usb1_host_enable_bemp_int(uint16_t pipe); +void usb1_host_disable_bemp_int(uint16_t pipe); +void usb1_host_clear_bemp_sts(uint16_t pipe); +void usb1_host_enable_nrdy_int(uint16_t pipe); +void usb1_host_disable_nrdy_int(uint16_t pipe); +void usb1_host_clear_nrdy_sts(uint16_t pipe); +void usb1_host_set_pid_buf(uint16_t pipe); +void usb1_host_set_pid_nak(uint16_t pipe); +void usb1_host_set_pid_stall(uint16_t pipe); +void usb1_host_clear_pid_stall(uint16_t pipe); +uint16_t usb1_host_get_pid(uint16_t pipe); +void usb1_host_set_sqclr(uint16_t pipe); +void usb1_host_set_sqset(uint16_t pipe); +void usb1_host_set_csclr(uint16_t pipe); +void usb1_host_aclrm(uint16_t pipe); +void usb1_host_set_aclrm(uint16_t pipe); +void usb1_host_clr_aclrm(uint16_t pipe); +uint16_t usb1_host_get_sqmon(uint16_t pipe); +uint16_t usb1_host_get_inbuf(uint16_t pipe); + +/* ==== host ==== */ +void usb1_host_init_pipe_status(void); +int32_t usb1_host_CtrlTransStart(uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len, uint8_t *Buf); +void usb1_host_SetupStage(uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len); +void usb1_host_CtrlReadStart(uint32_t Bsize, uint8_t *Table); +uint16_t usb1_host_CtrlWriteStart(uint32_t Bsize, uint8_t *Table); +void usb1_host_StatusStage(void); +void usb1_host_get_devadd(uint16_t addr, uint16_t *devadd); +void usb1_host_set_devadd(uint16_t addr, uint16_t *devadd); +void usb1_host_InitModule(void); +uint16_t usb1_host_CheckAttach(void); +void usb1_host_UsbDetach(void); +void usb1_host_UsbDetach2(void); +void usb1_host_UsbAttach(void); +uint16_t usb1_host_UsbBusReset(void); +int32_t usb1_host_UsbResume(void); +int32_t usb1_host_UsbSuspend(void); +void usb1_host_Enable_DetachINT(void); +void usb1_host_Disable_DetachINT(void); +void usb1_host_UsbStateManager(void); + + +#endif /* USB1_HOST_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/inc/usb1_host_api.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,112 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_api.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB1_HOST_API_H +#define USB1_HOST_API_H + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Variable Externs +*******************************************************************************/ + + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +void usb1_host_interrupt(uint32_t int_sense); +void usb1_host_dma_interrupt_d0fifo(uint32_t int_sense); +void usb1_host_dma_interrupt_d1fifo(uint32_t int_sense); + +uint16_t usb1_api_host_init(uint8_t int_level, uint16_t mode, uint16_t clockmode); +int32_t usb1_api_host_enumeration(uint16_t devadr); +int32_t usb1_api_host_detach(void); +int32_t usb1_api_host_data_in(uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t usb1_api_host_data_out(uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t *data_buf); +int32_t usb1_api_host_control_transfer(uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len, uint8_t *Buf); +int32_t usb1_api_host_set_endpoint(uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t *configdescriptor); +int32_t usb1_api_host_clear_endpoint(USB_HOST_CFG_PIPETBL_t *user_table); +int32_t usb1_api_host_clear_endpoint_pipe(uint16_t pipe_sel, USB_HOST_CFG_PIPETBL_t *user_table); +uint16_t usb1_api_host_SetEndpointTable(uint16_t devadr, USB_HOST_CFG_PIPETBL_t *user_table, uint8_t *Table); +int32_t usb1_api_host_data_count(uint16_t pipe, uint32_t *data_count); + +int32_t usb1_api_host_GetDeviceDescriptor(uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t usb1_api_host_GetConfigDescriptor(uint16_t devadr, uint16_t size, uint8_t *buf); +int32_t usb1_api_host_SetConfig(uint16_t devadr, uint16_t confignum); +int32_t usb1_api_host_SetInterface(uint16_t devadr, uint16_t interface_alt, uint16_t interface_index); +int32_t usb1_api_host_ClearStall(uint16_t devadr, uint16_t ep_dir); +uint16_t usb1_api_host_GetUsbDeviceState(void); + +void usb1_api_host_elt_4_4(void); +void usb1_api_host_elt_4_5(void); +void usb1_api_host_elt_4_6(void); +void usb1_api_host_elt_4_7(void); +void usb1_api_host_elt_4_8(void); +void usb1_api_host_elt_4_9(void); +void usb1_api_host_elt_get_desc(void); + +void usb1_host_EL_ModeInit(void); +void usb1_host_EL_SetUACT(void); +void usb1_host_EL_ClearUACT(void); +void usb1_host_EL_SetTESTMODE(uint16_t mode); +void usb1_host_EL_ClearNRDYSTS(uint16_t pipe); +uint16_t usb1_host_EL_GetINTSTS1(void); +void usb1_host_EL_UsbBusReset(void); +void usb1_host_EL_UsbAttach(void); +void usb1_host_EL_SetupStage(uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len); +void usb1_host_EL_StatusStage(void); +void usb1_host_EL_CtrlReadStart(uint32_t Bsize, uint8_t *Table); +int32_t usb1_host_EL_UsbSuspend(void); +int32_t usb1_host_EL_UsbResume(void); + +#if 0 /* prototype in devdrv_usb_host_api.h */ +uint16_t Userdef_USB_usb1_host_d0fifo_dmaintid(void); +uint16_t Userdef_USB_usb1_host_d1fifo_dmaintid(void); +void Userdef_USB_usb1_host_attach(void); +void Userdef_USB_usb1_host_detach(void); +void Userdef_USB_usb1_host_delay_1ms(void); +void Userdef_USB_usb1_host_delay_xms(uint32_t msec); +void Userdef_USB_usb1_host_delay_10us(uint32_t usec); +void Userdef_USB_usb1_host_delay_500ns(void); +void Userdef_USB_usb1_host_start_dma(USB_HOST_DMA_t *dma, uint16_t dfacc); +uint32_t Userdef_USB_usb1_host_stop_dma0(void); +uint32_t Userdef_USB_usb1_host_stop_dma1(void); +#endif + +#endif /* USB1_HOST_API_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/inc/usb1_host_dmacdrv.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,139 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_dmacdrv.h +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Description : RZ/A1H R7S72100 USB Sample Program +*******************************************************************************/ +#ifndef USB1_HOST_DMACDRV_H +#define USB1_HOST_DMACDRV_H + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ +typedef struct dmac_transinfo +{ + uint32_t src_addr; /* Transfer source address */ + uint32_t dst_addr; /* Transfer destination address */ + uint32_t count; /* Transfer byte count */ + uint32_t src_size; /* Transfer source data size */ + uint32_t dst_size; /* Transfer destination data size */ + uint32_t saddr_dir; /* Transfer source address direction */ + uint32_t daddr_dir; /* Transfer destination address direction */ +} dmac_transinfo_t; + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +/* ==== Transfer specification of the sample program ==== */ +#define DMAC_SAMPLE_SINGLE (0) /* Single transfer */ +#define DMAC_SAMPLE_CONTINUATION (1) /* Continuous transfer (use REN bit) */ + +/* ==== DMA modes ==== */ +#define DMAC_MODE_REGISTER (0) /* Register mode */ +#define DMAC_MODE_LINK (1) /* Link mode */ + +/* ==== Transfer requests ==== */ +#define DMAC_REQ_MODE_EXT (0) /* External request */ +#define DMAC_REQ_MODE_PERI (1) /* On-chip peripheral module request */ +#define DMAC_REQ_MODE_SOFT (2) /* Auto-request (request by software) */ + +/* ==== DMAC transfer sizes ==== */ +#define DMAC_TRANS_SIZE_8 (0) /* 8 bits */ +#define DMAC_TRANS_SIZE_16 (1) /* 16 bits */ +#define DMAC_TRANS_SIZE_32 (2) /* 32 bits */ +#define DMAC_TRANS_SIZE_64 (3) /* 64 bits */ +#define DMAC_TRANS_SIZE_128 (4) /* 128 bits */ +#define DMAC_TRANS_SIZE_256 (5) /* 256 bits */ +#define DMAC_TRANS_SIZE_512 (6) /* 512 bits */ +#define DMAC_TRANS_SIZE_1024 (7) /* 1024 bits */ + +/* ==== Address increment for transferring ==== */ +#define DMAC_TRANS_ADR_NO_INC (1) /* Not increment */ +#define DMAC_TRANS_ADR_INC (0) /* Increment */ + +/* ==== Method for detecting DMA request ==== */ +#define DMAC_REQ_DET_FALL (0) /* Falling edge detection */ +#define DMAC_REQ_DET_RISE (1) /* Rising edge detection */ +#define DMAC_REQ_DET_LOW (2) /* Low level detection */ +#define DMAC_REQ_DET_HIGH (3) /* High level detection */ + +/* ==== Request Direction ==== */ +#define DMAC_REQ_DIR_SRC (0) /* DMAREQ is the source/ DMAACK is active when reading */ +#define DMAC_REQ_DIR_DST (1) /* DMAREQ is the destination/ DMAACK is active when writing */ + +/* ==== Descriptors ==== */ +#define DMAC_DESC_HEADER (0) /* Header */ +#define DMAC_DESC_SRC_ADDR (1) /* Source Address */ +#define DMAC_DESC_DST_ADDR (2) /* Destination Address */ +#define DMAC_DESC_COUNT (3) /* Transaction Byte */ +#define DMAC_DESC_CHCFG (4) /* Channel Confg */ +#define DMAC_DESC_CHITVL (5) /* Channel Interval */ +#define DMAC_DESC_CHEXT (6) /* Channel Extension */ +#define DMAC_DESC_LINK_ADDR (7) /* Link Address */ + +/* ==== On-chip peripheral module requests ===== */ +typedef enum dmac_request_factor +{ + DMAC_REQ_USB0_DMA0_TX, /* USB_0 channel 0 transmit FIFO empty */ + DMAC_REQ_USB0_DMA0_RX, /* USB_0 channel 0 receive FIFO full */ + DMAC_REQ_USB0_DMA1_TX, /* USB_0 channel 1 transmit FIFO empty */ + DMAC_REQ_USB0_DMA1_RX, /* USB_0 channel 1 receive FIFO full */ + DMAC_REQ_USB1_DMA0_TX, /* USB_1 channel 0 transmit FIFO empty */ + DMAC_REQ_USB1_DMA0_RX, /* USB_1 channel 0 receive FIFO full */ + DMAC_REQ_USB1_DMA1_TX, /* USB_1 channel 1 transmit FIFO empty */ + DMAC_REQ_USB1_DMA1_RX, /* USB_1 channel 1 receive FIFO full */ +} dmac_request_factor_t; + + +/******************************************************************************* +Variable Externs +*******************************************************************************/ + + +/******************************************************************************* +Functions Prototypes +*******************************************************************************/ +void usb1_host_DMAC3_PeriReqInit(const dmac_transinfo_t *trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction); +int32_t usb1_host_DMAC3_Open(uint32_t req); +void usb1_host_DMAC3_Close(uint32_t *remain); +void usb1_host_DMAC3_Load_Set(uint32_t src_addr, uint32_t dst_addr, uint32_t count); + +void usb1_host_DMAC4_PeriReqInit(const dmac_transinfo_t *trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction); +int32_t usb1_host_DMAC4_Open(uint32_t req); +void usb1_host_DMAC4_Close(uint32_t *remain); +void usb1_host_DMAC4_Load_Set(uint32_t src_addr, uint32_t dst_addr, uint32_t count); + +#endif /* USB1_HOST_DMACDRV_H */ + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/src/common/usb1_host_dataio.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,2835 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_dataio.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +static uint16_t g_usb1_host_mbw[(USB_HOST_MAX_PIPE_NO + 1)]; + +static void usb1_host_start_receive_trns_c(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb1_host_start_receive_trns_d0(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb1_host_start_receive_trns_d1(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb1_host_start_receive_dma_d0(uint16_t pipe, uint32_t size, uint8_t *data); +static void usb1_host_start_receive_dma_d1(uint16_t pipe, uint32_t size, uint8_t *data); +static uint16_t usb1_host_read_dma_d0(uint16_t pipe); +static uint16_t usb1_host_read_dma_d1(uint16_t pipe); +static uint16_t usb1_host_write_dma_d0(uint16_t pipe); +static uint16_t usb1_host_write_dma_d1(uint16_t pipe); + +static void usb1_host_read_c_fifo(uint16_t pipe, uint16_t count); +static void usb1_host_write_c_fifo(uint16_t Pipe, uint16_t count); +static void usb1_host_read_d0_fifo(uint16_t pipe, uint16_t count); +static void usb1_host_write_d0_fifo(uint16_t pipe, uint16_t count); +static void usb1_host_read_d1_fifo(uint16_t pipe, uint16_t count); +static void usb1_host_write_d1_fifo(uint16_t pipe, uint16_t count); + +static void usb1_host_clear_transaction_counter(uint16_t pipe); +static void usb1_host_set_transaction_counter(uint16_t pipe, uint32_t count); + +static uint32_t usb1_host_com_get_dmasize(uint32_t trncount, uint32_t dtptr); + +static uint16_t usb1_host_set_dfacc_d0(uint16_t mbw, uint32_t count); +static uint16_t usb1_host_set_dfacc_d1(uint16_t mbw, uint32_t count); + + +/******************************************************************************* +* Function Name: usb1_host_start_send_transfer +* Description : Starts the USB data communication using pipe specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data data Address +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_start_send_transfer (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t status; + uint16_t usefifo; + uint16_t mbw; + + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + usb1_host_clear_bemp_sts(pipe); + usb1_host_clear_brdy_sts(pipe); + usb1_host_clear_nrdy_sts(pipe); + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + + usefifo = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + case USB_HOST_D0FIFO_DMA: + usefifo = USB_HOST_D0USE; + break; + + case USB_HOST_D1FIFO_USE: + case USB_HOST_D1FIFO_DMA: + usefifo = USB_HOST_D1USE; + break; + + default: + usefifo = USB_HOST_CUSE; + break; + }; + + usb1_host_set_curpipe(USB_HOST_PIPE0, usefifo, USB_HOST_NO, mbw); + + usb1_host_clear_transaction_counter(pipe); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + status = usb1_host_write_buffer(pipe); + + if (status != USB_HOST_FIFOERROR) + { + usb1_host_set_pid_buf(pipe); + } + + return status; +} + +/******************************************************************************* +* Function Name: usb1_host_write_buffer +* Description : Writes data in the buffer allocated in the pipe specified by +* : the argument. The FIFO for using is set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_write_buffer (uint16_t pipe) +{ + uint16_t status; + uint16_t usefifo; + + g_usb1_host_PipeIgnore[pipe] = 0; + usefifo = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + status = usb1_host_write_buffer_d0(pipe); + break; + + case USB_HOST_D1FIFO_USE: + status = usb1_host_write_buffer_d1(pipe); + break; + + case USB_HOST_D0FIFO_DMA: + status = usb1_host_write_dma_d0(pipe); + break; + + case USB_HOST_D1FIFO_DMA: + status = usb1_host_write_dma_d1(pipe); + break; + + default: + status = usb1_host_write_buffer_c(pipe); + break; + }; + + switch (status) + { + case USB_HOST_WRITING: /* Continue of data write */ + usb1_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + usb1_host_enable_brdy_int(pipe); /* Enable Ready Interrupt */ + break; + + case USB_HOST_WRITEEND: /* End of data write */ + case USB_HOST_WRITESHRT: /* End of data write */ + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + + usb1_host_clear_nrdy_sts(pipe); + usb1_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + + /* for last transfer */ + usb1_host_enable_bemp_int(pipe); /* Enable Empty Interrupt */ + break; + + case USB_HOST_WRITEDMA: /* DMA write */ + usb1_host_clear_nrdy_sts(pipe); + usb1_host_enable_nrdy_int(pipe); /* Error (NORES or STALL) */ + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + usb1_host_disable_bemp_int(pipe); /* Disable Empty Interrupt */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_write_buffer_c +* Description : Writes data in the buffer allocated in the pipe specified in +* : the argument. Writes data by CPU transfer using CFIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_write_buffer_c (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + + if (pipe == USB_HOST_PIPE0) + { + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_CFIFO_WRITE, mbw); + } + else + { + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_NO, mbw); + } + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb1_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb1_host_write_c_fifo(pipe, (uint16_t)count); + + if (g_usb1_host_data_count[pipe] < (uint32_t)size) + { + g_usb1_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB201.CFIFOCTR, + USB_CFIFOCTR_BVAL_SHIFT, + USB_CFIFOCTR_BVAL) == 0) + { + USB201.CFIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb1_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_write_buffer_d0 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by CPU transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_write_buffer_d0 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D0USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb1_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb1_host_write_d0_fifo(pipe, (uint16_t)count); + + if (g_usb1_host_data_count[pipe] < (uint32_t)size) + { + g_usb1_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB201.D0FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + USB201.D0FIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb1_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_write_buffer_d1 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by CPU transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND ; Write end +* : USB_HOST_WRITESHRT ; short data +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_WRITEDMA ; Write DMA +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_write_buffer_d1 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D1USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] <= (uint32_t)size) + { + status = USB_HOST_WRITEEND; /* write continues */ + count = g_usb1_host_data_count[pipe]; + + if (count == 0) + { + status = USB_HOST_WRITESHRT; /* Null Packet is end of write */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + } + else + { + status = USB_HOST_WRITING; /* write continues */ + count = (uint32_t)size; + } + + usb1_host_write_d1_fifo(pipe, (uint16_t)count); + + if (g_usb1_host_data_count[pipe] < (uint32_t)size) + { + g_usb1_host_data_count[pipe] = 0; + + if (RZA_IO_RegRead_16(&USB201.D1FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + USB201.D1FIFOCTR = USB_HOST_BITBVAL; /* Short Packet */ + } + } + else + { + g_usb1_host_data_count[pipe] -= count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_write_dma_d0 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by DMA transfer using D0FIFO. +* : The DMA-ch for using is specified by Userdef_USB_usb1_host_start_dma(). +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND : Write end +* : USB_HOST_WRITESHRT : short data +* : USB_HOST_WRITING : Continue of data write +* : USB_HOST_WRITEDMA : Write DMA +* : USB_HOST_FIFOERROR : FIFO status +*******************************************************************************/ +static uint16_t usb1_host_write_dma_d0 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + count = g_usb1_host_data_count[pipe]; + + if (count != 0) + { + g_usb1_host_DmaPipe[USB_HOST_D0FIFO] = pipe; + + if ((count % size) != 0) + { + g_usb1_host_DmaBval[USB_HOST_D0FIFO] = 1; + } + else + { + g_usb1_host_DmaBval[USB_HOST_D0FIFO] = 0; + } + + dfacc = usb1_host_set_dfacc_d0(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 0; /* 8bit transfer */ + } + + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].fifo = USB_HOST_D0FIFO_DMA; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].dir = USB_HOST_BUF2FIFO; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].buffer = (uint32_t)g_usb1_host_data_pointer[pipe]; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].bytes = count; + + Userdef_USB_usb1_host_start_dma(&g_usb1_host_DmaInfo[USB_HOST_D0FIFO], dfacc); + + usb1_host_set_curpipe2(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw, dfacc); + + RZA_IO_RegWrite_16(&USB201.D0FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + + g_usb1_host_data_count[pipe] = 0; + g_usb1_host_data_pointer[pipe] += count; + + status = USB_HOST_WRITEDMA; /* DMA write */ + } + else + { + if (RZA_IO_RegRead_16(&USB201.D0FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + RZA_IO_RegWrite_16(&USB201.D0FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); /* Short Packet */ + } + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_write_dma_d1 +* Description : Writes data in the buffer allocated in the pipe specified in the argument. +* : Writes data by DMA transfer using D1FIFO. +* : The DMA-ch for using is specified by Userdef_USB_usb1_host_start_dma(). +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_WRITEEND : Write end +* : USB_HOST_WRITESHRT : short data +* : USB_HOST_WRITING : Continue of data write +* : USB_HOST_WRITEDMA : Write DMA +* : USB_HOST_FIFOERROR : FIFO status +*******************************************************************************/ +static uint16_t usb1_host_write_dma_d1 (uint16_t pipe) +{ + uint32_t count; + uint16_t size; + uint16_t buffer; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + count = g_usb1_host_data_count[pipe]; + + if (count != 0) + { + g_usb1_host_DmaPipe[USB_HOST_D1FIFO] = pipe; + + if ((count % size) != 0) + { + g_usb1_host_DmaBval[USB_HOST_D1FIFO] = 1; + } + else + { + g_usb1_host_DmaBval[USB_HOST_D1FIFO] = 0; + } + + dfacc = usb1_host_set_dfacc_d1(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 0; /* 8bit transfer */ + } + + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].fifo = USB_HOST_D1FIFO_DMA; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].dir = USB_HOST_BUF2FIFO; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].buffer = (uint32_t)g_usb1_host_data_pointer[pipe]; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].bytes = count; + + Userdef_USB_usb1_host_start_dma(&g_usb1_host_DmaInfo[USB_HOST_D1FIFO], dfacc); + + usb1_host_set_curpipe2(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw , dfacc); + + RZA_IO_RegWrite_16(&USB201.D1FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + + g_usb1_host_data_count[pipe] = 0; + g_usb1_host_data_pointer[pipe] += count; + + status = USB_HOST_WRITEDMA; /* DMA write */ + } + else + { + if (RZA_IO_RegRead_16(&USB201.D1FIFOCTR, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL) == 0) + { + RZA_IO_RegWrite_16(&USB201.D1FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); /* Short Packet */ + } + status = USB_HOST_WRITESHRT; /* Short Packet is end of write */ + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_transfer +* Description : Starts USB data reception using the pipe specified in the argument. +* : The FIFO for using is set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +void usb1_host_start_receive_transfer (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t usefifo; + + usb1_host_clear_bemp_sts(pipe); + usb1_host_clear_brdy_sts(pipe); + usb1_host_clear_nrdy_sts(pipe); + + usefifo = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + usb1_host_start_receive_trns_d0(pipe, size, data); + break; + + case USB_HOST_D1FIFO_USE: + usb1_host_start_receive_trns_d1(pipe, size, data); + break; + + case USB_HOST_D0FIFO_DMA: + usb1_host_start_receive_dma_d0(pipe, size, data); + break; + + case USB_HOST_D1FIFO_DMA: + usb1_host_start_receive_dma_d1(pipe, size, data); + break; + + default: + usb1_host_start_receive_trns_c(pipe, size, data); + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_trns_c +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using CFIFO. +* : When storing data in the buffer allocated in the pipe specified in the +* : argument, BRDY interrupt is generated to read data +* : in the interrupt. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb1_host_start_receive_trns_c (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb1_host_set_pid_nak(pipe); + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_PipeIgnore[pipe] = 0; + + g_usb1_host_PipeDataSize[pipe] = size; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_CFIFO_READ, mbw); + USB201.CFIFOCTR = USB_HOST_BITBCLR; + + usb1_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + + usb1_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_trns_d0 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, BRDY interrupt is generated to read data in the +* : interrupt. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb1_host_start_receive_trns_d0 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb1_host_set_pid_nak(pipe); + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_PipeIgnore[pipe] = 0; + + g_usb1_host_PipeDataSize[pipe] = size; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, mbw); + + usb1_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + + usb1_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_trns_d1 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using D1FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, BRDY interrupt is generated to read data. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb1_host_start_receive_trns_d1 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb1_host_set_pid_nak(pipe); + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_PipeIgnore[pipe] = 0; + + g_usb1_host_PipeDataSize[pipe] = size; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, mbw); + + usb1_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + + usb1_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_dma_d0 +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by DMA transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, delivered read request to DMAC to read data from +* : the buffer by DMAC. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb1_host_start_receive_dma_d0 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb1_host_set_pid_nak(pipe); + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_PipeIgnore[pipe] = 0; + + g_usb1_host_PipeDataSize[pipe] = 0; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, mbw); + + usb1_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + usb1_host_read_dma(pipe); + + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + } + else + { + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + } + + usb1_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_start_receive_dma_d1 +* Description : Read data from the buffer allocated in the pipe specified in the argument. +* : Reads data by DMA transfer using D0FIFO. +* : This function does not read data from the buffer. +* : When storing data in the buffer allocated in the pipe specified +* : in the argument, delivered read request to DMAC to read data from +* : the buffer by DMAC. +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t size ; Data Size +* : uint8_t *data ; Data Address +* Return Value : none +*******************************************************************************/ +static void usb1_host_start_receive_dma_d1 (uint16_t pipe, uint32_t size, uint8_t * data) +{ + uint16_t mbw; + + usb1_host_set_pid_nak(pipe); + g_usb1_host_data_count[pipe] = size; + g_usb1_host_data_pointer[pipe] = (uint8_t *)data; + g_usb1_host_PipeIgnore[pipe] = 0; + + g_usb1_host_PipeDataSize[pipe] = 0; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_WAIT; + + mbw = usb1_host_get_mbw(size, (uint32_t)data); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, mbw); + + usb1_host_set_transaction_counter(pipe, size); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + usb1_host_read_dma(pipe); + + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + } + else + { + usb1_host_enable_nrdy_int(pipe); + usb1_host_enable_brdy_int(pipe); + } + + usb1_host_set_pid_buf(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_read_buffer +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Uses FIF0 set in the pipe definition table. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_read_buffer (uint16_t pipe) +{ + uint16_t status; + + g_usb1_host_PipeIgnore[pipe] = 0; + + if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_USE) + { + status = usb1_host_read_buffer_d0(pipe); + } + else if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_USE) + { + status = usb1_host_read_buffer_d1(pipe); + } + else + { + status = usb1_host_read_buffer_c(pipe); + } + + switch (status) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb1_host_disable_brdy_int(pipe); + g_usb1_host_PipeDataSize[pipe] -= g_usb1_host_data_count[pipe]; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + break; + + case USB_HOST_READOVER: /* buffer over */ + if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_USE) + { + USB201.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_USE) + { + USB201.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + USB201.CFIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#else + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; +#endif + g_usb1_host_PipeDataSize[pipe] -= g_usb1_host_data_count[pipe]; + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_buffer_c +* Description : Reads data from the buffer allocated in the pipe specified in the argument. +* : Reads data by CPU transfer using CFIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_read_buffer_c (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_CUSE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb1_host_data_count[pipe]; + } + else if (g_usb1_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + } + + if (count == 0) /* 0 length packet */ + { + USB201.CFIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb1_host_read_c_fifo(pipe, (uint16_t)count); + } + + g_usb1_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_buffer_d0 +* Description : Reads data from the buffer allocated in the pipe specified in +* : the argument. +* : Reads data by CPU transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_read_buffer_d0 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t pipebuf_size; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D0USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb1_host_data_count[pipe]; + } + else if (g_usb1_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + else + { + pipebuf_size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + } + } + + if (count == 0) /* 0 length packet */ + { + USB201.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb1_host_read_d0_fifo(pipe, (uint16_t)count); + } + + g_usb1_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_buffer_d1 +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by CPU transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_read_buffer_d1 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t pipebuf_size; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D1USE, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = g_usb1_host_data_count[pipe]; + } + else if (g_usb1_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + usb1_host_set_pid_nak(pipe); /* Set NAK */ + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) !=0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + else + { + pipebuf_size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + usb1_host_set_pid_nak(pipe); /* Set NAK */ + } + } + } + + if (count == 0) /* 0 length packet */ + { + USB201.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + } + else + { + usb1_host_read_d1_fifo(pipe, (uint16_t)count); + } + + g_usb1_host_data_count[pipe] -= count; + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_dma +* Description : Reads data from the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by DMA transfer using D0FIFO or D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +uint16_t usb1_host_read_dma (uint16_t pipe) +{ + uint16_t status; + + g_usb1_host_PipeIgnore[pipe] = 0; + + if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_DMA) + { + status = usb1_host_read_dma_d0(pipe); + } + else + { + status = usb1_host_read_dma_d1(pipe); + } + + switch (status) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READZERO: /* End of data read */ + usb1_host_disable_brdy_int(pipe); + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb1_host_disable_brdy_int(pipe); + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + g_usb1_host_PipeDataSize[pipe] -= g_usb1_host_data_count[pipe]; + } + break; + + case USB_HOST_READOVER: /* buffer over */ + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + g_usb1_host_PipeDataSize[pipe] -= g_usb1_host_data_count[pipe]; + } +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#else + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; +#endif + break; + + case USB_HOST_FIFOERROR: /* FIFO access status */ + default: + usb1_host_disable_brdy_int(pipe); /* Disable Ready Interrupt */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_ERROR; + break; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_dma_d0 +* Description : Writes data in the buffer allocated in the pipe specified +* : in the argument. +* : Reads data by DMA transfer using D0FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +static uint16_t usb1_host_read_dma_d0 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + uint16_t pipebuf_size; + + g_usb1_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_READY; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + count = g_usb1_host_data_count[pipe]; + status = USB_HOST_READING; + } + else + { + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + count = g_usb1_host_data_count[pipe]; + } + else if (g_usb1_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + else + { + pipebuf_size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + } + } + + if (count == 0) /* 0 length packet */ + { + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + USB201.D0FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + status = USB_HOST_READZERO; /* Null Packet receive */ + } + else + { + usb1_host_set_curpipe(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw); + /* transaction counter No set */ + /* FRDY = 1, DTLN = 0 -> BRDY */ + } + } + else + { + dfacc = usb1_host_set_dfacc_d0(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size = 0; /* 8bit transfer */ + } + + g_usb1_host_DmaPipe[USB_HOST_D0FIFO] = pipe; /* not use in read operation */ + g_usb1_host_DmaBval[USB_HOST_D0FIFO] = 0; /* not use in read operation */ + + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].fifo = USB_HOST_D0FIFO_DMA; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].dir = USB_HOST_FIFO2BUF; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].buffer = (uint32_t)g_usb1_host_data_pointer[pipe]; + g_usb1_host_DmaInfo[USB_HOST_D0FIFO].bytes = count; + + if (status == USB_HOST_READING) + { + g_usb1_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_BUSY; + } + else + { + g_usb1_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_BUSYEND; + } + + Userdef_USB_usb1_host_start_dma(&g_usb1_host_DmaInfo[USB_HOST_D0FIFO], dfacc); + + usb1_host_set_curpipe2(pipe, USB_HOST_D0DMA, USB_HOST_NO, mbw , dfacc); + + RZA_IO_RegWrite_16(&USB201.D0FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + g_usb1_host_data_count[pipe] -= count; + g_usb1_host_data_pointer[pipe] += count; + g_usb1_host_PipeDataSize[pipe] += count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_read_dma_d1 +* Description : Reads data from the buffer allocated in the pipe specified in +* : the argument. +* : Reads data by DMA transfer using D1FIFO. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : USB_HOST_READEND ; Read end +* : USB_HOST_READSHRT ; short data +* : USB_HOST_READZERO ; zero data +* : USB_HOST_READING ; Continue of data read +* : USB_HOST_READOVER ; buffer over +* : USB_HOST_FIFOERROR ; FIFO status +*******************************************************************************/ +static uint16_t usb1_host_read_dma_d1 (uint16_t pipe) +{ + uint32_t count; + uint32_t dtln; + uint16_t buffer; + uint16_t mxps; + uint16_t status; + uint16_t mbw; + uint16_t dfacc = 0; + uint16_t pipebuf_size; + + g_usb1_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_READY; + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[pipe], (uint32_t)g_usb1_host_data_pointer[pipe]); + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + count = g_usb1_host_data_count[pipe]; + status = USB_HOST_READING; + } + else + { + buffer = usb1_host_change_fifo_port(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + + if (buffer == USB_HOST_FIFOERROR) /* FIFO access status */ + { + return USB_HOST_FIFOERROR; + } + + dtln = (uint32_t)(buffer & USB_HOST_BITDTLN); + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if (g_usb1_host_data_count[pipe] < dtln) /* Buffer Over ? */ + { + status = USB_HOST_READOVER; + count = g_usb1_host_data_count[pipe]; + } + else if (g_usb1_host_data_count[pipe] == dtln) /* just Receive Size */ + { + status = USB_HOST_READEND; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + else /* continue Receive data */ + { + status = USB_HOST_READING; + count = dtln; + + if (count == 0) + { + status = USB_HOST_READSHRT; /* Null Packet receive */ + } + + if ((count % mxps) != 0) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + else + { + pipebuf_size = usb1_host_get_buf_size(pipe); /* Data buffer size */ + + if (count != pipebuf_size) + { + status = USB_HOST_READSHRT; /* Short Packet receive */ + } + } + } + } + + if (count == 0) /* 0 length packet */ + { + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + USB201.D1FIFOCTR = USB_HOST_BITBCLR; /* Clear BCLR */ + status = USB_HOST_READZERO; /* Null Packet receive */ + } + else + { + usb1_host_set_curpipe(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw); + /* transaction counter No set */ + /* FRDY = 1, DTLN = 0 -> BRDY */ + } + } + else + { + dfacc = usb1_host_set_dfacc_d1(mbw, count); + + if (mbw == USB_HOST_BITMBW_32) + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 2; /* 32bit transfer */ + } + else if (mbw == USB_HOST_BITMBW_16) + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 1; /* 16bit transfer */ + } + else + { + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size = 0; /* 8bit transfer */ + } + + g_usb1_host_DmaPipe[USB_HOST_D1FIFO] = pipe; /* not use in read operation */ + g_usb1_host_DmaBval[USB_HOST_D1FIFO] = 0; /* not use in read operation */ + + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].fifo = USB_HOST_D1FIFO_DMA; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].dir = USB_HOST_FIFO2BUF; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].buffer = (uint32_t)g_usb1_host_data_pointer[pipe]; + g_usb1_host_DmaInfo[USB_HOST_D1FIFO].bytes = count; + + if (status == USB_HOST_READING) + { + g_usb1_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_BUSY; + } + else + { + g_usb1_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_BUSYEND; + } + + Userdef_USB_usb1_host_start_dma(&g_usb1_host_DmaInfo[USB_HOST_D1FIFO], dfacc); + + usb1_host_set_curpipe2(pipe, USB_HOST_D1DMA, USB_HOST_NO, mbw , dfacc); + + RZA_IO_RegWrite_16(&USB201.D1FIFOSEL, + 1, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + g_usb1_host_data_count[pipe] -= count; + g_usb1_host_data_pointer[pipe] += count; + g_usb1_host_PipeDataSize[pipe] += count; + } + + return status; /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_change_fifo_port +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument. After allocating FIF0, waits in the software +* : till the corresponding pipe becomes ready. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* Return Value : USB_HOST_FIFOERROR ; Error +* : Others ; CFIFOCTR/D0FIFOCTR/D1FIFOCTR Register Value +*******************************************************************************/ +uint16_t usb1_host_change_fifo_port (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw) +{ + uint16_t buffer; + uint32_t loop; + volatile uint32_t loop2; + + usb1_host_set_curpipe(pipe, fifosel, isel, mbw); + + for (loop = 0; loop < 4; loop++) + { + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB201.CFIFOCTR; + break; + + case USB_HOST_D0USE: + case USB_HOST_D0DMA: + buffer = USB201.D0FIFOCTR; + break; + + case USB_HOST_D1USE: + case USB_HOST_D1DMA: + buffer = USB201.D1FIFOCTR; + break; + + default: + buffer = 0; + break; + } + + if ((buffer & USB_HOST_BITFRDY) == USB_HOST_BITFRDY) + { + return buffer; + } + + loop2 = 25; + + while (loop2-- > 0) + { + /* wait */ + } + } + + return USB_HOST_FIFOERROR; +} + +/******************************************************************************* +* Function Name: usb1_host_set_curpipe +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* Return Value : none +*******************************************************************************/ +void usb1_host_set_curpipe (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw) +{ + uint16_t buffer; + uint32_t loop; + volatile uint32_t loop2; + + g_usb1_host_mbw[pipe] = mbw; + + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB201.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(~isel & USB_HOST_BITISEL); + USB201.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(isel | pipe | mbw); + USB201.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D0DMA: + case USB_HOST_D0USE: + buffer = USB201.D0FIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + USB201.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB201.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D1DMA: + case USB_HOST_D1USE: + buffer = USB201.D1FIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + USB201.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB201.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + default: + break; + } + + /* Cautions !!! + * Depending on the external bus speed of CPU, you may need to wait for 450ns here. + * For details, please look at the data sheet. */ + loop2 = 100; + + while (loop2-- > 0) + { + /* wait */ + } +} + +/******************************************************************************* +* Function Name: usb1_host_set_curpipe2 +* Description : Allocates FIF0 specified by the argument in the pipe assigned +* : by the argument.(DFACC) +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t fifosel ; Select FIFO +* : uint16_t isel ; FIFO Access Direction +* : uint16_t mbw ; FIFO Port Access Bit Width +* : uint16_t dfacc ; DFACC Access mode +* Return Value : none +*******************************************************************************/ +void usb1_host_set_curpipe2 (uint16_t pipe, uint16_t fifosel, uint16_t isel, uint16_t mbw, uint16_t dfacc) +{ + uint16_t buffer; + uint32_t loop; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + uint32_t dummy; +#endif + volatile uint32_t loop2; + + g_usb1_host_mbw[pipe] = mbw; + + switch (fifosel) + { + case USB_HOST_CUSE: + buffer = USB201.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(~isel & USB_HOST_BITISEL); + USB201.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + + buffer &= (uint16_t)~(USB_HOST_BITISEL | USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(isel | pipe | mbw); + USB201.CFIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.CFIFOSEL & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE)) + == (buffer & (USB_HOST_BITISEL | USB_HOST_BITCURPIPE))) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D0DMA: + case USB_HOST_D0USE: + buffer = USB201.D0FIFOSEL; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + + if (dfacc != 0) + { + buffer |= (uint16_t)(USB_HOST_BITMBW_32); + } +#else + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); +#endif + USB201.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + +#ifdef __USB_HOST_DF_ACC_ENABLE__ + if (dfacc != 0) + { + dummy = USB201.D0FIFO.UINT32; + } +#endif + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB201.D0FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D0FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + case USB_HOST_D1DMA: + case USB_HOST_D1USE: + buffer = USB201.D1FIFOSEL; +#ifdef __USB_HOST_DF_ACC_ENABLE__ + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + + if (dfacc != 0) + { + buffer |= (uint16_t)(USB_HOST_BITMBW_32); + } +#else + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); +#endif + USB201.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + +#ifdef __USB_HOST_DF_ACC_ENABLE__ + if (dfacc != 0) + { + dummy = USB201.D1FIFO.UINT32; + loop = dummy; // avoid warning. + } +#endif + + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE | USB_HOST_BITMBW); + buffer |= (uint16_t)(pipe | mbw); + USB201.D1FIFOSEL = buffer; + + for (loop = 0; loop < 4; loop++) + { + if ((USB201.D1FIFOSEL & USB_HOST_BITCURPIPE) == (buffer & USB_HOST_BITCURPIPE)) + { + break; + } + + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } + } + break; + + default: + break; + } + + /* Cautions !!! + * Depending on the external bus speed of CPU, you may need to wait for 450ns here. + * For details, please look at the data sheet. */ + loop2 = 100; + while (loop2-- > 0) + { + /* wait */ + } +} + +/******************************************************************************* +* Function Name: usb1_host_write_c_fifo +* Description : Writes data in CFIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_write_c_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB201.CFIFO.UINT8[HH] = *g_usb1_host_data_pointer[pipe]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB201.CFIFO.UINT16[H] = *((uint16_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB201.CFIFO.UINT32 = *((uint32_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_read_c_fifo +* Description : Reads data from CFIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_read_c_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb1_host_data_pointer[pipe] = USB201.CFIFO.UINT8[HH]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb1_host_data_pointer[pipe]) = USB201.CFIFO.UINT16[H]; + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb1_host_data_pointer[pipe]) = USB201.CFIFO.UINT32; + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_write_d0_fifo +* Description : Writes data in D0FIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating CFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_write_d0_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB201.D0FIFO.UINT8[HH] = *g_usb1_host_data_pointer[pipe]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB201.D0FIFO.UINT16[H] = *((uint16_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB201.D0FIFO.UINT32 = *((uint32_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_read_d0_fifo +* Description : Reads data from D0FIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating DOFIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb0_host_mbw[]. +* Arguments : uint16_t Pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_read_d0_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb1_host_data_pointer[pipe] = USB201.D0FIFO.UINT8[HH]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb1_host_data_pointer[pipe]) = USB201.D0FIFO.UINT16[H]; + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb1_host_data_pointer[pipe]) = USB201.D0FIFO.UINT32; + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_write_d1_fifo +* Description : Writes data in D1FIFO. +* : Writes data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating D1FIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_write_d1_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + USB201.D1FIFO.UINT8[HH] = *g_usb1_host_data_pointer[pipe]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)(count / 2); even; --even) + { + USB201.D1FIFO.UINT16[H] = *((uint16_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)(count / 4); even; --even) + { + USB201.D1FIFO.UINT32 = *((uint32_t *)g_usb1_host_data_pointer[pipe]); + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_read_d1_fifo +* Description : Reads data from D1FIFO. +* : Reads data by BYTE/WORD/LONG according to access size +* : to the pipe specified by the arguments. +* : Before executing this function, allocating D1FIF0 in the specified pipe +* : should be completed. +* : Before executing this function, access size to the specified pipe +* : should be fixed and set in g_usb1_host_mbw[]. +* Arguments : uint16_t pipe ; Pipe Number +* : uint16_t count ; Data Size(Byte) +* Return Value : none +*******************************************************************************/ +static void usb1_host_read_d1_fifo (uint16_t pipe, uint16_t count) +{ + uint16_t even; + + if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_8) + { + for (even = count; even; --even) + { + *g_usb1_host_data_pointer[pipe] = USB201.D1FIFO.UINT8[HH]; + g_usb1_host_data_pointer[pipe] += 1; + } + } + else if (g_usb1_host_mbw[pipe] == USB_HOST_BITMBW_16) + { + for (even = (uint16_t)((count + 1) / 2); even; --even) + { + *((uint16_t *)g_usb1_host_data_pointer[pipe]) = USB201.D1FIFO.UINT16[H]; + g_usb1_host_data_pointer[pipe] += 2; + } + } + else + { + for (even = (uint16_t)((count + 3) / 4); even; --even) + { + *((uint32_t *)g_usb1_host_data_pointer[pipe]) = USB201.D1FIFO.UINT32; + g_usb1_host_data_pointer[pipe] += 4; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_com_get_dmasize +* Description : Calculates access width of DMA transfer by the argument to + return as the Return Value. +* Arguments : uint32_t trncount : transfer byte +* : uint32_t dtptr : transfer data pointer +* Return Value : DMA transfer size : 0 8bit +* : : 1 16bit +* : : 2 32bit +*******************************************************************************/ +static uint32_t usb1_host_com_get_dmasize (uint32_t trncount, uint32_t dtptr) +{ + uint32_t size; + + if (((trncount & 0x0001) != 0) || ((dtptr & 0x00000001) != 0)) + { + /* When transfer byte count is odd */ + /* or transfer data area is 8-bit alignment */ + size = 0; /* 8bit */ + } + else if (((trncount & 0x0003) != 0) || ((dtptr & 0x00000003) != 0)) + { + /* When the transfer byte count is multiples of 2 */ + /* or the transfer data area is 16-bit alignment */ + size = 1; /* 16bit */ + } + else + { + /* When the transfer byte count is multiples of 4 */ + /* or the transfer data area is 32-bit alignment */ + size = 2; /* 32bit */ + } + + return size; +} + +/******************************************************************************* +* Function Name: usb1_host_get_mbw +* Description : Calculates access width of DMA to return the value set in MBW. +* Arguments : uint32_t trncount : transfer byte +* : uint32_t dtptr : transfer data pointer +* Return Value : FIFO transfer size : USB_HOST_BITMBW_8 8bit +* : : USB_HOST_BITMBW_16 16bit +* : : USB_HOST_BITMBW_32 32bit +*******************************************************************************/ +uint16_t usb1_host_get_mbw (uint32_t trncount, uint32_t dtptr) +{ + uint32_t size; + uint16_t mbw; + + size = usb1_host_com_get_dmasize(trncount, dtptr); + + if (size == 0) + { + /* 8bit */ + mbw = USB_HOST_BITMBW_8; + } + else if (size == 1) + { + /* 16bit */ + mbw = USB_HOST_BITMBW_16; + } + else + { + /* 32bit */ + mbw = USB_HOST_BITMBW_32; + } + + return mbw; +} + +/******************************************************************************* +* Function Name: usb1_host_set_transaction_counter +* Description : Sets transaction counter by the argument(PIPEnTRN). +* : Clears transaction before setting to enable transaction counter setting. +* Arguments : uint16_t pipe ; Pipe number +* : uint32_t bsize : Data transfer size +* Return Value : none +*******************************************************************************/ +static void usb1_host_set_transaction_counter (uint16_t pipe, uint32_t bsize) +{ + uint16_t mxps; + uint16_t cnt; + + if (bsize == 0) + { + return; + } + + mxps = usb1_host_get_mxps(pipe); /* Max Packet Size */ + + if ((bsize % mxps) == 0) + { + cnt = (uint16_t)(bsize / mxps); + } + else + { + cnt = (uint16_t)((bsize / mxps) + 1); + } + + switch (pipe) + { + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE1TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE1TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE2TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE2TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE3TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE3TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE4TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE4TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE5TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE5TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + USB201.PIPE9TRN = cnt; + RZA_IO_RegWrite_16(&USB201.PIPE9TRE, + 1, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_clear_transaction_counter +* Description : Clears the transaction counter by the argument. +* : After executing this function, the transaction counter is invalid. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb1_host_clear_transaction_counter (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE1TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE2TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE3TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE4TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE5TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9TRE, + 0, + USB_PIPEnTRE_TRENB_SHIFT, + USB_PIPEnTRE_TRENB); + RZA_IO_RegWrite_16(&USB201.PIPE9TRE, + 1, + USB_PIPEnTRE_TRCLR_SHIFT, + USB_PIPEnTRE_TRCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_stop_transfer +* Description : Stops the USB transfer in the pipe specified by the argument. +* : After stopping the USB transfer, clears the buffer allocated in +* : the pipe. +* : After executing this function, allocation in FIF0 becomes USB_HOST_PIPE0; +* : invalid. After executing this function, BRDY/NRDY/BEMP interrupt +* : in the corresponding pipe becomes invalid. Sequence bit is also +* : cleared. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_stop_transfer (uint16_t pipe) +{ + uint16_t usefifo; + uint32_t remain; + + usb1_host_set_pid_nak(pipe); + + usefifo = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + switch (usefifo) + { + case USB_HOST_D0FIFO_USE: + usb1_host_clear_transaction_counter(pipe); + USB201.D0FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D1FIFO_USE: + usb1_host_clear_transaction_counter(pipe); + USB201.D1FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D0FIFO_DMA: + remain = Userdef_USB_usb1_host_stop_dma0(); + usb1_host_dma_stop_d0(pipe, remain); + usb1_host_clear_transaction_counter(pipe); + USB201.D0FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + case USB_HOST_D1FIFO_DMA: + remain = Userdef_USB_usb1_host_stop_dma1(); + usb1_host_dma_stop_d1(pipe, remain); + usb1_host_clear_transaction_counter(pipe); + USB201.D1FIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + + default: + usb1_host_clear_transaction_counter(pipe); + USB201.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + break; + } + + /* Interrupt of pipe set is disabled */ + usb1_host_disable_brdy_int(pipe); + usb1_host_disable_nrdy_int(pipe); + usb1_host_disable_bemp_int(pipe); + +#if(1) /* ohci_wrapp */ +#else + usb1_host_aclrm(pipe); +#endif + usb1_host_set_csclr(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_set_dfacc_d0 +* Description : Sets the DFACC setting value in D0FIFO using the transfer size. +* Arguments : uint16_t mbw ; MBW +* : uint16_t count ; data count +* Return Value : DFACC Access mode +*******************************************************************************/ +static uint16_t usb1_host_set_dfacc_d0 (uint16_t mbw, uint32_t count) +{ + uint16_t dfacc = 0; + +#ifndef __USB_HOST_DF_ACC_ENABLE__ + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; +#else + if (mbw == USB_HOST_BITMBW_32) + { + if ((count % 32) == 0) + { + /* 32byte transfer */ + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 2, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 2; + } + else if ((count % 16) == 0) + { + /* 16byte transfer */ + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 1, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 1; + } + else + { + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + } + else if (mbw == USB_HOST_BITMBW_16) + { + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + else + { + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D0FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } +#endif + + return dfacc; +} + +/******************************************************************************* +* Function Name: usb1_host_set_dfacc_d1 +* Description : Sets the DFACC setting value in D0FIFO using the transfer size. +* Arguments : uint16_t mbw ; MBW +* : uint16_t count ; data count +* Return Value : DFACC Access mode +*******************************************************************************/ +static uint16_t usb1_host_set_dfacc_d1 (uint16_t mbw, uint32_t count) +{ + uint16_t dfacc = 0; + +#ifndef __USB_HOST_DF_ACC_ENABLE__ + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; +#else + if (mbw == USB_HOST_BITMBW_32) + { + if ((count % 32) == 0) + { + /* 32byte transfer */ + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 2, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 2; + } + else if ((count % 16) == 0) + { + /* 16byte transfer */ + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 1, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 1; + } + else + { + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + } + else if (mbw == USB_HOST_BITMBW_16) + { + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } + else + { + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + RZA_IO_RegWrite_16(&USB201.D1FBCFG, + 0, + USB_DnFBCFG_TENDE_SHIFT, + USB_DnFBCFG_TENDE); + dfacc = 0; + } +#endif + + return dfacc; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/src/common/usb1_host_dma.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,355 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_dma.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +/* #include "usb1_host_dmacdrv.h" */ + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +static void usb1_host_dmaint(uint16_t fifo); +static void usb1_host_dmaint_buf2fifo(uint16_t pipe); +static void usb1_host_dmaint_fifo2buf(uint16_t pipe); + + +/******************************************************************************* +* Function Name: usb1_host_dma_stop_d0 +* Description : D0FIFO DMA stop +* Arguments : uint16_t pipe : pipe number +* : uint32_t remain : transfer byte +* Return Value : none +*******************************************************************************/ +void usb1_host_dma_stop_d0 (uint16_t pipe, uint32_t remain) +{ + uint16_t dtln; + uint16_t dfacc; + uint16_t buffer; + uint16_t sds_b = 1; + + dfacc = RZA_IO_RegRead_16(&USB201.D0FBCFG, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + if (dfacc == 2) + { + sds_b = 32; + } + else if (dfacc == 1) + { + sds_b = 16; + } + else + { + if (g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size == 2) + { + sds_b = 4; + } + else if (g_usb1_host_DmaInfo[USB_HOST_D0FIFO].size == 1) + { + sds_b = 2; + } + else + { + sds_b = 1; + } + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + if (g_usb1_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + buffer = USB201.D0FIFOCTR; + dtln = (buffer & USB_HOST_BITDTLN); + + if ((dtln % sds_b) != 0) + { + remain += (sds_b - (dtln % sds_b)); + } + g_usb1_host_PipeDataSize[pipe] = (g_usb1_host_data_count[pipe] - remain); + g_usb1_host_data_count[pipe] = remain; + } + } + + RZA_IO_RegWrite_16(&USB201.D0FIFOSEL, + 0, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); +} + +/******************************************************************************* +* Function Name: usb1_host_dma_stop_d1 +* Description : D1FIFO DMA stop +* Arguments : uint16_t pipe : pipe number +* : uint32_t remain : transfer byte +* Return Value : none +*******************************************************************************/ +void usb1_host_dma_stop_d1 (uint16_t pipe, uint32_t remain) +{ + uint16_t dtln; + uint16_t dfacc; + uint16_t buffer; + uint16_t sds_b = 1; + + dfacc = RZA_IO_RegRead_16(&USB201.D1FBCFG, + USB_DnFBCFG_DFACC_SHIFT, + USB_DnFBCFG_DFACC); + if (dfacc == 2) + { + sds_b = 32; + } + else if (dfacc == 1) + { + sds_b = 16; + } + else + { + if (g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size == 2) + { + sds_b = 4; + } + else if (g_usb1_host_DmaInfo[USB_HOST_D1FIFO].size == 1) + { + sds_b = 2; + } + else + { + sds_b = 1; + } + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 1) + { + if (g_usb1_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + buffer = USB201.D1FIFOCTR; + dtln = (buffer & USB_HOST_BITDTLN); + + if ((dtln % sds_b) != 0) + { + remain += (sds_b - (dtln % sds_b)); + } + g_usb1_host_PipeDataSize[pipe] = (g_usb1_host_data_count[pipe] - remain); + g_usb1_host_data_count[pipe] = remain; + } + } + + RZA_IO_RegWrite_16(&USB201.D1FIFOSEL, + 0, + USB_DnFIFOSEL_DREQE_SHIFT, + USB_DnFIFOSEL_DREQE); +} + +/******************************************************************************* +* Function Name: usb1_host_dma_interrupt_d0fifo +* Description : This function is DMA interrupt handler entry. +* : Execute usb1_host_dmaint() after disabling DMA interrupt in this function. +* : Disable DMA interrupt to DMAC executed when USB_HOST_D0FIFO_DMA is +* : specified by dma->fifo. +* : Register this function as DMA complete interrupt. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb1_host_dma_interrupt_d0fifo (uint32_t int_sense) +{ + usb1_host_dmaint(USB_HOST_D0FIFO); + g_usb1_host_DmaStatus[USB_HOST_D0FIFO] = USB_HOST_DMA_READY; +} + +/******************************************************************************* +* Function Name: usb1_host_dma_interrupt_d1fifo +* Description : This function is DMA interrupt handler entry. +* : Execute usb0_host_dmaint() after disabling DMA interrupt in this function. +* : Disable DMA interrupt to DMAC executed when USB_HOST_D1FIFO_DMA is +* : specified by dma->fifo. +* : Register this function as DMA complete interrupt. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb1_host_dma_interrupt_d1fifo (uint32_t int_sense) +{ + usb1_host_dmaint(USB_HOST_D1FIFO); + g_usb1_host_DmaStatus[USB_HOST_D1FIFO] = USB_HOST_DMA_READY; +} + +/******************************************************************************* +* Function Name: usb1_host_dmaint +* Description : This function is DMA transfer end interrupt +* Arguments : uint16_t fifo ; fifo number +* : ; USB_HOST_D0FIFO +* : ; USB_HOST_D1FIFO +* Return Value : none +*******************************************************************************/ +static void usb1_host_dmaint (uint16_t fifo) +{ + uint16_t pipe; + + pipe = g_usb1_host_DmaPipe[fifo]; + + if (g_usb1_host_DmaInfo[fifo].dir == USB_HOST_BUF2FIFO) + { + usb1_host_dmaint_buf2fifo(pipe); + } + else + { + usb1_host_dmaint_fifo2buf(pipe); + } +} + +/******************************************************************************* +* Function Name: usb1_host_dmaint_fifo2buf +* Description : Executes read completion from FIFO by DMAC. +* Arguments : uint16_t pipe : pipe number +* Return Value : none +*******************************************************************************/ +static void usb1_host_dmaint_fifo2buf (uint16_t pipe) +{ + uint32_t remain; + uint16_t useport; + + if (g_usb1_host_pipe_status[pipe] != USB_HOST_PIPE_DONE) + { + useport = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + if (useport == USB_HOST_D0FIFO_DMA) + { + remain = Userdef_USB_usb1_host_stop_dma0(); + usb1_host_dma_stop_d0(pipe, remain); + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + if (g_usb1_host_DmaStatus[USB_HOST_D0FIFO] == USB_HOST_DMA_BUSYEND) + { + USB201.D0FIFOCTR = USB_HOST_BITBCLR; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + else + { + usb1_host_enable_brdy_int(pipe); + } + } + } + else + { + remain = Userdef_USB_usb1_host_stop_dma1(); + usb1_host_dma_stop_d1(pipe, remain); + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + if (g_usb1_host_DmaStatus[USB_HOST_D1FIFO] == USB_HOST_DMA_BUSYEND) + { + USB201.D1FIFOCTR = USB_HOST_BITBCLR; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + else + { + usb1_host_enable_brdy_int(pipe); + } + } + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_dmaint_buf2fifo +* Description : Executes write completion in FIFO by DMAC. +* Arguments : uint16_t pipe : pipe number +* Return Value : none +*******************************************************************************/ +static void usb1_host_dmaint_buf2fifo (uint16_t pipe) +{ + uint16_t useport; + uint32_t remain; + + useport = (uint16_t)(g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE); + + if (useport == USB_HOST_D0FIFO_DMA) + { + remain = Userdef_USB_usb1_host_stop_dma0(); + usb1_host_dma_stop_d0(pipe, remain); + + if (g_usb1_host_DmaBval[USB_HOST_D0FIFO] != 0) + { + RZA_IO_RegWrite_16(&USB201.D0FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); + } + } + else + { + remain = Userdef_USB_usb1_host_stop_dma1(); + usb1_host_dma_stop_d1(pipe, remain); + + if (g_usb1_host_DmaBval[USB_HOST_D1FIFO] != 0) + { + RZA_IO_RegWrite_16(&USB201.D1FIFOCTR, + 1, + USB_DnFIFOCTR_BVAL_SHIFT, + USB_DnFIFOCTR_BVAL); + } + } + + usb1_host_enable_bemp_int(pipe); +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/src/common/usb1_host_intrn.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,285 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_intrn.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#if(1) /* ohci_wrapp */ +#include "ohci_wrapp_RZ_A1_local.h" +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_brdy_int +* Description : Executes BRDY interrupt(USB_HOST_PIPE1-9). +* : According to the pipe that interrupt is generated in, +* : reads/writes buffer allocated in the pipe. +* : This function is executed in the BRDY interrupt handler. +* : This function clears BRDY interrupt status and BEMP interrupt +* : status. +* Arguments : uint16_t status ; BRDYSTS Register Value +* : uint16_t int_enb ; BRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_brdy_int (uint16_t status, uint16_t int_enb) +{ + uint32_t int_sense = 0; + uint16_t pipe; + uint16_t pipebit; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + pipebit = g_usb1_host_bit_set[pipe]; + + if ((status & pipebit) && (int_enb & pipebit)) + { + USB201.BRDYSTS = (uint16_t)~pipebit; + USB201.BEMPSTS = (uint16_t)~pipebit; + + if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D0FIFO_DMA) + { + if (g_usb1_host_DmaStatus[USB_HOST_D0FIFO] != USB_HOST_DMA_READY) + { + usb1_host_dma_interrupt_d0fifo(int_sense); + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + usb1_host_read_dma(pipe); + usb1_host_disable_brdy_int(pipe); + } + else + { + USB201.D0FIFOCTR = USB_HOST_BITBCLR; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + } + else if ((g_usb1_host_PipeTbl[pipe] & USB_HOST_FIFO_USE) == USB_HOST_D1FIFO_DMA) + { + if (g_usb1_host_DmaStatus[USB_HOST_D1FIFO] != USB_HOST_DMA_READY) + { + usb1_host_dma_interrupt_d1fifo(int_sense); + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_BFRE_SHIFT, USB_PIPECFG_BFRE) == 0) + { + usb1_host_read_dma(pipe); + usb1_host_disable_brdy_int(pipe); + } + else + { + USB201.D1FIFOCTR = USB_HOST_BITBCLR; + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; + } + } + else + { + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 0) + { + usb1_host_read_buffer(pipe); + } + else + { + usb1_host_write_buffer(pipe); + } + } +#if(1) /* ohci_wrapp */ + switch (g_usb1_host_pipe_status[pipe]) + { + case USB_HOST_PIPE_DONE: + ohciwrapp_loc_TransEnd(pipe, TD_CC_NOERROR); + break; + case USB_HOST_PIPE_NORES: + case USB_HOST_PIPE_STALL: + case USB_HOST_PIPE_ERROR: + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); + break; + default: + /* Do Nothing */ + break; + } +#endif + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_nrdy_int +* Description : Executes NRDY interrupt(USB_HOST_PIPE1-9). +* : Checks NRDY interrupt cause by PID. When the cause if STALL, +* : regards the pipe state as STALL and ends the processing. +* : Then the cause is not STALL, increments the error count to +* : communicate again. When the error count is 3, determines +* : the pipe state as USB_HOST_PIPE_NORES and ends the processing. +* : This function is executed in the NRDY interrupt handler. +* : This function clears NRDY interrupt status. +* Arguments : uint16_t status ; NRDYSTS Register Value +* : uint16_t int_enb ; NRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_nrdy_int (uint16_t status, uint16_t int_enb) +{ + uint16_t pid; + uint16_t pipe; + uint16_t bitcheck; + + bitcheck = (uint16_t)(status & int_enb); + + USB201.NRDYSTS = (uint16_t)~status; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + if ((bitcheck&g_usb1_host_bit_set[pipe]) == g_usb1_host_bit_set[pipe]) + { + if (RZA_IO_RegRead_16(&USB201.SYSCFG0, + USB_SYSCFG_DCFM_SHIFT, + USB_SYSCFG_DCFM) == 1) + { + if (g_usb1_host_pipe_status[pipe] == USB_HOST_PIPE_WAIT) + { + pid = usb1_host_get_pid(pipe); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_STALL; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); +#endif + } + else + { +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_NORES; + ohciwrapp_loc_TransEnd(pipe, TD_CC_DEVICENOTRESPONDING); +#else + g_usb1_host_PipeIgnore[pipe]++; + + if (g_usb1_host_PipeIgnore[pipe] == 3) + { + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_NORES; + } + else + { + usb1_host_set_pid_buf(pipe); + } +#endif + } + } + } + else + { + /* USB Function */ + } + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_bemp_int +* Description : Executes BEMP interrupt(USB_HOST_PIPE1-9). +* Arguments : uint16_t status ; BEMPSTS Register Value +* : uint16_t int_enb ; BEMPENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_bemp_int (uint16_t status, uint16_t int_enb) +{ + uint16_t pid; + uint16_t pipe; + uint16_t bitcheck; + uint16_t inbuf; + + bitcheck = (uint16_t)(status & int_enb); + + USB201.BEMPSTS = (uint16_t)~status; + + for (pipe = USB_HOST_PIPE1; pipe <= USB_HOST_MAX_PIPE_NO; pipe++) + { + if ((bitcheck&g_usb1_host_bit_set[pipe]) == g_usb1_host_bit_set[pipe]) + { + pid = usb1_host_get_pid(pipe); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_STALL; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_STALL); +#endif + } + else + { + inbuf = usb1_host_get_inbuf(pipe); + + if (inbuf == 0) + { + usb1_host_disable_bemp_int(pipe); + usb1_host_set_pid_nak(pipe); + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_DONE; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(pipe, TD_CC_NOERROR); +#endif + } + } + } + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/src/common/usb1_host_lib.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,1598 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_lib.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#if(1) /* ohci_wrapp */ +#include "VKRZA1H.h" /* INTC Driver Header */ +#else +#include "devdrv_intc.h" /* INTC Driver Header */ +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_enable_brdy_int +* Description : Enables BRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : BRDY. Enables BRDY interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_enable_brdy_int (uint16_t pipe) +{ + /* enable brdy interrupt */ + USB201.BRDYENB |= (uint16_t)g_usb1_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb1_host_disable_brdy_int +* Description : Disables BRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : BRDY. Enables BRDY interrupt in the pipe specified by the argument +* : in the disabled status. After disabling BRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_disable_brdy_int (uint16_t pipe) +{ + /* disable brdy interrupt */ + USB201.BRDYENB &= (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_clear_brdy_sts +* Description : Clear BRDY interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_clear_brdy_sts (uint16_t pipe) +{ + /* clear brdy status */ + USB201.BRDYSTS = (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_enable_bemp_int +* Description : Enables BEMP interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : BEMP. Enables BEMP interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BEMP, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_enable_bemp_int (uint16_t pipe) +{ + /* enable bemp interrupt */ + USB201.BEMPENB |= (uint16_t)g_usb1_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb1_host_disable_bemp_int +* Description : Disables BEMP interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : BEMP. Enables BEMP interrupt in the pipe specified by the argument +* : in the disabled status. After enabling BEMP, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_disable_bemp_int (uint16_t pipe) +{ + /* disable bemp interrupt */ + USB201.BEMPENB &= (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_clear_bemp_sts +* Description : Clear BEMP interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_clear_bemp_sts (uint16_t pipe) +{ + /* clear bemp status */ + USB201.BEMPSTS = (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_enable_nrdy_int +* Description : Enables NRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before enabling +* : NRDY. Enables NRDY interrupt in the pipe specified by the argument +* : in the disabled status. After enabling NRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_enable_nrdy_int (uint16_t pipe) +{ + /* enable nrdy interrupt */ + USB201.NRDYENB |= (uint16_t)g_usb1_host_bit_set[pipe]; +} + +/******************************************************************************* +* Function Name: usb1_host_disable_nrdy_int +* Description : Disables NRDY interrupt in the pipe spceified by the argument. +* : Disables BEMP/NRDY/BRDY interrupts in all pipes before disabling +* : NRDY. Disables NRDY interrupt in the pipe specified by the argument +* : in the disabled status. After disabling NRDY, recover all +* : BEMP/NRDY/BRDY disabled/enabled status. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_disable_nrdy_int (uint16_t pipe) +{ + /* disable nrdy interrupt */ + USB201.NRDYENB &= (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_clear_nrdy_sts +* Description : Clear NRDY interrupt status in the pipe spceified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_clear_nrdy_sts (uint16_t pipe) +{ + /* clear nrdy status */ + USB201.NRDYSTS = (uint16_t)~(g_usb1_host_bit_set[pipe]); +} + +/******************************************************************************* +* Function Name: usb1_host_is_hispeed +* Description : Returns the result of USB reset hand shake (RHST) as +* : return value. +* Arguments : none +* Return Value : USB_HOST_HIGH_SPEED ; Hi-Speed +* : USB_HOST_FULL_SPEED ; Full-Speed +* : USB_HOST_LOW_SPEED ; Low-Speed +* : USB_HOST_NON_SPEED ; error +*******************************************************************************/ +uint16_t usb1_host_is_hispeed (void) +{ + uint16_t rhst; + uint16_t speed; + + rhst = RZA_IO_RegRead_16(&USB201.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (rhst == USB_HOST_HSMODE) + { + speed = USB_HOST_HIGH_SPEED; + } + else if (rhst == USB_HOST_FSMODE) + { + speed = USB_HOST_FULL_SPEED; + } + else if (rhst == USB_HOST_LSMODE) + { + speed = USB_HOST_LOW_SPEED; + } + else + { + speed = USB_HOST_NON_SPEED; + } + + return speed; +} + +/******************************************************************************* +* Function Name: usb1_host_is_hispeed_enable +* Description : Returns the USB High-Speed connection enabled status as +* : return value. +* Arguments : none +* Return Value : USB_HOST_YES : Hi-Speed Enable +* : USB_HOST_NO : Hi-Speed Disable +*******************************************************************************/ +uint16_t usb1_host_is_hispeed_enable (void) +{ + uint16_t ret; + + ret = USB_HOST_NO; + + if (RZA_IO_RegRead_16(&USB201.SYSCFG0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE) == 1) + { + ret = USB_HOST_YES; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_host_set_pid_buf +* Description : Enables communicaqtion in the pipe specified by the argument +* : (BUF). +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_pid_buf (uint16_t pipe) +{ + uint16_t pid; + + pid = usb1_host_get_pid(pipe); + + if (pid == USB_HOST_PID_STALL2) + { + usb1_host_set_pid_nak(pipe); + } + + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + USB_HOST_PID_BUF, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + USB_HOST_PID_BUF, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_set_pid_nak +* Description : Disables communication (NAK) in the pipe specified by the argument. +* : When the pipe status was enabling communication (BUF) before +* : executing before executing this function, waits in the software +* : until the pipe becomes ready after setting disabled. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_pid_nak (uint16_t pipe) +{ + uint16_t pid; + uint16_t pbusy; + uint32_t loop; + + pid = usb1_host_get_pid(pipe); + + if (pid == USB_HOST_PID_STALL2) + { + usb1_host_set_pid_stall(pipe); + } + + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + USB_HOST_PID_NAK, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + USB_HOST_PID_NAK, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + + if (pid == USB_HOST_PID_BUF) + { + for (loop = 0; loop < 200; loop++) + { + switch (pipe) + { + case USB_HOST_PIPE0: + pbusy = RZA_IO_RegRead_16(&USB201.DCPCTR, + USB_DCPCTR_PBUSY_SHIFT, + USB_DCPCTR_PBUSY); + break; + + case USB_HOST_PIPE1: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE1CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE2: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE2CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE3: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE3CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE4: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE4CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE5: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE5CTR, + USB_PIPEnCTR_1_5_PBUSY_SHIFT, + USB_PIPEnCTR_1_5_PBUSY); + break; + + case USB_HOST_PIPE6: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE6CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE7: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE7CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE8: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE8CTR, + USB_PIPEnCTR_6_8_PBUSY_SHIFT, + USB_PIPEnCTR_6_8_PBUSY); + break; + + case USB_HOST_PIPE9: + pbusy = RZA_IO_RegRead_16(&USB201.PIPE9CTR, + USB_PIPEnCTR_9_PBUSY_SHIFT, + USB_PIPEnCTR_9_PBUSY); + break; + + default: + pbusy = 1; + break; + } + + if (pbusy == 0) + { + break; + } + + Userdef_USB_usb1_host_delay_500ns(); + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_set_pid_stall +* Description : Disables communication (STALL) in the pipe specified by the +* : argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_pid_stall (uint16_t pipe) +{ + uint16_t pid; + + pid = usb1_host_get_pid(pipe); + + if (pid == USB_HOST_PID_BUF) + { + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + USB_HOST_PID_STALL2, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + USB_HOST_PID_STALL2, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + } + else + { + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + USB_HOST_PID_STALL, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + USB_HOST_PID_STALL, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + break; + } + } +} + +/******************************************************************************* +* Function Name: usb1_host_clear_pid_stall +* Description : Disables communication (NAK) in the pipe specified by the argument. +* Arguments : uint16_t pipe ; pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_clear_pid_stall (uint16_t pipe) +{ + usb1_host_set_pid_nak(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_get_pid +* Description : Returns the pipe state specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : PID +*******************************************************************************/ +uint16_t usb1_host_get_pid (uint16_t pipe) +{ + uint16_t pid; + + switch (pipe) + { + case USB_HOST_PIPE0: + pid = RZA_IO_RegRead_16(&USB201.DCPCTR, + USB_DCPCTR_PID_SHIFT, + USB_DCPCTR_PID); + break; + + case USB_HOST_PIPE1: + pid = RZA_IO_RegRead_16(&USB201.PIPE1CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE2: + pid = RZA_IO_RegRead_16(&USB201.PIPE2CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE3: + pid = RZA_IO_RegRead_16(&USB201.PIPE3CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE4: + pid = RZA_IO_RegRead_16(&USB201.PIPE4CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE5: + pid = RZA_IO_RegRead_16(&USB201.PIPE5CTR, + USB_PIPEnCTR_1_5_PID_SHIFT, + USB_PIPEnCTR_1_5_PID); + break; + + case USB_HOST_PIPE6: + pid = RZA_IO_RegRead_16(&USB201.PIPE6CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE7: + pid = RZA_IO_RegRead_16(&USB201.PIPE7CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE8: + pid = RZA_IO_RegRead_16(&USB201.PIPE8CTR, + USB_PIPEnCTR_6_8_PID_SHIFT, + USB_PIPEnCTR_6_8_PID); + break; + + case USB_HOST_PIPE9: + pid = RZA_IO_RegRead_16(&USB201.PIPE9CTR, + USB_PIPEnCTR_9_PID_SHIFT, + USB_PIPEnCTR_9_PID); + break; + + default: + pid = 0; + break; + } + + return pid; +} + +/******************************************************************************* +* Function Name: usb1_host_set_csclr +* Description : CSPLIT status clear setting of sprit transaction in specified +* : pipe is performed. +* : When SQSET bit or SQCLR bit, and SQSET bit or SQCLR bit +* : in DCPCTR register are continuously changed (when the sequence +* : toggle bit of data PID is continuously changed over two or more pipes), +* : the access cycle with 120 ns and more than 5 cycle bus clock is necessary. +* : Do not set both SQCLR bit and SQSET bit to 1 at the same time. +* : In addition, both bits should be operated after PID is set to NAK. +* : However, when it is set to the isochronous transfer as the transfer type +* : (TYPE=11), writing in SQSET bit is disabled. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_csclr (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + 1, + USB_DCPCTR_CSCLR_SHIFT, + USB_DCPCTR_CSCLR); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_CSCLR_SHIFT, + USB_PIPEnCTR_1_5_CSCLR); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_CSCLR_SHIFT, + USB_PIPEnCTR_6_8_CSCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + 1, + USB_PIPEnCTR_9_CSCLR_SHIFT, + USB_PIPEnCTR_9_CSCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_set_sqclr +* Description : Sets the sequence bit of the pipe specified by the argument to +* : DATA0. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_sqclr (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + 1, + USB_DCPCTR_SQCLR_SHIFT, + USB_DCPCTR_SQCLR); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_SQCLR_SHIFT, + USB_PIPEnCTR_1_5_SQCLR); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_SQCLR_SHIFT, + USB_PIPEnCTR_6_8_SQCLR); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + 1, + USB_PIPEnCTR_9_SQCLR_SHIFT, + USB_PIPEnCTR_9_SQCLR); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_set_sqset +* Description : Sets the sequence bit of the pipe specified by the argument to +* : DATA1. +* Arguments : uint16_t pipe ; Pipe number +* Return Value : none +*******************************************************************************/ +void usb1_host_set_sqset (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + RZA_IO_RegWrite_16(&USB201.DCPCTR, + 1, + USB_DCPCTR_SQSET_SHIFT, + USB_DCPCTR_SQSET); + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_SQSET_SHIFT, + USB_PIPEnCTR_1_5_SQSET); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_SQSET_SHIFT, + USB_PIPEnCTR_6_8_SQSET); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + 1, + USB_PIPEnCTR_9_SQSET_SHIFT, + USB_PIPEnCTR_9_SQSET); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_get_sqmon +* Description : Toggle bit of specified pipe is obtained +* Arguments : uint16_t pipe ; Pipe number +* Return Value : sqmon +*******************************************************************************/ +uint16_t usb1_host_get_sqmon (uint16_t pipe) +{ + uint16_t sqmon; + + switch (pipe) + { + case USB_HOST_PIPE0: + sqmon = RZA_IO_RegRead_16(&USB201.DCPCTR, + USB_DCPCTR_SQMON_SHIFT, + USB_DCPCTR_SQMON); + break; + + case USB_HOST_PIPE1: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE1CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE2: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE2CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE3: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE3CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE4: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE4CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE5: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE5CTR, + USB_PIPEnCTR_1_5_SQMON_SHIFT, + USB_PIPEnCTR_1_5_SQMON); + break; + + case USB_HOST_PIPE6: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE6CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE7: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE7CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE8: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE8CTR, + USB_PIPEnCTR_6_8_SQMON_SHIFT, + USB_PIPEnCTR_6_8_SQMON); + break; + + case USB_HOST_PIPE9: + sqmon = RZA_IO_RegRead_16(&USB201.PIPE9CTR, + USB_PIPEnCTR_9_SQMON_SHIFT, + USB_PIPEnCTR_9_SQMON); + break; + + default: + sqmon = 0; + break; + } + + return sqmon; +} + +/******************************************************************************* +* Function Name: usb1_host_aclrm +* Description : The buffer of specified pipe is initialized +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb1_host_aclrm (uint16_t pipe) +{ + usb1_host_set_aclrm(pipe); + usb1_host_clr_aclrm(pipe); +} + +/******************************************************************************* +* Function Name: usb1_host_set_aclrm +* Description : The auto buffer clear mode of specified pipe is enabled +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb1_host_set_aclrm (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + 1, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + 1, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + 1, + USB_PIPEnCTR_9_ACLRM_SHIFT, + USB_PIPEnCTR_9_ACLRM); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_clr_aclrm +* Description : The auto buffer clear mode of specified pipe is enabled +* Arguments : uint16_t pipe : Pipe +* Return Value : none +*******************************************************************************/ +void usb1_host_clr_aclrm (uint16_t pipe) +{ + switch (pipe) + { + case USB_HOST_PIPE0: + break; + + case USB_HOST_PIPE1: + RZA_IO_RegWrite_16(&USB201.PIPE1CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE2: + RZA_IO_RegWrite_16(&USB201.PIPE2CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE3: + RZA_IO_RegWrite_16(&USB201.PIPE3CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE4: + RZA_IO_RegWrite_16(&USB201.PIPE4CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE5: + RZA_IO_RegWrite_16(&USB201.PIPE5CTR, + 0, + USB_PIPEnCTR_1_5_ACLRM_SHIFT, + USB_PIPEnCTR_1_5_ACLRM); + break; + + case USB_HOST_PIPE6: + RZA_IO_RegWrite_16(&USB201.PIPE6CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE7: + RZA_IO_RegWrite_16(&USB201.PIPE7CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE8: + RZA_IO_RegWrite_16(&USB201.PIPE8CTR, + 0, + USB_PIPEnCTR_6_8_ACLRM_SHIFT, + USB_PIPEnCTR_6_8_ACLRM); + break; + + case USB_HOST_PIPE9: + RZA_IO_RegWrite_16(&USB201.PIPE9CTR, + 0, + USB_PIPEnCTR_9_ACLRM_SHIFT, + USB_PIPEnCTR_9_ACLRM); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_get_inbuf +* Description : Returns INBUFM of the pipe specified by the argument. +* Arguments : uint16_t pipe ; Pipe Number +* Return Value : inbuf +*******************************************************************************/ +uint16_t usb1_host_get_inbuf (uint16_t pipe) +{ + uint16_t inbuf; + + switch (pipe) + { + case USB_HOST_PIPE0: + inbuf = 0; + break; + + case USB_HOST_PIPE1: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE1CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE2: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE2CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE3: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE3CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE4: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE4CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE5: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE5CTR, + USB_PIPEnCTR_1_5_INBUFM_SHIFT, + USB_PIPEnCTR_1_5_INBUFM); + break; + + case USB_HOST_PIPE6: + inbuf = 0; + break; + + case USB_HOST_PIPE7: + inbuf = 0; + break; + + case USB_HOST_PIPE8: + inbuf = 0; + break; + + case USB_HOST_PIPE9: + inbuf = RZA_IO_RegRead_16(&USB201.PIPE9CTR, + USB_PIPEnCTR_9_INBUFM_SHIFT, + USB_PIPEnCTR_9_INBUFM); + break; + + default: + inbuf = 0; + break; + } + + return inbuf; +} + +/******************************************************************************* +* Function Name: usb1_host_setting_interrupt +* Description : Sets the USB module interrupt level. +* Arguments : uint8_t level ; interrupt level +* Return Value : none +*******************************************************************************/ +void usb1_host_setting_interrupt (uint8_t level) +{ +#if(1) /* ohci_wrapp */ + IRQn_Type d0fifo_dmaintid; + IRQn_Type d1fifo_dmaintid; + + InterruptHandlerRegister(USBI1_IRQn, usb1_host_interrupt); + GIC_SetPriority(USBI1_IRQn, level); + GIC_EnableIRQ(USBI1_IRQn); + + d0fifo_dmaintid = (IRQn_Type)Userdef_USB_usb1_host_d0fifo_dmaintid(); + + if (d0fifo_dmaintid != 0xFFFF) + { + InterruptHandlerRegister(d0fifo_dmaintid, usb1_host_dma_interrupt_d0fifo); + GIC_SetPriority(d0fifo_dmaintid, level); + GIC_EnableIRQ(d0fifo_dmaintid); + } + + d1fifo_dmaintid = (IRQn_Type)Userdef_USB_usb1_host_d1fifo_dmaintid(); + + if (d1fifo_dmaintid != 0xFFFF) + { + InterruptHandlerRegister(d1fifo_dmaintid, usb1_host_dma_interrupt_d1fifo); + GIC_SetPriority(d1fifo_dmaintid, level); + GIC_EnableIRQ(d1fifo_dmaintid); + } +#else + uint16_t d0fifo_dmaintid; + uint16_t d1fifo_dmaintid; + + R_INTC_RegistIntFunc(INTC_ID_USBI1, usb1_host_interrupt); + R_INTC_SetPriority(INTC_ID_USBI1, level); + R_INTC_Enable(INTC_ID_USBI1); + + d0fifo_dmaintid = Userdef_USB_usb1_host_d0fifo_dmaintid(); + + if (d0fifo_dmaintid != 0xFFFF) + { + R_INTC_RegistIntFunc(d0fifo_dmaintid, usb1_host_dma_interrupt_d0fifo); + R_INTC_SetPriority(d0fifo_dmaintid, level); + R_INTC_Enable(d0fifo_dmaintid); + } + + d1fifo_dmaintid = Userdef_USB_usb1_host_d1fifo_dmaintid(); + + if (d1fifo_dmaintid != 0xFFFF) + { + R_INTC_RegistIntFunc(d1fifo_dmaintid, usb1_host_dma_interrupt_d1fifo); + R_INTC_SetPriority(d1fifo_dmaintid, level); + R_INTC_Enable(d1fifo_dmaintid); + } +#endif +} + +/******************************************************************************* +* Function Name: usb1_host_reset_module +* Description : Initializes the USB module. +* : Enables providing clock to the USB module. +* : Sets USB bus wait register. +* Arguments : uint16_t clockmode ; 48MHz ; USBHCLOCK_X1_48MHZ +* : ; 12MHz ; USBHCLOCK_EXTAL_12MHZ +* Return Value : none +*******************************************************************************/ +void usb1_host_reset_module (uint16_t clockmode) +{ + if (RZA_IO_RegRead_16(&USB200.SYSCFG0, + USB_SYSCFG_UPLLE_SHIFT, + USB_SYSCFG_UPLLE) == 1) + { + if ((USB200.SYSCFG0 & USB_HOST_BITUCKSEL) != clockmode) + { + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + USB201.SYSCFG0 = 0; + USB200.SYSCFG0 = 0; + USB200.SYSCFG0 = (USB_HOST_BITUPLLE | clockmode); + Userdef_USB_usb1_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + else + { + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + Userdef_USB_usb1_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + } + else + { + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 0, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + USB201.SYSCFG0 = 0; + USB200.SYSCFG0 = 0; + USB200.SYSCFG0 = (USB_HOST_BITUPLLE | clockmode); + Userdef_USB_usb1_host_delay_xms(1); + RZA_IO_RegWrite_16(&USB200.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + RZA_IO_RegWrite_16(&USB201.SUSPMODE, + 1, + USB_SUSPMODE_SUSPM_SHIFT, + USB_SUSPMODE_SUSPM); + } + + USB201.BUSWAIT = (uint16_t)(USB_HOST_BUSWAIT_05 & USB_HOST_BITBWAIT); +} + +/******************************************************************************* +* Function Name: usb1_host_get_buf_size +* Description : Obtains pipe buffer size specified by the argument and +* : maximum packet size of the USB device in use. +* : When USB_HOST_PIPE0 is specified by the argument, obtains the maximum +* : packet size of the USB device using the corresponding pipe. +* : For the case that USB_HOST_PIPE0 is not assigned by the argument, when the +* : corresponding pipe is in continuous transfer mode, +* : obtains the buffer size allocated in the corresponcing pipe, +* : when incontinuous transfer, obtains maximum packet size. +* Arguments : uint16_t ; pipe Number +* Return Value : Maximum packet size or buffer size +*******************************************************************************/ +uint16_t usb1_host_get_buf_size (uint16_t pipe) +{ + uint16_t size; + uint16_t bufsize; + + if (pipe == USB_HOST_PIPE0) + { + size = RZA_IO_RegRead_16(&USB201.DCPMAXP, + USB_DCPMAXP_MXPS_SHIFT, + USB_DCPMAXP_MXPS); + } + else + { + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[pipe], USB_PIPECFG_CNTMD_SHIFT, USB_PIPECFG_CNTMD) == 1) + { + bufsize = RZA_IO_RegRead_16(&g_usb1_host_pipebuf[pipe], USB_PIPEBUF_BUFSIZE_SHIFT, USB_PIPEBUF_BUFSIZE); + size = (uint16_t)((bufsize + 1) * USB_HOST_PIPExBUF); + } + else + { + size = RZA_IO_RegRead_16(&g_usb1_host_pipemaxp[pipe], USB_PIPEMAXP_MXPS_SHIFT, USB_PIPEMAXP_MXPS); + } + } + return size; +} + +/******************************************************************************* +* Function Name: usb1_host_get_mxps +* Description : Obtains maximum packet size of the USB device using the pipe +* : specified by the argument. +* Arguments : uint16_t ; Pipe Number +* Return Value : Max Packet Size +*******************************************************************************/ +uint16_t usb1_host_get_mxps (uint16_t pipe) +{ + uint16_t size; + + if (pipe == USB_HOST_PIPE0) + { + size = RZA_IO_RegRead_16(&USB201.DCPMAXP, + USB_DCPMAXP_MXPS_SHIFT, + USB_DCPMAXP_MXPS); + } + else + { + size = RZA_IO_RegRead_16(&g_usb1_host_pipemaxp[pipe], USB_PIPEMAXP_MXPS_SHIFT, USB_PIPEMAXP_MXPS); + } + + return size; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/src/host/usb1_host_controlrw.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,434 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_controlrw.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_CtrlTransStart +* Description : Executes USB control transfer. +* Arguments : uint16_t devadr ; device address +* : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* : uint8_t *Buf ; Data buffer +* Return Value : DEVDRV_SUCCESS ; SUCCESS +* : DEVDRV_ERROR ; ERROR +*******************************************************************************/ +int32_t usb1_host_CtrlTransStart (uint16_t devadr, uint16_t Req, uint16_t Val, + uint16_t Indx, uint16_t Len, uint8_t * Buf) +{ + if (g_usb1_host_UsbDeviceSpeed == USB_HOST_LOW_SPEED) + { + RZA_IO_RegWrite_16(&USB201.SOFCFG, + 1, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + else + { + RZA_IO_RegWrite_16(&USB201.SOFCFG, + 0, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + + USB201.DCPMAXP = (uint16_t)((uint16_t)(devadr << 12) + g_usb1_host_default_max_packet[devadr]); + + if (g_usb1_host_pipe_status[USB_HOST_PIPE0] == USB_HOST_PIPE_IDLE) + { + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_WAIT; + g_usb1_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + g_usb1_host_CmdStage = (USB_HOST_STAGE_SETUP | USB_HOST_CMD_IDLE); + + if (Len == 0) + { + g_usb1_host_CmdStage |= USB_HOST_MODE_NO_DATA; /* No-data Control */ + } + else + { + if ((Req & 0x0080) != 0) + { + g_usb1_host_CmdStage |= USB_HOST_MODE_READ; /* Control Read */ + } + else + { + g_usb1_host_CmdStage |= USB_HOST_MODE_WRITE; /* Control Write */ + } + } + + g_usb1_host_SavReq = Req; /* save request */ + g_usb1_host_SavVal = Val; + g_usb1_host_SavIndx = Indx; + g_usb1_host_SavLen = Len; + } + else + { + if ((g_usb1_host_SavReq != Req) || (g_usb1_host_SavVal != Val) + || (g_usb1_host_SavIndx != Indx) || (g_usb1_host_SavLen != Len)) + { + return DEVDRV_ERROR; + } + } + + switch ((g_usb1_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + /* --------------- SETUP STAGE --------------- */ + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_IDLE): + usb1_host_SetupStage(Req, Val, Indx, Len); + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_DONE): /* goto next stage */ + g_usb1_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + switch ((g_usb1_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_WRITE: + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_DATA; + break; + + case USB_HOST_MODE_READ: + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_DATA; + break; + + case USB_HOST_MODE_NO_DATA: + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_STATUS; + break; + + default: + break; + } + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + case (USB_HOST_STAGE_SETUP | USB_HOST_CMD_NORES): + if (g_usb1_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb1_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_IDLE; + } + break; + + /* --------------- DATA STAGE --------------- */ + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_IDLE): + switch ((g_usb1_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_WRITE: + usb1_host_CtrlWriteStart((uint32_t)Len, Buf); + break; + + case USB_HOST_MODE_READ: + usb1_host_CtrlReadStart((uint32_t)Len, Buf); + break; + + default: + break; + } + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DONE): /* goto next stage */ + g_usb1_host_PipeIgnore[USB_HOST_PIPE0] = 0; /* Ignore count clear */ + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_STATUS; + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_NORES): + if (g_usb1_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb1_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DOING; + usb1_host_clear_pid_stall(USB_HOST_PIPE0); + usb1_host_set_pid_buf(USB_HOST_PIPE0); + } + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_STALL): + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + break; + + /* --------------- STATUS STAGE --------------- */ + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_IDLE): + usb1_host_StatusStage(); + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + /* do nothing */ + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DONE): /* end of Control transfer */ + usb1_host_set_pid_nak(USB_HOST_PIPE0); + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_DONE; /* exit DONE */ + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_NORES): + if (g_usb1_host_PipeIgnore[USB_HOST_PIPE0] == 3) + { + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + } + else + { + g_usb1_host_PipeIgnore[USB_HOST_PIPE0]++; /* Ignore count */ + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DOING; + usb1_host_clear_pid_stall(USB_HOST_PIPE0); + usb1_host_set_pid_buf(USB_HOST_PIPE0); + } + break; + + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_STALL): + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + break; + + default: + break; + } + + if (g_usb1_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_WAIT) + { + RZA_IO_RegWrite_16(&USB201.SOFCFG, + 0, + USB_SOFCFG_TRNENSEL_SHIFT, + USB_SOFCFG_TRNENSEL); + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb1_host_SetupStage +* Description : Executes USB control transfer/set up stage. +* Arguments : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* Return Value : none +*******************************************************************************/ +void usb1_host_SetupStage (uint16_t Req, uint16_t Val, uint16_t Indx, uint16_t Len) +{ + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DOING; + + USB201.INTSTS1 = (uint16_t)~(USB_HOST_BITSACK | USB_HOST_BITSIGN); /* Status Clear */ + USB201.USBREQ = Req; + USB201.USBVAL = Val; + USB201.USBINDX = Indx; + USB201.USBLENG = Len; + USB201.DCPCTR = USB_HOST_BITSUREQ; /* PID=NAK & Send Setup */ +} + +/******************************************************************************* +* Function Name: usb1_host_StatusStage +* Description : Executes USB control transfer/status stage. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_StatusStage (void) +{ + uint8_t Buf1[16]; + + switch ((g_usb1_host_CmdStage & (USB_HOST_MODE_FIELD))) + { + case USB_HOST_MODE_READ: + usb1_host_CtrlWriteStart((uint32_t)0, (uint8_t*)&Buf1); + break; + + case USB_HOST_MODE_WRITE: + usb1_host_CtrlReadStart((uint32_t)0, (uint8_t*)&Buf1); + break; + + case USB_HOST_MODE_NO_DATA: + usb1_host_CtrlReadStart((uint32_t)0, (uint8_t*)&Buf1); + break; + + default: + break; + } +} + +/******************************************************************************* +* Function Name: usb1_host_CtrlWriteStart +* Description : Executes USB control transfer/data stage(write). +* Arguments : uint32_t Bsize ; Data Size +* : uint8_t *Table ; Data Table Address +* Return Value : USB_HOST_WRITESHRT ; End of data write +* : USB_HOST_WRITEEND ; End of data write (not null) +* : USB_HOST_WRITING ; Continue of data write +* : USB_HOST_FIFOERROR ; FIFO access error +*******************************************************************************/ +uint16_t usb1_host_CtrlWriteStart (uint32_t Bsize, uint8_t * Table) +{ + uint16_t EndFlag_K; + uint16_t mbw; + + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DOING; + + usb1_host_set_pid_nak(USB_HOST_PIPE0); /* Set NAK */ + g_usb1_host_data_count[USB_HOST_PIPE0] = Bsize; /* Transfer size set */ + g_usb1_host_data_pointer[USB_HOST_PIPE0] = Table; /* Transfer address set */ + + USB201.DCPCTR = USB_HOST_BITSQSET; /* SQSET=1, PID=NAK */ +#if(1) /* ohci_wrapp */ + Userdef_USB_usb1_host_delay_10us(3); +#endif + RZA_IO_RegWrite_16(&USB201.DCPCFG, + 1, + USB_DCPCFG_DIR_SHIFT, + USB_DCPCFG_DIR); + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[USB_HOST_PIPE0], (uint32_t)g_usb1_host_data_pointer[USB_HOST_PIPE0]); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_BITISEL, mbw); + USB201.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + + usb1_host_clear_pid_stall(USB_HOST_PIPE0); + EndFlag_K = usb1_host_write_buffer_c(USB_HOST_PIPE0); + /* Host Control sequence */ + switch (EndFlag_K) + { + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_STATUS; + usb1_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb1_host_enable_bemp_int(USB_HOST_PIPE0); /* Enable Empty Interrupt */ + break; + + case USB_HOST_WRITEEND: /* End of data write (not null) */ + case USB_HOST_WRITING: /* Continue of data write */ + usb1_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb1_host_enable_bemp_int(USB_HOST_PIPE0); /* Enable Empty Interrupt */ + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + break; + + default: + break; + } + usb1_host_set_pid_buf(USB_HOST_PIPE0); /* Set BUF */ + return (EndFlag_K); /* End or Err or Continue */ +} + +/******************************************************************************* +* Function Name: usb1_host_CtrlReadStart +* Description : Executes USB control transfer/data stage(read). +* Arguments : uint32_t Bsize ; Data Size +* : uint8_t *Table ; Data Table Address +* Return Value : none +*******************************************************************************/ +void usb1_host_CtrlReadStart (uint32_t Bsize, uint8_t * Table) +{ + uint16_t mbw; + + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DOING; + + usb1_host_set_pid_nak(USB_HOST_PIPE0); /* Set NAK */ + g_usb1_host_data_count[USB_HOST_PIPE0] = Bsize; /* Transfer size set */ + g_usb1_host_data_pointer[USB_HOST_PIPE0] = Table; /* Transfer address set */ + + USB201.DCPCTR = USB_HOST_BITSQSET; /* SQSET=1, PID=NAK */ +#if(1) /* ohci_wrapp */ + Userdef_USB_usb1_host_delay_10us(3); +#endif + RZA_IO_RegWrite_16(&USB201.DCPCFG, + 0, + USB_DCPCFG_DIR_SHIFT, + USB_DCPCFG_DIR); + + mbw = usb1_host_get_mbw(g_usb1_host_data_count[USB_HOST_PIPE0], (uint32_t)g_usb1_host_data_pointer[USB_HOST_PIPE0]); + usb1_host_set_curpipe(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_NO, mbw); + USB201.CFIFOCTR = USB_HOST_BITBCLR; /* Buffer Clear */ + + usb1_host_enable_nrdy_int(USB_HOST_PIPE0); /* Error (NORES or STALL) */ + usb1_host_enable_brdy_int(USB_HOST_PIPE0); /* Ok */ + usb1_host_clear_pid_stall(USB_HOST_PIPE0); + usb1_host_set_pid_buf(USB_HOST_PIPE0); /* Set BUF */ +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/src/host/usb1_host_drv_api.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,889 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_drv_api.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb1_host_resetEP(USB_HOST_CFG_PIPETBL_t *tbl); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_api_host_init +* Description : Initializes USB module in the USB host mode. +* : USB connection is executed when executing this function in +* : the states that USB device isconnected to the USB port. +* Arguments : uint8_t int_level : USB Module interrupt level +* : USBU16 mode : USB_HOST_HIGH_SPEED +* : USB_HOST_FULL_SPEED +* : uint16_t clockmode : USB Clock mode +* Return Value : USB detach or attach +* : USB_HOST_ATTACH +* : USB_HOST_DETACH +*******************************************************************************/ +uint16_t usb1_api_host_init (uint8_t int_level, uint16_t mode, uint16_t clockmode) +{ + uint16_t connect; + volatile uint8_t dummy_buf; + + CPG.STBCR7 &= 0xfc; /*The clock of USB0/1 modules is permitted */ + dummy_buf = CPG.STBCR7; /* (Dummy read) */ + + g_usb1_host_SupportUsbDeviceSpeed = mode; + + usb1_host_setting_interrupt(int_level); + usb1_host_reset_module(clockmode); + + g_usb1_host_bchg_flag = USB_HOST_NO; + g_usb1_host_detach_flag = USB_HOST_NO; + g_usb1_host_attach_flag = USB_HOST_NO; + + g_usb1_host_driver_state = USB_HOST_DRV_DETACHED; + g_usb1_host_default_max_packet[USB_HOST_DEVICE_0] = 64; + + usb1_host_InitModule(); + + connect = usb1_host_CheckAttach(); + + if (connect == USB_HOST_ATTACH) + { + g_usb1_host_attach_flag = USB_HOST_YES; + } + else + { + usb1_host_UsbDetach2(); + } + + return connect; +} + +#if(1) /* ohci_wrapp */ +#else +/******************************************************************************* +* Function Name: usb1_api_host_enumeration +* Description : Initializes USB module in the USB host mode. +* : USB connection is executed when executing this function in +* : the states that USB device isconnected to the USB port. +* Arguments : uint16_t devadr : device address +* Return Value : DEVDRV_USBH_DETACH_ERR : device detach +* : DEVDRV_SUCCESS : device enumeration success +* : DEVDRV_ERROR : device enumeration error +*******************************************************************************/ +int32_t usb1_api_host_enumeration (uint16_t devadr) +{ + int32_t ret; + uint16_t driver_sts; + + g_usb1_host_setUsbAddress = devadr; + + while (1) + { + driver_sts = usb1_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + ret = DEVDRV_USBH_DETACH_ERR; + break; + } + else if (driver_sts == USB_HOST_DRV_CONFIGURED) + { + ret = DEVDRV_SUCCESS; + break; + } + else if (driver_sts == USB_HOST_DRV_STALL) + { + ret = DEVDRV_ERROR; + break; + } + else if (driver_sts == USB_HOST_DRV_NORES) + { + ret = DEVDRV_ERROR; + break; + } + else + { + /* Do Nothing */ + } + } + + if (driver_sts == USB_HOST_DRV_NORES) + { + while (1) + { + driver_sts = usb1_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + break; + } + } + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_api_host_detach +* Description : USB detach routine +* Arguments : none +* Return Value : USB_HOST_DETACH : USB detach +* : USB_HOST_ATTACH : USB attach +* : DEVDRV_ERROR : error +*******************************************************************************/ +int32_t usb1_api_host_detach (void) +{ + int32_t ret; + uint16_t driver_sts; + + while (1) + { + driver_sts = usb1_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + ret = USB_HOST_DETACH; + break; + } + else if (driver_sts == USB_HOST_DRV_CONFIGURED) + { + ret = USB_HOST_ATTACH; + break; + } + else if (driver_sts == USB_HOST_DRV_STALL) + { + ret = DEVDRV_ERROR; + break; + } + else if (driver_sts == USB_HOST_DRV_NORES) + { + ret = DEVDRV_ERROR; + break; + } + else + { + /* Do Nothing */ + } + } + + if (driver_sts == USB_HOST_DRV_NORES) + { + while (1) + { + driver_sts = usb1_api_host_GetUsbDeviceState(); + + if (driver_sts == USB_HOST_DRV_DETACHED) + { + break; + } + } + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_api_host_data_in +* Description : Executes USB transfer as data-in in the argument specified pipe. +* Arguments : uint16_t devadr ; device address +* : uint16_t Pipe ; Pipe Number +* : uint32_t Size ; Data Size +* : uint8_t *data_buf ; Data data_buf Address +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_data_in (uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t * data_buf) +{ + int32_t ret; + + if (Pipe == USB_HOST_PIPE0) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipemaxp[Pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL) != devadr) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[Pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 1) + { + return DEVDRV_ERROR; + } + + if (g_usb1_host_pipe_status[Pipe] == USB_HOST_PIPE_IDLE) + { + usb1_host_start_receive_transfer(Pipe, Size, data_buf); + } + else + { + return DEVDRV_ERROR; /* Now pipe is busy */ + } + + /* waiting for completing routine */ + do + { + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb1_host_pipe_status[Pipe] != USB_HOST_PIPE_IDLE) && (g_usb1_host_pipe_status[Pipe] != USB_HOST_PIPE_WAIT)) + { + break; + } + + } while (1); + + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb1_host_pipe_status[Pipe]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + usb1_host_stop_transfer(Pipe); + + g_usb1_host_pipe_status[Pipe] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_api_host_data_out +* Description : Executes USB transfer as data-out in the argument specified pipe. +* Arguments : uint16_t devadr ; device address +* : uint16_t Pipe ; Pipe Number +* : uint32_t Size ; Data Size +* : uint8_t *data_buf ; Data data_buf Address +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_data_out (uint16_t devadr, uint16_t Pipe, uint32_t Size, uint8_t * data_buf) +{ + int32_t ret; + + if (Pipe == USB_HOST_PIPE0) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipemaxp[Pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL) != devadr) + { + return DEVDRV_ERROR; + } + + if (RZA_IO_RegRead_16(&g_usb1_host_pipecfg[Pipe], USB_PIPECFG_DIR_SHIFT, USB_PIPECFG_DIR) == 0) + { + return DEVDRV_ERROR; + } + + if (g_usb1_host_pipe_status[Pipe] == USB_HOST_PIPE_IDLE) + { + usb1_host_start_send_transfer(Pipe, Size, data_buf); + } + else + { + return DEVDRV_ERROR; /* Now pipe is busy */ + } + + /* waiting for completing routine */ + do + { + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb1_host_pipe_status[Pipe] != USB_HOST_PIPE_IDLE) && (g_usb1_host_pipe_status[Pipe] != USB_HOST_PIPE_WAIT)) + { + break; + } + + } while (1); + + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb1_host_pipe_status[Pipe]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + usb1_host_stop_transfer(Pipe); + + g_usb1_host_pipe_status[Pipe] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_api_host_control_transfer +* Description : Executes USB control transfer. +* Arguments : uint16_t devadr ; device address +* : uint16_t Req ; bmRequestType & bRequest +* : uint16_t Val ; wValue +* : uint16_t Indx ; wIndex +* : uint16_t Len ; wLength +* : uint8_t *buf ; Buffer +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_USBH_DETACH_ERR ; device detach +* : DEVDRV_USBH_CTRL_COM_ERR ; device no response +* : DEVDRV_USBH_STALL ; STALL +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_control_transfer (uint16_t devadr, uint16_t Req, uint16_t Val, uint16_t Indx, + uint16_t Len, uint8_t * Buf) +{ + int32_t ret; + + do + { + ret = usb1_host_CtrlTransStart(devadr, Req, Val, Indx, Len, Buf); + + if (ret == DEVDRV_SUCCESS) + { + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + break; + } + + if ((g_usb1_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_IDLE) + && (g_usb1_host_pipe_status[USB_HOST_PIPE0] != USB_HOST_PIPE_WAIT)) + { + break; + } + } + else + { + return DEVDRV_ERROR; + } + } while (1); + + if (g_usb1_host_detach_flag == USB_HOST_YES) + { + return DEVDRV_USBH_DETACH_ERR; + } + + switch (g_usb1_host_pipe_status[USB_HOST_PIPE0]) + { + case USB_HOST_PIPE_DONE: + ret = DEVDRV_SUCCESS; + break; + + case USB_HOST_PIPE_STALL: + ret = DEVDRV_USBH_STALL; + break; + + case USB_HOST_PIPE_NORES: + ret = DEVDRV_USBH_CTRL_COM_ERR; + break; + + default: + ret = DEVDRV_ERROR; + break; + } + + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_IDLE; + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_api_host_set_endpoint +* Description : Sets end point on the information specified in the argument. +* Arguments : uint16_t devadr ; device address +* : uint8_t *configdescriptor ; device configration descriptor +* : USB_HOST_CFG_PIPETBL_t *user_table ; pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_set_endpoint (uint16_t devadr, USB_HOST_CFG_PIPETBL_t * user_table, uint8_t * configdescriptor) +{ + uint16_t ret; + uint32_t end_point; + uint32_t offset; + uint32_t totalLength; + USB_HOST_CFG_PIPETBL_t * pipe_table; + + /* End Point Search */ + end_point = 0; + offset = configdescriptor[0]; + totalLength = (uint16_t)(configdescriptor[2] + ((uint16_t)configdescriptor[3] << 8)); + + do + { + if (configdescriptor[offset + 1] == USB_HOST_ENDPOINT_DESC) + { + pipe_table = &user_table[end_point]; + + if (pipe_table->pipe_number == 0xffff) + { + break; + } + + ret = usb1_api_host_SetEndpointTable(devadr, pipe_table, (uint8_t *)&configdescriptor[offset]); + + if ((ret != USB_HOST_PIPE_IN) && (ret != USB_HOST_PIPE_OUT)) + { + return DEVDRV_ERROR; + } + + ++end_point; + } + + /* Next End Point Search */ + offset += configdescriptor[offset]; + + } while (offset < totalLength); + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb1_api_host_clear_endpoint +* Description : Clears the pipe definition table specified in the argument. +* Arguments : uint16_t pipe_sel : Pipe Number +* : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_clear_endpoint (USB_HOST_CFG_PIPETBL_t * user_table) +{ + uint16_t pipe; + + for (pipe = USB_HOST_PIPE0; pipe <= USB_HOST_MAX_PIPE_NO; ++pipe) + { + if (user_table->pipe_number == 0xffff) + { + break; + } + user_table->pipe_cfg &= (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD); + user_table->pipe_max_pktsize = 0; + user_table->pipe_cycle = 0; + + user_table++; + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb1_api_host_clear_endpoint_pipe +* Description : Clears the pipe definition table specified in the argument. +* Arguments : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_clear_endpoint_pipe (uint16_t pipe_sel, USB_HOST_CFG_PIPETBL_t * user_table) +{ + uint16_t pipe; + + for (pipe = USB_HOST_PIPE0; pipe <= USB_HOST_MAX_PIPE_NO; ++pipe) + { + if (user_table->pipe_number == 0xffff) + { + break; + } + + if (user_table->pipe_number == pipe_sel) + { + user_table->pipe_cfg &= (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD); + user_table->pipe_max_pktsize = 0; + user_table->pipe_cycle = 0; + break; + } + + user_table++; + } + + return DEVDRV_SUCCESS; +} +#endif + +/******************************************************************************* +* Function Name: usb1_api_host_SetEndpointTable +* Description : Sets the end point on the information specified by the argument. +* Arguments : uint16_t devadr : device address +* : USB_HOST_CFG_PIPETBL_t *user_table : pipe table +* : uint8_t *Table : Endpoint descriptor +* Return Value : USB_HOST_DIR_H_IN ; IN endpoint +* : USB_HOST_DIR_H_OUT ; OUT endpoint +* : USB_END_POINT_ERROR ; error +*******************************************************************************/ +uint16_t usb1_api_host_SetEndpointTable (uint16_t devadr, USB_HOST_CFG_PIPETBL_t * user_table, uint8_t * Table) +{ + uint16_t PipeCfg; + uint16_t PipeMaxp; + uint16_t pipe_number; + uint16_t ret; + uint16_t ret_flag = 0; // avoid warning. + + pipe_number = user_table->pipe_number; + + if (Table[1] != USB_HOST_ENDPOINT_DESC) + { + return USB_END_POINT_ERROR; + } + + switch (Table[3] & USB_HOST_EP_TYPE) + { + case USB_HOST_EP_CNTRL: + ret_flag = USB_END_POINT_ERROR; + break; + + case USB_HOST_EP_ISO: + if ((pipe_number != USB_HOST_PIPE1) && (pipe_number != USB_HOST_PIPE2)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_ISO; + break; + + case USB_HOST_EP_BULK: + if ((pipe_number < USB_HOST_PIPE1) || (pipe_number > USB_HOST_PIPE5)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_BULK; + break; + + case USB_HOST_EP_INT: + if ((pipe_number < USB_HOST_PIPE6) || (pipe_number > USB_HOST_PIPE9)) + { + return USB_END_POINT_ERROR; + } + + PipeCfg = USB_HOST_INTERRUPT; + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + + /* Set pipe configuration table */ + if ((Table[2] & USB_HOST_EP_DIR_MASK) == USB_HOST_EP_IN) /* IN(receive) */ + { + if (PipeCfg == USB_HOST_ISO) + { + /* Transfer Type is ISO*/ + PipeCfg |= USB_HOST_DIR_H_IN; + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + case USB_HOST_D0USE: + case USB_HOST_D1USE: + case USB_HOST_D0DMA: + case USB_HOST_D1DMA: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & USB_HOST_DBLBFIELD); + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + } + else + { + /* Transfer Type is BULK or INT */ + PipeCfg |= (USB_HOST_SHTNAKON | USB_HOST_DIR_H_IN); /* Compulsory SHTNAK */ + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + case USB_HOST_D0USE: + case USB_HOST_D1USE: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); + break; + + case USB_HOST_D0DMA: + case USB_HOST_D1DMA: + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); +#ifdef __USB_DMA_BFRE_ENABLE__ + /* this routine cannnot be perfomred if read operation is executed in buffer size */ + PipeCfg |= USB_HOST_BFREON; +#endif + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + } + ret = USB_HOST_PIPE_IN; + } + else /* OUT(send) */ + { + if (PipeCfg == USB_HOST_ISO) + { + /* Transfer Type is ISO*/ + PipeCfg |= (uint16_t)(user_table->pipe_cfg & USB_HOST_DBLBFIELD); + } + else + { + /* Transfer Type is BULK or INT */ + PipeCfg |= (uint16_t)(user_table->pipe_cfg & (USB_HOST_DBLBFIELD | USB_HOST_CNTMDFIELD)); + } + PipeCfg |= USB_HOST_DIR_H_OUT; + ret = USB_HOST_PIPE_OUT; + } + + switch (user_table->fifo_port) + { + case USB_HOST_CUSE: + g_usb1_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_CFIFO_USE; + break; + + case USB_HOST_D0USE: + g_usb1_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D0FIFO_USE; + break; + + case USB_HOST_D1USE: + g_usb1_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D1FIFO_USE; + break; + + case USB_HOST_D0DMA: + g_usb1_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D0FIFO_DMA; + break; + + case USB_HOST_D1DMA: + g_usb1_host_PipeTbl[pipe_number] = (uint16_t)USB_HOST_D1FIFO_DMA; + break; + + default: + ret_flag = USB_END_POINT_ERROR; + break; + } + + if (ret_flag == USB_END_POINT_ERROR) + { + return ret_flag; + } + + /* Endpoint number set */ + PipeCfg |= (uint16_t)(Table[2] & USB_HOST_EP_NUM_MASK); + g_usb1_host_PipeTbl[pipe_number] |= (uint16_t)(Table[2] & USB_HOST_EP_NUM_MASK); + + /* Max packet size set */ + PipeMaxp = (uint16_t)((uint16_t)Table[4] | (uint16_t)((uint16_t)Table[5] << 8)); + + if (PipeMaxp == 0u) + { + return USB_END_POINT_ERROR; + } + + /* Set device address */ + PipeMaxp |= (uint16_t)(devadr << 12); + + user_table->pipe_cfg = PipeCfg; + user_table->pipe_max_pktsize = PipeMaxp; + + usb1_host_resetEP(user_table); + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_host_resetEP +* Description : Sets the end point on the information specified by the argument. +* Arguments : USB_HOST_CFG_PIPETBL_t *tbl : pipe table +* Return Value : none +*******************************************************************************/ +static void usb1_host_resetEP (USB_HOST_CFG_PIPETBL_t * tbl) +{ + + uint16_t pipe; + + /* Host pipe */ + /* The pipe number of pipe definition table is obtained */ + pipe = (uint16_t)(tbl->pipe_number & USB_HOST_BITCURPIPE); /* Pipe Number */ + + /* FIFO port access pipe is set to initial value */ + /* The connection with FIFO should be cut before setting the pipe */ + if (RZA_IO_RegRead_16(&USB201.CFIFOSEL, + USB_CFIFOSEL_CURPIPE_SHIFT, + USB_CFIFOSEL_CURPIPE) == pipe) + { + usb1_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_CUSE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + if (RZA_IO_RegRead_16(&USB201.D0FIFOSEL, + USB_DnFIFOSEL_CURPIPE_SHIFT, + USB_DnFIFOSEL_CURPIPE) == pipe) + { + usb1_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_D0USE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + if (RZA_IO_RegRead_16(&USB201.D1FIFOSEL, + USB_DnFIFOSEL_CURPIPE_SHIFT, + USB_DnFIFOSEL_CURPIPE) == pipe) + { + usb1_host_change_fifo_port(USB_HOST_PIPE0, USB_HOST_D1USE, USB_HOST_NO, USB_HOST_BITMBW_16); + } + + /* Interrupt of pipe set is disabled */ + usb1_host_disable_brdy_int(pipe); + usb1_host_disable_nrdy_int(pipe); + usb1_host_disable_bemp_int(pipe); + + /* Pipe to set is set to NAK */ + usb1_host_set_pid_nak(pipe); + + /* Pipe is set */ + USB201.PIPESEL = pipe; + + USB201.PIPECFG = tbl->pipe_cfg; + USB201.PIPEBUF = tbl->pipe_buf; + USB201.PIPEMAXP = tbl->pipe_max_pktsize; + USB201.PIPEPERI = tbl->pipe_cycle; + + g_usb1_host_pipecfg[pipe] = tbl->pipe_cfg; + g_usb1_host_pipebuf[pipe] = tbl->pipe_buf; + g_usb1_host_pipemaxp[pipe] = tbl->pipe_max_pktsize; + g_usb1_host_pipeperi[pipe] = tbl->pipe_cycle; + + /* Sequence bit clear */ + usb1_host_set_sqclr(pipe); + + usb1_host_aclrm(pipe); + usb1_host_set_csclr(pipe); + + /* Pipe window selection is set to unused */ + USB201.PIPESEL = USB_HOST_PIPE0; + +} + +#if(1) /* ohci_wrapp */ +#else +/******************************************************************************* +* Function Name: usb1_api_host_data_count +* Description : Get g_usb0_host_data_count[pipe] +* Arguments : uint16_t pipe ; Pipe Number +* : uint32_t *data_count ; return g_usb0_data_count[pipe] +* Return Value : DEVDRV_SUCCESS ; success +* : DEVDRV_ERROR ; error +*******************************************************************************/ +int32_t usb1_api_host_data_count (uint16_t pipe, uint32_t * data_count) +{ + if (pipe > USB_HOST_MAX_PIPE_NO) + { + return DEVDRV_ERROR; + } + + *data_count = g_usb1_host_PipeDataSize[pipe]; + + return DEVDRV_SUCCESS; +} +#endif + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/src/host/usb1_host_global.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,137 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_global.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +const uint16_t g_usb1_host_bit_set[16] = +{ + 0x0001, 0x0002, 0x0004, 0x0008, + 0x0010, 0x0020, 0x0040, 0x0080, + 0x0100, 0x0200, 0x0400, 0x0800, + 0x1000, 0x2000, 0x4000, 0x8000 +}; + +uint32_t g_usb1_host_data_count[USB_HOST_MAX_PIPE_NO + 1]; +uint8_t * g_usb1_host_data_pointer[USB_HOST_MAX_PIPE_NO + 1]; + +uint16_t g_usb1_host_PipeIgnore[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb1_host_PipeTbl[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb1_host_pipe_status[USB_HOST_MAX_PIPE_NO + 1]; +uint32_t g_usb1_host_PipeDataSize[USB_HOST_MAX_PIPE_NO + 1]; + +USB_HOST_DMA_t g_usb1_host_DmaInfo[2]; + +uint16_t g_usb1_host_DmaPipe[2]; +uint16_t g_usb1_host_DmaBval[2]; +uint16_t g_usb1_host_DmaStatus[2]; + +uint16_t g_usb1_host_driver_state; +uint16_t g_usb1_host_ConfigNum; +uint16_t g_usb1_host_CmdStage; +uint16_t g_usb1_host_bchg_flag; +uint16_t g_usb1_host_detach_flag; +uint16_t g_usb1_host_attach_flag; + +uint16_t g_usb1_host_UsbAddress; +uint16_t g_usb1_host_setUsbAddress; +uint16_t g_usb1_host_default_max_packet[USB_HOST_MAX_DEVICE + 1]; +uint16_t g_usb1_host_UsbDeviceSpeed; +uint16_t g_usb1_host_SupportUsbDeviceSpeed; + +uint16_t g_usb1_host_SavReq; +uint16_t g_usb1_host_SavVal; +uint16_t g_usb1_host_SavIndx; +uint16_t g_usb1_host_SavLen; + +uint16_t g_usb1_host_pipecfg[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb1_host_pipebuf[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb1_host_pipemaxp[USB_HOST_MAX_PIPE_NO + 1]; +uint16_t g_usb1_host_pipeperi[USB_HOST_MAX_PIPE_NO + 1]; + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_init_pipe_status +* Description : Initialize pipe status. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_init_pipe_status (void) +{ + uint16_t loop; + + g_usb1_host_ConfigNum = 0; + + for (loop = 0; loop < (USB_HOST_MAX_PIPE_NO + 1); ++loop) + { + g_usb1_host_pipe_status[loop] = USB_HOST_PIPE_IDLE; + g_usb1_host_PipeDataSize[loop] = 0; + + /* pipe configuration in usb1_host_resetEP() */ + g_usb1_host_pipecfg[loop] = 0; + g_usb1_host_pipebuf[loop] = 0; + g_usb1_host_pipemaxp[loop] = 0; + g_usb1_host_pipeperi[loop] = 0; + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/src/host/usb1_host_usbint.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,497 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_usbint.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#if(1) /* ohci_wrapp */ +#include "ohci_wrapp_RZ_A1_local.h" +#endif + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb1_host_interrupt1(void); +static void usb1_host_BRDYInterrupt(uint16_t Status, uint16_t Int_enbl); +static void usb1_host_NRDYInterrupt(uint16_t Status, uint16_t Int_enbl); +static void usb1_host_BEMPInterrupt(uint16_t Status, uint16_t Int_enbl); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_interrupt +* Description : Executes USB interrupt. +* : Register this function in the USB interrupt handler. +* : Set CFIF0 in the pipe set before the interrupt after executing +* : this function. +* Arguments : uint32_t int_sense ; Interrupts detection mode +* : ; INTC_LEVEL_SENSITIVE : Level sense +* : ; INTC_EDGE_TRIGGER : Edge trigger +* Return Value : none +*******************************************************************************/ +void usb1_host_interrupt (uint32_t int_sense) +{ + uint16_t savepipe1; + uint16_t savepipe2; + uint16_t buffer; + + savepipe1 = USB201.CFIFOSEL; + savepipe2 = USB201.PIPESEL; + usb1_host_interrupt1(); + + /* Control transmission changes ISEL within interruption processing. */ + /* For this reason, write return of ISEL cannot be performed. */ + buffer = USB201.CFIFOSEL; + buffer &= (uint16_t)~(USB_HOST_BITCURPIPE); + buffer |= (uint16_t)(savepipe1 & USB_HOST_BITCURPIPE); + USB201.CFIFOSEL = buffer; + USB201.PIPESEL = savepipe2; +} + +/******************************************************************************* +* Function Name: usb1_host_interrupt1 +* Description : Execue the USB interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_interrupt1 (void) +{ + uint16_t intsts0; + uint16_t intsts1; + uint16_t intenb0; + uint16_t intenb1; + uint16_t brdysts; + uint16_t nrdysts; + uint16_t bempsts; + uint16_t brdyenb; + uint16_t nrdyenb; + uint16_t bempenb; + volatile uint16_t dumy_sts; + + intsts0 = USB201.INTSTS0; + intsts1 = USB201.INTSTS1; + intenb0 = USB201.INTENB0; + intenb1 = USB201.INTENB1; + + if ((intsts1 & USB_HOST_BITBCHG) && (intenb1 & USB_HOST_BITBCHGE)) + { + USB201.INTSTS1 = (uint16_t)~USB_HOST_BITBCHG; + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); + g_usb1_host_bchg_flag = USB_HOST_YES; + } + else if ((intsts1 & USB_HOST_BITSACK) && (intenb1 & USB_HOST_BITSACKE)) + { + USB201.INTSTS1 = (uint16_t)~USB_HOST_BITSACK; +#if(1) /* ohci_wrapp */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); +#else + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; +#endif + } + else if ((intsts1 & USB_HOST_BITSIGN) && (intenb1 & USB_HOST_BITSIGNE)) + { + USB201.INTSTS1 = (uint16_t)~USB_HOST_BITSIGN; +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; /* exit NORES */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#else + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_NORES; +#endif + } + else if (((intsts1 & USB_HOST_BITDTCH) == USB_HOST_BITDTCH) + && ((intenb1 & USB_HOST_BITDTCHE) == USB_HOST_BITDTCHE)) + { + USB201.INTSTS1 = (uint16_t)~USB_HOST_BITDTCH; + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); + g_usb1_host_detach_flag = USB_HOST_YES; + + Userdef_USB_usb1_host_detach(); + + usb1_host_UsbDetach2(); + } + else if (((intsts1 & USB_HOST_BITATTCH) == USB_HOST_BITATTCH) + && ((intenb1 & USB_HOST_BITATTCHE) == USB_HOST_BITATTCHE)) + { + USB201.INTSTS1 = (uint16_t)~USB_HOST_BITATTCH; + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); + g_usb1_host_attach_flag = USB_HOST_YES; + + Userdef_USB_usb1_host_attach(); + + usb1_host_UsbAttach(); + } + else if ((intsts0 & intenb0 & (USB_HOST_BITBEMP | USB_HOST_BITNRDY | USB_HOST_BITBRDY))) + { + brdysts = USB201.BRDYSTS; + nrdysts = USB201.NRDYSTS; + bempsts = USB201.BEMPSTS; + brdyenb = USB201.BRDYENB; + nrdyenb = USB201.NRDYENB; + bempenb = USB201.BEMPENB; + + if ((intsts0 & USB_HOST_BITBRDY) && (intenb0 & USB_HOST_BITBRDYE) && (brdysts & brdyenb)) + { + usb1_host_BRDYInterrupt(brdysts, brdyenb); + } + else if ((intsts0 & USB_HOST_BITBEMP) && (intenb0 & USB_HOST_BITBEMPE) && (bempsts & bempenb)) + { + usb1_host_BEMPInterrupt(bempsts, bempenb); + } + else if ((intsts0 & USB_HOST_BITNRDY) && (intenb0 & USB_HOST_BITNRDYE) && (nrdysts & nrdyenb)) + { + usb1_host_NRDYInterrupt(nrdysts, nrdyenb); + } + else + { + /* Do Nothing */ + } + } + else + { + /* Do Nothing */ + } + + /* Three dummy read for clearing interrupt requests */ + dumy_sts = USB201.INTSTS0; + dumy_sts = USB201.INTSTS1; + +} + +/******************************************************************************* +* Function Name: usb1_host_BRDYInterrupt +* Description : Executes USB BRDY interrupt. +* Arguments : uint16_t Status ; BRDYSTS Register Value +* : uint16_t Int_enbl ; BRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_BRDYInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t buffer; + volatile uint16_t dumy_sts; + + if ((Status & g_usb1_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb1_host_bit_set[USB_HOST_PIPE0])) + { + USB201.BRDYSTS = (uint16_t)~g_usb1_host_bit_set[USB_HOST_PIPE0]; + +#if(1) /* ohci_wrapp */ + switch ((g_usb1_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + buffer = usb1_host_read_buffer_c(USB_HOST_PIPE0); + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb1_host_read_buffer_c(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_READOVER: /* buffer over */ + USB201.CFIFOCTR = USB_HOST_BITBCLR; + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + break; + } +#else + switch ((g_usb1_host_CmdStage & (USB_HOST_MODE_FIELD | USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + case (USB_HOST_MODE_NO_DATA | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + buffer = usb1_host_read_buffer_c(USB_HOST_PIPE0); + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case (USB_HOST_MODE_READ | USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb1_host_read_buffer_c(USB_HOST_PIPE0); + + switch (buffer) + { + case USB_HOST_READING: /* Continue of data read */ + break; + + case USB_HOST_READEND: /* End of data read */ + case USB_HOST_READSHRT: /* End of data read */ + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case USB_HOST_READOVER: /* buffer over */ + USB201.CFIFOCTR = USB_HOST_BITBCLR; + usb1_host_disable_brdy_int(USB_HOST_PIPE0); + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + break; + } +#endif + } + else + { + usb1_host_brdy_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB201.BRDYSTS; +} + +/******************************************************************************* +* Function Name: usb1_host_NRDYInterrupt +* Description : Executes USB NRDY interrupt. +* Arguments : uint16_t Status ; NRDYSTS Register Value +* : uint16_t Int_enbl ; NRDYENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_NRDYInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t pid; + volatile uint16_t dumy_sts; + + if ((Status & g_usb1_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb1_host_bit_set[USB_HOST_PIPE0])) + { + USB201.NRDYSTS = (uint16_t)~g_usb1_host_bit_set[USB_HOST_PIPE0]; + pid = usb1_host_get_pid(USB_HOST_PIPE0); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_STALL; +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + + } + else if (pid == USB_HOST_PID_NAK) + { + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_NORES; +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_NORES; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + } + else + { + /* Do Nothing */ + } + } + else + { + usb1_host_nrdy_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB201.NRDYSTS; +} + +/******************************************************************************* +* Function Name: usb1_host_BEMPInterrupt +* Description : Executes USB BEMP interrupt. +* Arguments : uint16_t Status ; BEMPSTS Register Value +* : uint16_t Int_enbl ; BEMPENB Register Value +* Return Value : none +*******************************************************************************/ +void usb1_host_BEMPInterrupt (uint16_t Status, uint16_t Int_enbl) +{ + uint16_t buffer; + uint16_t pid; + volatile uint16_t dumy_sts; + + if ((Status & g_usb1_host_bit_set[USB_HOST_PIPE0]) && (Int_enbl & g_usb1_host_bit_set[USB_HOST_PIPE0])) + { + USB201.BEMPSTS = (uint16_t)~g_usb1_host_bit_set[USB_HOST_PIPE0]; + pid = usb1_host_get_pid(USB_HOST_PIPE0); + + if ((pid == USB_HOST_PID_STALL) || (pid == USB_HOST_PID_STALL2)) + { + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_STALL; +#if(1) /* ohci_wrapp */ + g_usb1_host_pipe_status[USB_HOST_PIPE0] = USB_HOST_PIPE_STALL; /* exit STALL */ + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_STALL); +#endif + } + else + { +#if(1) /* ohci_wrapp */ + switch ((g_usb1_host_CmdStage & (USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case (USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb1_host_write_buffer(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_WRITING: /* Continue of data write */ + case USB_HOST_WRITEEND: /* End of data write (zero-length) */ + break; + + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_STATUS; + ohciwrapp_loc_TransEnd(USB_HOST_PIPE0, TD_CC_NOERROR); + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + default: + /* do nothing */ + break; + } +#else + switch ((g_usb1_host_CmdStage & (USB_HOST_MODE_FIELD | USB_HOST_STAGE_FIELD | USB_HOST_CMD_FIELD))) + { + case (USB_HOST_MODE_READ | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_DONE; + break; + + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_DATA | USB_HOST_CMD_DOING): + buffer = usb1_host_write_buffer(USB_HOST_PIPE0); + switch (buffer) + { + case USB_HOST_WRITING: /* Continue of data write */ + case USB_HOST_WRITEEND: /* End of data write (zero-length) */ + break; + + case USB_HOST_WRITESHRT: /* End of data write */ + g_usb1_host_CmdStage &= (~USB_HOST_STAGE_FIELD); + g_usb1_host_CmdStage |= USB_HOST_STAGE_STATUS; + break; + + case USB_HOST_FIFOERROR: /* FIFO access error */ + default: + break; + } + break; + + case (USB_HOST_MODE_WRITE | USB_HOST_STAGE_STATUS | USB_HOST_CMD_DOING): + g_usb1_host_CmdStage &= (~USB_HOST_CMD_FIELD); + g_usb1_host_CmdStage |= USB_HOST_CMD_IDLE; + break; + + default: + /* do nothing */ + break; + } +#endif + } + } + else + { + usb1_host_bemp_int(Status, Int_enbl); + } + + /* Three dummy reads for clearing interrupt requests */ + dumy_sts = USB201.BEMPSTS; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/src/host/usb1_host_usbsig.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,637 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_usbsig.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "usb1_host.h" +#include "dev_drv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb1_host_EnableINT_Module(void); +static void usb1_host_Enable_AttachINT(void); +static void usb1_host_Disable_AttachINT(void); +static void usb1_host_Disable_BchgINT(void); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: usb1_host_InitModule +* Description : Initializes the USB module in USB host module. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_InitModule (void) +{ + uint16_t buf1; + uint16_t buf2; + uint16_t buf3; + + usb1_host_init_pipe_status(); + + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 1, + USB_SYSCFG_DCFM_SHIFT, + USB_SYSCFG_DCFM); /* HOST mode */ + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 1, + USB_SYSCFG_DRPD_SHIFT, + USB_SYSCFG_DRPD); /* PORT0 D+, D- setting */ + + do + { + buf1 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb1_host_delay_xms(50); + buf2 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb1_host_delay_xms(50); + buf3 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + + } while ((buf1 != buf2) || (buf1 != buf3)); + + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 1, + USB_SYSCFG_USBE_SHIFT, + USB_SYSCFG_USBE); + + USB201.CFIFOSEL = (uint16_t)(USB_HOST_BITRCNT | USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); + USB201.D0FIFOSEL = (uint16_t)( USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); + USB201.D1FIFOSEL = (uint16_t)( USB_HOST_BITMBW_8 | USB_HOST_BITBYTE_LITTLE); +} + +/******************************************************************************* +* Function Name: usb1_host_CheckAttach +* Description : Returns the USB device connection state. +* Arguments : none +* Return Value : uint16_t ; USB_HOST_ATTACH : Attached +* : ; USB_HOST_DETACH : not Attached +*******************************************************************************/ +uint16_t usb1_host_CheckAttach (void) +{ + uint16_t buf1; + uint16_t buf2; + uint16_t buf3; + uint16_t rhst; + + do + { + buf1 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb1_host_delay_xms(50); + buf2 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + Userdef_USB_usb1_host_delay_xms(50); + buf3 = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + + } while ((buf1 != buf2) || (buf1 != buf3)); + + rhst = RZA_IO_RegRead_16(&USB201.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (rhst == USB_HOST_UNDECID) + { + if (buf1 == USB_HOST_FS_JSTS) + { + if (g_usb1_host_SupportUsbDeviceSpeed == USB_HOST_HIGH_SPEED) + { + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 1, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + } + else + { + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + } + return USB_HOST_ATTACH; + } + else if (buf1 == USB_HOST_LS_JSTS) + { + /* Low Speed Device */ + RZA_IO_RegWrite_16(&USB201.SYSCFG0, + 0, + USB_SYSCFG_HSE_SHIFT, + USB_SYSCFG_HSE); + return USB_HOST_ATTACH; + } + else + { + /* Do Nothing */ + } + } + else if ((rhst == USB_HOST_HSMODE) || (rhst == USB_HOST_FSMODE)) + { + return USB_HOST_ATTACH; + } + else if (rhst == USB_HOST_LSMODE) + { + return USB_HOST_ATTACH; + } + else + { + /* Do Nothing */ + } + + return USB_HOST_DETACH; +} + +/******************************************************************************* +* Function Name: usb1_host_UsbAttach +* Description : Connects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_UsbAttach (void) +{ + usb1_host_EnableINT_Module(); + usb1_host_Disable_BchgINT(); + usb1_host_Disable_AttachINT(); + usb1_host_Enable_DetachINT(); +} + +/******************************************************************************* +* Function Name: usb1_host_UsbDetach +* Description : Disconnects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_UsbDetach (void) +{ + uint16_t pipe; + uint16_t devadr; + + g_usb1_host_driver_state = USB_HOST_DRV_DETACHED; + + /* Terminate all the pipes in which communications on port */ + /* are currently carried out */ + for (pipe = 0; pipe < (USB_HOST_MAX_PIPE_NO + 1); ++pipe) + { + if (g_usb1_host_pipe_status[pipe] != USB_HOST_PIPE_IDLE) + { + if (pipe == USB_HOST_PIPE0) + { + devadr = RZA_IO_RegRead_16(&USB201.DCPMAXP, + USB_DCPMAXP_DEVSEL_SHIFT, + USB_DCPMAXP_DEVSEL); + } + else + { + devadr = RZA_IO_RegRead_16(&g_usb1_host_pipemaxp[pipe], USB_PIPEMAXP_DEVSEL_SHIFT, USB_PIPEMAXP_DEVSEL); + } + + if (devadr == g_usb1_host_UsbAddress) + { + usb1_host_stop_transfer(pipe); + } + + g_usb1_host_pipe_status[pipe] = USB_HOST_PIPE_IDLE; + } + } + + g_usb1_host_ConfigNum = 0; + g_usb1_host_UsbAddress = 0; + g_usb1_host_default_max_packet[USB_HOST_DEVICE_0] = 64; + + usb1_host_UsbDetach2(); +} + +/******************************************************************************* +* Function Name: usb1_host_UsbDetach2 +* Description : Disconnects the USB device. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_UsbDetach2 (void) +{ + usb1_host_Disable_DetachINT(); + usb1_host_Disable_BchgINT(); + usb1_host_Enable_AttachINT(); +} + +/******************************************************************************* +* Function Name: usb1_host_UsbBusReset +* Description : Issues the USB bus reset signal. +* Arguments : none +* Return Value : uint16_t ; RHST +*******************************************************************************/ +uint16_t usb1_host_UsbBusReset (void) +{ + uint16_t buffer; + uint16_t loop; + + RZA_IO_RegWrite_16(&USB201.DVSTCTR0, + 1, + USB_DVSTCTR0_USBRST_SHIFT, + USB_DVSTCTR0_USBRST); + RZA_IO_RegWrite_16(&USB201.DVSTCTR0, + 0, + USB_DVSTCTR0_UACT_SHIFT, + USB_DVSTCTR0_UACT); + + Userdef_USB_usb1_host_delay_xms(50); + + buffer = USB201.DVSTCTR0; + buffer &= (uint16_t)(~(USB_HOST_BITRST)); + buffer |= USB_HOST_BITUACT; + USB201.DVSTCTR0 = buffer; + + Userdef_USB_usb1_host_delay_xms(20); + + for (loop = 0, buffer = USB_HOST_HSPROC; loop < 3; ++loop) + { + buffer = RZA_IO_RegRead_16(&USB201.DVSTCTR0, + USB_DVSTCTR0_RHST_SHIFT, + USB_DVSTCTR0_RHST); + if (buffer == USB_HOST_HSPROC) + { + Userdef_USB_usb1_host_delay_xms(10); + } + else + { + break; + } + } + + return buffer; +} + +/******************************************************************************* +* Function Name: usb1_host_UsbResume +* Description : Issues the USB resume signal. +* Arguments : none +* Return Value : int32_t ; DEVDRV_SUCCESS +* : ; DEVDRV_ERROR +*******************************************************************************/ +int32_t usb1_host_UsbResume (void) +{ + uint16_t buf; + + if ((g_usb1_host_driver_state & USB_HOST_DRV_SUSPEND) == 0) + { + /* not SUSPEND */ + return DEVDRV_ERROR; + } + + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); + RZA_IO_RegWrite_16(&USB201.DVSTCTR0, + 1, + USB_DVSTCTR0_RESUME_SHIFT, + USB_DVSTCTR0_RESUME); + Userdef_USB_usb1_host_delay_xms(20); + + buf = USB201.DVSTCTR0; + buf &= (uint16_t)(~(USB_HOST_BITRESUME)); + buf |= USB_HOST_BITUACT; + USB201.DVSTCTR0 = buf; + + g_usb1_host_driver_state &= (uint16_t)~USB_HOST_DRV_SUSPEND; + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb1_host_UsbSuspend +* Description : Issues the USB suspend signal. +* Arguments : none +* Return Value : int32_t ; DEVDRV_SUCCESS :not SUSPEND +* : ; DEVDRV_ERROR :SUSPEND +*******************************************************************************/ +int32_t usb1_host_UsbSuspend (void) +{ + uint16_t buf; + + if ((g_usb1_host_driver_state & USB_HOST_DRV_SUSPEND) != 0) + { + /* SUSPEND */ + return DEVDRV_ERROR; + } + + RZA_IO_RegWrite_16(&USB201.DVSTCTR0, + 0, + USB_DVSTCTR0_UACT_SHIFT, + USB_DVSTCTR0_UACT); + + Userdef_USB_usb1_host_delay_xms(5); + + buf = RZA_IO_RegRead_16(&USB201.SYSSTS0, + USB_SYSSTS0_LNST_SHIFT, + USB_SYSSTS0_LNST); + if ((buf != USB_HOST_FS_JSTS) && (buf != USB_HOST_LS_JSTS)) + { + usb1_host_UsbDetach(); + } + else + { + g_usb1_host_driver_state |= USB_HOST_DRV_SUSPEND; + } + + return DEVDRV_SUCCESS; +} + +/******************************************************************************* +* Function Name: usb1_host_Enable_DetachINT +* Description : Enables the USB disconnection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_Enable_DetachINT (void) +{ + USB201.INTSTS1 = (uint16_t)(~(USB_HOST_BITDTCH)); + RZA_IO_RegWrite_16(&USB201.INTENB1, + 1, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); +} + +/******************************************************************************* +* Function Name: usb1_host_Disable_DetachINT +* Description : Disables the USB disconnection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_Disable_DetachINT (void) +{ + USB201.INTSTS1 = (uint16_t)(~(USB_HOST_BITDTCH)); + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_DTCHE_SHIFT, + USB_INTENB1_DTCHE); +} + +/******************************************************************************* +* Function Name: usb1_host_Enable_AttachINT +* Description : Enables the USB connection detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_Enable_AttachINT (void) +{ + USB201.INTSTS1 = (uint16_t)(~(USB_HOST_BITATTCH)); + RZA_IO_RegWrite_16(&USB201.INTENB1, + 1, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); +} + +/******************************************************************************* +* Function Name: usb1_host_Disable_AttachINT +* Description : Disables the USB connection detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_Disable_AttachINT (void) +{ + USB201.INTSTS1 = (uint16_t)(~(USB_HOST_BITATTCH)); + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_ATTCHE_SHIFT, + USB_INTENB1_ATTCHE); +} + +/******************************************************************************* +* Function Name: usb1_host_Disable_BchgINT +* Description : Disables the USB bus change detection interrupt. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_Disable_BchgINT (void) +{ + USB201.INTSTS1 = (uint16_t)(~(USB_HOST_BITBCHG)); + RZA_IO_RegWrite_16(&USB201.INTENB1, + 0, + USB_INTENB1_BCHGE_SHIFT, + USB_INTENB1_BCHGE); +} + +/******************************************************************************* +* Function Name: usb1_host_set_devadd +* Description : DEVADDn register is set by specified value +* Arguments : uint16_t addr : Device address +* : uint16_t *devadd : Set value +* Return Value : none +*******************************************************************************/ +void usb1_host_set_devadd (uint16_t addr, uint16_t * devadd) +{ + uint16_t * ptr; + uint16_t ret_flag = DEVDRV_FLAG_ON; // avoid warning. + + switch (addr) + { + case USB_HOST_DEVICE_0: + ptr = (uint16_t *)&USB201.DEVADD0; + break; + + case USB_HOST_DEVICE_1: + ptr = (uint16_t *)&USB201.DEVADD1; + break; + + case USB_HOST_DEVICE_2: + ptr = (uint16_t *)&USB201.DEVADD2; + break; + + case USB_HOST_DEVICE_3: + ptr = (uint16_t *)&USB201.DEVADD3; + break; + + case USB_HOST_DEVICE_4: + ptr = (uint16_t *)&USB201.DEVADD4; + break; + + case USB_HOST_DEVICE_5: + ptr = (uint16_t *)&USB201.DEVADD5; + break; + + case USB_HOST_DEVICE_6: + ptr = (uint16_t *)&USB201.DEVADD6; + break; + + case USB_HOST_DEVICE_7: + ptr = (uint16_t *)&USB201.DEVADD7; + break; + + case USB_HOST_DEVICE_8: + ptr = (uint16_t *)&USB201.DEVADD8; + break; + + case USB_HOST_DEVICE_9: + ptr = (uint16_t *)&USB201.DEVADD9; + break; + + case USB_HOST_DEVICE_10: + ptr = (uint16_t *)&USB201.DEVADDA; + break; + + default: + ret_flag = DEVDRV_FLAG_OFF; + break; + } + + if (ret_flag == DEVDRV_FLAG_ON) + { + *ptr = (uint16_t)(*devadd & USB_HOST_DEVADD_MASK); + } +} + +/******************************************************************************* +* Function Name: usb1_host_get_devadd +* Description : DEVADDn register is obtained +* Arguments : uint16_t addr : Device address +* : uint16_t *devadd : USB_HOST_DEVADD register value +* Return Value : none +*******************************************************************************/ +void usb1_host_get_devadd (uint16_t addr, uint16_t * devadd) +{ + uint16_t * ptr; + uint16_t ret_flag = DEVDRV_FLAG_ON; // avoid warning. + + switch (addr) + { + case USB_HOST_DEVICE_0: + ptr = (uint16_t *)&USB201.DEVADD0; + break; + + case USB_HOST_DEVICE_1: + ptr = (uint16_t *)&USB201.DEVADD1; + break; + + case USB_HOST_DEVICE_2: + ptr = (uint16_t *)&USB201.DEVADD2; + break; + + case USB_HOST_DEVICE_3: + ptr = (uint16_t *)&USB201.DEVADD3; + break; + + case USB_HOST_DEVICE_4: + ptr = (uint16_t *)&USB201.DEVADD4; + break; + + case USB_HOST_DEVICE_5: + ptr = (uint16_t *)&USB201.DEVADD5; + break; + + case USB_HOST_DEVICE_6: + ptr = (uint16_t *)&USB201.DEVADD6; + break; + + case USB_HOST_DEVICE_7: + ptr = (uint16_t *)&USB201.DEVADD7; + break; + + case USB_HOST_DEVICE_8: + ptr = (uint16_t *)&USB201.DEVADD8; + break; + + case USB_HOST_DEVICE_9: + ptr = (uint16_t *)&USB201.DEVADD9; + break; + + case USB_HOST_DEVICE_10: + ptr = (uint16_t *)&USB201.DEVADDA; + break; + + default: + ret_flag = DEVDRV_FLAG_OFF; + break; + } + + if (ret_flag == DEVDRV_FLAG_ON) + { + *devadd = *ptr; + } +} + +/******************************************************************************* +* Function Name: usb1_host_EnableINT_Module +* Description : Enables BEMP/NRDY/BRDY interrupt and SIGN/SACK interrupt. +* : Enables NRDY/BEMP interrupt in the pipe0. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void usb1_host_EnableINT_Module (void) +{ + uint16_t buf; + + buf = USB201.INTENB0; + buf |= (USB_HOST_BITBEMPE | USB_HOST_BITNRDYE | USB_HOST_BITBRDYE); + USB201.INTENB0 = buf; + + buf = USB201.INTENB1; + buf |= (USB_HOST_BITSIGNE | USB_HOST_BITSACKE); + USB201.INTENB1 = buf; + + usb1_host_enable_nrdy_int(USB_HOST_PIPE0); + usb1_host_enable_bemp_int(USB_HOST_PIPE0); +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/src/userdef/usb1_host_dmacdrv.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,698 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_dmacdrv.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include "r_typedefs.h" +#include "iodefine.h" +#include "rza_io_regrw.h" +#include "usb1_host_dmacdrv.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define DMAC_INDEFINE (255) /* Macro definition when REQD bit is not used */ + +/* ==== Request setting information for on-chip peripheral module ==== */ +typedef enum dmac_peri_req_reg_type +{ + DMAC_REQ_MID, + DMAC_REQ_RID, + DMAC_REQ_AM, + DMAC_REQ_LVL, + DMAC_REQ_REQD +} dmac_peri_req_reg_type_t; + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ +/* ==== Prototype declaration ==== */ + +/* ==== Global variable ==== */ +/* On-chip peripheral module request setting table */ +static const uint8_t usb1_host_dmac_peri_req_init_table[8][5] = +{ + /* MID,RID, AM,LVL,REQD */ + { 32, 3, 2, 1, 1}, /* USB_0 channel 0 transmit FIFO empty */ + { 32, 3, 2, 1, 0}, /* USB_0 channel 0 receive FIFO full */ + { 33, 3, 2, 1, 1}, /* USB_0 channel 1 transmit FIFO empty */ + { 33, 3, 2, 1, 0}, /* USB_0 channel 1 receive FIFO full */ + { 34, 3, 2, 1, 1}, /* USB_1 channel 0 transmit FIFO empty */ + { 34, 3, 2, 1, 0}, /* USB_1 channel 0 receive FIFO full */ + { 35, 3, 2, 1, 1}, /* USB_1 channel 1 transmit FIFO empty */ + { 35, 3, 2, 1, 0}, /* USB_1 channel 1 receive FIFO full */ +}; + + +/******************************************************************************* +* Function Name: usb1_host_DMAC3_PeriReqInit +* Description : Sets the register mode for DMA mode and the on-chip peripheral +* : module request for transfer request for DMAC channel 3. +* : Executes DMAC initial setting using the DMA information +* : specified by the argument *trans_info and the enabled/disabled +* : continuous transfer specified by the argument continuation. +* : Registers DMAC channel 3 interrupt handler function and sets +* : the interrupt priority level. Then enables transfer completion +* : interrupt. +* Arguments : dmac_transinfo_t * trans_info : Setting information to DMAC +* : : register +* : uint32_t dmamode : DMA mode (only for DMAC_MODE_REGISTER) +* : uint32_t continuation : Set continuous transfer to be valid +* : : after DMA transfer has been completed +* : DMAC_SAMPLE_CONTINUATION : Execute continuous transfer +* : DMAC_SAMPLE_SINGLE : Do not execute continuous +* : : transfer +* : uint32_t request_factor : Factor for on-chip peripheral module +* : : request +* : DMAC_REQ_OSTM0TINT : OSTM_0 compare match +* : DMAC_REQ_OSTM1TINT : OSTM_1 compare match +* : DMAC_REQ_TGI0A : MTU2_0 input capture/compare match +* : : +* : uint32_t req_direction : Setting value of CHCFG_n register +* : : REQD bit +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC3_PeriReqInit (const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction) +{ + /* ==== Register mode ==== */ + if (DMAC_MODE_REGISTER == dmamode) + { + /* ==== Next0 register set ==== */ + DMAC3.N0SA_n = trans_info->src_addr; /* Start address of transfer source */ + DMAC3.N0DA_n = trans_info->dst_addr; /* Start address of transfer destination */ + DMAC3.N0TB_n = trans_info->count; /* Total transfer byte count */ + + /* DAD : Transfer destination address counting direction */ + /* SAD : Transfer source address counting direction */ + /* DDS : Transfer destination transfer size */ + /* SDS : Transfer source transfer size */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + trans_info->daddr_dir, + DMAC3_CHCFG_n_DAD_SHIFT, + DMAC3_CHCFG_n_DAD); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + trans_info->saddr_dir, + DMAC3_CHCFG_n_SAD_SHIFT, + DMAC3_CHCFG_n_SAD); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + trans_info->dst_size, + DMAC3_CHCFG_n_DDS_SHIFT, + DMAC3_CHCFG_n_DDS); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + trans_info->src_size, + DMAC3_CHCFG_n_SDS_SHIFT, + DMAC3_CHCFG_n_SDS); + + /* DMS : Register mode */ + /* RSEL : Select Next0 register set */ + /* SBE : No discharge of buffer data when aborted */ + /* DEM : No DMA interrupt mask */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_DMS_SHIFT, + DMAC3_CHCFG_n_DMS); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_RSEL_SHIFT, + DMAC3_CHCFG_n_RSEL); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_SBE_SHIFT, + DMAC3_CHCFG_n_SBE); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_DEM_SHIFT, + DMAC3_CHCFG_n_DEM); + + /* ---- Continuous transfer ---- */ + if (DMAC_SAMPLE_CONTINUATION == continuation) + { + /* REN : Execute continuous transfer */ + /* RSW : Change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 1, + DMAC3_CHCFG_n_REN_SHIFT, + DMAC3_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 1, + DMAC3_CHCFG_n_RSW_SHIFT, + DMAC3_CHCFG_n_RSW); + } + /* ---- Single transfer ---- */ + else + { + /* REN : Do not execute continuous transfer */ + /* RSW : Do not change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_REN_SHIFT, + DMAC3_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_RSW_SHIFT, + DMAC3_CHCFG_n_RSW); + } + + /* TM : Single transfer */ + /* SEL : Channel setting */ + /* HIEN, LOEN : On-chip peripheral module request */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_TM_SHIFT, + DMAC3_CHCFG_n_TM); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 3, + DMAC3_CHCFG_n_SEL_SHIFT, + DMAC3_CHCFG_n_SEL); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 1, + DMAC3_CHCFG_n_HIEN_SHIFT, + DMAC3_CHCFG_n_HIEN); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + 0, + DMAC3_CHCFG_n_LOEN_SHIFT, + DMAC3_CHCFG_n_LOEN); + + /* ---- Set factor by specified on-chip peripheral module request ---- */ + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_AM], + DMAC3_CHCFG_n_AM_SHIFT, + DMAC3_CHCFG_n_AM); + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_LVL], + DMAC3_CHCFG_n_LVL_SHIFT, + DMAC3_CHCFG_n_LVL); + if (usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD] != DMAC_INDEFINE) + { + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD], + DMAC3_CHCFG_n_REQD_SHIFT, + DMAC3_CHCFG_n_REQD); + } + else + { + RZA_IO_RegWrite_32(&DMAC3.CHCFG_n, + req_direction, + DMAC3_CHCFG_n_REQD_SHIFT, + DMAC3_CHCFG_n_REQD); + } + RZA_IO_RegWrite_32(&DMAC23.DMARS, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_RID], + DMAC23_DMARS_CH3_RID_SHIFT, + DMAC23_DMARS_CH3_RID); + RZA_IO_RegWrite_32(&DMAC23.DMARS, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_MID], + DMAC23_DMARS_CH3_MID_SHIFT, + DMAC23_DMARS_CH3_MID); + + /* PR : Round robin mode */ + RZA_IO_RegWrite_32(&DMAC07.DCTRL_0_7, + 1, + DMAC07_DCTRL_0_7_PR_SHIFT, + DMAC07_DCTRL_0_7_PR); + } +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC3_Open +* Description : Enables DMAC channel 3 transfer. +* Arguments : uint32_t req : DMAC request mode +* Return Value : 0 : Succeeded in enabling DMA transfer +* : -1 : Failed to enable DMA transfer (due to DMA operation) +*******************************************************************************/ +int32_t usb1_host_DMAC3_Open (uint32_t req) +{ + int32_t ret; + volatile uint8_t dummy; + + /* Transferable? */ + if ((0 == RZA_IO_RegRead_32(&DMAC3.CHSTAT_n, + DMAC3_CHSTAT_n_EN_SHIFT, + DMAC3_CHSTAT_n_EN)) && + (0 == RZA_IO_RegRead_32(&DMAC3.CHSTAT_n, + DMAC3_CHSTAT_n_TACT_SHIFT, + DMAC3_CHSTAT_n_TACT))) + { + /* Clear Channel Status Register */ + RZA_IO_RegWrite_32(&DMAC3.CHCTRL_n, + 1, + DMAC3_CHCTRL_n_SWRST_SHIFT, + DMAC3_CHCTRL_n_SWRST); + dummy = RZA_IO_RegRead_32(&DMAC3.CHCTRL_n, + DMAC3_CHCTRL_n_SWRST_SHIFT, + DMAC3_CHCTRL_n_SWRST); + /* Enable DMA transfer */ + RZA_IO_RegWrite_32(&DMAC3.CHCTRL_n, + 1, + DMAC3_CHCTRL_n_SETEN_SHIFT, + DMAC3_CHCTRL_n_SETEN); + + /* ---- Request by software ---- */ + if (DMAC_REQ_MODE_SOFT == req) + { + /* DMA transfer Request by software */ + RZA_IO_RegWrite_32(&DMAC3.CHCTRL_n, + 1, + DMAC3_CHCTRL_n_STG_SHIFT, + DMAC3_CHCTRL_n_STG); + } + + ret = 0; + } + else + { + ret = -1; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC3_Close +* Description : Aborts DMAC channel 3 transfer. Returns the remaining transfer +* : byte count at the time of DMA transfer abort to the argument +* : *remain. +* Arguments : uint32_t * remain : Remaining transfer byte count when +* : : DMA transfer is aborted +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC3_Close (uint32_t * remain) +{ + + /* ==== Abort transfer ==== */ + RZA_IO_RegWrite_32(&DMAC3.CHCTRL_n, + 1, + DMAC3_CHCTRL_n_CLREN_SHIFT, + DMAC3_CHCTRL_n_CLREN); + + while (1 == RZA_IO_RegRead_32(&DMAC3.CHSTAT_n, + DMAC3_CHSTAT_n_TACT_SHIFT, + DMAC3_CHSTAT_n_TACT)) + { + /* Loop until transfer is aborted */ + } + + while (1 == RZA_IO_RegRead_32(&DMAC3.CHSTAT_n, + DMAC3_CHSTAT_n_EN_SHIFT, + DMAC3_CHSTAT_n_EN)) + { + /* Loop until 0 is set in EN before checking the remaining transfer byte count */ + } + /* ==== Obtain remaining transfer byte count ==== */ + *remain = DMAC3.CRTB_n; +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC3_Load_Set +* Description : Sets the transfer source address, transfer destination +* : address, and total transfer byte count respectively +* : specified by the argument src_addr, dst_addr, and count to +* : DMAC channel 3 as DMA transfer information. +* : Sets the register set selected by the CHCFG_n register +* : RSEL bit from the Next0 or Next1 register set. +* : This function should be called when DMA transfer of DMAC +* : channel 3 is aboted. +* Arguments : uint32_t src_addr : Transfer source address +* : uint32_t dst_addr : Transfer destination address +* : uint32_t count : Total transfer byte count +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC3_Load_Set (uint32_t src_addr, uint32_t dst_addr, uint32_t count) +{ + uint8_t reg_set; + + /* Obtain register set in use */ + reg_set = RZA_IO_RegRead_32(&DMAC3.CHSTAT_n, + DMAC3_CHSTAT_n_SR_SHIFT, + DMAC3_CHSTAT_n_SR); + + /* ==== Load ==== */ + if (0 == reg_set) + { + /* ---- Next0 Register Set ---- */ + DMAC3.N0SA_n = src_addr; /* Start address of transfer source */ + DMAC3.N0DA_n = dst_addr; /* Start address of transfer destination */ + DMAC3.N0TB_n = count; /* Total transfer byte count */ + } + else + { + /* ---- Next1 Register Set ---- */ + DMAC3.N1SA_n = src_addr; /* Start address of transfer source */ + DMAC3.N1DA_n = dst_addr; /* Start address of transfer destination */ + DMAC3.N1TB_n = count; /* Total transfer byte count */ + } +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC4_PeriReqInit +* Description : Sets the register mode for DMA mode and the on-chip peripheral +* : module request for transfer request for DMAC channel 4. +* : Executes DMAC initial setting using the DMA information +* : specified by the argument *trans_info and the enabled/disabled +* : continuous transfer specified by the argument continuation. +* : Registers DMAC channel 4 interrupt handler function and sets +* : the interrupt priority level. Then enables transfer completion +* : interrupt. +* Arguments : dmac_transinfo_t * trans_info : Setting information to DMAC +* : : register +* : uint32_t dmamode : DMA mode (only for DMAC_MODE_REGISTER) +* : uint32_t continuation : Set continuous transfer to be valid +* : : after DMA transfer has been completed +* : DMAC_SAMPLE_CONTINUATION : Execute continuous transfer +* : DMAC_SAMPLE_SINGLE : Do not execute continuous +* : : transfer +* : uint32_t request_factor : Factor for on-chip peripheral module +* : : request +* : DMAC_REQ_OSTM0TINT : OSTM_0 compare match +* : DMAC_REQ_OSTM1TINT : OSTM_1 compare match +* : DMAC_REQ_TGI0A : MTU2_0 input capture/compare match +* : : +* : uint32_t req_direction : Setting value of CHCFG_n register +* : : REQD bit +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC4_PeriReqInit (const dmac_transinfo_t * trans_info, uint32_t dmamode, uint32_t continuation, + uint32_t request_factor, uint32_t req_direction) +{ + /* ==== Register mode ==== */ + if (DMAC_MODE_REGISTER == dmamode) + { + /* ==== Next0 register set ==== */ + DMAC4.N0SA_n = trans_info->src_addr; /* Start address of transfer source */ + DMAC4.N0DA_n = trans_info->dst_addr; /* Start address of transfer destination */ + DMAC4.N0TB_n = trans_info->count; /* Total transfer byte count */ + + /* DAD : Transfer destination address counting direction */ + /* SAD : Transfer source address counting direction */ + /* DDS : Transfer destination transfer size */ + /* SDS : Transfer source transfer size */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + trans_info->daddr_dir, + DMAC4_CHCFG_n_DAD_SHIFT, + DMAC4_CHCFG_n_DAD); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + trans_info->saddr_dir, + DMAC4_CHCFG_n_SAD_SHIFT, + DMAC4_CHCFG_n_SAD); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + trans_info->dst_size, + DMAC4_CHCFG_n_DDS_SHIFT, + DMAC4_CHCFG_n_DDS); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + trans_info->src_size, + DMAC4_CHCFG_n_SDS_SHIFT, + DMAC4_CHCFG_n_SDS); + + /* DMS : Register mode */ + /* RSEL : Select Next0 register set */ + /* SBE : No discharge of buffer data when aborted */ + /* DEM : No DMA interrupt mask */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_DMS_SHIFT, + DMAC4_CHCFG_n_DMS); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_RSEL_SHIFT, + DMAC4_CHCFG_n_RSEL); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_SBE_SHIFT, + DMAC4_CHCFG_n_SBE); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_DEM_SHIFT, + DMAC4_CHCFG_n_DEM); + + /* ---- Continuous transfer ---- */ + if (DMAC_SAMPLE_CONTINUATION == continuation) + { + /* REN : Execute continuous transfer */ + /* RSW : Change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 1, + DMAC4_CHCFG_n_REN_SHIFT, + DMAC4_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 1, + DMAC4_CHCFG_n_RSW_SHIFT, + DMAC4_CHCFG_n_RSW); + } + /* ---- Single transfer ---- */ + else + { + /* REN : Do not execute continuous transfer */ + /* RSW : Do not change register set when DMA transfer is completed. */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_REN_SHIFT, + DMAC4_CHCFG_n_REN); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_RSW_SHIFT, + DMAC4_CHCFG_n_RSW); + } + + /* TM : Single transfer */ + /* SEL : Channel setting */ + /* HIEN, LOEN : On-chip peripheral module request */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_TM_SHIFT, + DMAC4_CHCFG_n_TM); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 4, + DMAC4_CHCFG_n_SEL_SHIFT, + DMAC4_CHCFG_n_SEL); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 1, + DMAC4_CHCFG_n_HIEN_SHIFT, + DMAC4_CHCFG_n_HIEN); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + 0, + DMAC4_CHCFG_n_LOEN_SHIFT, + DMAC4_CHCFG_n_LOEN); + + /* ---- Set factor by specified on-chip peripheral module request ---- */ + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_AM], + DMAC4_CHCFG_n_AM_SHIFT, + DMAC4_CHCFG_n_AM); + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_LVL], + DMAC4_CHCFG_n_LVL_SHIFT, + DMAC4_CHCFG_n_LVL); + if (usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD] != DMAC_INDEFINE) + { + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_REQD], + DMAC4_CHCFG_n_REQD_SHIFT, + DMAC4_CHCFG_n_REQD); + } + else + { + RZA_IO_RegWrite_32(&DMAC4.CHCFG_n, + req_direction, + DMAC4_CHCFG_n_REQD_SHIFT, + DMAC4_CHCFG_n_REQD); + } + RZA_IO_RegWrite_32(&DMAC45.DMARS, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_RID], + DMAC45_DMARS_CH4_RID_SHIFT, + DMAC45_DMARS_CH4_RID); + RZA_IO_RegWrite_32(&DMAC45.DMARS, + usb1_host_dmac_peri_req_init_table[request_factor][DMAC_REQ_MID], + DMAC45_DMARS_CH4_MID_SHIFT, + DMAC45_DMARS_CH4_MID); + + /* PR : Round robin mode */ + RZA_IO_RegWrite_32(&DMAC07.DCTRL_0_7, + 1, + DMAC07_DCTRL_0_7_PR_SHIFT, + DMAC07_DCTRL_0_7_PR); + } +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC4_Open +* Description : Enables DMAC channel 4 transfer. +* Arguments : uint32_t req : DMAC request mode +* Return Value : 0 : Succeeded in enabling DMA transfer +* : -1 : Failed to enable DMA transfer (due to DMA operation) +*******************************************************************************/ +int32_t usb1_host_DMAC4_Open (uint32_t req) +{ + int32_t ret; + volatile uint8_t dummy; + + /* Transferable? */ + if ((0 == RZA_IO_RegRead_32(&DMAC4.CHSTAT_n, + DMAC4_CHSTAT_n_EN_SHIFT, + DMAC4_CHSTAT_n_EN)) && + (0 == RZA_IO_RegRead_32(&DMAC4.CHSTAT_n, + DMAC4_CHSTAT_n_TACT_SHIFT, + DMAC4_CHSTAT_n_TACT))) + { + /* Clear Channel Status Register */ + RZA_IO_RegWrite_32(&DMAC4.CHCTRL_n, + 1, + DMAC4_CHCTRL_n_SWRST_SHIFT, + DMAC4_CHCTRL_n_SWRST); + dummy = RZA_IO_RegRead_32(&DMAC4.CHCTRL_n, + DMAC4_CHCTRL_n_SWRST_SHIFT, + DMAC4_CHCTRL_n_SWRST); + /* Enable DMA transfer */ + RZA_IO_RegWrite_32(&DMAC4.CHCTRL_n, + 1, + DMAC4_CHCTRL_n_SETEN_SHIFT, + DMAC4_CHCTRL_n_SETEN); + + /* ---- Request by software ---- */ + if (DMAC_REQ_MODE_SOFT == req) + { + /* DMA transfer Request by software */ + RZA_IO_RegWrite_32(&DMAC4.CHCTRL_n, + 1, + DMAC4_CHCTRL_n_STG_SHIFT, + DMAC4_CHCTRL_n_STG); + } + + ret = 0; + } + else + { + ret = -1; + } + + return ret; +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC4_Close +* Description : Aborts DMAC channel 4 transfer. Returns the remaining transfer +* : byte count at the time of DMA transfer abort to the argument +* : *remain. +* Arguments : uint32_t * remain : Remaining transfer byte count when +* : : DMA transfer is aborted +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC4_Close (uint32_t * remain) +{ + + /* ==== Abort transfer ==== */ + RZA_IO_RegWrite_32(&DMAC4.CHCTRL_n, + 1, + DMAC4_CHCTRL_n_CLREN_SHIFT, + DMAC4_CHCTRL_n_CLREN); + + while (1 == RZA_IO_RegRead_32(&DMAC4.CHSTAT_n, + DMAC4_CHSTAT_n_TACT_SHIFT, + DMAC4_CHSTAT_n_TACT)) + { + /* Loop until transfer is aborted */ + } + + while (1 == RZA_IO_RegRead_32(&DMAC4.CHSTAT_n, + DMAC4_CHSTAT_n_EN_SHIFT, + DMAC4_CHSTAT_n_EN)) + { + /* Loop until 0 is set in EN before checking the remaining transfer byte count */ + } + /* ==== Obtain remaining transfer byte count ==== */ + *remain = DMAC4.CRTB_n; +} + +/******************************************************************************* +* Function Name: usb1_host_DMAC4_Load_Set +* Description : Sets the transfer source address, transfer destination +* : address, and total transfer byte count respectively +* : specified by the argument src_addr, dst_addr, and count to +* : DMAC channel 4 as DMA transfer information. +* : Sets the register set selected by the CHCFG_n register +* : RSEL bit from the Next0 or Next1 register set. +* : This function should be called when DMA transfer of DMAC +* : channel 4 is aboted. +* Arguments : uint32_t src_addr : Transfer source address +* : uint32_t dst_addr : Transfer destination address +* : uint32_t count : Total transfer byte count +* Return Value : none +*******************************************************************************/ +void usb1_host_DMAC4_Load_Set (uint32_t src_addr, uint32_t dst_addr, uint32_t count) +{ + uint8_t reg_set; + + /* Obtain register set in use */ + reg_set = RZA_IO_RegRead_32(&DMAC4.CHSTAT_n, + DMAC4_CHSTAT_n_SR_SHIFT, + DMAC4_CHSTAT_n_SR); + + /* ==== Load ==== */ + if (0 == reg_set) + { + /* ---- Next0 Register Set ---- */ + DMAC4.N0SA_n = src_addr; /* Start address of transfer source */ + DMAC4.N0DA_n = dst_addr; /* Start address of transfer destination */ + DMAC4.N0TB_n = count; /* Total transfer byte count */ + } + else + { + /* ---- Next1 Register Set ---- */ + DMAC4.N1SA_n = src_addr; /* Start address of transfer source */ + DMAC4.N1DA_n = dst_addr; /* Start address of transfer destination */ + DMAC4.N1TB_n = count; /* Total transfer byte count */ + } +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb1/src/userdef/usb1_host_userdef.c Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,778 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ +/******************************************************************************* +* File Name : usb1_host_userdef.c +* $Rev: 1116 $ +* $Date:: 2014-07-09 16:29:19 +0900#$ +* Device(s) : RZ/A1H +* Tool-Chain : +* OS : None +* H/W Platform : +* Description : RZ/A1H R7S72100 USB Sample Program +* Operation : +* Limitations : +*******************************************************************************/ + + +/******************************************************************************* +Includes <System Includes> , "Project Includes" +*******************************************************************************/ +#include <stdio.h> +#include "cmsis_os.h" +#include "r_typedefs.h" +#include "iodefine.h" +#include "devdrv_usb_host_api.h" +#include "usb1_host.h" +#include "VKRZA1H.h" /* INTC Driver Header */ +#include "usb1_host_dmacdrv.h" +#include "ohci_wrapp_RZ_A1_local.h" + + +/******************************************************************************* +Typedef definitions +*******************************************************************************/ + + +/******************************************************************************* +Macro definitions +*******************************************************************************/ +#define DUMMY_ACCESS OSTM0CNT + +/* #define CACHE_WRITEBACK */ + + +/******************************************************************************* +Imported global variables and functions (from other files) +*******************************************************************************/ +extern int32_t io_cwb(unsigned long start, unsigned long end); + + +/******************************************************************************* +Exported global variables and functions (to be accessed by other files) +*******************************************************************************/ +static void usb1_host_enable_dmac0(uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc); +static void usb1_host_enable_dmac1(uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc); +static void Userdef_USB_usb1_host_delay_10us_2(void); + + +/******************************************************************************* +Private global variables and functions +*******************************************************************************/ + + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_d0fifo_dmaintid +* Description : get D0FIFO DMA Interrupt ID +* Arguments : none +* Return Value : D0FIFO DMA Interrupt ID +*******************************************************************************/ +uint16_t Userdef_USB_usb1_host_d0fifo_dmaintid (void) +{ +#if(1) /* ohci_wrapp */ + return 0xFFFF; +#else + return DMAINT1_IRQn; +#endif +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_d1fifo_dmaintid +* Description : get D1FIFO DMA Interrupt ID +* Arguments : none +* Return Value : D1FIFO DMA Interrupt ID +*******************************************************************************/ +uint16_t Userdef_USB_usb1_host_d1fifo_dmaintid (void) +{ +#if(1) /* ohci_wrapp */ + return 0xFFFF; +#else + return DMAINT2_IRQn; +#endif +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_attach +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_attach (void) +{ +// printf("\n"); +// printf("channel 1 attach device\n"); +// printf("\n"); + ohciwrapp_loc_Connect(1); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_detach +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_detach (void) +{ +// printf("\n"); +// printf("channel 1 detach device\n"); +// printf("\n"); + ohciwrapp_loc_Connect(0); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_delay_1ms +* Description : Wait for the software of 1ms. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_delay_1ms (void) +{ + osDelay(1); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_delay_xms +* Description : Wait for the software in the period of time specified by the +* : argument. +* : Alter this function according to the user's system. +* Arguments : uint32_t msec ; Wait Time (msec) +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_delay_xms (uint32_t msec) +{ + osDelay(msec); +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_delay_10us +* Description : Waits for software for the period specified by the argument. +* : Alter this function according to the user's system. +* Arguments : uint32_t usec ; Wait Time(x 10usec) +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_delay_10us (uint32_t usec) +{ + volatile int i; + + /* Wait 10us (Please change for your MCU) */ + for (i = 0; i < usec; ++i) + { + Userdef_USB_usb1_host_delay_10us_2(); + } +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_delay_10us_2 +* Description : Waits for software for the period specified by the argument. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +static void Userdef_USB_usb1_host_delay_10us_2 (void) +{ + volatile int i; + volatile unsigned long tmp; + + /* Wait 1us (Please change for your MCU) */ + for (i = 0; i < 14; ++i) + { + tmp = DUMMY_ACCESS; + } +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_delay_500ns +* Description : Wait for software for 500ns. +* : Alter this function according to the user's system. +* Arguments : none +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_delay_500ns (void) +{ + volatile int i; + volatile unsigned long tmp; + + /* Wait 500ns (Please change for your MCU) */ + /* Wait 500ns I clock 266MHz */ + tmp = DUMMY_ACCESS; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_start_dma +* Description : Enables DMA transfer on the information specified by the argument. +* : Set DMAC register by this function to enable DMA transfer. +* : After executing this function, USB module is set to start DMA +* : transfer. DMA transfer should not wait for DMA transfer complete. +* Arguments : USB_HOST_DMA_t *dma : DMA parameter +* : typedef struct{ +* : uint32_t fifo; FIFO for using +* : uint32_t buffer; Start address of transfer source/destination +* : uint32_t bytes; Transfer size(Byte) +* : uint32_t dir; Transfer direction(0:Buffer->FIFO, 1:FIFO->Buffer) +* : uint32_t size; DMA transfer size +* : } USB_HOST_DMA_t; +* : uint16_t dfacc ; 0 : cycle steal mode +* : 1 : 16byte continuous mode +* : 2 : 32byte continuous mode +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_start_dma (USB_HOST_DMA_t * dma, uint16_t dfacc) +{ + uint32_t trncount; + uint32_t src; + uint32_t dst; + uint32_t size; + uint32_t dir; +#ifdef CACHE_WRITEBACK + uint32_t ptr; +#endif + + trncount = dma->bytes; + dir = dma->dir; + + if (dir == USB_HOST_FIFO2BUF) + { + /* DxFIFO determination */ + dst = dma->buffer; +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB201.D1FIFO.UINT32); + } + size = dma->size; + + if (size == 0) + { + src += 3; /* byte access */ + } + else if (size == 1) + { + src += 2; /* short access */ + } + else + { + /* Do Nothing */ + } +#else + size = dma->size; + + if (size == 2) + { + /* 32bit access */ + if (dfacc == 2) + { + /* 32byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFOB0); + } + else + { + src = (uint32_t)(&USB201.D1FIFOB0); + } + } + else if (dfacc == 1) + { + /* 16byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFOB0); + } + else + { + src = (uint32_t)(&USB201.D1FIFOB0); + } + } + else + { + /* normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB201.D1FIFO.UINT32); + } + } + } + else if (size == 1) + { + /* 16bit access */ + dfacc = 0; /* force normal access */ + + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB201.D1FIFO.UINT32); + } + src += 2; /* short access */ + } + else + { + /* 8bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + src = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + src = (uint32_t)(&USB201.D1FIFO.UINT32); + } + src += 3; /* byte access */ + } +#endif + } + else + { + /* DxFIFO determination */ + src = dma->buffer; +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB201.D1FIFO.UINT32); + } + size = dma->size; + + if (size == 0) + { + dst += 3; /* byte access */ + } + else if (size == 1) + { + dst += 2; /* short access */ + } + else + { + /* Do Nothing */ + } +#else + size = dma->size; + if (size == 2) + { + /* 32bit access */ + if (dfacc == 2) + { + /* 32byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFOB0); + } + else + { + dst = (uint32_t)(&USB201.D1FIFOB0); + } + } + else if (dfacc == 1) + { + /* 16byte access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFOB0); + } + else + { + dst = (uint32_t)(&USB201.D1FIFOB0); + } + } + else + { + /* normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB201.D1FIFO.UINT32); + } + } + } + else if (size == 1) + { + /* 16bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB201.D1FIFO.UINT32); + } + dst += 2; /* short access */ + } + else + { + /* 8bit access */ + dfacc = 0; /* force normal access */ + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + dst = (uint32_t)(&USB201.D0FIFO.UINT32); + } + else + { + dst = (uint32_t)(&USB201.D1FIFO.UINT32); + } + dst += 3; /* byte access */ + } +#endif + } + +#ifdef CACHE_WRITEBACK + ptr = (uint32_t)dma->buffer; + if ((ptr & 0x20000000ul) == 0) + { + io_cwb((uint32_t)ptr,(uint32_t)(ptr)+trncount); + } +#endif + + if (dma->fifo == USB_HOST_D0FIFO_DMA) + { + usb1_host_enable_dmac0(src, dst, trncount, size, dir, dma->fifo, dfacc); + } + else + { + usb1_host_enable_dmac1(src, dst, trncount, size, dir, dma->fifo, dfacc); + } +} + +/******************************************************************************* +* Function Name: usb1_host_enable_dmac0 +* Description : Enables DMA transfer on the information specified by the argument. +* Arguments : uint32_t src : src address +* : uint32_t dst : dst address +* : uint32_t count : transfer byte +* : uint32_t size : transfer size +* : uint32_t dir : direction +* : uint32_t fifo : FIFO(D0FIFO or D1FIFO) +* : uint16_t dfacc : 0 : normal access +* : : 1 : 16byte access +* : : 2 : 32byte access +* Return Value : none +*******************************************************************************/ +static void usb1_host_enable_dmac0 (uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc) +{ + dmac_transinfo_t trans_info; + uint32_t request_factor = 0; + int32_t ret; + + /* ==== Variable setting for DMAC initialization ==== */ + trans_info.src_addr = (uint32_t)src; /* Start address of transfer source */ + trans_info.dst_addr = (uint32_t)dst; /* Start address of transfer destination */ + trans_info.count = (uint32_t)count; /* Total byte count to be transferred */ +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } +#else + if (dfacc == 2) + { + /* 32byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_256; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_256; /* Transfer destination transfer size */ + } + else if (dfacc == 1) + { + /* 16byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_128; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_128; /* Transfer destination transfer size */ + } + else + { + /* normal access */ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } + } +#endif + + if (dir == USB_HOST_FIFO2BUF) + { + request_factor = DMAC_REQ_USB1_DMA0_RX; /* USB_0 channel 0 receive FIFO full */ + trans_info.saddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer destination address */ + } + else if (dir == USB_HOST_BUF2FIFO) + { + request_factor = DMAC_REQ_USB1_DMA0_TX; /* USB_0 channel 0 receive FIFO empty */ + trans_info.saddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer destination address */ + } + else + { + /* Do Nothing */ + } + + /* ==== DMAC initialization ==== */ + usb1_host_DMAC3_PeriReqInit((const dmac_transinfo_t *)&trans_info, + DMAC_MODE_REGISTER, + DMAC_SAMPLE_SINGLE, + request_factor, + 0); /* Don't care DMAC_REQ_REQD is setting in usb1_host_DMAC3_PeriReqInit() */ + + /* ==== DMAC startup ==== */ + ret = usb1_host_DMAC3_Open(DMAC_REQ_MODE_PERI); + + if (ret != 0) + { +// printf("DMAC3 Open error!!\n"); + } + + return; +} + +/******************************************************************************* +* Function Name: usb1_host_enable_dmac1 +* Description : Enables DMA transfer on the information specified by the argument. +* Arguments : uint32_t src : src address +* : uint32_t dst : dst address +* : uint32_t count : transfer byte +* : uint32_t size : transfer size +* : uint32_t dir : direction +* : uint32_t fifo : FIFO(D0FIFO or D1FIFO) +* : uint16_t dfacc : 0 : normal access +* : : 1 : 16byte access +* : : 2 : 32byte access +* Return Value : none +*******************************************************************************/ +static void usb1_host_enable_dmac1 (uint32_t src, uint32_t dst, uint32_t count, + uint32_t size, uint32_t dir, uint32_t fifo, uint16_t dfacc) +{ + dmac_transinfo_t trans_info; + uint32_t request_factor = 0; + int32_t ret; + + /* ==== Variable setting for DMAC initialization ==== */ + trans_info.src_addr = (uint32_t)src; /* Start address of transfer source */ + trans_info.dst_addr = (uint32_t)dst; /* Start address of transfer destination */ + trans_info.count = (uint32_t)count; /* Total byte count to be transferred */ +#ifndef __USB_HOST_DF_ACC_ENABLE__ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } +#else + if (dfacc == 2) + { + /* 32byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_256; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_256; /* Transfer destination transfer size */ + } + else if (dfacc == 1) + { + /* 16byte access */ + trans_info.src_size = DMAC_TRANS_SIZE_128; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_128; /* Transfer destination transfer size */ + } + else + { + /* normal access */ + if (size == 0) + { + trans_info.src_size = DMAC_TRANS_SIZE_8; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_8; /* Transfer destination transfer size */ + } + else if (size == 1) + { + trans_info.src_size = DMAC_TRANS_SIZE_16; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_16; /* Transfer destination transfer size */ + } + else if (size == 2) + { + trans_info.src_size = DMAC_TRANS_SIZE_32; /* Transfer source transfer size */ + trans_info.dst_size = DMAC_TRANS_SIZE_32; /* Transfer destination transfer size */ + } + else + { +// printf("size error!!\n"); + } + } +#endif + + if (dir == USB_HOST_FIFO2BUF) + { + request_factor =DMAC_REQ_USB1_DMA1_RX; /* USB_0 channel 0 receive FIFO full */ + trans_info.saddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer destination address */ + } + else if (dir == USB_HOST_BUF2FIFO) + { + request_factor =DMAC_REQ_USB1_DMA1_TX; /* USB_0 channel 0 receive FIFO empty */ + trans_info.saddr_dir = DMAC_TRANS_ADR_INC; /* Count direction of transfer source address */ + trans_info.daddr_dir = DMAC_TRANS_ADR_NO_INC; /* Count direction of transfer destination address */ + } + else + { + /* Do Nothing */ + } + + /* ==== DMAC initialization ==== */ + usb1_host_DMAC4_PeriReqInit((const dmac_transinfo_t *)&trans_info, + DMAC_MODE_REGISTER, + DMAC_SAMPLE_SINGLE, + request_factor, + 0); /* Don't care DMAC_REQ_REQD is setting in usb1_host_DMAC4_PeriReqInit() */ + + /* ==== DMAC startup ==== */ + ret = usb1_host_DMAC4_Open(DMAC_REQ_MODE_PERI); + + if (ret != 0) + { +// printf("DMAC4 Open error!!\n"); + } + + return; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_stop_dma0 +* Description : Disables DMA transfer. +* Arguments : none +* Return Value : uint32_t return Transfer Counter register(DMATCRn) value +* : regarding to the bus width. +* Notice : This function should be executed to DMAC executed at the time +* : of specification of D0_FIF0_DMA in dma->fifo. +*******************************************************************************/ +uint32_t Userdef_USB_usb1_host_stop_dma0 (void) +{ + uint32_t remain; + + /* ==== DMAC release ==== */ + usb1_host_DMAC3_Close(&remain); + + return remain; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_stop_dma1 +* Description : Disables DMA transfer. +* : This function should be executed to DMAC executed at the time +* : of specification of D1_FIF0_DMA in dma->fifo. +* Arguments : none +* Return Value : uint32_t return Transfer Counter register(DMATCRn) value +* : regarding to the bus width. +*******************************************************************************/ +uint32_t Userdef_USB_usb1_host_stop_dma1 (void) +{ + uint32_t remain; + + /* ==== DMAC release ==== */ + usb1_host_DMAC4_Close(&remain); + + return remain; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_notice +* Description : Notice of USER +* Arguments : const char *format +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_notice (const char * format) +{ +// printf(format); + + return; +} + +/******************************************************************************* +* Function Name: Userdef_USB_usb1_host_user_rdy +* Description : This function notify a user and wait for trigger +* Arguments : const char *format +* : uint16_t data +* Return Value : none +*******************************************************************************/ +void Userdef_USB_usb1_host_user_rdy (const char * format, uint16_t data) +{ +// printf(format, data); + getchar(); + + return; +} + +/* End of File */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/TARGET_VK_RZ_A1H/usb_host_setting.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,100 @@ +/******************************************************************************* +* DISCLAIMER +* This software is supplied by Renesas Electronics Corporation and is only +* intended for use with Renesas products. No other uses are authorized. This +* software is owned by Renesas Electronics Corporation and is protected under +* all applicable laws, including copyright laws. +* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING +* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT +* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE +* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. +* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS +* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE +* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR +* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE +* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +* Renesas reserves the right, without notice, to make changes to this software +* and to discontinue the availability of this software. By using this software, +* you agree to the additional terms and conditions found by accessing the +* following link: +* http://www.renesas.com/disclaimer +* Copyright (C) 2014 - 2015 Renesas Electronics Corporation. All rights reserved. +*******************************************************************************/ + +#ifndef USB_HOST_SETTING_H +#define USB_HOST_SETTING_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define USB_HOST_CH 0 +#define USB_HOST_HISPEED 1 + +#define INT_TRANS_MAX_NUM 4 /* min:1 max:4 */ +#define ISO_TRANS_MAX_NUM 0 /* min:0 max:2 */ + +#if (USB_HOST_CH == 0) +#include "usb0_host.h" +#define USB20X USB200 +#define USBIXUSBIX USBI0_IRQn +#define g_usbx_host_SupportUsbDeviceSpeed g_usb0_host_SupportUsbDeviceSpeed +#define g_usbx_host_UsbDeviceSpeed g_usb0_host_UsbDeviceSpeed +#define g_usbx_host_CmdStage g_usb0_host_CmdStage +#define g_usbx_host_pipe_status g_usb0_host_pipe_status +#define g_usbx_host_data_pointer g_usb0_host_data_pointer +#define g_usbx_host_data_count g_usb0_host_data_count +#define usbx_api_host_init usb0_api_host_init +#define usbx_host_UsbBusReset usb0_host_UsbBusReset +#define usbx_host_get_devadd usb0_host_get_devadd +#define usbx_host_set_devadd usb0_host_set_devadd +#define usbx_host_SetupStage usb0_host_SetupStage +#define usbx_host_CtrlWriteStart usb0_host_CtrlWriteStart +#define usbx_host_CtrlReadStart usb0_host_CtrlReadStart +#define usbx_api_host_SetEndpointTable usb0_api_host_SetEndpointTable +#define usbx_host_start_send_transfer usb0_host_start_send_transfer +#define usbx_host_start_receive_transfer usb0_host_start_receive_transfer +#define usbx_host_stop_transfer usb0_host_stop_transfer +#define usbx_host_set_sqclr usb0_host_set_sqclr +#define usbx_host_set_sqset usb0_host_set_sqset +#define usbx_host_CheckAttach usb0_host_CheckAttach +#define usbx_host_UsbDetach usb0_host_UsbDetach +#define usbx_host_UsbAttach usb0_host_UsbAttach +#define usbx_host_init_pipe_status usb0_host_init_pipe_status +#define usbx_host_get_sqmon usb0_host_get_sqmon +#else +#include "usb1_host.h" +#define USB20X USB201 +#define USBIXUSBIX USBI1_IRQn +#define g_usbx_host_SupportUsbDeviceSpeed g_usb1_host_SupportUsbDeviceSpeed +#define g_usbx_host_UsbDeviceSpeed g_usb1_host_UsbDeviceSpeed +#define g_usbx_host_CmdStage g_usb1_host_CmdStage +#define g_usbx_host_pipe_status g_usb1_host_pipe_status +#define g_usbx_host_data_pointer g_usb1_host_data_pointer +#define g_usbx_host_data_count g_usb1_host_data_count +#define usbx_api_host_init usb1_api_host_init +#define usbx_host_UsbBusReset usb1_host_UsbBusReset +#define usbx_host_get_devadd usb1_host_get_devadd +#define usbx_host_set_devadd usb1_host_set_devadd +#define usbx_host_SetupStage usb1_host_SetupStage +#define usbx_host_CtrlWriteStart usb1_host_CtrlWriteStart +#define usbx_host_CtrlReadStart usb1_host_CtrlReadStart +#define usbx_api_host_SetEndpointTable usb1_api_host_SetEndpointTable +#define usbx_host_start_send_transfer usb1_host_start_send_transfer +#define usbx_host_start_receive_transfer usb1_host_start_receive_transfer +#define usbx_host_stop_transfer usb1_host_stop_transfer +#define usbx_host_set_sqclr usb1_host_set_sqclr +#define usbx_host_set_sqset usb1_host_set_sqset +#define usbx_host_CheckAttach usb1_host_CheckAttach +#define usbx_host_UsbDetach usb1_host_UsbDetach +#define usbx_host_UsbAttach usb1_host_UsbAttach +#define usbx_host_init_pipe_status usb1_host_init_pipe_status +#define usbx_host_get_sqmon usb1_host_get_sqmon +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* USB_HOST_SETTING_H */
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_RENESAS/USBHALHost_RZ_A1.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,282 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if defined(TARGET_RZ_A1H) || defined(TARGET_VK_RZ_A1H) + +#include "mbed.h" +#include "USBHALHost.h" +#include "dbg.h" + +#include "ohci_wrapp_RZ_A1.h" + + +#define HCCA_SIZE sizeof(HCCA) +#define ED_SIZE sizeof(HCED) +#define TD_SIZE sizeof(HCTD) + +#define TOTAL_SIZE (HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE) + (MAX_TD*TD_SIZE)) +#define ALIGNE_MSK (0x0000000F) + +static volatile uint8_t usb_buf[TOTAL_SIZE + ALIGNE_MSK]; //16 bytes aligned! + +USBHALHost * USBHALHost::instHost; + +USBHALHost::USBHALHost() { + instHost = this; + memInit(); + memset((void*)usb_hcca, 0, HCCA_SIZE); + for (int i = 0; i < MAX_ENDPOINT; i++) { + edBufAlloc[i] = false; + } + for (int i = 0; i < MAX_TD; i++) { + tdBufAlloc[i] = false; + } +} + +void USBHALHost::init() { + ohciwrapp_init(&_usbisr); + + ohciwrapp_reg_w(OHCI_REG_CONTROL, 1); // HARDWARE RESET + ohciwrapp_reg_w(OHCI_REG_CONTROLHEADED, 0); // Initialize Control list head to Zero + ohciwrapp_reg_w(OHCI_REG_BULKHEADED, 0); // Initialize Bulk list head to Zero + + // Wait 100 ms before apply reset + wait_ms(100); + + // software reset + ohciwrapp_reg_w(OHCI_REG_COMMANDSTATUS, OR_CMD_STATUS_HCR); + + // Write Fm Interval and Largest Data Packet Counter + ohciwrapp_reg_w(OHCI_REG_FMINTERVAL, DEFAULT_FMINTERVAL); + ohciwrapp_reg_w(OHCI_REG_PERIODICSTART, FI * 90 / 100); + + // Put HC in operational state + ohciwrapp_reg_w(OHCI_REG_CONTROL, (ohciwrapp_reg_r(OHCI_REG_CONTROL) & (~OR_CONTROL_HCFS)) | OR_CONTROL_HC_OPER); + // Set Global Power + ohciwrapp_reg_w(OHCI_REG_RHSTATUS, OR_RH_STATUS_LPSC); + + ohciwrapp_reg_w(OHCI_REG_HCCA, (uint32_t)(usb_hcca)); + + // Clear Interrrupt Status + ohciwrapp_reg_w(OHCI_REG_INTERRUPTSTATUS, ohciwrapp_reg_r(OHCI_REG_INTERRUPTSTATUS)); + + ohciwrapp_reg_w(OHCI_REG_INTERRUPTENABLE, OR_INTR_ENABLE_MIE | OR_INTR_ENABLE_WDH | OR_INTR_ENABLE_RHSC); + + // Enable the USB Interrupt + ohciwrapp_reg_w(OHCI_REG_RHPORTSTATUS1, OR_RH_PORT_CSC); + ohciwrapp_reg_w(OHCI_REG_RHPORTSTATUS1, OR_RH_PORT_PRSC); + + // Check for any connected devices + if (ohciwrapp_reg_r(OHCI_REG_RHPORTSTATUS1) & OR_RH_PORT_CCS) { + //Device connected + wait_ms(150); + USB_DBG("Device connected (%08x)\n\r", ohciwrapp_reg_r(OHCI_REG_RHPORTSTATUS1)); + deviceConnected(0, 1, ohciwrapp_reg_r(OHCI_REG_RHPORTSTATUS1) & OR_RH_PORT_LSDA); + } +} + +uint32_t USBHALHost::controlHeadED() { + return ohciwrapp_reg_r(OHCI_REG_CONTROLHEADED); +} + +uint32_t USBHALHost::bulkHeadED() { + return ohciwrapp_reg_r(OHCI_REG_BULKHEADED); +} + +uint32_t USBHALHost::interruptHeadED() { + return usb_hcca->IntTable[0]; +} + +void USBHALHost::updateBulkHeadED(uint32_t addr) { + ohciwrapp_reg_w(OHCI_REG_BULKHEADED, addr); +} + + +void USBHALHost::updateControlHeadED(uint32_t addr) { + ohciwrapp_reg_w(OHCI_REG_CONTROLHEADED, addr); +} + +void USBHALHost::updateInterruptHeadED(uint32_t addr) { + usb_hcca->IntTable[0] = addr; +} + + +void USBHALHost::enableList(ENDPOINT_TYPE type) { + uint32_t wk_data; + + switch(type) { + case CONTROL_ENDPOINT: + ohciwrapp_reg_w(OHCI_REG_COMMANDSTATUS, OR_CMD_STATUS_CLF); + wk_data = (ohciwrapp_reg_r(OHCI_REG_CONTROL) | OR_CONTROL_CLE); + ohciwrapp_reg_w(OHCI_REG_CONTROL, wk_data); + break; + case ISOCHRONOUS_ENDPOINT: + break; + case BULK_ENDPOINT: + ohciwrapp_reg_w(OHCI_REG_COMMANDSTATUS, OR_CMD_STATUS_BLF); + wk_data = (ohciwrapp_reg_r(OHCI_REG_CONTROL) | OR_CONTROL_BLE); + ohciwrapp_reg_w(OHCI_REG_CONTROL, wk_data); + break; + case INTERRUPT_ENDPOINT: + wk_data = (ohciwrapp_reg_r(OHCI_REG_CONTROL) | OR_CONTROL_PLE); + ohciwrapp_reg_w(OHCI_REG_CONTROL, wk_data); + break; + } +} + + +bool USBHALHost::disableList(ENDPOINT_TYPE type) { + uint32_t wk_data; + + switch(type) { + case CONTROL_ENDPOINT: + wk_data = ohciwrapp_reg_r(OHCI_REG_CONTROL); + if(wk_data & OR_CONTROL_CLE) { + wk_data &= ~OR_CONTROL_CLE; + ohciwrapp_reg_w(OHCI_REG_CONTROL, wk_data); + return true; + } + return false; + case ISOCHRONOUS_ENDPOINT: + return false; + case BULK_ENDPOINT: + wk_data = ohciwrapp_reg_r(OHCI_REG_CONTROL); + if(wk_data & OR_CONTROL_BLE) { + wk_data &= ~OR_CONTROL_BLE; + ohciwrapp_reg_w(OHCI_REG_CONTROL, wk_data); + return true; + } + return false; + case INTERRUPT_ENDPOINT: + wk_data = ohciwrapp_reg_r(OHCI_REG_CONTROL); + if(wk_data & OR_CONTROL_PLE) { + wk_data &= ~OR_CONTROL_PLE; + ohciwrapp_reg_w(OHCI_REG_CONTROL, wk_data); + return true; + } + return false; + } + return false; +} + + +void USBHALHost::memInit() { + volatile uint8_t *p_wk_buf = (uint8_t *)(((uint32_t)usb_buf + ALIGNE_MSK) & ~ALIGNE_MSK); + + usb_hcca = (volatile HCCA *)p_wk_buf; + usb_edBuf = (volatile uint8_t *)(p_wk_buf + HCCA_SIZE); + usb_tdBuf = (volatile uint8_t *)(p_wk_buf + HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE)); +} + +volatile uint8_t * USBHALHost::getED() { + for (int i = 0; i < MAX_ENDPOINT; i++) { + if ( !edBufAlloc[i] ) { + edBufAlloc[i] = true; + return (volatile uint8_t *)(usb_edBuf + i*ED_SIZE); + } + } + perror("Could not allocate ED\r\n"); + return NULL; //Could not alloc ED +} + +volatile uint8_t * USBHALHost::getTD() { + int i; + for (i = 0; i < MAX_TD; i++) { + if ( !tdBufAlloc[i] ) { + tdBufAlloc[i] = true; + return (volatile uint8_t *)(usb_tdBuf + i*TD_SIZE); + } + } + perror("Could not allocate TD\r\n"); + return NULL; //Could not alloc TD +} + + +void USBHALHost::freeED(volatile uint8_t * ed) { + int i; + i = (ed - usb_edBuf) / ED_SIZE; + edBufAlloc[i] = false; +} + +void USBHALHost::freeTD(volatile uint8_t * td) { + int i; + i = (td - usb_tdBuf) / TD_SIZE; + tdBufAlloc[i] = false; +} + + +void USBHALHost::resetRootHub() { + // Initiate port reset + ohciwrapp_reg_w(OHCI_REG_RHPORTSTATUS1, OR_RH_PORT_PRS); + + while (ohciwrapp_reg_r(OHCI_REG_RHPORTSTATUS1) & OR_RH_PORT_PRS); + + // ...and clear port reset signal + ohciwrapp_reg_w(OHCI_REG_RHPORTSTATUS1, OR_RH_PORT_PRSC); +} + + +void USBHALHost::_usbisr(void) { + if (instHost) { + instHost->UsbIrqhandler(); + } +} + +void USBHALHost::UsbIrqhandler() { + uint32_t int_status = ohciwrapp_reg_r(OHCI_REG_INTERRUPTSTATUS) & ohciwrapp_reg_r(OHCI_REG_INTERRUPTENABLE); + uint32_t data; + + if (int_status != 0) { //Is there something to actually process? + // Root hub status change interrupt + if (int_status & OR_INTR_STATUS_RHSC) { + if (ohciwrapp_reg_r(OHCI_REG_RHPORTSTATUS1) & OR_RH_PORT_CSC) { + if (ohciwrapp_reg_r(OHCI_REG_RHSTATUS) & OR_RH_STATUS_DRWE) { + // When DRWE is on, Connect Status Change + // means a remote wakeup event. + } else { + + //Root device connected + if (ohciwrapp_reg_r(OHCI_REG_RHPORTSTATUS1) & OR_RH_PORT_CCS) { + + // wait 150ms to avoid bounce + wait_ms(150); + + //Hub 0 (root hub), Port 1 (count starts at 1), Low or High speed + data = ohciwrapp_reg_r(OHCI_REG_RHPORTSTATUS1) & OR_RH_PORT_LSDA; + deviceConnected(0, 1, data); + } + + //Root device disconnected + else { + deviceDisconnected(0, 1, NULL, usb_hcca->DoneHead & 0xFFFFFFFE); + } + } + ohciwrapp_reg_w(OHCI_REG_RHPORTSTATUS1, OR_RH_PORT_CSC); + } + if (ohciwrapp_reg_r(OHCI_REG_RHPORTSTATUS1) & OR_RH_PORT_PRSC) { + ohciwrapp_reg_w(OHCI_REG_RHPORTSTATUS1, OR_RH_PORT_PRSC); + } + ohciwrapp_reg_w(OHCI_REG_INTERRUPTSTATUS, OR_INTR_STATUS_RHSC); + } + + // Writeback Done Head interrupt + if (int_status & OR_INTR_STATUS_WDH) { + transferCompleted(usb_hcca->DoneHead & 0xFFFFFFFE); + ohciwrapp_reg_w(OHCI_REG_INTERRUPTSTATUS, OR_INTR_STATUS_WDH); + } + } +} +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F2/TARGET_NUCLEO_F207ZG/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,19 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_STM_144_64pins.h" +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F401xE/TARGET_NUCLEO_F401RE/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,20 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#define USBHALHOST_64pins +#include "USBHALHost_STM_144_64pins.h" +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F411xE/TARGET_NUCLEO_F411RE/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,40 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/* 144 pins boards */ +#if defined(TARGET_NUCLEO_F429ZI) || defined(TARGET_NUCLEO_F446ZE) || defined(TARGET_NUCLEO_F207ZG) \ +|| defined(TARGET_NUCLEO_F767ZI) || defined(TARGET_NUCLEO_F746ZG) || defined(TARGET_NUCLEO_F412ZG) \ +|| defined(TARGET_DISCO_F413ZH) +#include "USBHALHost_STM_144_64pins.h" +#endif + +/* 64 pins boards */ +#if defined(TARGET_NUCLEO_F401RE) || defined(TARGET_NUCLEO_L476RG) || defined(TARGET_NUCLEO_F411RE) +#define USBHALHOST_64pins +#include "USBHALHost_STM_144_64pins.h" +#endif + +/* DISCO board */ + +#ifdef TARGET_DISCO_F429ZI +#include "USBHALHost_DISCOF429ZI.h" +#endif + +#ifdef TARGET_DISCO_L476VG +#include "USBHALHost_DISCOL476VG.h" +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F412xG/TARGET_NUCLEO_F412ZG/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,19 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_STM_144_64pins.h" +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/USBHALHost_DISCOF429ZI.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,112 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef USBHALHOST_DISCOF429ZI +#define USBHALHOST_DISCOF429ZI + +#define USBHAL_IRQn OTG_HS_IRQn + +#define HCCA_SIZE sizeof(HCD_HandleTypeDef) +#define ED_SIZE sizeof(HCED) +#define TD_SIZE sizeof(HCTD) + +#define TOTAL_SIZE (HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE) + (MAX_TD*TD_SIZE)) +/* STM device FS have 11 channels (definition is for 60 channels) */ +static volatile uint8_t usb_buf[TOTAL_SIZE]; +typedef struct +{ + /* store the request ongoing on each endpoit */ + /* 1st field of structure avoid giving knowledge of all structure to + * endpoint */ + volatile uint32_t addr[MAX_ENDPOINT]; + USBHALHost *inst; + void (USBHALHost::*deviceConnected)(int hub, int port, bool lowSpeed, USBHostHub * hub_parent); + void (USBHALHost::*deviceDisconnected)(int hub, int port, USBHostHub * hub_parent, volatile uint32_t addr); + void (USBHALHost::*transferCompleted)(volatile uint32_t addr); +}USBHALHost_Private_t; +/* CONFIGURATION for USB_VBUS + * on 64 bits board PC_0 is used (0 VBUS on, 1 VBUS off) + * on 144 pins board PG_6 is used ( 1 VBUS on, 0 VBUS on) + */ +static gpio_t gpio_vbus; + +#define VBUS_OFF 1 +#define VBUS_ON 0 +#define USB_VBUS_CONFIG \ + do {__HAL_RCC_GPIOC_CLK_ENABLE();\ + gpio_init_out_ex(&gpio_vbus, PC_4, VBUS_OFF);\ + }while(0); + + +void usb_vbus( uint8_t state) +{ + if(state == 0) + { + gpio_write(&gpio_vbus, VBUS_OFF); + } + else + { + gpio_write(&gpio_vbus, VBUS_ON); + } + wait(0.2); +} + + +USBHALHost::USBHALHost() { + gpio_t pin_vbus; + instHost = this; + HCD_HandleTypeDef *hhcd; + USBHALHost_Private_t *HALPriv = new(USBHALHost_Private_t); + memset(HALPriv, 0, sizeof(USBHALHost_Private_t)); + memInit(); + memset((void*)usb_hcca, 0, HCCA_SIZE); + hhcd = (HCD_HandleTypeDef *)usb_hcca; + hhcd->Instance = USB_OTG_HS; + hhcd->pData = (void*)HALPriv; + hhcd->Init.Host_channels = 11; + /* for now failed with dma */ + hhcd->Init.dma_enable = 0; + hhcd->Init.speed = HCD_SPEED_HIGH; + hhcd->Init.phy_itface = HCD_PHY_EMBEDDED; + hhcd->Init.use_external_vbus = 1; + HALPriv->inst = this; + HALPriv->deviceConnected = &USBHALHost::deviceConnected; + HALPriv->deviceDisconnected = &USBHALHost::deviceDisconnected; + HALPriv->transferCompleted = &USBHALHost::transferCompleted; + for (int i = 0; i < MAX_ENDPOINT; i++) { + edBufAlloc[i] = false; + HALPriv->addr[i]=(uint32_t)-1; + } + for (int i = 0; i < MAX_TD; i++) { + tdBufAlloc[i] = false; + } + /* Configure USB HS GPIOs */ + __HAL_RCC_GPIOB_CLK_ENABLE(); + + /*USB DM and DP */ + pin_function(PB_14, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF12_OTG_HS_FS)); + pin_function(PB_15, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF12_OTG_HS_FS)); + /* Configure VBUS Pin */ + gpio_init_in(&pin_vbus, PB_13); + /* Configure POWER_SWITCH IO pin */ + USB_VBUS_CONFIG; + /* Enable USB HS Clocks */ + __HAL_RCC_USB_OTG_HS_CLK_ENABLE(); + + /* Set USBFS Interrupt priority */ + HAL_NVIC_SetPriority(USBHAL_IRQn, 5, 0); + NVIC_SetVector(USBHAL_IRQn, (uint32_t)&_usbisr); +} +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_DISCO_F429ZI/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,18 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_DISCOF429ZI.h"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F429xI/TARGET_NUCLEO_F429ZI/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,18 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_STM_144_64pins.h"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F439xI/TARGET_NUCLEO_F439ZI/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,18 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_STM_144_64pins.h"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446RE/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,18 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_STM_144_64pins.h"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F4/TARGET_STM32F446xE/TARGET_NUCLEO_F446ZE/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,19 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_STM_144_64pins.h" +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F746xG/TARGET_NUCLEO_F746ZG/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,18 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_STM_144_64pins.h"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F756xG/TARGET_NUCLEO_F756ZG/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,18 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_STM_144_64pins.h"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32F7/TARGET_STM32F767xI/TARGET_NUCLEO_F767ZI/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,19 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_STM_144_64pins.h" +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L475xG/TARGET_DISCO_L475VG_IOT01A/USBHALHost_DISCO_L475VG_IOT01A.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,120 @@ +/* Copyright (c) 2017 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#ifndef USBHALHOST_DISCO_L475VG_IOT01A +#define USBHALHOST_DISCO_L475VG_IOT01A + +#define USBHAL_IRQn OTG_FS_IRQn + +#define HCCA_SIZE sizeof(HCD_HandleTypeDef) +#define ED_SIZE sizeof(HCED) +#define TD_SIZE sizeof(HCTD) + +#define TOTAL_SIZE (HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE) + (MAX_TD*TD_SIZE)) + +/* STM device FS have 11 channels (definition is for 60 channels) */ +static volatile uint8_t usb_buf[TOTAL_SIZE]; + +typedef struct { + /* store the request ongoing on each endpoit */ + /* 1st field of structure avoid giving knowledge of all structure to + * endpoint */ + volatile uint32_t addr[MAX_ENDPOINT]; + USBHALHost *inst; + void (USBHALHost::*deviceConnected)(int hub, int port, bool lowSpeed, USBHostHub * hub_parent); + void (USBHALHost::*deviceDisconnected)(int hub, int port, USBHostHub * hub_parent, volatile uint32_t addr); + void (USBHALHost::*transferCompleted)(volatile uint32_t addr); +} USBHALHost_Private_t; + +static gpio_t gpio_powerpin; + +#define USB_POWER_OFF 1 +#define USB_POWER_ON 0 +#define USB_POWERPIN_CONFIG {gpio_init_out_ex(&gpio_powerpin, PD_12, USB_POWER_OFF);} + + +void usb_vbus( uint8_t state) +{ + if (state == 0) { + gpio_write(&gpio_powerpin, USB_POWER_OFF); + } else { + gpio_write(&gpio_powerpin, USB_POWER_ON); + } + wait(0.2); +} + + +USBHALHost::USBHALHost() +{ + instHost = this; + HCD_HandleTypeDef *hhcd; + USBHALHost_Private_t *HALPriv = new(USBHALHost_Private_t); + + memset(HALPriv, 0, sizeof(USBHALHost_Private_t)); + memInit(); + memset((void*)usb_hcca, 0, HCCA_SIZE); + + hhcd = (HCD_HandleTypeDef *)usb_hcca; + hhcd->Instance = USB_OTG_FS; + hhcd->pData = (void*)HALPriv; + hhcd->Init.Host_channels = 11; + + /* for now failed with dma */ + hhcd->Init.dma_enable = 0; + hhcd->Init.speed = HCD_SPEED_FULL; + hhcd->Init.phy_itface = HCD_PHY_EMBEDDED; + hhcd->Init.use_external_vbus = 1; + + HALPriv->inst = this; + HALPriv->deviceConnected = &USBHALHost::deviceConnected; + HALPriv->deviceDisconnected = &USBHALHost::deviceDisconnected; + HALPriv->transferCompleted = &USBHALHost::transferCompleted; + + for (int i = 0; i < MAX_ENDPOINT; i++) { + edBufAlloc[i] = false; + HALPriv->addr[i]=(uint32_t)-1; + } + + for (int i = 0; i < MAX_TD; i++) { + tdBufAlloc[i] = false; + } + + __HAL_RCC_PWR_CLK_ENABLE(); + +#ifdef TARGET_STM32L4 + HAL_PWREx_EnableVddUSB(); +#endif + + /* Configure USB GPIOs */ + __HAL_RCC_GPIOA_CLK_ENABLE(); + pin_function(PA_11, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF10_OTG_FS)); // DM pin + pin_function(PA_12, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF10_OTG_FS)); // DP pin + pin_function(PA_9, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF10_OTG_FS)); // VBUS pin + + /* Configure USB POWER pin */ + USB_POWERPIN_CONFIG; + + /* Enable USB FS Clocks */ + __HAL_RCC_SYSCFG_CLK_ENABLE(); + __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + /* Set USBFS Interrupt priority */ + HAL_NVIC_SetPriority(USBHAL_IRQn, 5, 0); + NVIC_SetVector(USBHAL_IRQn, (uint32_t)&_usbisr); +} + +#endif // USBHALHOST_DISCO_L475VG_IOT01A
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L475xG/TARGET_DISCO_L475VG_IOT01A/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,18 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_DISCO_L475VG_IOT01A.h"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/USBHALHost_DISCOL476VG.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,118 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#ifndef USBHALHOST_DISCOL476VG +#define USBHALHOST_DISCOL476VG + +#define USBHAL_IRQn OTG_FS_IRQn + +#define HCCA_SIZE sizeof(HCD_HandleTypeDef) +#define ED_SIZE sizeof(HCED) +#define TD_SIZE sizeof(HCTD) + +#define TOTAL_SIZE (HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE) + (MAX_TD*TD_SIZE)) +/* STM device FS have 11 channels (definition is for 60 channels) */ +static volatile uint8_t usb_buf[TOTAL_SIZE]; +typedef struct +{ + /* store the request ongoing on each endpoit */ + /* 1st field of structure avoid giving knowledge of all structure to + * endpoint */ + volatile uint32_t addr[MAX_ENDPOINT]; + USBHALHost *inst; + void (USBHALHost::*deviceConnected)(int hub, int port, bool lowSpeed, USBHostHub * hub_parent); + void (USBHALHost::*deviceDisconnected)(int hub, int port, USBHostHub * hub_parent, volatile uint32_t addr); + void (USBHALHost::*transferCompleted)(volatile uint32_t addr); +}USBHALHost_Private_t; + +static gpio_t gpio_vbus; + +#define VBUS_OFF 1 +#define VBUS_ON 0 +#define USB_VBUS_CONFIG \ + do {\ + gpio_init_out_ex(&gpio_vbus, PC_9, VBUS_OFF);\ + }while(0); + + +void usb_vbus( uint8_t state) +{ + if(state == 0) + { + gpio_write(&gpio_vbus, VBUS_OFF); + } + else + { + gpio_write(&gpio_vbus, VBUS_ON); + } + wait(0.2); +} + + +USBHALHost::USBHALHost() { + instHost = this; + HCD_HandleTypeDef *hhcd; + USBHALHost_Private_t *HALPriv = new(USBHALHost_Private_t); + memset(HALPriv, 0, sizeof(USBHALHost_Private_t)); + memInit(); + memset((void*)usb_hcca, 0, HCCA_SIZE); + hhcd = (HCD_HandleTypeDef *)usb_hcca; + hhcd->Instance = USB_OTG_FS; + hhcd->pData = (void*)HALPriv; + hhcd->Init.Host_channels = 11; + /* for now failed with dma */ + hhcd->Init.dma_enable = 0; + hhcd->Init.speed = HCD_SPEED_FULL; + hhcd->Init.phy_itface = HCD_PHY_EMBEDDED; + hhcd->Init.use_external_vbus = 1; + HALPriv->inst = this; + HALPriv->deviceConnected = &USBHALHost::deviceConnected; + HALPriv->deviceDisconnected = &USBHALHost::deviceDisconnected; + HALPriv->transferCompleted = &USBHALHost::transferCompleted; + for (int i = 0; i < MAX_ENDPOINT; i++) { + edBufAlloc[i] = false; + HALPriv->addr[i]=(uint32_t)-1; + } + for (int i = 0; i < MAX_TD; i++) { + tdBufAlloc[i] = false; + } + __HAL_RCC_PWR_CLK_ENABLE(); +#ifdef TARGET_STM32L4 + HAL_PWREx_EnableVddUSB(); +#endif + + /* Configure USB HS GPIOs */ + __HAL_RCC_GPIOA_CLK_ENABLE(); + + /*USB DM and DP */ + pin_function(PA_11, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF10_OTG_FS)); + pin_function(PA_12, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF10_OTG_FS)); + + /* Configure VBUS Pin */ + __HAL_RCC_GPIOC_CLK_ENABLE(); + pin_function(PC_11, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF10_OTG_FS)); + /* Configure POWER_SWITCH IO pin */ + USB_VBUS_CONFIG; + __HAL_RCC_SYSCFG_CLK_ENABLE(); + + /* Enable USB FS Clocks */ + __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + /* Set USBFS Interrupt priority */ + HAL_NVIC_SetPriority(USBHAL_IRQn, 5, 0); + NVIC_SetVector(USBHAL_IRQn, (uint32_t)&_usbisr); +} +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_DISCO_L476VG/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,18 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#include "USBHALHost_DISCOL476VG.h"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L476xG/TARGET_NUCLEO_L476RG/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,19 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#define USBHALHOST_64pins +#include "USBHALHost_STM_144_64pins.h"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/TARGET_STM32L4/TARGET_STM32L486xG/TARGET_NUCLEO_L486RG/USBHALHost_STM_TARGET.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,19 @@ +/* Copyright (c) 2016 mbed.org, MIT License +* +* Permission is hereby granted, free of charge, to any person obtaining a copy of this software +* and associated documentation files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all copies or +* substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +#define USBHALHOST_64pins +#include "USBHALHost_STM_144_64pins.h"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/USBEndpoint_STM.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,182 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#if defined(TARGET_STM) && defined(USBHOST_OTHER) + +#include "dbg.h" +#include "USBEndpoint.h" +extern uint32_t HAL_HCD_HC_GetMaxPacket(HCD_HandleTypeDef *hhcd, uint8_t chn_num); +extern uint32_t HAL_HCD_HC_GetType(HCD_HandleTypeDef *hhcd, uint8_t chn_num); +extern void HAL_HCD_DisableInt(HCD_HandleTypeDef* hhcd, uint8_t chn_num); +extern void HAL_HCD_EnableInt(HCD_HandleTypeDef* hhcd, uint8_t chn_num); + + + + +void USBEndpoint::init(HCED * hced_, ENDPOINT_TYPE type_, ENDPOINT_DIRECTION dir_, uint32_t size, uint8_t ep_number, HCTD* td_list_[2]) +{ + HCD_HandleTypeDef *hhcd; + uint32_t *addr; + + hced = hced_; + type = type_; + dir = dir_; + setup = (type == CONTROL_ENDPOINT) ? true : false; + + //TDs have been allocated by the host + memcpy((HCTD**)td_list, td_list_, sizeof(HCTD*)*2); //TODO: Maybe should add a param for td_list size... at least a define + memset(td_list_[0], 0, sizeof(HCTD)); + memset(td_list_[1], 0, sizeof(HCTD)); + + td_list[0]->ep = this; + td_list[1]->ep = this; + + address = (ep_number & 0x7F) | ((dir - 1) << 7); + this->size = size; + this->ep_number = ep_number; + transfer_len = 0; + transferred = 0; + buf_start = 0; + nextEp = NULL; + + td_current = td_list[0]; + td_next = td_list[1]; + /* remove potential post pending from previous endpoint */ + ep_queue.get(0); + intf_nb = 0; + hhcd = (HCD_HandleTypeDef*)hced->hhcd; + addr = &((uint32_t *)hhcd->pData)[hced->ch_num]; + *addr = 0; + state = USB_TYPE_IDLE; + speed =false; +} +void USBEndpoint::setSize(uint32_t size) +{ + this->size = size; +} + + +void USBEndpoint::setDeviceAddress(uint8_t addr) +{ + HCD_HandleTypeDef *hhcd; + uint8_t hcd_speed = HCD_SPEED_FULL; + /* fix me : small speed device with hub not supported + if (this->speed) hcd_speed = HCD_SPEED_LOW; */ + if (this->speed) { + USB_WARN("small speed device on hub not supported"); + } + MBED_ASSERT(HAL_HCD_HC_Init((HCD_HandleTypeDef*)hced->hhcd,hced->ch_num, address, addr, hcd_speed, type, size)!=HAL_BUSY); + this->device_address = addr; + +} + +void USBEndpoint::setSpeed(uint8_t speed) +{ + this->speed = speed; +} + + + +void USBEndpoint::setState(USB_TYPE st) +{ + /* modify this state is possible only with a plug */ + if (state == USB_TYPE_FREE) { + return; + } + + state = st; + if (st == USB_TYPE_FREE) { + HCD_HandleTypeDef *hhcd = (HCD_HandleTypeDef*)hced->hhcd; + uint32_t *addr = &((uint32_t *)hhcd->pData)[hced->ch_num]; + if ((*addr) && (type != INTERRUPT_ENDPOINT)) { + this->ep_queue.put((uint8_t*)1); + } + MBED_ASSERT(HAL_HCD_HC_Halt((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num)!=HAL_BUSY); + HAL_HCD_DisableInt((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num); + *addr = 0; + + } + if (st == USB_TYPE_ERROR) { + MBED_ASSERT(HAL_HCD_HC_Halt((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num)!=HAL_BUSY); + HAL_HCD_DisableInt((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num); + + } + if (st == USB_TYPE_ERROR) { + uint8_t hcd_speed = HCD_SPEED_FULL; + /* small speed device with hub not supported + if (this->speed) hcd_speed = HCD_SPEED_LOW;*/ + MBED_ASSERT(HAL_HCD_HC_Init((HCD_HandleTypeDef*)hced->hhcd,hced->ch_num, address, 0, hcd_speed, type, size)!=HAL_BUSY); + } +} + + +extern uint32_t HAL_HCD_HC_GetMaxPacket(HCD_HandleTypeDef *hhcd, uint8_t chn_num); +extern uint32_t HAL_HCD_HC_GetType(HCD_HandleTypeDef *hhcd, uint8_t chn_num); + + +USB_TYPE USBEndpoint::queueTransfer() +{ + HCD_HandleTypeDef *hhcd = (HCD_HandleTypeDef*)hced->hhcd; + uint32_t *addr = &((uint32_t *)hhcd->pData)[hced->ch_num]; + uint32_t type = HAL_HCD_HC_GetType(hhcd, hced->ch_num); + uint32_t max_size = HAL_HCD_HC_GetMaxPacket(hhcd, hced->ch_num); + /* if a packet is queue on disconnected ; no solution for now */ + if (state == USB_TYPE_FREE) { + td_current->state = USB_TYPE_FREE; + return USB_TYPE_FREE; + } + ep_queue.get(0); + MBED_ASSERT(*addr ==0); + transfer_len = td_current->size <= max_size ? td_current->size : max_size; + buf_start = (uint8_t *)td_current->currBufPtr; + + //Now add this free TD at this end of the queue + state = USB_TYPE_PROCESSING; + /* one request */ + td_current->nextTD = (hcTd*)0; +#if defined(MAX_NYET_RETRY) + td_current->retry = 0; +#endif + td_current->setup = setup; + *addr = (uint32_t)td_current; + /* dir /setup is inverted for ST */ + /* token is useful only ctrl endpoint */ + /* last parameter is ping ? */ + MBED_ASSERT(HAL_HCD_HC_SubmitRequest((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num, dir-1, type,!setup,(uint8_t*) td_current->currBufPtr, transfer_len, 0)==HAL_OK); + HAL_HCD_EnableInt((HCD_HandleTypeDef*)hced->hhcd, hced->ch_num); + + return USB_TYPE_PROCESSING; +} + +void USBEndpoint::unqueueTransfer(volatile HCTD * td) +{ + if (state==USB_TYPE_FREE) { + return; + } + uint32_t *addr = &((uint32_t *)((HCD_HandleTypeDef*)hced->hhcd)->pData)[hced->ch_num]; + td->state=0; + td->currBufPtr=0; + td->size=0; + td->nextTD=0; + *addr = 0; + td_current = td_next; + td_next = td; +} + +void USBEndpoint::queueEndpoint(USBEndpoint * ed) +{ + nextEp = ed; +} +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/USBHALHost_STM.cpp Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,284 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef TARGET_STM +#include "mbed.h" +#include "USBHALHost.h" +#include "dbg.h" +#include "pinmap.h" + +#include "USBHALHost_STM_TARGET.h" + +void HAL_HCD_Connect_Callback(HCD_HandleTypeDef *hhcd) +{ + USBHALHost_Private_t *priv=(USBHALHost_Private_t *)(hhcd->pData); + USBHALHost *obj= priv->inst; + void (USBHALHost::*func)(int hub, int port, bool lowSpeed, USBHostHub * hub_parent ) = priv->deviceConnected; + (obj->*func)(0,1,0,NULL); +} +void HAL_HCD_Disconnect_Callback(HCD_HandleTypeDef *hhcd) +{ + USBHALHost_Private_t *priv=(USBHALHost_Private_t *)(hhcd->pData); + USBHALHost *obj= priv->inst; + void (USBHALHost::*func1)(int hub, int port, USBHostHub * hub_parent, volatile uint32_t addr)= priv->deviceDisconnected; + (obj->*func1)(0,1,(USBHostHub *)NULL,0); +} +int HAL_HCD_HC_GetDirection(HCD_HandleTypeDef *hhcd,uint8_t chnum) +{ + /* useful for transmission */ + return hhcd->hc[chnum].ep_is_in; +} + +uint32_t HAL_HCD_HC_GetMaxPacket(HCD_HandleTypeDef *hhcd,uint8_t chnum) +{ + /* useful for transmission */ + return hhcd->hc[chnum].max_packet; +} + +void HAL_HCD_EnableInt(HCD_HandleTypeDef *hhcd,uint8_t chnum) +{ + USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + USBx_HOST->HAINTMSK |= (1 << chnum); +} + + +void HAL_HCD_DisableInt(HCD_HandleTypeDef *hhcd,uint8_t chnum) +{ + USB_OTG_GlobalTypeDef *USBx = hhcd->Instance; + USBx_HOST->HAINTMSK &= ~(1 << chnum); +} +uint32_t HAL_HCD_HC_GetType(HCD_HandleTypeDef *hhcd,uint8_t chnum) +{ + /* useful for transmission */ + return hhcd->hc[chnum].ep_type; +} + +void HAL_HCD_HC_NotifyURBChange_Callback(HCD_HandleTypeDef *hhcd,uint8_t chnum, HCD_URBStateTypeDef urb_state) +{ + USBHALHost_Private_t *priv=(USBHALHost_Private_t *)(hhcd->pData); + USBHALHost *obj= priv->inst; + void (USBHALHost::*func)(volatile uint32_t addr)= priv->transferCompleted; + + uint32_t addr = priv->addr[chnum]; + uint32_t max_size = HAL_HCD_HC_GetMaxPacket(hhcd, chnum); + uint32_t type = HAL_HCD_HC_GetType(hhcd, chnum); + uint32_t dir = HAL_HCD_HC_GetDirection(hhcd,chnum); + uint32_t length; + if ( (addr!=0)) { + HCTD *td = (HCTD *)addr; + + if ((type == EP_TYPE_BULK) || (type == EP_TYPE_CTRL )) { + switch (urb_state) { + case URB_DONE: +#if defined(MAX_NYET_RETRY) + td->retry = 0; +#endif + if (td->size > max_size) { + /* enqueue another request */ + td->currBufPtr += max_size; + td->size -= max_size; + length = td->size <= max_size ? td->size : max_size; + MBED_ASSERT(HAL_HCD_HC_SubmitRequest(hhcd, chnum, dir ,type , !td->setup,(uint8_t*) td->currBufPtr, length, 0)==HAL_OK); + HAL_HCD_EnableInt(hhcd, chnum); + return; + } + break; + case URB_NOTREADY: + /* try again */ + /* abritary limit , to avoid dead lock if other error than + * slow response is */ +#if defined(MAX_NYET_RETRY) + if (td->retry < MAX_NYET_RETRY) { + /* increment retry counter */ + td->retry++; +#endif + length = td->size <= max_size ? td->size : max_size; + MBED_ASSERT(HAL_HCD_HC_SubmitRequest(hhcd, chnum, dir ,type , !td->setup,(uint8_t*) td->currBufPtr, length, 0)==HAL_OK); + HAL_HCD_EnableInt(hhcd, chnum); + return; +#if defined(MAX_NYET_RETRY) + } else { + USB_ERR("urb_state != URB_NOTREADY"); + } +#endif + break; + } + } + if ((type == EP_TYPE_INTR) ) { + /* reply a packet of length NULL, this will be analyse in call back + * for mouse or hub */ + td->state =USB_TYPE_IDLE ; + HAL_HCD_DisableInt(hhcd, chnum); + + } else { + td->state = (urb_state == URB_DONE) ? USB_TYPE_IDLE : USB_TYPE_ERROR; + } + td->currBufPtr +=HAL_HCD_HC_GetXferCount(hhcd, chnum); + (obj->*func)(addr); + } else { + if (urb_state !=0) { + USB_DBG_EVENT("spurious %d %d",chnum, urb_state); + } + } +} + +USBHALHost * USBHALHost::instHost; + + +void USBHALHost::init() +{ + + NVIC_DisableIRQ(USBHAL_IRQn); + NVIC_SetVector(USBHAL_IRQn, (uint32_t)(_usbisr)); + HAL_HCD_Init((HCD_HandleTypeDef *) usb_hcca); + NVIC_EnableIRQ(USBHAL_IRQn); + control_disable = 0; + HAL_HCD_Start((HCD_HandleTypeDef *) usb_hcca); + usb_vbus(1); +} + +uint32_t USBHALHost::controlHeadED() +{ + return 0xffffffff; +} + +uint32_t USBHALHost::bulkHeadED() +{ + return 0xffffffff; +} + +uint32_t USBHALHost::interruptHeadED() +{ + return 0xffffffff; +} + +void USBHALHost::updateBulkHeadED(uint32_t addr) +{ +} + + +void USBHALHost::updateControlHeadED(uint32_t addr) +{ +} + +void USBHALHost::updateInterruptHeadED(uint32_t addr) +{ +} + + +void USBHALHost::enableList(ENDPOINT_TYPE type) +{ + /* react when the 3 lists are requested to be disabled */ + if (type == CONTROL_ENDPOINT) { + control_disable--; + if (control_disable == 0) { + NVIC_EnableIRQ(USBHAL_IRQn); + } else { + printf("reent\n"); + } + } +} + + +bool USBHALHost::disableList(ENDPOINT_TYPE type) +{ + if (type == CONTROL_ENDPOINT) { + NVIC_DisableIRQ(USBHAL_IRQn); + control_disable++; + if (control_disable > 1) { + printf("disable reentrance !!!\n"); + } + return true; + } + return false; +} + + +void USBHALHost::memInit() +{ + usb_hcca = (volatile HCD_HandleTypeDef *)usb_buf; + usb_edBuf = usb_buf + HCCA_SIZE; + usb_tdBuf = usb_buf + HCCA_SIZE +(MAX_ENDPOINT*ED_SIZE); + /* init channel */ + memset((void*)usb_buf,0, TOTAL_SIZE); + for (int i=0; i < MAX_ENDPOINT; i++) { + HCED *hced = (HCED*)(usb_edBuf + i*ED_SIZE); + hced->ch_num = i; + hced->hhcd = (HCCA *) usb_hcca; + } +} + +volatile uint8_t * USBHALHost::getED() +{ + for (int i = 0; i < MAX_ENDPOINT; i++) { + if ( !edBufAlloc[i] ) { + edBufAlloc[i] = true; + return (volatile uint8_t *)(usb_edBuf + i*ED_SIZE); + } + } + perror("Could not allocate ED\r\n"); + return NULL; //Could not alloc ED +} + +volatile uint8_t * USBHALHost::getTD() +{ + int i; + for (i = 0; i < MAX_TD; i++) { + if ( !tdBufAlloc[i] ) { + tdBufAlloc[i] = true; + return (volatile uint8_t *)(usb_tdBuf + i*TD_SIZE); + } + } + perror("Could not allocate TD\r\n"); + return NULL; //Could not alloc TD +} + + +void USBHALHost::freeED(volatile uint8_t * ed) +{ + int i; + i = (ed - usb_edBuf) / ED_SIZE; + edBufAlloc[i] = false; +} + +void USBHALHost::freeTD(volatile uint8_t * td) +{ + int i; + i = (td - usb_tdBuf) / TD_SIZE; + tdBufAlloc[i] = false; +} + + +void USBHALHost::resetRootHub() +{ + // Initiate port reset + wait(0.2); + HAL_HCD_ResetPort((HCD_HandleTypeDef *)usb_hcca); +} + + +void USBHALHost::_usbisr(void) +{ + if (instHost) { + instHost->UsbIrqhandler(); + } +} + +void USBHALHost::UsbIrqhandler() +{ + HAL_HCD_IRQHandler((HCD_HandleTypeDef *)usb_hcca); +} +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/targets/TARGET_STM/USBHALHost_STM_144_64pins.h Fri Sep 25 10:17:49 2020 +0000 @@ -0,0 +1,121 @@ +/* mbed USBHost Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef USBHALHOST_STM32_144_64 +#define USBHALHOST_STM32_144_64 + +#define USBHAL_IRQn OTG_FS_IRQn + +#define HCCA_SIZE sizeof(HCD_HandleTypeDef) +#define ED_SIZE sizeof(HCED) +#define TD_SIZE sizeof(HCTD) + +#define TOTAL_SIZE (HCCA_SIZE + (MAX_ENDPOINT*ED_SIZE) + (MAX_TD*TD_SIZE)) +/* STM device FS have 11 channels (definition is for 60 channels) */ +static volatile uint8_t usb_buf[TOTAL_SIZE]; +typedef struct +{ + /* store the request ongoing on each endpoit */ + /* 1st field of structure avoid giving knowledge of all structure to + * endpoint */ + volatile uint32_t addr[MAX_ENDPOINT]; + USBHALHost *inst; + void (USBHALHost::*deviceConnected)(int hub, int port, bool lowSpeed, USBHostHub * hub_parent); + void (USBHALHost::*deviceDisconnected)(int hub, int port, USBHostHub * hub_parent, volatile uint32_t addr); + void (USBHALHost::*transferCompleted)(volatile uint32_t addr); +}USBHALHost_Private_t; + +/* CONFIGURATION for USB_VBUS + * on 64 bits board PC_0 is used (0 VBUS on, 1 VBUS off) + * on 144 pins board PG_6 is used ( 1 VBUS on, 0 VBUS on) + */ +static gpio_t gpio_vbus; + +#if defined(USBHALHOST_64pins) +#define VBUS_OFF 1 +#define VBUS_ON 0 +#define USB_VBUS_CONFIG \ + do {__HAL_RCC_GPIOC_CLK_ENABLE();\ + gpio_init_out_ex(&gpio_vbus, PC_0, VBUS_OFF);\ + }while(0); +#else +#define VBUS_OFF 0 +#define VBUS_ON 1 +#define USB_VBUS_CONFIG \ + do {__HAL_RCC_GPIOG_CLK_ENABLE();\ + gpio_init_out_ex(&gpio_vbus, PG_6, VBUS_OFF);\ + }while(0); +#endif + +void usb_vbus( uint8_t state) +{ + if(state == 0) + { + gpio_write(&gpio_vbus, VBUS_OFF); + } + else + { + gpio_write(&gpio_vbus, VBUS_ON); + } + wait(0.2); +} + +USBHALHost::USBHALHost() { + instHost = this; + HCD_HandleTypeDef *hhcd; + USBHALHost_Private_t *HALPriv = new(USBHALHost_Private_t); + memset(HALPriv, 0, sizeof(USBHALHost_Private_t)); + memInit(); + memset((void*)usb_hcca, 0, HCCA_SIZE); + hhcd = (HCD_HandleTypeDef *)usb_hcca; + hhcd->Instance = USB_OTG_FS; + hhcd->pData = (void*)HALPriv; + hhcd->Init.Host_channels = 11; + hhcd->Init.speed = HCD_SPEED_FULL; + hhcd->Init.phy_itface = HCD_PHY_EMBEDDED; + HALPriv->inst = this; + HALPriv->deviceConnected = &USBHALHost::deviceConnected; + HALPriv->deviceDisconnected = &USBHALHost::deviceDisconnected; + HALPriv->transferCompleted = &USBHALHost::transferCompleted; + for (int i = 0; i < MAX_ENDPOINT; i++) { + edBufAlloc[i] = false; + HALPriv->addr[i]=(uint32_t)-1; + } + for (int i = 0; i < MAX_TD; i++) { + tdBufAlloc[i] = false; + } + __HAL_RCC_PWR_CLK_ENABLE(); +#ifdef TARGET_STM32L4 + HAL_PWREx_EnableVddUSB(); +#endif + /* Configure USB FS GPIOs */ + __HAL_RCC_GPIOA_CLK_ENABLE(); + + /*USB DM and DP */ + pin_function(PA_11, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF10_OTG_FS)); + pin_function(PA_12, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_NOPULL, GPIO_AF10_OTG_FS)); + /*USB ID */ + pin_function(PA_10, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_PULLUP, GPIO_AF10_OTG_FS)); + + __HAL_RCC_SYSCFG_CLK_ENABLE(); + /* Configure POWER_SWITCH IO pin */ + USB_VBUS_CONFIG; + /* Enable USB FS Clocks */ + __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + /* Set USBFS Interrupt priority */ + HAL_NVIC_SetPriority(OTG_FS_IRQn, 6, 0); +} +#endif