summaryrefslogtreecommitdiff
path: root/boards/dk-tm4c123g/qs-logger/flashstore.c
blob: 5001a3899e785e7662f68d0a5b31e266438d4942 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//*****************************************************************************
//
// flashstore.c - Data logger module to handle storage in flash.
//
// Copyright (c) 2011-2014 Texas Instruments Incorporated.  All rights reserved.
// Software License Agreement
// 
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
// 
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
// 
// This is part of revision 2.1.0.12573 of the DK-TM4C123G Firmware Package.
//
//*****************************************************************************

#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "inc/hw_types.h"
#include "driverlib/debug.h"
#include "driverlib/flash.h"
#include "utils/ustdlib.h"
#include "qs-logger.h"
#include "usbstick.h"
#include "flashstore.h"

//*****************************************************************************
//
// This module manages the storage of data logger data into flash memory.
//
//*****************************************************************************

//*****************************************************************************
//
// Define the beginning and end of the flash storage area.  You must make sure
// that this area is well clear of any space occupied by the application
// binary, and that this space is not used for any other purpose.
// The start and end addresses must be 1K aligned.  The end address is
// exclusive - it is 1 value greater than the last valid location used for
// storage.
//
//*****************************************************************************
#define FLASH_STORE_START_ADDR  0x20000
#define FLASH_STORE_END_ADDR    0x40000

//*****************************************************************************
//
// The next address in flash, that will be used for storing a data record.
//
//*****************************************************************************
static uint32_t g_ui32StoreAddr;

//*****************************************************************************
//
// A buffer used to assemble a complete record of data prior to storing it
// in the flash.
//
//*****************************************************************************
static uint32_t g_pui32RecordBuf[32];

//*****************************************************************************
//
// Initializes the flash storage. This is a stub because there is nothing
// special to do.
//
//*****************************************************************************
void
FlashStoreInit(void)
{
}

//*****************************************************************************
//
// Saves data records that are stored in the flash to an externally connected
// USB memory storage device (USB stick).
// The flash memory is scanned for the presence of store data records.  When
// records are found they are written in CSV format to the USB stick.  This
// function assumes a non-corrupted storage area, and that any records, once
// found, are contiguous with all stored records.  It will find the oldest
// record and start with that when storing.
//
//*****************************************************************************
int32_t
FlashStoreSave(void)
{
    uint32_t ui32Addr, ui32OldestRecord, ui32OldestSeconds, ui32Count,
             ui32PartialCount;
    tLogRecord *psRecord;

    //
    // Initialize locals.
    //
    ui32OldestRecord = FLASH_STORE_START_ADDR;
    ui32OldestSeconds = 0xFFFFFFFF;

    //
    // Show a message to the user.
    //
    SetStatusText("SAVE", "SCANNING", "FLASH", 0);

    //
    // Start at beginning of flash storage area
    //
    ui32Addr = FLASH_STORE_START_ADDR;

    //
    // Search all of flash area checking every stored record.
    //
    while(ui32Addr < FLASH_STORE_END_ADDR)
    {
        //
        // If a record signature is found, check for oldest record, then
        // increment to the next record
        //
        if((HWREG(ui32Addr) & 0xFFFFFF00) == 0x53554100)
        {
            //
            // Get a pointer to the data record (account for flash header word)
            //
            psRecord = (tLogRecord *)(ui32Addr + 4);

            //
            // If the seconds in this record are older than any found so far
            // then save the seconds value, and the address of this record
            //
            if(psRecord->ui32Seconds < ui32OldestSeconds)
            {
                ui32OldestSeconds = psRecord->ui32Seconds;
                ui32OldestRecord = ui32Addr;
            }

            //
            // Advance the address to the next record.
            //
            ui32Addr += HWREG(ui32Addr) & 0xFF;
        }
        else
        {
            //
            // A record was not found so just advance to the next location in
            // flash
            //
            ui32Addr += 4;
        }
    }

    //
    // If no "oldest" seconds was found, then there is no valid data stored
    //
    if(ui32OldestSeconds == 0xFFFFFFFF)
    {
        SetStatusText("SAVE", "NO RECORDS", "FOUND", "PRESS <");
        return(1);
    }

    //
    // Open the output file on the USB stick.  It will return NULL if there
    // was any problem.
    //
    if(!USBStickOpenLogFile(0))
    {
        SetStatusText("SAVE", 0, "USB ERROR", "PRESS <");
        return(1);
    }

    //
    // Notify user we are saving data to USB
    //
    SetStatusText("SAVE", "SAVING", "TO USB", 0);

    //
    // Start reading records from flash, start at the address of the oldest
    // record, as found above.  We scan through records, assuming the flash
    // store is not corrupted.  Continue scanning until a blank space is
    // found which should indicate the end of recorded data, or until we
    // have read all the records.
    //
    ui32Addr = ui32OldestRecord;
    while(HWREG(ui32Addr) != 0xFFFFFFFF)
    {
        //
        // If a record signature is found (which it should be), extract the
        // record data and send it to USB stick.
        //
        if((HWREG(ui32Addr) & 0xFFFFFF00) == 0x53554100)
        {
            //
            // Get byte count for this record
            //
            ui32Count = HWREG(ui32Addr) & 0xFF;

            //
            // Adjust the count and the address to remove the flash header
            //
            ui32Count -= 4;
            ui32Addr += 4;

            //
            // Adjust for memory wrap
            //
            if(ui32Addr >= FLASH_STORE_END_ADDR)
            {
                ui32Addr = FLASH_STORE_START_ADDR;
            }

            //
            // If the contents of this record go past the end of the memory
            // storage area, then perform a partial copy first.
            //
            ui32PartialCount = 0;
            if((ui32Addr + ui32Count) >= FLASH_STORE_END_ADDR)
            {
                //
                // Find how many bytes are left on this page
                //
                ui32PartialCount = FLASH_STORE_END_ADDR - ui32Addr;

                //
                // Copy the portion until the end of memory store, adjust
                // remaining count and address
                //
                memcpy(g_pui32RecordBuf, (void *)ui32Addr, ui32PartialCount);
                ui32Count -= ui32PartialCount;
                ui32Addr = FLASH_STORE_START_ADDR;
            }

            //
            // Copy entire record (or remaining part of record if memory wrap)
            // into record buffer
            //
            memcpy(&g_pui32RecordBuf[ui32PartialCount / 4], (void *)ui32Addr,
                   ui32Count);

            //
            // Update address pointer to next record
            //
            ui32Addr += ui32Count;

            //
            // Now we have an entire data logger record copied from flash
            // storage into a local (contiguous) memory buffer.  Pass it
            // to the USB file writing function to write the record to the
            // USB stick.
            //
            USBStickWriteRecord((tLogRecord *)g_pui32RecordBuf);
        }
        else
        {
            //
            // This should not happen, but it means we ended up in a non-blank
            // location that is not the start of a record.  In this case just
            // advance through memory until either a blank location or another
            // record is found.
            //
            // Increment to next word in flash, adjust for memory wrap.
            //
            ui32Addr += 4;
            if(ui32Addr >= FLASH_STORE_END_ADDR)
            {
                ui32Addr = FLASH_STORE_START_ADDR;
            }
        }
    }

    //
    // Close the USB stick file so that any buffers will be flushed.
    //
    USBStickCloseFile();

    //
    // Inform user that save is complete.
    //
    SetStatusText("SAVE", "USB SAVE", "COMPLETE", "PRESS <");

    //
    // Return success
    //
    return(0);
}

//*****************************************************************************
//
// This is called at the start of logging to prepare space in flash for
// storage of logged data.  It searches for the first blank area in the
// flash storage to be used for storing records.
//
// If a starting address is specified then the search is skipped and it goes
// directly to the new address.  If the starting address is 0, then it performs
// the search.
//
//*****************************************************************************
int32_t
FlashStoreOpenLogFile(uint32_t ui32StartAddr)
{
    uint32_t ui32Addr;

    //
    // If a valid starting address is specified, then just use that and skip
    // the search below.
    //
    if((ui32StartAddr >= FLASH_STORE_START_ADDR) &&
       (ui32StartAddr < FLASH_STORE_END_ADDR))
    {
        g_ui32StoreAddr = ui32StartAddr;
        return(0);
    }

    //
    // Start at beginning of flash storage area
    //
    ui32Addr = FLASH_STORE_START_ADDR;

    //
    // Search until a blank is found or the end of flash storage area
    //
    while((HWREG(ui32Addr) != 0xFFFFFFFF) && (ui32Addr < FLASH_STORE_END_ADDR))
    {
        //
        // If a record signature is found, then increment to the next record
        //
        if((HWREG(ui32Addr) & 0xFFFFFF00) == 0x53554100)
        {
            ui32Addr += HWREG(ui32Addr) & 0xFF;
        }
        else
        {
            //
            // Just advance to the next location in flash
            //
            ui32Addr += 4;
        }
    }

    //
    // If we are at the end of flash that means no blank area was found.
    // So reset to the beginning and erase the first page.
    //
    if(ui32Addr >= FLASH_STORE_END_ADDR)
    {
        ui32Addr = FLASH_STORE_START_ADDR;
        FlashErase(ui32Addr);
    }

    //
    // When we reach here we either found a blank location, or made a new
    // blank location by erasing the first page.
    // To keep things simple we are making an assumption that the flash store
    // is not corrupted and that the first blank location implies the start
    // of a blank area suitable for storing data records.
    //
    g_ui32StoreAddr = ui32Addr;

    //
    // Return success indication to caller
    //
    return(0);
}

//*****************************************************************************
//
// This is called each time there is a new data record to log to the flash
// storage area.  A simple algorithm is used which rotates programming
// data log records through an area of flash.  It is assumed that the current
// page is blank.  Records are stored on the current page until a page
// boundary is crossed.  If the page boundary is crossed and the new page
// is not blank (testing only the first location), then the new page is
// erased.  Finally the entire record is programmed into flash and the
// storage pointers are updated.
//
// While storing and when crossing to a new page, if the flash page is not
// blank it is erased.  So this algorithm overwrites old data.
//
// The data is stored in flash as a record, with a flash header prepended,
// and with the record length padded to be a multiple of 4 bytes.  The flash
// header is a 3-byte magic number and one byte of record length.
//
//*****************************************************************************
int32_t
FlashStoreWriteRecord(tLogRecord *psRecord)
{
    uint32_t ui32Idx, ui32ItemCount, *pui32Record;

    //
    // Check the arguments
    //
    ASSERT(psRecord);
    if(!psRecord)
    {
        return(1);
    }

    //
    // Determine how many channels are to be logged
    //
    ui32Idx = psRecord->ui16ItemMask;
    ui32ItemCount = 0;
    while(ui32Idx)
    {
        if(ui32Idx & 1)
        {
            ui32ItemCount++;
        }
        ui32Idx >>= 1;
    }

    //
    // Add 16-bit count equivalent of record header, time stamp, and
    // selected items mask.  This is the total number of 16 bit words
    // of the record.
    //
    ui32ItemCount += 6;

    //
    // Convert the count to bytes, be sure to pad to 32-bit alignment.
    //
    ui32ItemCount = ((ui32ItemCount * 2) + 3) & ~3;

    //
    // Create the flash record header, which is a 3-byte signature and a
    // one byte count of bytes in the record.  Save it at the beginning
    // of the write buffer.
    //
    ui32Idx = 0x53554100 | (ui32ItemCount & 0xFF);
    g_pui32RecordBuf[0] = ui32Idx;

    //
    // Copy the rest of the record to the buffer, and get a pointer to
    // the buffer.
    //
    memcpy(&g_pui32RecordBuf[1], psRecord, ui32ItemCount - 4);
    pui32Record = g_pui32RecordBuf;

    //
    // Check to see if the record is going to cross a page boundary.
    //
    if(((g_ui32StoreAddr & 0x3FF) + ui32ItemCount) > 0x3FF)
    {
        //
        // Find number of bytes remaining on this page
        //
        ui32Idx = 0x400 - (g_ui32StoreAddr & 0x3FF);

        //
        // Program part of the record on the space remaining on the current
        // page
        //
        FlashProgram(pui32Record, g_ui32StoreAddr, ui32Idx);

        //
        // Increment the store address by the amount just written, which
        // should make the new store address be at the beginning of the next
        // flash page.
        //
        g_ui32StoreAddr += ui32Idx;

        //
        // Adjust the remaining bytes to program, and the pointer to the
        // remainder of the record data.
        //
        ui32ItemCount -= ui32Idx;
        pui32Record = &g_pui32RecordBuf[ui32Idx / 4];

        //
        // Check to see if the new page is past the end of store and adjust
        //
        if(g_ui32StoreAddr  >= FLASH_STORE_END_ADDR)
        {
            g_ui32StoreAddr = FLASH_STORE_START_ADDR;
        }

        //
        // If new page is not blank, then erase it
        //
        if(HWREG(g_ui32StoreAddr) != 0xFFFFFFFF)
        {
            FlashErase(g_ui32StoreAddr);
        }
    }

    //
    // Now program the remaining part of the record (if we crossed a page
    // boundary above) or the full record to the current location in flash
    //
    FlashProgram(pui32Record, g_ui32StoreAddr, ui32ItemCount);

    //
    // Increment the storage address to the next location.
    //
    g_ui32StoreAddr += ui32ItemCount;

    //
    // Return success indication to caller.
    //
    return(0);
}

//*****************************************************************************
//
// Return the current address being used for storing records.
//
//*****************************************************************************
uint32_t
FlashStoreGetAddr(void)
{
    return(g_ui32StoreAddr);
}

//*****************************************************************************
//
// Erase the data storage area of flash.
//
//*****************************************************************************
void
FlashStoreErase(void)
{
    uint32_t ui32Addr;

    //
    // Inform user we are erasing
    //
    SetStatusText("ERASE", 0, "ERASING", 0);

    //
    // Loop through entire storage area and erase each page.
    //
    for(ui32Addr = FLASH_STORE_START_ADDR; ui32Addr < FLASH_STORE_END_ADDR;
        ui32Addr += 0x400)
    {
        FlashErase(ui32Addr);
    }

    //
    // Inform user the erase is done.
    //
    SetStatusText("SAVE", "ERASE", "COMPLETE", "PRESS <");
}

//*****************************************************************************
//
// Determine if the flash block that contains the address is blank.
//
//*****************************************************************************
static int32_t
IsBlockFree(uint32_t ui32BaseAddr)
{
    uint32_t ui32Addr;

    //
    // Make sure we start at the beginning of a 1K block
    //
    ui32BaseAddr &= ~0x3FF;

    //
    // Loop through every address in this block and test if it is blank.
    //
    for(ui32Addr = 0; ui32Addr < 0x400; ui32Addr += 4)
    {
        if(HWREG(ui32BaseAddr + ui32Addr) != 0xFFFFFFFF)
        {
            //
            // Found a non-blank location, so return indication that block
            // is not free.
            //
            return(0);
        }
    }

    //
    // If we made it to here then every location in this block is erased,
    // so return indication that the block is free.
    //
    return(1);
}

//*****************************************************************************
//
// Report to the user the amount of free space and used space in the data
// storage area.
//
//*****************************************************************************
void
FlashStoreReport(void)
{
    uint32_t ui32Addr, ui32FreeBlocks, ui32UsedBlocks = 0;
    static char pcBufFree[16], pcBufUsed[16];

    //
    // Initialize locals.
    //
    ui32FreeBlocks = 0;
    ui32UsedBlocks = 0;

    //
    // Loop through each block of the storage area and count how many blocks
    // are free and non-free.
    //
    for(ui32Addr = FLASH_STORE_START_ADDR; ui32Addr < FLASH_STORE_END_ADDR;
        ui32Addr += 0x400)
    {
        if(IsBlockFree(ui32Addr))
        {
            ui32FreeBlocks++;
        }
        else
        {
            ui32UsedBlocks++;
        }
    }

    //
    // Report the result to the user via a status display screen.
    //
    usnprintf(pcBufFree, sizeof(pcBufFree), "FREE: %3uK", ui32FreeBlocks);
    usnprintf(pcBufUsed, sizeof(pcBufUsed), "USED: %3uK", ui32UsedBlocks);
    SetStatusText("FREE FLASH", pcBufFree, pcBufUsed, "PRESS <");
}