+/rtos

git clone https://git.julia.blue/+/rtos

Vivek MalneediMerge branch 'master' of github.com:EE445M-Sp20/lab-6-vm22967_jbr2558ee4080a

master
16.3 KiB500 linesraw
1#include "tivaware/gpio.h"
2#include "tivaware/hw_memmap.h"
3#include "tivaware/hw_ssi.h"
4#include "tivaware/hw_types.h"
5#include "tivaware/pin_map.h"
6#include "tivaware/rom.h"
7#include "tivaware/ssi.h"
8#include "tivaware/sysctl.h"
9
10#include "OS.h"
11#include "eDisk.h"
12#include "printf.h"
13#include <stdint.h>
14
15static void chip_select(void) {
16    while (ROM_SSIBusy(SSI0_BASE)) {}
17    ROM_GPIOPinWrite(GPIO_PORTA_BASE, GPIO_PIN_3, GPIO_PIN_3);
18    ROM_GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_0, 0);
19}
20
21static void chip_deselect(void) {
22    while (ROM_SSIBusy(SSI0_BASE)) {}
23    ROM_GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_0, GPIO_PIN_0);
24}
25
26// Initialize SSI0 interface to SDC
27// inputs:  clock divider to set clock frequency
28// outputs: none
29// assumes: system clock rate is 80 MHz, SCR=0
30// SSIClk = SysClk / (CPSDVSR * (1 + SCR)) = 80 MHz/CPSDVSR
31// 200 for    400,000 bps slow mode, used during initialization
32// 8   for 10,000,000 bps fast mode, used during disk I/O
33void SSI0_Init(unsigned long CPSDVSR) {
34    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_SSI0);
35    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
36    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
37    ROM_GPIOPinTypeGPIOOutput(GPIO_PORTB_BASE, GPIO_PIN_0);
38    chip_deselect();
39    ROM_GPIOPinTypeGPIOOutput(GPIO_PORTA_BASE, 0xC8); // 3, 6, and 7
40    ROM_GPIOPinConfigure(GPIO_PA2_SSI0CLK);
41    ROM_GPIOPinConfigure(GPIO_PA4_SSI0RX);
42    ROM_GPIOPinConfigure(GPIO_PA5_SSI0TX);
43    ROM_GPIOPinTypeSSI(GPIO_PORTA_BASE, GPIO_PIN_5 | GPIO_PIN_4 | GPIO_PIN_2);
44
45    // PA7, PA3 high (disable LCD)
46    ROM_GPIOPinWrite(GPIO_PORTA_BASE, GPIO_PIN_3, 1);
47    ROM_GPIOPinWrite(GPIO_PORTA_BASE, GPIO_PIN_7, 1);
48
49    ROM_SSIDisable(SSI0_BASE);
50    ROM_SSIClockSourceSet(SSI0_BASE, SSI_CLOCK_SYSTEM);
51    ROM_SSIConfigSetExpClk(SSI0_BASE, ROM_SysCtlClockGet(), SSI_FRF_MOTO_MODE_0,
52                           SSI_MODE_MASTER, ROM_SysCtlClockGet() / CPSDVSR, 8);
53    ROM_SSIEnable(SSI0_BASE);
54
55    // read any residual data from ssi port
56    uint32_t _temp;
57    while (ROM_SSIDataGetNonBlocking(SSI0_BASE, &_temp)) {}
58}
59
60// SSIClk = PIOSC / (CPSDVSR * (1 + SCR)) = 80 MHz/CPSDVSR
61// 200 for   400,000 bps slow mode, used during initialization
62// 8  for 10,000,000 bps fast mode, used during disk I/O
63static inline void spi_clock_slow() {
64    HWREG(SSI_O_CPSR) = (HWREG(SSI_O_CPSR) & ~HWREG(SSI_CPSR_CPSDVSR_M)) + 200;
65}
66
67static void spi_clock_fast() {
68    HWREG(SSI_O_CPSR) = (HWREG(SSI_O_CPSR) & ~HWREG(SSI_CPSR_CPSDVSR_M)) + 200;
69}
70
71// MMC/SD command
72#define CMD0 (0)           // GO_IDLE_STATE
73#define CMD1 (1)           // SEND_OP_COND (MMC)
74#define ACMD41 (0x80 + 41) // SEND_OP_COND (SDC)
75#define CMD8 (8)           // SEND_IF_COND
76#define CMD9 (9)           // SEND_CSD
77#define CMD10 (10)         // SEND_CID
78#define CMD12 (12)         // STOP_TRANSMISSION
79#define ACMD13 (0x80 + 13) // SD_STATUS (SDC)
80#define CMD16 (16)         // SET_BLOCKLEN
81#define CMD17 (17)         // READ_SINGLE_BLOCK
82#define CMD18 (18)         // READ_MULTIPLE_BLOCK
83#define CMD23 (23)         // SET_BLOCK_COUNT (MMC)
84#define ACMD23 (0x80 + 23) // SET_WR_BLK_ERASE_COUNT (SDC)
85#define CMD24 (24)         // WRITE_BLOCK
86#define CMD25 (25)         // WRITE_MULTIPLE_BLOCK
87#define CMD32 (32)         // ERASE_ER_BLK_START
88#define CMD33 (33)         // ERASE_ER_BLK_END
89#define CMD38 (38)         // ERASE
90#define CMD55 (55)         // APP_CMD
91#define CMD58 (58)         // READ_OCR
92
93static volatile DSTATUS Stat = STA_NOINIT; // Physical drive status
94
95// 1kHz decrement timer stopped at zero (disk_timerproc())
96static volatile uint32_t Timer1, Timer2;
97
98static uint8_t CardType; // Card type flags
99
100// Exchange a byte
101static uint8_t xchg_spi(uint8_t dat) {
102    uint32_t rcvdat;
103    // wait until SSI0 not busy/transmit FIFO empty
104    while (ROM_SSIBusy(SSI0_BASE)) {}
105    ROM_SSIDataPut(SSI0_BASE, dat);
106    ROM_SSIDataGet(SSI0_BASE, &rcvdat);
107    return rcvdat & 0xFF;
108}
109
110// Receive a byte
111static uint8_t rcvr_spi(void) {
112    // wait until SSI0 not busy/transmit FIFO empty
113    while (ROM_SSIBusy(SSI0_BASE)) {}
114    ROM_SSIDataPut(SSI0_BASE, 0xFF); // data out, garbage
115    uint32_t response;
116    ROM_SSIDataGet(SSI0_BASE, &response);
117    return (uint8_t)(response & 0xFF);
118}
119
120// Receive multiple byte
121// count: Number of bytes to receive (must be even)
122static void rcvr_spi_multi(uint8_t* buff, uint32_t count) {
123    while (count) {
124        *buff = rcvr_spi(); // return by reference
125        count--;
126        buff++;
127    }
128}
129
130// Send multiple bytes
131// btx: Number of bytes to send (even number)
132static void xmit_spi_multi(const uint8_t* buff, uint32_t btx) {
133    uint32_t rcvdat;
134    while (btx) {
135        ROM_SSIDataPut(SSI0_BASE, *buff);   // data out
136        ROM_SSIDataGet(SSI0_BASE, &rcvdat); // get response
137        btx--;
138        buff++;
139    }
140}
141
142// Wait for card ready
143// Input: time to wait in ms
144// returns false on timeout
145static bool wait_ready(uint32_t wt) {
146    uint8_t d;
147    Timer2 = wt;
148    do {
149        d = xchg_spi(0xFF);
150        // This loop takes a time. Insert rot_rdq() here for multitask
151        // environment.
152    } while (d != 0xFF && Timer2); // Wait for card goes ready or timeout
153    return (d == 0xFF) ? 1 : 0;
154}
155
156// Deselect card and release SPI
157static void deselect(void) {
158    chip_deselect();
159    xchg_spi(0xFF); // Dummy clock (force DO hi-z for multiple slave SPI)
160}
161
162// Select card and wait for ready
163// returns false on 500ms timeout
164static bool select(void) {
165    chip_select();
166    xchg_spi(0xFF); // Dummy clock (force DO enabled)
167    if (wait_ready(500))
168        return 1; // OK
169    chip_deselect();
170    return 0; // Timeout
171}
172
173// Receive a data packet from the MMC
174// btr: Number of bytes to receive (even number)
175// returns false on timeout
176static bool rcvr_datablock(uint8_t* buff, uint32_t btr) {
177    uint8_t token;
178    Timer1 = 200;
179    do { // Wait for DataStart token in timeout of 200ms
180        token = xchg_spi(0xFF);
181        /* This loop will take a time. Insert rot_rdq() here for multitask
182         * envilonment. */
183    } while ((token == 0xFF) && Timer1);
184    if (token != 0xFE)
185        return 0; // Function fails if invalid DataStart token or timeout
186
187    rcvr_spi_multi(buff, btr); // Store trailing data to the buffer
188    xchg_spi(0xFF);
189    xchg_spi(0xFF); // Discard CRC
190    return 1;       // Function succeeded
191}
192
193// Send a data packet to the MMC
194// Input:  buff: 512 byte packet which will be sent
195// returns false on timeout
196static bool xmit_datablock(const uint8_t* buff, uint8_t token) {
197    uint8_t resp;
198    if (!wait_ready(500))
199        return 0; // Wait for card ready
200
201    xchg_spi(token);               // Send token
202    if (token != 0xFD) {           // Send data if token is other than StopTran
203        xmit_spi_multi(buff, 512); // Data
204        xchg_spi(0xFF);
205        xchg_spi(0xFF); // Dummy CRC
206
207        resp = xchg_spi(0xFF); // Receive data resp
208        if ((resp & 0x1F) !=
209            0x05) // Function fails if the data packet was not accepted
210            return 0;
211    }
212    return 1;
213}
214
215// Send a command packet to the MMC
216// Inputs:  Command index
217// Outputs: response (bit7==1: Failed to send)
218static uint8_t send_cmd(uint8_t cmd, uint32_t arg) {
219    uint8_t n, res;
220    if (cmd & 0x80) { // Send a CMD55 prior to ACMD
221        cmd &= 0x7F;
222        res = send_cmd(CMD55, 0);
223        if (res > 1)
224            return res;
225    }
226
227    // Select the card and wait for ready except to stop multiple block read
228    if (cmd != CMD12) {
229        deselect();
230        if (!select())
231            return 0xFF;
232    }
233
234    // Send command packet
235    xchg_spi(0x40 | cmd);           // Start + command index
236    xchg_spi((uint8_t)(arg >> 24)); // Argument[31..24]
237    xchg_spi((uint8_t)(arg >> 16)); // Argument[23..16]
238    xchg_spi((uint8_t)(arg >> 8));  // Argument[15..8]
239    xchg_spi((uint8_t)arg);         // Argument[7..0]
240    n = 0x01;                       // Dummy CRC + Stop
241    if (cmd == CMD0)
242        n = 0x95; // Valid CRC for CMD0(0)
243    if (cmd == CMD8)
244        n = 0x87; // Valid CRC for CMD8(0x1AA)
245    xchg_spi(n);
246
247    // Receive command resp
248    if (cmd == CMD12)
249        xchg_spi(0xFF); // Diacard following one byte when CMD12
250    n = 10;             // Wait for response (10 bytes max)
251    do
252        res = xchg_spi(0xFF);
253    while ((res & 0x80) && --n);
254
255    return res; // Return received response
256}
257
258DSTATUS eDisk_Init() {
259    static bool started_timerproc = false;
260    if (!started_timerproc) {
261        OS_AddPeriodicThread(&disk_timerproc, ms(1), 1);
262        started_timerproc = true;
263    }
264    uint8_t n, cmd, ty, ocr[4];
265
266    chip_select();
267    for (Timer1 = 10; Timer1;) {} // 10ms
268
269    if (Stat & STA_NODISK)
270        return Stat; // Is card existing in the socket?
271
272    spi_clock_slow();
273    for (n = 10; n; n--) xchg_spi(0xFF); // Send 80 dummy clocks
274
275    ty = 0;
276    if (send_cmd(CMD0, 0) == 1) {         // Put the card SPI/Idle state
277        Timer1 = 1000;                    // Initialization timeout = 1 sec
278        if (send_cmd(CMD8, 0x1AA) == 1) { // SDv2?
279            for (n = 0; n < 4; n++)
280                ocr[n] = xchg_spi(0xFF); // Get 32 bit return value of R7 resp
281            if (ocr[2] == 0x01 &&
282                ocr[3] == 0xAA) { // Is the card supports vcc of 2.7-3.6V?
283                while (Timer1 && send_cmd(ACMD41, 1 << 30))
284                    ; // Wait for end of initialization with ACMD41(HCS)
285                if (Timer1 &&
286                    send_cmd(CMD58, 0) == 0) { // Check CCS bit in the OCR
287                    for (n = 0; n < 4; n++) ocr[n] = xchg_spi(0xFF);
288                    ty = (ocr[0] & 0x40) ? CT_SD2 | CT_BLOCK
289                                         : CT_SD2; // Card id SDv2
290                }
291            }
292        } else {                            // Not SDv2 card
293            if (send_cmd(ACMD41, 0) <= 1) { // SDv1 or MMC?
294                ty = CT_SD1;
295                cmd = ACMD41; // SDv1 (ACMD41(0))
296            } else {
297                ty = CT_MMC;
298                cmd = CMD1; // MMCv3 (CMD1(0))
299            }
300            while (Timer1 && send_cmd(cmd, 0))
301                ; // Wait for end of initialization
302            if (!Timer1 || send_cmd(CMD16, 512) != 0) // Set block length: 512
303                ty = 0;
304        }
305    }
306    CardType = ty; // Card type
307    deselect();
308
309    if (ty) {                // OK
310        spi_clock_fast();    // Set fast clock
311        Stat &= ~STA_NOINIT; // Clear STA_NOINIT flag
312    } else {                 // Failed
313        Stat = STA_NOINIT;
314    }
315
316    return Stat;
317}
318
319DSTATUS eDisk_Status() {
320    return Stat; // Return disk status
321}
322
323DRESULT eDisk_Read(uint8_t* buff, uint32_t sector, uint8_t count) {
324    if (!count)
325        return RES_PARERR; // Check parameter
326    if (Stat & STA_NOINIT)
327        return RES_NOTRDY; // Check if drive is ready
328
329    if (!(CardType & CT_BLOCK))
330        sector *= 512; // LBA ot BA conversion (byte addressing cards)
331
332    if (count == 1) {                      // Single sector read
333        if ((send_cmd(CMD17, sector) == 0) // READ_SINGLE_BLOCK
334            && rcvr_datablock(buff, 512))
335            count = 0;
336    } else {                                // Multiple sector read
337        if (send_cmd(CMD18, sector) == 0) { // READ_MULTIPLE_BLOCK
338            do {
339                if (!rcvr_datablock(buff, 512))
340                    break;
341                buff += 512;
342            } while (--count);
343            send_cmd(CMD12, 0); // STOP_TRANSMISSION
344        }
345    }
346    deselect();
347
348    return count ? RES_ERROR : RES_OK; // Return result
349}
350
351DRESULT eDisk_ReadBlock(void* buff, uint32_t sector) {
352    return eDisk_Read((uint8_t*)buff, sector, 1);
353}
354
355DRESULT eDisk_Write(const uint8_t* buff, uint32_t sector, uint8_t count) {
356    if (Stat & STA_NOINIT)
357        return RES_NOTRDY; // Check drive status
358    if (Stat & STA_PROTECT)
359        return RES_WRPRT; // Check write protect
360
361    if (!(CardType & CT_BLOCK))
362        sector *= 512; // LBA ==> BA conversion (byte addressing cards)
363
364    if (count == 1) {                      // Single sector write
365        if ((send_cmd(CMD24, sector) == 0) // WRITE_BLOCK
366            && xmit_datablock(buff, 0xFE))
367            count = 0;
368    } else { // Multiple sector write
369        if (CardType & CT_SDC)
370            send_cmd(ACMD23, count);        // Predefine number of sectors
371        if (send_cmd(CMD25, sector) == 0) { // WRITE_MULTIPLE_BLOCK
372            do {
373                if (!xmit_datablock(buff, 0xFC))
374                    break;
375                buff += 512;
376            } while (--count);
377            if (!xmit_datablock(0, 0xFD)) // STOP_TRAN token
378                count = 1;
379        }
380    }
381    deselect();
382
383    return count ? RES_ERROR : RES_OK; // Return result
384}
385
386DRESULT eDisk_WriteBlock(const void* buff, uint32_t sector) {
387    return eDisk_Write((uint8_t*)buff, sector, 1); // 1 block
388}
389
390// Miscellaneous drive controls other than data read/write
391DRESULT disk_ioctl(uint8_t cmd, void* buff) {
392    DRESULT res;
393    uint8_t n, csd[16];
394    uint16_t *dp, st, ed, csize;
395
396    if (Stat & STA_NOINIT)
397        return RES_NOTRDY; // Check if drive is ready
398
399    res = RES_ERROR;
400
401    switch (cmd) {
402    case CTRL_SYNC: // Wait for end of internal write process of the drive
403        if (select())
404            res = RES_OK;
405        break;
406
407    case GET_SECTOR_COUNT: // Get drive capacity in unit of sector (uint16_t)
408        if ((send_cmd(CMD9, 0) == 0) && rcvr_datablock(csd, 16)) {
409            if ((csd[0] >> 6) == 1) { // SDC ver 2.00
410                csize = csd[9] + ((uint16_t)csd[8] << 8) +
411                        ((uint16_t)(csd[7] & 63) << 16) + 1;
412                *(uint16_t*)buff = csize << 10;
413            } else { // SDC ver 1.XX or MMC ver 3
414                n = (csd[5] & 15) + ((csd[10] & 128) >> 7) +
415                    ((csd[9] & 3) << 1) + 2;
416                csize = (csd[8] >> 6) + ((uint16_t)csd[7] << 2) +
417                        ((uint16_t)(csd[6] & 3) << 10) + 1;
418                *(uint16_t*)buff = csize << (n - 9);
419            }
420            res = RES_OK;
421        }
422        break;
423
424    case GET_BLOCK_SIZE: // Get erase block size in unit of sector (uint16_t)
425        if (CardType & CT_SD2) {            // SDC ver 2.00
426            if (send_cmd(ACMD13, 0) == 0) { // Read SD status
427                xchg_spi(0xFF);
428                if (rcvr_datablock(csd, 16)) { // Read partial block
429                    for (n = 64 - 16; n; n--)
430                        xchg_spi(0xFF); // Purge trailing data
431                    *(uint16_t*)buff = 16UL << (csd[10] >> 4);
432                    res = RES_OK;
433                }
434            }
435        } else { // SDC ver 1.XX or MMC
436            if ((send_cmd(CMD9, 0) == 0) &&
437                rcvr_datablock(csd, 16)) { // Read CSD
438                if (CardType & CT_SD1) {   // SDC ver 1.XX
439                    *(uint16_t*)buff = (((csd[10] & 63) << 1) +
440                                        ((uint16_t)(csd[11] & 128) >> 7) + 1)
441                                       << ((csd[13] >> 6) - 1);
442                } else { // MMC
443                    *(uint16_t*)buff =
444                        ((uint16_t)((csd[10] & 124) >> 2) + 1) *
445                        (((csd[11] & 3) << 3) + ((csd[11] & 224) >> 5) + 1);
446                }
447                res = RES_OK;
448            }
449        }
450        break;
451
452    case CTRL_TRIM: // Erase a block of sectors (used when _USE_ERASE == 1)
453        if (!(CardType & CT_SDC))
454            break; // Check if the card is SDC
455        if (disk_ioctl(MMC_GET_CSD, csd))
456            break; // Get CSD
457        if (!(csd[0] >> 6) && !(csd[10] & 0x40))
458            break; // Check if sector erase can be applied to the card
459        dp = buff;
460        st = dp[0];
461        ed = dp[1]; // Load sector block
462        if (!(CardType & CT_BLOCK)) {
463            st *= 512;
464            ed *= 512;
465        }
466        if (send_cmd(CMD32, st) == 0 && send_cmd(CMD33, ed) == 0 &&
467            send_cmd(CMD38, 0) == 0 && wait_ready(30000)) // Erase sector block
468            res = RES_OK; // FatFs does not check result of this command
469        break;
470
471    default: res = RES_PARERR;
472    }
473
474    deselect();
475
476    return res;
477}
478
479// This function must be called from timer interrupt routine in period
480// of 1 ms to generate card control timing.
481// OS will schedule this periodic task
482void disk_timerproc(void) {
483    uint16_t n;
484
485    n = Timer1; // 1kHz decrement timer stopped at 0
486    if (n)
487        Timer1 = --n;
488    n = Timer2;
489    if (n)
490        Timer2 = --n;
491
492    // uint8_t s = Stat;
493    // TODO: check write protection
494    // if (MMC_WP) s |= STA_PROTECT;
495    // else s &= ~STA_PROTECT;
496    // TODO: check if card is in socket
497    // if (MMC_CD) s &= ~STA_NODISK;
498    // else s |= (STA_NODISK | STA_NOINIT);
499    // Stat = s;
500}