1 /*
2  * fs.h - CC31xx/CC32xx Host Driver Implementation
3  *
4  * Copyright (C) 2017 Texas Instruments Incorporated - http://www.ti.com/
5  *
6  *
7  *  Redistribution and use in source and binary forms, with or without
8  *  modification, are permitted provided that the following conditions
9  *  are met:
10  *
11  *    Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  *    Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the
17  *    distribution.
18  *
19  *    Neither the name of Texas Instruments Incorporated nor the names of
20  *    its contributors may be used to endorse or promote products derived
21  *    from this software without specific prior written permission.
22  *
23  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29  *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30  *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31  *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33  *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  *
35 */
36 
37 
38 
39 /*****************************************************************************/
40 /* Include files                                                             */
41 /*****************************************************************************/
42 #include <ti/drivers/net/wifi/simplelink.h>
43 
44 #ifndef __FS_H__
45 #define __FS_H__
46 
47 
48 
49 #ifdef __cplusplus
50 extern "C" {
51 #endif
52 
53 /*!
54     \defgroup FileSystem
55     \short Provides file system capabilities to TI's CC31XX that can be used by both the CC31XX device and the user
56 
57 */
58 
59 /*!
60 
61     \addtogroup FileSystem
62     @{
63 
64 */
65 
66 /*****************************************************************************/
67 /* Macro declarations                                                        */
68 /*****************************************************************************/
69 
70 /* Create file max size mode  */
71 #define SL_FS_OPEN_MODE_BIT_MASK    (0xF8000000)
72 #define SL_NUM_OF_MODE_BIT          (5)
73 
74 #define SL_FS_OPEN_FLAGS_BIT_MASK   (0x07FE0000)
75 #define SL_NUM_OF_FLAGS_BIT         (10)
76 
77 #define SL_FS_OPEN_MAXSIZE_BIT_MASK (0x1FFFF)
78 #define SL_NUM_OF_MAXSIZE_BIT       (17)
79 
80 
81 /*
82   sl_FsGetInfo and sl_FsGetFileList flags
83   ------------------
84 */
85 
86 #define SL_FS_INFO_OPEN_WRITE                    0x1000   /* File is opened for write */
87 #define SL_FS_INFO_OPEN_READ                     0x800    /* File is opened for read */
88 
89 #define SL_FS_INFO_MUST_COMMIT                   0x1      /* File is currently open with SL_FS_WRITE_MUST_COMMIT */
90 #define SL_FS_INFO_BUNDLE_FILE                   0x2      /* File is currently open with SL_FS_WRITE_BUNDLE_FILE */
91 
92 #define SL_FS_INFO_PENDING_COMMIT                0x4      /* File that was open with SL_FS_WRITE_MUST_COMMIT is closed */
93 #define SL_FS_INFO_PENDING_BUNDLE_COMMIT         0x8      /* File that was open with SL_FS_WRITE_BUNDLE_FILE is closed */
94 
95 #define SL_FS_INFO_NOT_FAILSAFE                  0x20     /* File was not created with SL_FS_CREATE_FAILSAFE */
96 #define SL_FS_INFO_NOT_VALID                     0x100    /* No valid image exists for the file */
97 #define SL_FS_INFO_SYS_FILE                      0x40     /* File is system file */
98 #define SL_FS_INFO_SECURE                        0x10     /* File is secured */
99 #define SL_FS_INFO_NOSIGNATURE                   0x2000   /* File is unsigned, the flag is returns only for sl_FsGetInfo function and not for sl_FsGetFileList */
100 #define SL_FS_INFO_PUBLIC_WRITE                  0x200    /* File is open for public write */
101 #define SL_FS_INFO_PUBLIC_READ                   0x400    /* File is open for public read */
102 
103 
104 /*
105   fs_Open flags
106   --------------
107 */
108 
109 /* mode */
110 #define     SL_FS_CREATE                         ((_u32)0x1<<(SL_NUM_OF_MAXSIZE_BIT+SL_NUM_OF_FLAGS_BIT))
111 #define     SL_FS_WRITE                          ((_u32)0x2<<(SL_NUM_OF_MAXSIZE_BIT+SL_NUM_OF_FLAGS_BIT))
112 #define     SL_FS_OVERWRITE                      ((_u32)0x4<<(SL_NUM_OF_MAXSIZE_BIT+SL_NUM_OF_FLAGS_BIT))
113 #define     SL_FS_READ                           ((_u32)0x8<<(SL_NUM_OF_MAXSIZE_BIT+SL_NUM_OF_FLAGS_BIT))
114 /* creation flags */
115 #define     SL_FS_CREATE_FAILSAFE                ((_u32)0x1<<SL_NUM_OF_MAXSIZE_BIT)         /* Fail safe */
116 #define     SL_FS_CREATE_SECURE                  ((_u32)0x2<<SL_NUM_OF_MAXSIZE_BIT)         /* SECURE */
117 #define     SL_FS_CREATE_NOSIGNATURE             ((_u32)0x4<<SL_NUM_OF_MAXSIZE_BIT)         /* Relevant to secure file only  */
118 #define     SL_FS_CREATE_STATIC_TOKEN            ((_u32)0x8<<SL_NUM_OF_MAXSIZE_BIT)         /* Relevant to secure file only */
119 #define     SL_FS_CREATE_VENDOR_TOKEN            ((_u32)0x10<<SL_NUM_OF_MAXSIZE_BIT)        /* Relevant to secure file only */
120 #define     SL_FS_CREATE_PUBLIC_WRITE            ((_u32)0x20<<SL_NUM_OF_MAXSIZE_BIT)        /* Relevant to secure file only, the file can be opened for write without Token */
121 #define     SL_FS_CREATE_PUBLIC_READ             ((_u32)0x40<<SL_NUM_OF_MAXSIZE_BIT)        /* Relevant to secure file only, the file can be opened for read without Token  */
122 
123 #define     SL_FS_CREATE_MAX_SIZE( MaxFileSize ) ((((_u32)MaxFileSize + 255) / 256 ) & SL_FS_OPEN_MAXSIZE_BIT_MASK )
124 
125 /* open for write flags */
126 #define    SL_FS_WRITE_MUST_COMMIT               ((_u32)0x80<<SL_NUM_OF_MAXSIZE_BIT)        /* The file is locked for changes */
127 #define    SL_FS_WRITE_BUNDLE_FILE               ((_u32)0x100<<SL_NUM_OF_MAXSIZE_BIT)       /* The file is locked for changes as part of Bundle */
128 #define    SL_FS_WRITE_ENCRYPTED                 ((_u32)0x200<<SL_NUM_OF_MAXSIZE_BIT)       /* This indicates the start of a secured content write session */
129 
130 /*****************************************************************************/
131 /* Structure/Enum declarations                                               */
132 /*****************************************************************************/
133 
134 typedef enum
135 {
136     SL_FS_TOKEN_MASTER               = 0,
137     SL_FS_TOKEN_WRITE_READ           = 1,
138     SL_FS_TOKEN_WRITE_ONLY           = 2,
139     SL_FS_TOKEN_READ_ONLY            = 3
140 }SlFsTokenId_e;
141 
142 typedef struct
143 {
144     _u16  Flags;                    /* see Flags options */
145     _u32  Len;                      /* In bytes, The actual size of the copy which is used for read*/
146     _u32  MaxSize;                  /* In bytes, The max file size  */
147     _u32  Token[4];                 /* see SlFsTokenId_e */
148     _u32  StorageSize;              /* In bytes, The total size that the file required on the storage including the mirror */
149     _u32  WriteCounter;             /* Number of times in which the file have been written successfully */
150 }SlFsFileInfo_t;
151 
152 
153 /*
154   sl_FsCtl
155   --------
156 */
157 typedef enum
158 {
159   SL_FS_CTL_RESTORE = 0,   /* restores the factory default */
160   SL_FS_CTL_ROLLBACK = 1,
161   SL_FS_CTL_COMMIT = 2,
162   SL_FS_CTL_RENAME = 3,
163   SL_FS_CTL_GET_STORAGE_INFO = 5,
164   SL_FS_CTL_BUNDLE_ROLLBACK = 6,
165   SL_FS_CTL_BUNDLE_COMMIT = 7
166 }SlFsCtl_e;
167 
168 typedef enum
169 {
170   SL_FS_BUNDLE_STATE_STOPPED = 0,
171   SL_FS_BUNDLE_STATE_STARTED = 1,
172   SL_FS_BUNDLE_STATE_PENDING_COMMIT = 3
173 }SlFsBundleState_e;
174 
175 typedef struct
176 {
177     _u32  Key[4];/*16 bytes*/
178 }SlFsKey_t;
179 
180 typedef struct
181 {
182   _u8   Index;
183 }SlFsFileNameIndex_t;
184 
185 typedef union
186 {
187   SlFsFileNameIndex_t  Index;
188   _i32                 ErrorNumber;
189 }SlFsFileNameIndexOrError_t;
190 
191 /* File control helper structures */
192 
193 /*SL_FS_CTL_RESTORE*/
194 typedef enum
195 {
196   SL_FS_FACTORY_RET_TO_IMAGE =  0,/*The system will be back to the production image.*/
197   SL_FS_FACTORY_RET_TO_DEFAULT = 2 /*return to factory default*/
198 }SlFsRetToFactoryOper_e;
199 
200 typedef struct
201 {
202   _u32 Operation;/*see _SlFsRetToFactoryOper_e*/
203 }SlFsRetToFactoryCommand_t;
204 
205 /******************* Input flags end *****************************************/
206 
207 typedef struct
208 {
209   _u32           IncludeFilters;
210 
211 }SlFsControl_t;
212 
213 typedef struct
214 {
215   _u16 DeviceBlockSize;
216   _u16 DeviceBlocksCapacity;
217   _u16 NumOfAllocatedBlocks;
218   _u16 NumOfReservedBlocks;
219   _u16 NumOfReservedBlocksForSystemfiles;
220   _u16 LargestAllocatedGapInBlocks;
221   _u16 NumOfAvailableBlocksForUserFiles;
222   _u8  Padding[2];
223 } SlFsControlDeviceUsage_t;
224 
225 typedef struct
226 {
227   _u8  MaxFsFiles;
228   _u8  IsDevlopmentFormatType;
229   _u8  Bundlestate; /*see SlFsBundleState_e*/
230   _u8  Reserved;
231   _u8  MaxFsFilesReservedForSysFiles;
232   _u8  ActualNumOfUserFiles;
233   _u8  ActualNumOfSysFiles;
234   _u8  Padding;
235   _u32 NumOfAlerts;
236   _u32 NumOfAlertsThreshold;
237   _u16 FATWriteCounter;/*Though it is increased during the programming, the programming and ret to factory takes only 1- write to the FAT, independ of the number of the programming files */
238   _u16 Padding2;
239 }SlFsControlFilesUsage_t;
240 
241 /*SL_FS_CTL_GET_STORAGE_INFO*/
242 typedef struct
243 {
244     SlFsControlDeviceUsage_t DeviceUsage;
245     SlFsControlFilesUsage_t  FilesUsage;
246 } SlFsControlGetStorageInfoResponse_t;
247 
248 typedef struct
249 {
250    _u32   IncludeFilters; /* see SlFsControlFilterCounterFlags_e*/
251    _u8    OpenedForWriteCnt;
252    _u8    OpeneForReadCnt;
253    _u8    ClosedFilesCnt;
254    _u8    OpenedForWriteCntWithValidFailSafeImage;
255    _u8    OpeneForReadCntWithValidFailSafeImage;
256    _u8    ClosedFilesCntWithValidFailSafeImage;
257    _u8    padding[2];
258 } SlFsControlGetCountersResponse_t;
259 
260 /* GetFileList */
261 #define SL_FS_MAX_FILE_NAME_LENGTH                       180
262 
263 typedef enum
264 {
265     SL_FS_GET_FILE_ATTRIBUTES = 0x1
266 }SlFileListFlags_t;
267 
268 
269 
270 
271 typedef struct
272 {
273    _u32  FileMaxSize;
274    _u32  Properties; /* see SL_FS_INFO_  flags */
275    _u32  FileAllocatedBlocks;/*1 block = 4096 bytes*/
276 }SlFileAttributes_t;
277 /*!
278     \cond DOXYGEN_REMOVE
279 */
280 /*****************************************************************************/
281 /* external Function prototypes                                              */
282 /*****************************************************************************/
283 
284 /*****************************************************************************/
285 /* Function prototypes                                                       */
286 /*****************************************************************************/
287 /*!
288     \endcond
289 */
290 /*!
291     \brief open file for read or write from/to storage device
292 
293     \param[in]      pFileName                  File Name buffer pointer
294     \param[in]      AccessModeAndMaxSize       Options: As described below
295     \param[in]      pToken                     input Token for read, output Token for write
296 
297      AccessModeAndMaxSize possible input                                                                        \n
298      SL_FS_READ                                        - Read a file                                                                  \n
299      SL_FS_WRITE                                       - Open for write for an existing file (whole file content needs to be rewritten)\n
300      SL_FS_CREATE|maxSizeInBytes,accessModeFlags
301      SL_FS_CREATE|SL_FS_OVERWRITE|maxSizeInBytes,accessModeFlags  - Open for creating a new file. Max file size is defined in bytes.             \n
302                                                                     For optimal FS size, use max size in 4K-512 bytes steps (e.g. 3584,7680,117760)  \n
303                                                                     Several access modes bits can be combined together from SlFileOpenFlags_e enum
304 
305     \return         File handle on success. Negative error code on fail
306 
307     \sa             sl_FsRead sl_FsWrite sl_FsClose
308     \note           belongs to \ref basic_api
309     \warning
310     \par            Example
311 
312     - Creating file and writing data to it
313     \code
314         char*           DeviceFileName = "MyFile.txt";
315         unsigned long   MaxSize = 63 * 1024; //62.5K is max file size
316         long            DeviceFileHandle = -1;
317         _i32            RetVal;        //negative retval is an error
318         unsigned long   Offset = 0;
319         unsigned char   InputBuffer[100];
320         _u32            MasterToken = 0;
321 
322         // Create a file and write data. The file in this example is secured, without signature and with a fail safe commit
323 
324         //create a secure file if not exists and open it for write.
325         DeviceFileHandle =  sl_FsOpen(unsigned char *)DeviceFileName,
326                                       SL_FS_CREATE|SL_FS_OVERWRITE | SL_FS_CREATE_SECURE | SL_FS_CREATE_NOSIGNATURE | SL_FS_CREATE_MAX_SIZE( MaxSize ),
327                                       &MasterToken);
328 
329         Offset = 0;
330         //Preferred in secure file that the Offset and the length will be aligned to 16 bytes.
331         RetVal = sl_FsWrite( DeviceFileHandle, Offset, (unsigned char *)"HelloWorld", strlen("HelloWorld"));
332 
333         RetVal = sl_FsClose(DeviceFileHandle, NULL, NULL , 0);
334 
335         // open the same file for read, using the Token we got from the creation procedure above
336         DeviceFileHandle =  sl_FsOpen(unsigned char *)DeviceFileName,
337                                       SL_FS_READ,
338                                       &MasterToken);
339 
340         Offset = 0;
341         RetVal = sl_FsRead( DeviceFileHandle, Offset, (unsigned char *)InputBuffer, strlen("HelloWorld"));
342 
343         RetVal = sl_FsClose(DeviceFileHandle, NULL, NULL , 0);
344     \endcode
345     <br>
346 
347     - Create a non secure file if not already exists and open it for write
348     \code
349         DeviceFileHandle = sl_FsOpen((unsigned char *)DeviceFileName,
350                                       SL_FS_CREATE|SL_FS_OVERWRITE| SL_FS_CREATE_MAX_SIZE( MaxSize ),
351                                       NULL);
352     \endcode
353 
354     \note             Some of the flags are creation flags and can only be set when the file is created. When opening the file for write the creation flags are ignored. For more information, refer to chapter 8 in the user manual.
355 
356 */
357 
358 #if _SL_INCLUDE_FUNC(sl_FsOpen)
359 _i32 sl_FsOpen(const _u8 *pFileName,const _u32 AccessModeAndMaxSize,_u32 *pToken);
360 #endif
361 
362 /*!
363     \brief Close file in storage device
364 
365     \param[in]      FileHdl               Pointer to the file (assigned from sl_FsOpen)
366     \param[in]      pCeritificateFileName Certificate file, or NULL if irrelevant.
367     \param[in]      pSignature            The signature is either SHA-1 or SHA-256, the certificate chain may include SHA-256
368     \param[in]      SignatureLen          The signature actual length
369 
370     \return         Zero on success, or a negative value if an error occurred
371     \sa             sl_FsRead sl_FsWrite sl_FsOpen
372     \note           Call the fs_Close  with signature = 'A' signature len = 1 for activating an abort action\n
373                     Creating signature : OpenSSL> dgst -binary -sha1 -sign <file-location>\<private_key>.pem -out <file-location>\<output>.sig <file-location>\<input>.txt
374     \warning
375     \par            Examples
376 
377     - Closing file:
378     \code
379         _i16 RetVal;
380         RetVal = sl_FsClose(FileHandle,0,0,0);
381     \endcode
382     <br>
383 
384     - Aborting file:
385     \code
386         _u8  Signature;
387         Signature = 'A';
388         sl_FsClose(FileHandle,0,&Signature, 1);
389     \endcode
390 
391     \note            In case the file was opened as not secure file or as secure-not signed, any certificate or signature provided are ignored, those fields should be set to NULL.
392 */
393 #if _SL_INCLUDE_FUNC(sl_FsClose)
394 _i16 sl_FsClose(const _i32 FileHdl,const _u8* pCeritificateFileName,const _u8* pSignature,const _u32 SignatureLen);
395 #endif
396 
397 /*!
398     \brief Read block of data from a file in storage device
399 
400     \param[in]      FileHdl Pointer to the file (assigned from sl_FsOpen)
401     \param[in]      Offset  Offset to specific read block
402     \param[out]     pData   Pointer for the received data
403     \param[in]      Len     Length of the received data
404 
405     \return         Number of read bytes on success, negative error code on failure
406 
407     \sa             sl_FsClose sl_FsWrite sl_FsOpen
408     \note           belongs to \ref basic_api
409     \warning
410     \par            Example
411 
412     - Reading File:
413     \code
414     Status = sl_FsRead(FileHandle, 0, &readBuff[0], readSize);
415     \endcode
416 */
417 #if _SL_INCLUDE_FUNC(sl_FsRead)
418 _i32 sl_FsRead(const _i32 FileHdl,_u32 Offset ,_u8*  pData,_u32 Len);
419 #endif
420 
421 /*!
422     \brief Write block of data to a file in storage device
423 
424     \param[in]      FileHdl  Pointer to the file (assigned from sl_FsOpen)
425     \param[in]      Offset   Offset to specific block to be written
426     \param[in]      pData    Pointer the transmitted data to the storage device
427     \param[in]      Len      Length of the transmitted data
428 
429     \return         Number of wireted bytes on success, negative error code on failure
430 
431     \sa
432     \note           belongs to \ref basic_api
433     \warning
434     \par            Example
435 
436     - Writing file:
437     \code
438     Status = sl_FsWrite(FileHandle, 0, &buff[0], readSize);
439     \endcode
440 */
441 #if _SL_INCLUDE_FUNC(sl_FsWrite)
442 _i32 sl_FsWrite(const _i32 FileHdl,_u32 Offset,_u8*  pData,_u32 Len);
443 #endif
444 
445 /*!
446     \brief Get information of a file
447 
448     \param[in]      pFileName    File name
449     \param[in]      Token        File token. if irrelevant set to 0.
450     \param[out]     pFsFileInfo Returns the File's Information (SlFsFileInfo_t)
451                                 - Flags
452                                 - File size
453                                 - Allocated size
454                                 - Tokens
455 
456     \return         Zero on success, negative error code on failure \n
457                     When file not exists : SL_ERROR_FS_FILE_NOT_EXISTS
458     \note
459                     - If the return value is SL_ERROR_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY or  SL_ERROR_FS_FILE_IS_ALREADY_OPENED information about the file is valid.
460                     - Belongs to \ref basic_api
461 
462     \sa             sl_FsOpen
463     \warning
464     \par            Example
465 
466     - Getting file info:
467     \code
468     Status = sl_FsGetInfo("FileName.html",Token,&FsFileInfo);
469     \endcode
470 */
471 #if _SL_INCLUDE_FUNC(sl_FsGetInfo)
472 _i16 sl_FsGetInfo(const _u8 *pFileName,const _u32 Token,SlFsFileInfo_t* pFsFileInfo);
473 #endif
474 
475 /*!
476     \brief Delete specific file from a storage or all files from a storage (format)
477 
478     \param[in]      pFileName    File Name
479     \param[in]      Token        File token. if irrelevant set to 0
480     \return         Zero on success, or a negative value if an error occurred
481 
482     \sa
483     \note           belongs to \ref basic_api
484     \warning
485     \par            Example
486 
487     - Deleting file:
488     \code
489         Status = sl_FsDel("FileName.html",Token);
490     \endcode
491 */
492 #if _SL_INCLUDE_FUNC(sl_FsDel)
493 _i16 sl_FsDel(const _u8 *pFileName,const _u32 Token);
494 #endif
495 
496 
497 
498 /*!
499     \brief Controls various file system operations
500 
501    \param[in]  Command , the command to execute, \see SlFsCtl_e
502     SL_FS_CTL_RESTORE , Return to factory default, return to factory image , see fs programming
503     SL_FS_CTL_ROLLBACK , Roll-back file which was created with 'SL_FS_WRITE_MUST_COMMIT'
504     SL_FS_CTL_COMMIT,Commit file which was created with 'SL_FS_WRITE_MUST_COMMIT'
505     SL_FS_CTL_RENAME, Rename file
506     SL_FS_CTL_GET_STORAGE_INFO, Total size of storage , available size of storage
507     SL_FS_CTL_BUNDLE_ROLLBACK, Rollback bundle files
508     SL_FS_CTL_BUNDLE_COMMIT, Commit Bundle files
509     \param[in]      Token         Set to NULL if not relevant to the command
510     \param[in]      pFileName     Set to NULL if not relevant to the command
511     \param[in]      pData         The data according the command.
512     \param[in]      DataLen       Length of data buffer
513     \param[out]     pOutputData   Buffer for the output data
514     \param[out]     OutputDataLen Length of the output data buffer
515     \param[out]     pNewToken     The new valid file token, if irrelevant can be set to NULL.
516     \return
517                     - Zero on success, or a negative value if an error occurred
518                     - For SL_FS_CTL_BUNDLE_ROLLBACK, On success bundle the new bundle state is returned (see SlFsBundleState_e) else negative error number
519                     - For SL_FS_CTL_BUNDLE_COMMIT, On success the new bundle state is returned (see SlFsBundleState_e) else negative error number
520 
521     \sa
522     \note           belongs to \ref ext_api
523     \warning
524     \par            Examples
525 
526     - SL_FS_CTL_ROLLBACK:
527     \code
528             FsControl.IncludeFilters = 0;
529             slRetVal = sl_FsCtl( (SlFsCtl_e)SL_FS_CTL_FILE_ROLLBACK, Token, NWPfileName ,(_u8 *)&FsControl, sizeof(SlFsControl_t), NULL, 0 , pNewToken);
530     \endcode
531     <br>
532 
533     - SL_FS_CTL_COMMIT:
534     \code
535             FsControl.IncludeFilters = 0;
536             slRetVal = sl_FsCtl(SL_FS_CTL_COMMIT, Token, NWPfileName ,(_u8 *)&FsControl, sizeof(SlFsControl_t), NULL, 0, pNewToken );
537     \endcode
538     <br>
539 
540     - SL_FS_CTL_RENAME:
541     \code
542             slRetVal = sl_FsCtl(SL_FS_CTL_RENAME, Token, NWPfileName, NewFileName, 0, NULL, 0, NULL );
543     \endcode
544     <br>
545 
546     - SL_FS_CTL_GET_STORAGE_INFO:
547     \code
548         _i32  GetStorageInfo( SlFsControlGetStorageInfoResponse_t* pSlFsControlGetStorageInfoResponse )
549         {
550             _i32 slRetVal;
551 
552             slRetVal = sl_FsCtl( ( SlFsCtl_e)SL_FS_CTL_GET_STORAGE_INFO, 0, NULL , NULL , 0, (_u8 *)pSlFsControlGetStorageInfoResponse, sizeof(SlFsControlGetStorageInfoResponse_t), NULL );
553             return slRetVal;
554         }
555     \endcode
556     <br>
557 
558     - SL_FS_CTL_RESTORE:
559     \code
560         //Return 0 for OK, else Error
561         _i32 ProgramRetToImage( )
562         {
563             _i32 slRetVal;
564             SlFsRetToFactoryCommand_t RetToFactoryCommand;
565             _i32 RetVal, ExtendedError;
566 
567             RetToFactoryCommand.Operation = SL_FS_FACTORY_RET_TO_IMAGE;
568             slRetVal = sl_FsCtl( (SlFsCtl_e)SL_FS_CTL_RESTORE, 0, NULL , (_u8 *)&RetToFactoryCommand , sizeof(SlFsRetToFactoryCommand_t), NULL, 0 , NULL );
569             if ((_i32)slRetVal < 0)
570                 {
571                     //Pay attention, for this function the slRetVal is composed from Signed RetVal & extended error
572                     RetVal = (_i16)slRetVal>> 16;
573                     ExtendedError = (_u16)slRetVal& 0xFFFF;
574                     printf("\tError SL_FS_FACTORY_RET_TO_IMAGE, 5d, %d\n", RetVal, ExtendedError);
575                     return slRetVal;
576             }
577             //Reset
578             sl_Stop(0);
579             Sleep(1000);
580             sl_Start(NULL, NULL, NULL);
581 
582             return slRetVal;
583         }
584     \endcode
585     <br>
586 
587     - SL_FS_CTL_BUNDLE_ROLLBACK:
588     \code
589         //return 0 for O.K else negative
590         _i32 BundleRollback()
591         {
592             _i32 slRetVal = 0;
593             SlFsControl_t FsControl;
594             FsControl.IncludeFilters = 0; //Use default behaviour
595             slRetVal = sl_FsCtl( (SlFsCtl_e)SL_FS_CTL_BUNDLE_ROLLBACK, 0, NULL ,(_u8 *)&FsControl, sizeof(SlFsControl_t), NULL, 0 , NULL);
596             return slRetVal;
597         }
598     \endcode
599     <br>
600 
601     - SL_FS_CTL_BUNDLE_COMMIT:
602     \code
603         //return 0 for O.K else negative
604         _i32 BundleCommit()
605         {
606             _i32 slRetVal = 0;
607             SlFsControl_t FsControl;
608             FsControl.IncludeFilters = 0; //Use default behaviour
609             slRetVal = sl_FsCtl( (SlFsCtl_e)SL_FS_CTL_BUNDLE_COMMIT, 0, NULL ,(_u8 *)&FsControl, sizeof(SlFsControl_t), NULL, 0 , NULL);
610             return slRetVal;
611         }
612     \endcode
613  */
614 #if _SL_INCLUDE_FUNC(sl_FsCtl)
615 _i32   sl_FsCtl(  SlFsCtl_e Command,  _u32 Token,  _u8 *pFileName, const _u8 *pData, _u16 DataLen, _u8 *pOutputData, _u16 OutputDataLen,_u32 *pNewToken );
616 #endif
617 /*!
618     \brief Enables to format and configure the device with pre-prepared configuration
619 
620     \param[in]      Flags          For future use
621     \param[in]      pKey        In case the ucf is encrypted the encryption key, otherwise NULL
622     \param[in]      pData       The file is download in data chunks, the chunk size should be aligned to 16 bytes, if no data Set to NULL
623     \param[in]      Len         The length of pData in bytes
624     \return         The return value is:
625                     - On error < 0 , contains the error number and extended error number
626                     - On success > 0, represent the number of bytes received
627                     - On successful end == 0 , when all file chunks are download
628     \sa
629     \note           belongs to \ref ext_api
630     \warning
631     \par            Example
632 
633     - FS programming:
634     \code
635 
636         //Return 0 for OK, else Error
637         _i32 ProgramImage( char* UcfFileName, char * KeyFileName )
638         {
639             #define PROGRAMMING_CHUNK_SIZE 4096
640             _i32 slRetVal = 0;
641             SlFsKey_t Key;
642             FILE *hostFileHandle = NULL;
643             _u16 bytesRead;
644             _u8 DataBuf[PROGRAMMING_CHUNK_SIZE];
645             FILE *KeyFileHandle = NULL;
646             short ErrorNum;
647             unsigned short ExtendedErrorNum;
648             time_t start,end;
649             double dif;
650             _u8* pKey = NULL;
651             errno_t err;
652 
653             if (KeyFileName != "")
654             {
655                 //Read key
656                 err   = fopen_s( &KeyFileHandle, KeyFileName, "rb");
657                 if (err != 0)
658                 {
659                     return __LINE__;//error
660                 }
661                 fread((_u8*)&Key, 1, sizeof(SlFsKey_t), KeyFileHandle);
662                 fclose(KeyFileHandle);
663                 pKey = (_u8*)&Key;
664             }
665 
666             // Downlaoding the Data with the key, the key can be set only in the first chunk,no need to download it with each chunk
667             if (UcfFileName != "")
668             {
669                 //Read data
670                  err   = fopen_s( &hostFileHandle, UcfFileName, "rb");
671                 if (err != 0)
672                 {
673                     return __LINE__;//error
674                 }
675 
676                 time (&start);
677 
678                 bytesRead = fread(DataBuf, 1, PROGRAMMING_CHUNK_SIZE, hostFileHandle);
679 
680                 while ( bytesRead  )
681                 {
682                     slRetVal =  sl_FsProgram( DataBuf , bytesRead , (_u8*)pKey,  0 );
683                     if(slRetVal ==  SL_API_ABORTED)//timeout
684                     {
685                         return( slRetVal );
686                     }
687                     else if (slRetVal < 0 )//error
688                     {
689                         ErrorNum = (long)slRetVal >> 16;
690                         ExtendedErrorNum = (_u16)(slRetVal & 0xFFFF);
691                         printf("\tError sl_FsProgram = %d , %d \n", ErrorNum, ExtendedErrorNum);
692                         fclose(hostFileHandle);
693                         return( ErrorNum );
694                     }
695                     if(slRetVal == 0)//finished succesfully
696                         break;
697                     pKey = NULL;//no need to download the key with each chunk;
698                     bytesRead = fread(DataBuf, 1, PROGRAMMING_CHUNK_SIZE, hostFileHandle);
699                 }
700 
701 
702                 time (&end);
703                 dif = difftime (end,start);
704             #ifdef PRINT
705                 printf ("\tProgramming took %.2lf seconds to run.\n", dif );
706             #endif
707                 //The file was downloaded but it was not detected by the programming as the EOF.
708                 if((bytesRead == 0 ) && (slRetVal > 0 ))
709                 {
710                     return __LINE__;//error
711                 }
712 
713 
714                 fclose(hostFileHandle);
715             }//if (UcfFileName != "")
716 
717             //this scenario is in case the image was already "burned" to the SFLASH by external tool and only the key is downloaded
718             else if (KeyFileName != "")
719             {
720                 slRetVal =  sl_FsProgram(NULL , 0 , (_u8*)pKey,  0 );
721                 if (slRetVal < 0)//error
722                 {
723                     ErrorNum = (long)slRetVal >> 16;
724                     ExtendedErrorNum = (_u16)slRetVal && 0xFF;;
725                     printf("\tError sl_FsProgram = %d , %d \n", ErrorNum, ExtendedErrorNum);
726                     fclose(hostFileHandle);
727                     return( ErrorNum );
728                 }
729             }
730 
731             if( slRetVal == 0 )
732             {
733                 //Reset the nWP
734                 sl_Stop(100);
735                 Sleep(1000);
736                 sl_Start(NULL, NULL, NULL);
737                 Sleep(2000);
738              }
739 
740             return slRetVal;
741 
742         }
743 
744     \endcode
745 */
746 
747 #if _SL_INCLUDE_FUNC(sl_FsProgram)
748 _i32   sl_FsProgram(const _u8*  pData , _u16 Len , const _u8 * pKey ,  _u32 Flags );
749 #endif
750 /*!
751     \brief The list of file names, the files are retrieve in chunks
752 
753     \param[in, out] pIndex      The first chunk should start with value of  -1, afterwards the Index from the previous call should be set as input\n
754                                 Returns current chunk intex, start the next chunk from that number
755     \param[in]      Count       Number of entries to retrieve
756     \param[in]      MaxEntryLen The total size of the buffer is Count * MaxEntryLen
757     \param[out]     pBuff       The buffer contains list of SlFileAttributes_t + file name
758     \param[in]      Flags       Is to retrieve file attributes see SlFileAttributes_t.
759     \return         The actual number of entries which are contained in the buffer. On error negative number which contains the error number.
760     \sa
761     \note           belongs to \ref ext_api
762     \warning
763     \par            Example
764 
765     - Getting file list
766     \code
767         typedef struct
768         {
769             SlFileAttributes_t attribute;
770             char fileName[SL_FS_MAX_FILE_NAME_LENGTH];
771         }slGetfileList_t;
772 
773         #define COUNT 5
774 
775         void PrintFileListProperty(_u16 prop);
776 
777         INT32 GetFileList()
778         {
779             _i32 NumOfEntriesOrError = 1;
780             _i32 Index = -1;
781             slGetfileList_t File[COUNT];
782             _i32  i;
783             _i32 RetVal = 0;
784 
785             printf("%\n");
786             while( NumOfEntriesOrError > 0 )
787             {
788                 NumOfEntriesOrError = sl_FsGetFileList( &Index, COUNT, (_u8)(SL_FS_MAX_FILE_NAME_LENGTH + sizeof(SlFileAttributes_t)), (unsigned char*)File, SL_FS_GET_FILE_ATTRIBUTES);
789                 if (NumOfEntriesOrError < 0)
790                 {
791                     RetVal = NumOfEntriesOrError;//error
792                     break;
793                 }
794                 for (i = 0; i < NumOfEntriesOrError; i++)
795                 {
796                    printf("Name: %s\n", File[i].fileName);
797                    printf("AllocatedBlocks: %5d ",File[i].attribute.FileAllocatedBlocks);
798                    printf("MaxSize(byte): %5d \n", File[i].attribute.FileMaxSize);
799                    PrintFileListProperty((_u16)File[i].attribute.Properties);
800                    printf("%\n\n");
801                }
802            }
803            printf("%\n");
804            return RetVal;//0 means O.K
805        }
806 
807        void PrintFileListProperty(_u16 prop)
808        {
809            printf("Flags : ");
810            if (prop & SL_FS_INFO_MUST_COMMIT)
811                printf("Open file commit,");
812            if (prop & SL_FS_INFO_BUNDLE_FILE)
813                printf("Open bundle commit,");
814            if (prop & SL_FS_INFO_PENDING_COMMIT)
815                printf("Pending file commit,");
816            if (prop & SL_FS_INFO_PENDING_BUNDLE_COMMIT)
817                 printf("Pending bundle commit,");
818             if (prop & SL_FS_INFO_SECURE)
819                 printf("Secure,");
820             if (prop & SL_FS_INFO_NOT_FAILSAFE)
821                 printf("File safe,");
822             if (prop & SL_FS_INFO_SYS_FILE)
823                 printf("System,");
824             if (prop & SL_FS_INFO_NOT_VALID)
825                 printf("No valid copy,");
826             if (prop & SL_FS_INFO_PUBLIC_WRITE)
827                 printf("Public write,");
828             if (prop & SL_FS_INFO_PUBLIC_READ)
829                 printf("Public read,");
830         }
831 
832     \endcode
833 */
834 #if _SL_INCLUDE_FUNC(sl_FsGetFileList)
835 _i32  sl_FsGetFileList(_i32* pIndex, _u8 Count, _u8 MaxEntryLen , _u8* pBuff, SlFileListFlags_t Flags );
836 #endif
837 
838 /*!
839 
840  Close the Doxygen group.
841  @}
842 
843  */
844 
845 #ifdef  __cplusplus
846 }
847 #endif /*  __cplusplus */
848 
849 #endif /*  __FS_H__ */
850 
851