source: soft/giet_vm/giet_fat32/fat32.c @ 653

Last change on this file since 653 was 653, checked in by guerin, 9 years ago

fat32: buf descriptor allocation fixes

Don't leak buffer on IOC access failure.

  • Property svn:executable set to *
File size: 160.2 KB
Line 
1//////////////////////////////////////////////////////////////////////////////////
2// Date     : 01/06/2015
3// Authors  : Alain Greiner
4// Copyright (c) UPMC-LIP6
5//////////////////////////////////////////////////////////////////////////////////
6// The fat32.h and fat32.c files define a library of access functions
7// to a FAT32 disk on a block device. It is intended to be used by both
8// the boot code and the kernel code.
9//////////////////////////////////////////////////////////////////////////////////
10// Implementation notes:
11// 1. the "lba" (Logical Block Address) is the physical sector index on
12//    the block device. The physical sector size is supposed to be 512 bytes.
13// 2. the "cluster" variable is actually a cluster index. A cluster contains
14//    8 sectors (4K bytes) and the cluster index is a 32 bits word.
15// 3. Each file or directory referenced by the software is represented
16//    by an "inode". The set of "inodes" is organised as a tree, that is
17//    a sub-tree of the complete file system existing on the block device.
18// 4. A given file can be referenced by several software tasks, and each task
19//    will use a private handler, called a "file descriptor", allocated by the OS
20//    when the task open the file, that is organised as an indexed array.
21// 5. This FAT32 library implements (N+1) caches : one private "File_ Cache"
22//    for each referenced file or directory, and a specific "Fat_Cache" for
23//    the FAT itself. Each cache contain a variable number of clusters that are
24//    dynamically allocated when they are accessed, and organised as a 64-Tree.
25//////////////////////////////////////////////////////////////////////////////////
26// General Debug Policy:
27// The global variable GIET_DEBUG_FAT is defined in the giet_config.h file.
28// The debug is activated if (proctime > GIET_DEBUG_FAT) && (GIET_DEBUG_FAT != 0)
29// The GIET_DEBUG_FAT bit 0 defines the level of debug:
30//    if   (GIET_DEBUG_FAT & 0x1)    => detailed debug
31//    else                           => external functions only
32//////////////////////////////////////////////////////////////////////////////////
33
34#include <giet_config.h>
35#include <hard_config.h>
36#include <fat32.h>
37#include <utils.h>
38#include <vmem.h>
39#include <kernel_malloc.h>
40#include <bdv_driver.h>
41#include <hba_driver.h>
42#include <sdc_driver.h>
43#include <rdk_driver.h>
44#include <mmc_driver.h>
45#include <tty0.h>
46
47//////////////////////////////////////////////////////////////////////////////////
48//               Global variables
49//////////////////////////////////////////////////////////////////////////////////
50
51// Fat-Descriptor
52__attribute__((section(".kdata")))
53fat_desc_t _fat __attribute__((aligned(64))); 
54
55// buffer used by boot code as a simple cache when scanning FAT
56__attribute__((section(".kdata")))
57unsigned char  _fat_buffer_fat[4096] __attribute__((aligned(64)));
58
59// buffer used by boot code as a simple cache when scanning a directory in DATA region
60__attribute__((section(".kdata")))
61unsigned char  _fat_buffer_data[4096] __attribute__((aligned(64)));
62
63// lba of cluster in fat_buffer_fat
64__attribute__((section(".kdata")))
65unsigned int   _fat_buffer_fat_lba;
66
67// lba of cluster in fat_buffer_data
68__attribute__((section(".kdata")))
69unsigned int   _fat_buffer_data_lba;
70
71//////////////////////////////////////////////////////////////////////////////////
72//////////////////////////////////////////////////////////////////////////////////
73//                  Static functions declaration
74//////////////////////////////////////////////////////////////////////////////////
75//////////////////////////////////////////////////////////////////////////////////
76
77
78///////////////////////////////////////////////////////////////////////////////////
79// This debug function displays the content of a 512 bytes buffer "buf",
80// with an identifier defined by the "string" and "block_id" arguments.
81///////////////////////////////////////////////////////////////////////////////////
82
83#if GIET_DEBUG_FAT
84static void _display_one_block( unsigned char* buf,
85                                char*          string,
86                                unsigned int   block_id );
87#endif
88
89//////////////////////////////////////////////////////////////////////////////////
90// This debug function displays the FAT descriptor.
91//////////////////////////////////////////////////////////////////////////////////
92
93#if GIET_DEBUG_FAT
94static void _display_fat_descriptor();
95#endif
96
97/////////////////////////////////////////////////////////////////////////////////
98// This debug function displays the sequence of clusters allocated to a
99// file (or directory) identified by the "inode" argument.
100/////////////////////////////////////////////////////////////////////////////////
101
102#if GIET_DEBUG_FAT
103static void _display_clusters_list( fat_inode_t* inode );
104#endif
105
106/////////////////////////////////////////////////////////////////////////////////
107// The following function transfers one or several blocks between the device
108// and a memory buffer identified by a virtual address.
109// It computes the memory buffer physical address, and calls the proper
110// IOC driver depending on the subtype (BDV / HBA / SDC / SPI / RDK).
111// The use_irq argument allows to activate the descheduling mode,
112// if it supported by the IOC driver subtype
113// It returns O  in case of success.
114// It returns -1 in case of error.
115/////////////////////////////////////////////////////////////////////////////////
116
117static int _fat_ioc_access( unsigned int use_irq,
118                            unsigned int to_mem,
119                            unsigned int lba,
120                            unsigned int buf_vaddr,
121                            unsigned int count );
122
123//////////////////////////////////////////////////////////////////////////////////
124// The following function returns in the "desc" argument a pointer on a buffer
125// descriptor contained in a File_Cache, or in the Fat_Cache.
126// The searched buffer is idenfified by the "inode" and "cluster_id" arguments.
127// If the "inode" pointer is not NULL, the searched cache is a File-Cache.
128// If the "inode" pointer is NULL, the searched cache is the Fat-Cache,
129// The "cluster_id" argument is the buffer index in the file (or in the FAT).
130// In case of miss, it allocate a 4 Kbytes buffer and a cluster descriptor
131// from the local kernel heap, and calls the _fat_ioc_access() function to load
132// the missing cluster from the block device.
133// It returns O  in case of success.
134// It returns 1 in case of error.
135//////////////////////////////////////////////////////////////////////////////////
136
137static unsigned int _get_buffer_from_cache( fat_inode_t*        inode,
138                                            unsigned int        cluster_id,
139                                            fat_cache_desc_t**  desc );
140
141////////////////////////////////////////////////////////////////////////////////
142// This function extract a (partial) name from a LFN directory entry.
143////////////////////////////////////////////////////////////////////////////////
144
145static void _get_name_from_long( unsigned char* buffer, 
146                                 char*          name );
147
148////////////////////////////////////////////////////////////////////////////////
149// The following function extract a name from a NORMAL directory entry.
150////////////////////////////////////////////////////////////////////////////////
151
152static void _get_name_from_short( unsigned char* buffer,
153                                  char*          name );
154
155//////////////////////////////////////////////////////////////////////////////////
156// This function returns the number of levels of a File-Cache (or Fat-Cache)
157// from the size of the file (or FAT).
158//////////////////////////////////////////////////////////////////////////////////
159
160static inline unsigned int _get_levels_from_size( unsigned int size );
161
162///////////////////////////////////////////////////////////////////////////////////
163// The following function analyses the "pathname" argument, from the character
164// defined by the "nb_read" argument.
165// It copies the found name in the "name" buffer (without '/'),
166// and updates the "nb_read" argument.
167// It returns 0 if success.
168// It returns 1 if one name length > NAME_MAX_SIZE characters
169///////////////////////////////////////////////////////////////////////////////////
170
171static unsigned int _get_name_from_path( char*          pathname,
172                                         char*          name,
173                                         unsigned int*  nb_read );
174
175////////////////////////////////////////////////////////////////////////////////
176// The following function scan the "pathname" argument, and copies in the
177// "name" buffer the last name in path (leaf name).
178// It returns 0 if success.
179// It returns 1 if one name length > NAME_MAX_SIZE characters
180////////////////////////////////////////////////////////////////////////////////
181static unsigned int _get_last_name( char*   pathname,
182                                    char*   name );
183
184//////////////////////////////////////////////////////////////////////////////////
185// The following function access the Fat-Cache and returns in the "value"
186// argument the content of the FAT slot identified by the "cluster" argument.
187// It loads the missing cluster from block device into cache in case of miss.
188// It returns 0 if success.
189// It returns 1 if error.
190//////////////////////////////////////////////////////////////////////////////////
191
192static unsigned int _get_fat_entry( unsigned int  cluster,
193                                    unsigned int* value );
194
195//////////////////////////////////////////////////////////////////////////////////
196// The following function writes a new "value" in the Fat-Cache, in the slot
197// identified by the "cluster" argument. 
198// It loads the missing cluster from block device into cache in case of miss.
199// It returns 0 if success,
200// It returns 1 if error.
201//////////////////////////////////////////////////////////////////////////////////
202
203static unsigned int _set_fat_entry( unsigned int  cluster,
204                                    unsigned int  value );
205
206//////////////////////////////////////////////////////////////////////////////////
207// The following function introduces the inode identified by the "child" argument,
208// as a new child of the "parent" inode in the Inode-Tree.
209// All checking are supposed to be done by the caller.
210// Nor the File-Cache, neither the block device are modified.
211//////////////////////////////////////////////////////////////////////////////////
212
213static void _add_inode_in_tree( fat_inode_t*  child,
214                                fat_inode_t*  parent );
215
216//////////////////////////////////////////////////////////////////////////////////
217// The following function removes one inode identified by the "inode" argument
218// from the Inode-Tree. All checking are supposed to be done by the caller.
219// Nor the File-Cache, neither the block device are modified.
220//////////////////////////////////////////////////////////////////////////////////
221
222static void _remove_inode_from_tree( fat_inode_t* inode );
223
224//////////////////////////////////////////////////////////////////////////////////
225// This recursive function scan one File-Cache (or Fat-Cache) from root to leaves,
226// to writes all dirty clusters to block device, and reset the dirty bits.
227// The cache is identified by the "root" an "levels" arguments.
228// The "string" argument is only used for debug : inode name or Fat.
229// It returns 0 if success.
230// It returns 1 if error.
231//////////////////////////////////////////////////////////////////////////////////
232
233static unsigned int _update_device_from_cache( unsigned int      levels,
234                                               fat_cache_node_t* root,
235                                               char*             string );
236
237//////////////////////////////////////////////////////////////////////////////////
238// The following function access directly the FS_INFO block on the block device,
239// to update the "first_free_cluster" and "free_clusters_number" values,
240// using only the Fat-Descriptor single block buffer.
241// It return 0 in case of success.
242// It return 1 in case of error.
243//////////////////////////////////////////////////////////////////////////////////
244
245static unsigned int _update_fs_info();
246
247//////////////////////////////////////////////////////////////////////////////
248// The following function read a data field (from one to four bytes)
249// from an unsigned char[] buffer, taking endianness into account.
250// The analysed field is defined by the "offset" and "size" arguments.
251//////////////////////////////////////////////////////////////////////////////
252
253static unsigned int _read_entry( unsigned int    offset,
254                                 unsigned int    size,
255                                 unsigned char*  buffer,
256                                 unsigned int    little_indian );
257
258//////////////////////////////////////////////////////////////////////////////////
259// The following function returns the lba of first sector in DATA region
260// from the cluster index. The cluster index must be larger than 2.
261//////////////////////////////////////////////////////////////////////////////////
262
263static unsigned int _cluster_to_lba( unsigned int cluster );
264
265//////////////////////////////////////////////////////////////////////////////////
266// The following function returns in the "nb_entries" argument the number of files
267// (or directories) contained in a directory identified by the "inode " pointer.
268// It returns  0 if success.
269// It returns  1 if error.
270//////////////////////////////////////////////////////////////////////////////////
271
272static unsigned int _get_nb_entries( fat_inode_t*   inode,
273                                     unsigned int*  nb_entries );
274
275//////////////////////////////////////////////////////////////////////////////////
276// The following function search in the directory identified by the "parent"
277// inode pointer a child (file or directory) identified by its "name".
278// It returns in the "inode" argument the searched child inode pointer.
279// If the searched name is not found in the Inode-Tree, the function access
280// the "file_cache" associated to the parent directory.
281// If the child exist on block device, the Inode-Tree is updated, and
282// a success code is returned.
283// If the file/dir does not exist on block device, a error code is returned.
284// It returns 0 if inode found.
285// It returns 1 if inode not found.
286// It returns 2 if error in cache access.
287//////////////////////////////////////////////////////////////////////////////////
288
289static unsigned int _get_child_from_parent( fat_inode_t*   parent,
290                                            char*          name,
291                                            fat_inode_t**  inode ); 
292
293/////////////////////////////////////////////////////////////////////////////////
294// For a file (or a directory) identified by the "pathname" argument, the
295// following function returns in the "inode" argument the inode pointer
296// associated to the searched file (or directory), with code (0).
297// If the searched file (or directory) is not found, but the parent directory
298// is found, it returns in the "inode" argument the pointer on the parent inode,
299// with code (1).  Finally, code (2) and code (3) are error codes.
300// Both the Inode-Tree and the involved Cache-Files are updated from the block
301// device in case of miss on one inode during the search in path.
302// Neither the Fat-Cache, nor the block device are updated.
303// It returns 0 if searched inode found
304// It returns 1 if searched inode not found but parent directory found
305// It returns 2 if searched inode not found and parent directory not found
306// It returns 3 if one name too long
307/////////////////////////////////////////////////////////////////////////////////
308
309static unsigned int _get_inode_from_path( char*          pathname,
310                                          fat_inode_t**  inode );
311
312//////////////////////////////////////////////////////////////////////////////////
313// The following function checks if node "a" is an ancestor of inode "b".
314// It returns 0 on failure.
315// It returns 1 otherwise.
316//////////////////////////////////////////////////////////////////////////////////
317
318static unsigned int _is_ancestor( fat_inode_t* a,
319                                  fat_inode_t* b);
320
321//////////////////////////////////////////////////////////////////////////////////
322// This function computes the length and the number of LFN entries required
323// to store a node name in the "length" and "nb_lfn" arguments.
324// Short name (less than 13 characters) require 1 LFN entry.
325// Medium names (from 14 to 26 characters require 2 LFN entries.
326// Large names (up to 31 characters) require 3 LFN entries.
327// It returns 0 if success.
328// It returns 1 if length larger than 31 characters.
329//////////////////////////////////////////////////////////////////////////////////
330
331static unsigned int _check_name_length( char* name,
332                                        unsigned int* length,
333                                        unsigned int* nb_lfn );
334
335//////////////////////////////////////////////////////////////////////////////////
336// For a node identified by the "inode" argument, this function updates the
337// "size" and "cluster" values in the entry of the parent directory File-Cache.
338// It set the dirty bit in the modified buffer of the parent directory File-Cache.
339//////////////////////////////////////////////////////////////////////////////////
340
341static unsigned int _update_dir_entry( fat_inode_t*  inode );
342
343//////////////////////////////////////////////////////////////////////////////////
344// The following function add new "child" in Cache-File of "parent" directory.
345// It access the File_Cache associated to the parent directory, and scan the
346// clusters allocated to this directory to find the NO_MORE entry.
347// This entry will be the first modified entry in the directory.
348// Regarding the name storage, it uses LFN entries for all names.
349// Therefore, it writes 1, 2, or 3 LFN entries (depending on the child name
350// actual length, it writes one NORMAL entry, and writes the new NOMORE entry.
351// It updates the dentry field in the child inode.
352// It set the dirty bit for all modified File-Cache buffers.
353// The block device is not modified by this function.
354//////////////////////////////////////////////////////////////////////////////////
355
356static unsigned int _add_dir_entry( fat_inode_t* child,
357                                    fat_inode_t* parent );
358
359//////////////////////////////////////////////////////////////////////////////////
360// The following function invalidates all dir_entries associated to the "inode"
361// argument from its parent directory.
362// It set the dirty bit for all modified buffers in parent directory Cache-File.
363// The inode itself is not modified by this function.
364// The block device is not modified by this function.
365//////////////////////////////////////////////////////////////////////////////////
366
367static unsigned int _remove_dir_entry( fat_inode_t*  inode );
368
369//////////////////////////////////////////////////////////////////////////////////
370// The following function add the special entries "." and ".." in the File-Cache
371// of the directory identified by the "child" argument.
372// The parent directory is defined by the "parent" argument.
373// The child directory File-Cache is supposed to be empty.
374// We use two NORMAL entries for these "." and ".." entries.
375// The block device is not modified by this function.
376//////////////////////////////////////////////////////////////////////////////////
377
378static void _add_special_directories( fat_inode_t* child,
379                                      fat_inode_t* parent );
380
381//////////////////////////////////////////////////////////////////////////////////
382// The following function releases all clusters allocated to a file or directory,
383// from the cluster index defined by the "cluster" argument, until the end
384// of the FAT linked list.
385// It calls _get_fat_entry() and _set_fat_entry() functions to scan the FAT,
386// and to update the clusters chaining.
387// The FAT region on block device is updated.
388// It returns 0 if success.
389// It returns 1 if error.
390//////////////////////////////////////////////////////////////////////////////////
391
392static unsigned int _clusters_release( unsigned int cluster );
393
394//////////////////////////////////////////////////////////////////////////////////
395// This function allocate "nb_clusters_more" new clusters to a file (or directory)
396// identified by the "inode" pointer. It allocates also the associated buffers
397// and buffer descriptors in the Cache-File.
398// It calls _get_fat_entry() and _set_fat_entry() functions to update the
399// clusters chaining in the Cache-Fat. The FAT region on block device is updated.
400// It returns 0 if success.
401// It returns 1 if error.
402//////////////////////////////////////////////////////////////////////////////////
403
404static unsigned int _clusters_allocate( fat_inode_t* inode, 
405                                        unsigned int nb_clusters_current,
406                                        unsigned int nb_clusters_more );
407
408//////////////////////////////////////////////////////////////////////////////////
409// This recursive function scans one File-Cache (or Fat-Cache) from root to
410// leaves. All memory allocated for 4KB buffers, and buffer descriptors (in
411// leaves) is released, along with the 64-Tree structure (root node is kept).
412// The cache is identified by the "root" and "levels" arguments.
413// It should not contain any dirty clusters.
414//////////////////////////////////////////////////////////////////////////////////
415
416static void _release_cache_memory( fat_cache_node_t*  root,
417                                   unsigned int       levels );
418
419//////////////////////////////////////////////////////////////////////////////////
420// The following function allocates and initializes a new Fat-Cache node.
421// Its first child can be specified (used when adding a cache level).
422// The Fat-Cache is initialized as empty: all children set to NULL.
423// It returns a pointer to a new Fat-Cache node.
424//////////////////////////////////////////////////////////////////////////////////
425
426static fat_cache_node_t* _allocate_one_cache_node( fat_cache_node_t* first_child );
427
428//////////////////////////////////////////////////////////////////////////////////
429// The following function allocates and initializes a new inode,
430// using the values defined by the arguments.
431// If the "cache_allocate" argument is true ans empty cache is allocated.
432// It returns a pointer on the new inode.
433//////////////////////////////////////////////////////////////////////////////////
434
435static fat_inode_t* _allocate_one_inode( char*        name,
436                                         unsigned int is_dir,
437                                         unsigned int cluster,
438                                         unsigned int size,
439                                         unsigned int count,
440                                         unsigned int dentry,
441                                         unsigned int cache_allocate );
442
443//////////////////////////////////////////////////////////////////////////////////
444// The following function allocates one 4 Kbytes buffer and associated cluster
445// descriptor for the file (or directory) identified by the "inode" argument,
446// and updates the Cache_File slot identified by the "cluster_id" argument.
447// The File-Cache slot must be empty.
448// It updates the cluster descriptor, using the "cluster" argument, that is
449// the cluster index in FAT.  The cluster descriptor dirty field is set.
450// It traverse the 64-tree Cache-file from top to bottom to find the last level.
451//////////////////////////////////////////////////////////////////////////////////
452
453static void _allocate_one_buffer( fat_inode_t*    inode,
454                                  unsigned int    cluster_id,
455                                  unsigned int    cluster );
456
457//////////////////////////////////////////////////////////////////////////////////
458// The following function allocates one free cluster from the FAT "heap" of free
459// clusters, and returns the cluster index in the "cluster" argument.
460// It updates the FAT slot, and the two FAT global variables: first_free_cluster,
461// and free_clusters_number.
462// It returns O if success.
463// It returns 1 if error.
464//////////////////////////////////////////////////////////////////////////////////
465
466static unsigned int _allocate_one_cluster( unsigned int*  cluster );
467
468/////////////////////////////////////////////////////////////////////////////
469// This function remove from the file system a file or a directory
470// identified by the "inode" argument.
471// The remove condition must be checked by the caller.
472// The relevant lock(s) must have been taken by te caller.
473// It returns O if success.
474// It returns 1 if error.
475/////////////////////////////////////////////////////////////////////////////
476
477static unsigned int _remove_node_from_fs( fat_inode_t* inode );
478
479/////////////////////////////////////////////////////////////////////////////
480// This function return the cluster index and the size for a file
481// identified by the "pathname" argument, scanning directly the block
482// device DATA region.
483// It is intended to be called only by the _fat_load_no_cache() function,
484// it does not use the dynamically allocated File Caches, but uses only
485// the 4 Kbytes _fat_buffer_data.
486// It returns 0 if success.
487// It returns 1 if error.
488/////////////////////////////////////////////////////////////////////////////
489
490static unsigned int _file_info_no_cache( char*          pathname,
491                                         unsigned int*  file_cluster,
492                                         unsigned int*  file_size );
493
494/////////////////////////////////////////////////////////////////////////////
495// This function scan directly the FAT region on the block device,
496// and returns in the "next" argument the value stored in the fat slot
497// identified by the "cluster" argument.
498// It is intended to be called only by the _fat_load_no_cache() function,
499// as it does not use the dynamically allocated Fat-Cache, but uses only
500// the 4 Kbytes _fat_buffer_fat.
501// It returns 0 if success.
502// It returns 1 if error.
503/////////////////////////////////////////////////////////////////////////////
504
505static unsigned int _next_cluster_no_cache( unsigned int   cluster,
506                                            unsigned int*  next );
507
508
509//////////////////////////////////////////////////////////////////////////////////
510// The following functions return the length or the size of a FAT field,
511// identified by an (offset,length) mnemonic defined in the fat32.h file.
512//////////////////////////////////////////////////////////////////////////////////
513
514static inline int get_length( int offset , int length ) { return length; }
515
516static inline int get_offset( int offset , int length ) { return offset; }
517
518
519
520
521
522//////////////////////////////////////////////////////////////////////////////////
523//////////////////////////////////////////////////////////////////////////////////
524//                  Static functions definition
525//////////////////////////////////////////////////////////////////////////////////
526//////////////////////////////////////////////////////////////////////////////////
527
528#if GIET_DEBUG_FAT
529///////////////////////////////////////////////////
530static void _display_one_block( unsigned char* buf,
531                                char*          string,
532                                unsigned int   block_id )
533{
534    unsigned int line;
535    unsigned int word;
536
537    _printf("\n***  <%s>  block %x  ***********************************\n",
538            string , block_id );
539
540    for ( line = 0 ; line < 16 ; line++ )
541    {
542        // display line index
543        _printf("%x : ", line );
544
545        // display 8*4 bytes hexa
546        for ( word=0 ; word<8 ; word++ )
547        {
548            unsigned int byte  = (line<<5) + (word<<2);
549            unsigned int hexa  = (buf[byte  ]<<24) |
550                                 (buf[byte+1]<<16) |
551                                 (buf[byte+2]<< 8) |
552                                 (buf[byte+3]      );
553            _printf(" %X |", hexa );
554        }
555        _printf("\n");
556    }
557    _printf("*******************************************************************\n"); 
558} // end _display_one_block() 
559#endif
560
561
562
563#if GIET_DEBUG_FAT
564/////////////////////////////////////
565static void _display_fat_descriptor()
566{
567    _printf("\n###############  FAT DESCRIPTOR  ################################" 
568            "\nFAT initialised                  %x"
569            "\nBlock Size  (bytes)              %x"
570            "\nCluster Size  (bytes)            %x"
571            "\nFAT region first lba             %x"
572            "\nFAT region size (blocks)         %x"
573            "\nDATA region first lba            %x"
574            "\nDATA region size (blocks)        %x"
575            "\nNumber of free clusters          %x"
576            "\nFirst free cluster index         %x" 
577            "\nFat_cache_levels                 %d" 
578            "\n#################################################################\n",
579            _fat.initialised,
580            _fat.sector_size,
581            _fat.cluster_size,
582            _fat.fat_lba,
583            _fat.fat_sectors,
584            _fat.data_lba,
585            _fat.data_sectors,
586            _fat.free_clusters_number,
587            _fat.first_free_cluster,
588            _fat.fat_cache_levels );
589
590} // end _display_fat_descriptor()
591#endif
592
593
594
595#if GIET_DEBUG_FAT
596////////////////////////////////////////////////////////
597static void _display_clusters_list( fat_inode_t* inode )
598{
599    _printf("\n**************** clusters for <%s> ***********************\n", inode->name );
600    unsigned int next;
601    unsigned int n       = 0;
602    unsigned int current = inode->cluster;
603    while( (current < END_OF_CHAIN_CLUSTER_MIN) && (n < 1024) )
604    {
605        _get_fat_entry( current , &next );
606        _printf(" > %X", current );
607        n++;
608        if ( (n & 0x7) == 0 ) _printf("\n");
609        current = next;
610    }
611    _printf("\n");
612}  // end _display_clusters_list()
613#endif
614
615
616
617/////////////////////////////////////////////////////////////////////////////////
618static int _fat_ioc_access( unsigned int use_irq,       // descheduling if non zero
619                            unsigned int to_mem,        // read / write
620                            unsigned int lba,           // first sector on device
621                            unsigned int buf_vaddr,     // memory buffer vaddr
622                            unsigned int count )        // number of sectors
623{
624    // compute memory buffer physical address
625    unsigned int       flags;         // for _v2p_translate
626    unsigned long long buf_paddr;     // buffer physical address
627
628    if ( ((_get_mmu_mode() & 0x4) == 0 ) || USE_IOC_RDK )  // identity
629    { 
630        buf_paddr = (unsigned long long)buf_vaddr;
631    }
632    else                                // V2P translation required
633    {
634        buf_paddr = _v2p_translate( buf_vaddr , &flags );
635    }
636
637#if (GIET_DEBUG_FAT & 1)
638if ( _get_proctime() > GIET_DEBUG_FAT )
639_printf("\n[DEBUG FAT] _fat_ioc_access() : enters at cycle %d\n"
640        "  to_mem = %d / vaddr = %x / paddr = %l / sectors = %d / lba = %x\n",
641        _get_proctime(), to_mem, buf_vaddr, buf_paddr, count, lba );
642#endif
643
644
645#if GIET_NO_HARD_CC     // L1 cache inval (virtual addresses)
646    if ( to_mem ) _dcache_buf_invalidate( buf_vaddr, count<<9 );
647#endif
648
649
650#if   ( USE_IOC_BDV )   // call the proper driver
651    return( _bdv_access( use_irq , to_mem , lba , buf_paddr , count ) ); 
652#elif ( USE_IOC_HBA )
653    return( _hba_access( use_irq , to_mem , lba , buf_paddr , count ) );
654#elif ( USE_IOC_SDC )
655    return( _sdc_access( use_irq , to_mem , lba , buf_paddr , count ) );
656#elif ( USE_IOC_SPI )
657    return( _spi_access( use_irq , to_mem , lba , buf_paddr , count ) );
658#elif ( USE_IOC_RDK )
659    return( _rdk_access( use_irq , to_mem , lba , buf_paddr , count ) );
660#else
661    _printf("\n[FAT ERROR] in _fat_ioc_access() : no IOC driver\n");
662    _exit();
663#endif
664
665}  // end _fat_ioc_access()
666
667
668
669
670/////////////////////////////////////////////////////////////////////
671static inline unsigned int _get_levels_from_size( unsigned int size )
672{ 
673    if      ( size <= (1<<18) ) return 1;     // 64 clusters == 256 Kbytes
674    else if ( size <= (1<<24) ) return 2;     // 64 * 64 clusters => 16 Mbytes
675    else if ( size <= (1<<30) ) return 3;     // 64 * 64 * 64 cluster => 1 Gbytes
676    else                        return 4;     // 64 * 64 * 64 * 64 clusters
677}
678
679
680
681////////////////////////////////////////////////////////
682static unsigned int _read_entry( unsigned int    offset,
683                                 unsigned int    size,
684                                 unsigned char*  buffer,
685                                 unsigned int    little_endian )
686{
687    unsigned int n;
688    unsigned int res  = 0;
689
690    if ( little_endian)
691    {
692        for( n = size ; n > 0 ; n-- ) res = (res<<8) | buffer[offset+n-1];
693    }
694    else
695    {
696        for( n = 0 ; n < size ; n++ ) res = (res<<8) | buffer[offset+n];
697    }
698    return res;
699
700}  // end _read_entry
701
702
703
704//////////////////////////////////////////////////////////////////
705static inline unsigned int _cluster_to_lba( unsigned int cluster )       
706{
707    if ( cluster < 2 )
708    { 
709        _printf("\n[FAT ERROR] in _cluster_to_lba() cluster smaller than 2\n"); 
710        _exit();
711    }
712
713   return  ((cluster - 2) << 3) + _fat.data_lba;
714}
715
716
717//////////////////////////////////////////////////////
718static inline unsigned char _to_lower(unsigned char c)
719{
720   if (c >= 'A' && c <= 'Z') return (c | 0x20);
721   else                      return c;
722}
723
724
725//////////////////////////////////////////////////////
726static inline unsigned char _to_upper(unsigned char c)
727{
728   if (c >= 'a' && c <= 'z') return (c & ~(0x20));
729   else                      return c;
730}
731
732
733
734///////////////////////////////////////////////////////////////////////////
735static unsigned int _get_name_from_path( char*          pathname,  // input
736                                         char*          name,      // output
737                                         unsigned int*  nb_read )  // input & output   
738{
739    // skip leading "/" character
740    if ( pathname[*nb_read] == '/' ) *nb_read = *nb_read + 1;
741
742    // initialises current indexes
743    unsigned int i = *nb_read;
744    unsigned int j = 0;
745   
746    while ( (pathname[i] != '/') && (pathname[i] != 0) )
747    {
748        name[j++] = pathname[i++];   
749        if ( j > NAME_MAX_SIZE ) return 1;
750    }
751
752    // set end of string
753    name[j] = 0;
754
755    // skip trailing "/" character
756    if ( pathname[i] == '/' ) *nb_read += j+1;
757    else                      *nb_read += j;
758
759    return 0;
760}
761
762
763
764////////////////////////////////////////////////////////////////////
765static unsigned int _get_last_name( char*   pathname,       // input
766                                    char*   name )          // output
767{
768    unsigned int nb_read = 0;     
769    while ( pathname[nb_read] != 0 )
770    {
771        if ( _get_name_from_path( pathname, name, &nb_read ) ) return 1;
772    }
773
774    return 0;
775}   // end _get_last_name()
776
777
778
779////////////////////////////////////////////////////////////////////////////////
780static void _get_name_from_short( unsigned char* buffer,  // input:  SFN dir_entry
781                                  char*          name )   // output: name
782{
783    unsigned int i;
784    unsigned int j = 0;
785
786    // get name
787    for ( i = 0; i < 8 && buffer[i] != ' '; i++ )
788    {
789        name[j] = _to_lower( buffer[i] );
790        j++;
791    }
792
793    // get extension
794    for ( i = 8; i < 8 + 3 && buffer[i] != ' '; i++ )
795    {
796        // we entered the loop so there is an extension. add the dot
797        if ( i == 8 )
798        {
799            name[j] = '.';
800            j++;
801        }
802
803        name[j] = _to_lower( buffer[i] );
804        j++;
805    }
806
807    name[j] = '\0';
808}
809
810///////////////////////////////////////////////////////////////////////////////
811static void _get_name_from_long( unsigned char*  buffer, // input : LFN dir_entry
812                                 char*           name )  // output : name
813{
814    unsigned int   name_offset         = 0;
815    unsigned int   buffer_offset       = get_length(LDIR_ORD);
816    unsigned int   l_name_1            = get_length(LDIR_NAME_1);
817    unsigned int   l_name_2            = get_length(LDIR_NAME_2);
818    unsigned int   l_name_3            = get_length(LDIR_NAME_3);
819    unsigned int   l_attr              = get_length(LDIR_ATTR);
820    unsigned int   l_type              = get_length(LDIR_TYPE);
821    unsigned int   l_chksum            = get_length(LDIR_CHKSUM);
822    unsigned int   l_rsvd              = get_length(LDIR_RSVD);
823
824    unsigned int j            = 0;
825    unsigned int eof          = 0;
826
827    while ( (buffer_offset != DIR_ENTRY_SIZE)  && (!eof) )
828    {
829        while (j != l_name_1 && !eof )
830        {
831            if ( (buffer[buffer_offset] == 0x00) || 
832                 (buffer[buffer_offset] == 0xFF) )
833            {
834                eof = 1;
835                continue;
836            }
837            name[name_offset] = buffer[buffer_offset];
838            buffer_offset += 2;
839            j += 2;
840            name_offset++;
841        }
842
843        buffer_offset += (l_attr + l_type + l_chksum);
844        j = 0;
845
846        while (j != l_name_2 && !eof )
847        {
848            if ( (buffer[buffer_offset] == 0x00) || 
849                 (buffer[buffer_offset] == 0xFF) )
850            {
851                eof = 1;
852                continue;
853            }
854            name[name_offset] = buffer[buffer_offset];
855            buffer_offset += 2;
856            j += 2;
857            name_offset++;
858        }
859
860        buffer_offset += l_rsvd;
861        j = 0;
862
863        while (j != l_name_3 && !eof )
864        {
865            if ( (buffer[buffer_offset] == 0x00) || 
866                 (buffer[buffer_offset] == 0xFF) )
867            {
868                eof = 1;
869                continue;
870            }
871            name[name_offset] = buffer[buffer_offset];
872            buffer_offset += 2;
873            j += 2;
874            name_offset++;
875        }
876    }
877    name[name_offset] = 0;
878} // end get_name_from_long()
879
880
881
882////////////////////////////////////////////////////////////
883static fat_cache_node_t* _allocate_one_cache_node( fat_cache_node_t* first_child )
884{
885    fat_cache_node_t* cnode;
886    unsigned int i;
887
888    cnode = _malloc( sizeof(fat_cache_node_t) );
889
890    cnode->children[0] = first_child;
891    for ( i = 1 ; i < 64 ; i++ )
892        cnode->children[i] = NULL;
893
894    return cnode;
895}   // end _allocate_one_cache_node()
896
897
898
899////////////////////////////////////////////////////////////
900static fat_inode_t* _allocate_one_inode( char*        name,
901                                         unsigned int is_dir,
902                                         unsigned int cluster,
903                                         unsigned int size, 
904                                         unsigned int count,
905                                         unsigned int dentry,
906                                         unsigned int cache_allocate )
907{
908    fat_inode_t* new_inode  = _malloc( sizeof(fat_inode_t) );
909
910    new_inode->parent   = NULL;                 // set by _add_inode_in_tree()
911    new_inode->next     = NULL;                 // set by _add_inode_in_tree()
912    new_inode->child    = NULL;                 // set by _add_inode_in_tree()
913    new_inode->cluster  = cluster;
914    new_inode->size     = size; 
915    new_inode->cache    = NULL;
916    new_inode->levels   = 0;
917    new_inode->count    = count;
918    new_inode->is_dir   = (is_dir != 0);
919    new_inode->dentry   = dentry;             
920
921    _strcpy( new_inode->name , name ); 
922
923    if ( cache_allocate )
924    {
925        new_inode->cache    = _allocate_one_cache_node( NULL );
926        new_inode->levels   = _get_levels_from_size( size );
927    }
928
929    return new_inode;
930}   // end _allocate_one_inode()
931
932
933
934
935////////////////////////////////////////////////////
936static void _add_inode_in_tree( fat_inode_t*  child,
937                                fat_inode_t*  parent )
938{
939    child->parent = parent;
940    child->next   = parent->child;
941    parent->child = child;
942}   // end _add_inode-in_tree()
943
944
945
946
947//////////////////////////////////////////////////////////
948static void _remove_inode_from_tree( fat_inode_t*  inode )
949{
950    fat_inode_t*  current;
951    fat_inode_t*  prev = inode->parent->child;
952
953    if ( inode == prev )  // removed inode is first in its linked list
954    {
955        inode->parent->child = inode->next;
956    }
957    else                  // removed inode is not the first
958    {
959        for( current = prev->next ; current ; current = current->next )
960        {
961            if ( current == inode )
962            {
963                prev->next = current->next;
964            }
965            prev = current;
966        }   
967    }   
968}  // end _delete_one_inode()
969
970
971
972
973//////////////////////////////////////////////////////////////////////
974static unsigned int _get_buffer_from_cache( fat_inode_t*        inode,
975                                            unsigned int        cluster_id,
976                                            fat_cache_desc_t**  desc )
977{
978    // get cache pointer and levels
979    fat_cache_node_t*   node;         // pointer on a 64-tree node
980    unsigned int        level;        // cache level
981
982    if ( inode == NULL )   // searched cache is the Fat-Cache
983    {
984        node   = _fat.fat_cache_root;
985        level  = _fat.fat_cache_levels;
986
987#if (GIET_DEBUG_FAT & 1)
988if ( _get_proctime() > GIET_DEBUG_FAT )
989_printf("\n[DEBUG FAT] _get_buffer_from_cache() : enters in FAT-Cache"
990        " for cluster_id = %d\n", cluster_id );
991#endif
992
993    }
994    else                   // searched cache is a File-Cache
995    {
996        node   = inode->cache;
997        level  = inode->levels;
998
999#if (GIET_DEBUG_FAT & 1)
1000if ( _get_proctime() > GIET_DEBUG_FAT )
1001_printf("\n[DEBUG FAT] _get_buffer_from_cache() : enters in File-Cache <%s>"
1002        " for cluster_id = %d\n", inode->name , cluster_id );
1003#endif
1004
1005    }
1006
1007    // search the 64-tree cache from top to bottom
1008    while ( level )
1009    {
1010        // compute child index at each level
1011        unsigned int index = (cluster_id >> (6*(level-1))) & 0x3F;
1012
1013        if ( level == 1 )        // last level => children are cluster descriptors
1014        {
1015            fat_cache_desc_t* pdesc = (fat_cache_desc_t*)node->children[index];
1016
1017            if ( pdesc == NULL )      // miss
1018            {
1019                // get missing cluster index lba
1020                unsigned int lba;
1021                unsigned int next;
1022                unsigned int current = inode->cluster;
1023                unsigned int count   = cluster_id;
1024
1025                if ( inode == NULL )      // searched cache is the Fat-Cache
1026                {
1027
1028#if (GIET_DEBUG_FAT & 1)
1029if ( _get_proctime() > GIET_DEBUG_FAT )
1030_printf("\n[DEBUG FAT] _get_buffer_from_cache() : miss in FAT-Cache for cluster_id %d\n",
1031        cluster_id );
1032#endif
1033                    lba = _fat.fat_lba + (cluster_id << 3);
1034                }
1035                else                      // searched cache is a File-Cache
1036                {
1037
1038#if (GIET_DEBUG_FAT & 1)
1039if ( _get_proctime() > GIET_DEBUG_FAT )
1040_printf("\n[DEBUG FAT] _get_buffer_from_cache() : miss in File-Cache <%s> "
1041        "for cluster_id %d\n", inode->name, cluster_id );
1042#endif
1043                    while ( count )
1044                    { 
1045                        if ( _get_fat_entry( current , &next ) ) return 1;
1046                        current = next;
1047                        count--;
1048                    }
1049                    lba = _cluster_to_lba( current );
1050                }
1051
1052                // allocate 4K buffer
1053                void* buf = _malloc( 4096 );
1054
1055                // load one cluster (8 blocks) from block device
1056                if ( _fat_ioc_access( 1,         // descheduling
1057                                      1,         // to memory
1058                                      lba,
1059                                      (unsigned int)buf,
1060                                      8 ) )
1061                {
1062                    _free( buf );
1063                    _printf("\n[FAT ERROR] in _get_buffer_from_cache()"
1064                            " : cannot access block device for lba = %x\n", lba );
1065                    return 1;
1066                }
1067
1068                // allocate buffer descriptor
1069                pdesc          = _malloc( sizeof(fat_cache_desc_t) );
1070                pdesc->lba     = lba;
1071                pdesc->buffer  = buf;
1072                pdesc->dirty   = 0;
1073                node->children[index] = pdesc;
1074
1075#if (GIET_DEBUG_FAT & 1)
1076if ( _get_proctime() > GIET_DEBUG_FAT )
1077_printf("\n[DEBUG FAT] _get_buffer_from_cache() : buffer loaded from device"
1078        " at vaddr = %x\n", (unsigned int)buf );
1079#endif
1080            }
1081
1082            // return pdesc pointer
1083            *desc = pdesc;
1084
1085            // prepare next iteration
1086            level--;
1087        }
1088        else                      // not last level => children are 64-tree nodes
1089        {
1090            fat_cache_node_t* child = (fat_cache_node_t*)node->children[index];
1091            if ( child == NULL )  // miss
1092            {
1093                // allocate a cache node if miss
1094                child = _allocate_one_cache_node( NULL );
1095                node->children[index] = child;   
1096            }
1097
1098            // prepare next iteration
1099            node = child;
1100            level--;
1101        }
1102    } // end while
1103
1104    return 0;
1105}  // end _get_buffer_from_cache()
1106
1107
1108
1109
1110/////////////////////////////////////
1111static unsigned int _update_fs_info()
1112{
1113    // update buffer if miss
1114    if ( _fat.fs_info_lba != _fat.block_buffer_lba )
1115    {
1116        if ( _fat_ioc_access( 1,                 // descheduling
1117                              1,                 // read
1118                              _fat.fs_info_lba, 
1119                              (unsigned int)_fat.block_buffer, 
1120                              1 ) )              // one block
1121        {
1122            _printf("\n[FAT_ERROR] in _update_fs_info() cannot read block\n");
1123            return 1;
1124        }
1125        _fat.block_buffer_lba = _fat.fs_info_lba;
1126    }
1127
1128    // update FAT buffer
1129    unsigned int* ptr;
1130    ptr  = (unsigned int*)(_fat.block_buffer + get_offset(FS_FREE_CLUSTERS) );
1131    *ptr = _fat.free_clusters_number;
1132
1133    ptr  = (unsigned int*)(_fat.block_buffer + get_offset(FS_FREE_CLUSTER_HINT) );
1134    *ptr = _fat.first_free_cluster;
1135   
1136    // write bloc to FAT
1137    if ( _fat_ioc_access( 1,                // descheduling
1138                          0,                // write
1139                          _fat.fs_info_lba,
1140                          (unsigned int)_fat.block_buffer, 
1141                          1 ) )             // one block
1142    {
1143        _printf("\n[FAT_ERROR] in _update_fs_info() cannot write block\n");
1144        return 1;
1145    }
1146
1147#if (GIET_DEBUG_FAT & 1)
1148if ( _get_proctime() > GIET_DEBUG_FAT )
1149_printf("\n[DEBUG FAT] _update_fs_info() : nb_free = %x / first_free = %x\n",
1150        _fat.free_clusters_number , _fat.first_free_cluster );
1151#endif
1152
1153    return 0;
1154}  // end _update_fs_info()
1155
1156
1157
1158/////////////////////////////////////////////////////////////////
1159static inline unsigned int _get_fat_entry( unsigned int  cluster,
1160                                           unsigned int* value )
1161{
1162    // compute cluster_id & entry_id in FAT
1163    // a FAT cluster is an array of 1024 unsigned int entries
1164    unsigned int       cluster_id = cluster >> 10;       
1165    unsigned int       entry_id   = cluster & 0x3FF;
1166
1167    // get pointer on the relevant cluster descriptor in FAT cache
1168    fat_cache_desc_t*  pdesc;
1169    unsigned int*      buffer;
1170    if ( _get_buffer_from_cache( NULL,               // Fat-Cache
1171                                 cluster_id,
1172                                 &pdesc ) ) return 1;
1173
1174    // get value from FAT slot
1175    buffer = (unsigned int*)pdesc->buffer;
1176    *value = buffer[entry_id];
1177
1178    return 0;
1179}  // end _get_fat_entry()
1180
1181
1182
1183////////////////////////////////////////////////////////////////
1184static inline unsigned int _set_fat_entry( unsigned int cluster, 
1185                                           unsigned int value  )
1186{
1187    // compute cluster_id & entry_id in FAT
1188    // a FAT cluster is an array of 1024 unsigned int entries
1189    unsigned int cluster_id = cluster >> 10;
1190    unsigned int entry_id   = cluster & 0x3FF;
1191
1192    // get pointer on the relevant cluster descriptor in FAT cache
1193    fat_cache_desc_t*  pdesc;
1194    unsigned int*      buffer; 
1195    if ( _get_buffer_from_cache( NULL,               // Fat-Cache
1196                                 cluster_id,
1197                                 &pdesc ) )  return 1;           
1198
1199    // set value into FAT slot
1200    buffer           = (unsigned int*)pdesc->buffer;
1201    buffer[entry_id] = value;
1202    pdesc->dirty     = 1;
1203
1204    return 0;
1205} // end _set_fat_entry()
1206
1207
1208
1209//////////////////////////////////////////////////////
1210static void _allocate_one_buffer( fat_inode_t*  inode,
1211                                  unsigned int  cluster_id,
1212                                  unsigned int  cluster )
1213{
1214    // add cache levels if needed
1215    while ( _get_levels_from_size( (cluster_id + 1) * 4096 ) > inode->levels )
1216    {
1217#if (GIET_DEBUG_FAT & 1)
1218if ( _get_proctime() > GIET_DEBUG_FAT )
1219_printf("\n[DEBUG FAT] _allocate_one_buffer() : adding a cache level\n" );
1220#endif
1221
1222        inode->cache = _allocate_one_cache_node( inode->cache );
1223        inode->levels++;
1224    }
1225
1226    // search the 64-tree cache from top to bottom
1227    fat_cache_node_t*  node   = inode->cache;
1228    unsigned int       level;
1229
1230    for ( level = inode->levels; level != 0; level-- )
1231    {
1232        // compute child index
1233        unsigned int index = (cluster_id >> (6*(level-1))) & 0x3F;
1234
1235        if ( level == 1 )        // last level => children are cluster descriptors
1236        {
1237            fat_cache_desc_t* pdesc = (fat_cache_desc_t*)node->children[index];
1238            if ( pdesc != NULL )      // slot not empty!!!
1239            {
1240                _printf("\n[FAT ERROR] in allocate_one buffer() : slot not empty "
1241                        "in File-Cache <%s> / cluster_id = %d\n", inode->name , cluster_id );
1242                _exit();
1243            }
1244
1245#if (GIET_DEBUG_FAT & 1)
1246if ( _get_proctime() > GIET_DEBUG_FAT )
1247_printf("\n[DEBUG FAT] _allocate_one_buffer() : buffer allocated to <%s> for cluster_id %d\n",
1248        inode->name, cluster_id );
1249#endif
1250
1251            // allocate buffer descriptor
1252            pdesc = _malloc( sizeof(fat_cache_desc_t) );
1253            pdesc->lba     = _cluster_to_lba( cluster );
1254            pdesc->buffer  = _malloc( 4096 );
1255            pdesc->dirty   = 1;
1256            node->children[index] = pdesc;
1257        }
1258        else                      // not last level => children are 64-tree nodes
1259        {
1260            fat_cache_node_t* child = (fat_cache_node_t*)node->children[index];
1261            if ( child == NULL )  // miss
1262            {
1263                // allocate a cache node if miss
1264                child = _allocate_one_cache_node( NULL );
1265                node->children[index] = child;   
1266            }
1267
1268            // prepare next iteration
1269            node  = child;
1270        }
1271    } // end for
1272} // end _allocate_one_buffer
1273
1274
1275
1276
1277///////////////////////////////////////////////////////////////////
1278static unsigned int _allocate_one_cluster( unsigned int*  cluster ) 
1279{
1280    unsigned int nb_free = _fat.free_clusters_number;
1281    unsigned int free    = _fat.first_free_cluster;
1282
1283    // scan FAT to get next free cluster index
1284    unsigned int current = free;
1285    unsigned int found   = 0;
1286    unsigned int max     = (_fat.data_sectors >> 3);
1287    unsigned int value;
1288    do
1289    {
1290        // increment current
1291        current++;
1292
1293        // get FAT entry indexed by current
1294        if ( _get_fat_entry( current , &value ) ) return 1;
1295        // test if free
1296        if ( value == FREE_CLUSTER ) found = 1;
1297    }
1298    while ( (current < max) && (found == 0) );
1299       
1300    // check found 
1301    if ( found == 0 )
1302    {
1303        _printf("\n[FAT_ERROR] in _allocate_one_cluster() : unconsistent FAT state");
1304        return 1;
1305    }
1306
1307    // update allocated FAT slot
1308    if ( _set_fat_entry( free , END_OF_CHAIN_CLUSTER_MAX ) ) return 1;
1309
1310    // update FAT descriptor global variables
1311    _fat.free_clusters_number = nb_free - 1;
1312    _fat.first_free_cluster   = current;
1313
1314#if (GIET_DEBUG_FAT & 1)
1315if ( _get_proctime() > GIET_DEBUG_FAT )
1316_printf("\n[DEBUG FAT] _allocate_one_cluster() : cluster = %x / first_free = %x\n",
1317        free , current );
1318#endif
1319
1320    // returns free cluster index
1321    *cluster = free;
1322    return 0;
1323
1324}  // end _allocate_one_cluster()
1325
1326
1327
1328
1329//////////////////////////////////////////////////////////////////////////
1330static unsigned int _update_device_from_cache( unsigned int        levels,
1331                                               fat_cache_node_t*   root,
1332                                               char*               string )
1333{
1334    unsigned int index;
1335    unsigned int ret = 0;
1336
1337    if ( levels == 1 )  // last level => children are cluster descriptors
1338    {
1339        for( index = 0 ; index < 64 ; index++ )
1340        { 
1341            fat_cache_desc_t* pdesc = root->children[index];
1342            if ( pdesc != NULL )
1343            { 
1344                // update cluster on device if dirty
1345                if ( pdesc->dirty )
1346                {
1347                    if ( _fat_ioc_access( 1,           // descheduling
1348                                          0,           // to block device
1349                                          pdesc->lba,
1350                                          (unsigned int)pdesc->buffer,
1351                                          8 ) )
1352                    {
1353                        _printf("\n[FAT_ERROR] in _update_device from_cache() : "
1354                                " cannot access lba = %x\n", pdesc->lba );
1355                        ret = 1;
1356                    }
1357                    else
1358                    {
1359                        pdesc->dirty = 0;
1360
1361#if (GIET_DEBUG_FAT & 1)
1362if ( _get_proctime() > GIET_DEBUG_FAT )
1363_printf("\n[DEBUG FAT] _update_device_from_cache() : cluster_id = %d for <%s>\n",
1364        index , string );
1365#endif
1366
1367                    }
1368                }
1369            }
1370        }
1371    }
1372    else               // not the last level = recursive call on each children
1373    {
1374        for( index = 0 ; index < 64 ; index++ )
1375        { 
1376            fat_cache_node_t* pnode = root->children[index];
1377            if ( pnode != NULL )
1378            {
1379                if ( _update_device_from_cache( levels - 1,
1380                                                root->children[index],
1381                                                string ) ) ret = 1;
1382            }   
1383        }
1384    }
1385    return ret;
1386}  // end _update_device_from_cache()
1387
1388
1389
1390///////////////////////////////////////////////////////////////////
1391static void _release_cache_memory( fat_cache_node_t*  root,
1392                                   unsigned int       levels )
1393{
1394    unsigned int i;
1395
1396    if ( levels == 1 )  // last level => children are cluster descriptors
1397    {
1398        for( i = 0 ; i < 64 ; i++ )
1399        { 
1400            fat_cache_desc_t* pdesc = root->children[i];
1401
1402            if ( pdesc != NULL )
1403            { 
1404                // check dirty
1405                if ( pdesc->dirty )
1406                    _printf("\n[FAT ERROR] in _release_cache_memory() : dirty cluster\n");
1407
1408                _free( pdesc->buffer );
1409                _free( pdesc );
1410                root->children[i] = NULL;
1411            }
1412        }
1413    }
1414    else               // not the last level = recursive call on each children
1415    {
1416        for( i = 0 ; i < 64 ; i++ )
1417        { 
1418            fat_cache_node_t* cnode = root->children[i];
1419
1420            if ( cnode != NULL )
1421            {
1422                _release_cache_memory( cnode, levels - 1 );
1423                _free( cnode );
1424                root->children[i] = NULL;
1425            }
1426        }
1427    }
1428}  // end _release_cache_memory()
1429
1430
1431
1432
1433
1434/////////////////////////////////////////////////////////////
1435static unsigned int _clusters_allocate( fat_inode_t* inode, 
1436                                        unsigned int nb_current_clusters,
1437                                        unsigned int nb_required_clusters )
1438{
1439    // Check if FAT contains enough free clusters
1440    if ( nb_required_clusters > _fat.free_clusters_number )
1441    {
1442        _printf("\n[FAT ERROR] in _clusters_allocate() : required_clusters = %d"
1443                " / free_clusters = %d\n", nb_required_clusters , _fat.free_clusters_number );
1444        return 1;
1445    }
1446
1447#if (GIET_DEBUG_FAT & 1)
1448if ( _get_proctime() > GIET_DEBUG_FAT )
1449_printf("\n[DEBUG FAT] _clusters_allocate() : enters for <%s> / nb_current_clusters = %d "
1450        "/ nb_required_clusters = %d\n", 
1451        inode->name , nb_current_clusters , nb_required_clusters );
1452#endif
1453 
1454    // compute last allocated cluster index when (nb_current_clusters > 0)
1455    unsigned int current = inode->cluster;
1456    unsigned int next;
1457    unsigned int last;
1458    if ( nb_current_clusters )   // clusters allocated => search last
1459    {   
1460        while ( current < END_OF_CHAIN_CLUSTER_MIN )
1461        {
1462            // get next cluster
1463            if ( _get_fat_entry( current , &next ) )  return 1;
1464            last    = current;
1465            current = next;
1466        }
1467    } 
1468
1469    // Loop on the new clusters to be allocated
1470    // if (nb_current_clusters == 0) the first new cluster index must
1471    //                               be written in inode->cluster field
1472    // if (nb_current_clusters >  0) the first new cluster index must
1473    //                               be written in FAT[last]
1474    unsigned int      cluster_id;
1475    unsigned int      new;
1476    for ( cluster_id = nb_current_clusters ; 
1477          cluster_id < (nb_current_clusters + nb_required_clusters) ; 
1478          cluster_id ++ )
1479    {
1480        // allocate one cluster on block device
1481        if ( _allocate_one_cluster( &new ) ) return 1;
1482
1483        // allocate one 4K buffer to File-Cache
1484        _allocate_one_buffer( inode,
1485                              cluster_id,
1486                              new );
1487
1488        if ( cluster_id == 0 )  // update inode
1489        {
1490            inode->cluster = new;
1491        }
1492        else                    // update FAT
1493        {
1494            if ( _set_fat_entry( last , new ) ) return 1;
1495        }
1496
1497#if (GIET_DEBUG_FAT & 1)
1498if ( _get_proctime() > GIET_DEBUG_FAT )
1499_printf("\n[DEBUG FAT] _clusters_allocate() : done for cluster_id = %d / cluster = %x\n",
1500        cluster_id , new );
1501#endif
1502
1503        // update loop variables
1504        last = new;
1505
1506    } // end for loop
1507
1508    // update FAT : last slot should contain END_OF_CHAIN_CLUSTER_MAX
1509    if ( _set_fat_entry( last , END_OF_CHAIN_CLUSTER_MAX ) )  return 1;
1510
1511    // update the FAT on block device
1512    if ( _update_device_from_cache( _fat.fat_cache_levels,
1513                                    _fat.fat_cache_root,
1514                                    "FAT" ) )              return 1;
1515    return 0;
1516}  // end _clusters_allocate()
1517
1518
1519
1520//////////////////////////////////////////////////////////////
1521static unsigned int _clusters_release( unsigned int cluster )
1522{
1523    // scan the FAT
1524    unsigned int current = cluster;
1525    unsigned int next;
1526    do
1527    { 
1528        // get next_cluster index
1529        if ( _get_fat_entry( current , &next ) )  return 1;
1530
1531        // release current_cluster
1532        if ( _set_fat_entry( current , FREE_CLUSTER ) )   return 1;
1533
1534        // update first_free_cluster and free_clusters_number in FAT descriptor
1535        _fat.free_clusters_number = _fat.free_clusters_number + 1;
1536        if ( _fat.first_free_cluster > current ) _fat.first_free_cluster = current;
1537
1538        // update loop variable
1539        current = next;
1540    }
1541    while ( next < END_OF_CHAIN_CLUSTER_MIN );
1542
1543    // update the FAT on block device
1544    if ( _update_device_from_cache( _fat.fat_cache_levels,
1545                                    _fat.fat_cache_root,
1546                                    "FAT" ) )                return 1;
1547    return 0;
1548}  // end _clusters_release()
1549
1550
1551
1552///////////////////////////////////////////////////////////
1553static void _add_special_directories( fat_inode_t*  child, 
1554                                      fat_inode_t*  parent )
1555{
1556    // get first File-Cache buffer for child
1557    fat_cache_desc_t*   pdesc  = (fat_cache_desc_t*)child->cache->children[0];
1558    unsigned char*      entry;
1559
1560    unsigned int i;
1561    unsigned int cluster;
1562    unsigned int size;
1563
1564    // set "." entry (32 bytes)
1565    cluster = child->cluster;
1566    size    = child->size;
1567    entry   = pdesc->buffer;
1568   
1569    for ( i = 0 ; i < 32 ; i++ )
1570    {
1571        if      (i == 0 )     entry[i] = 0x2E;          // SFN
1572        else if (i <  11)     entry[i] = 0x20;          // SFN
1573        else if (i == 11)     entry[i] = 0x10;          // ATTR == dir
1574        else if (i == 20)     entry[i] = cluster>>16;   // cluster.B2
1575        else if (i == 21)     entry[i] = cluster>>24;   // cluster.B3
1576        else if (i == 26)     entry[i] = cluster>>0;    // cluster.B0
1577        else if (i == 27)     entry[i] = cluster>>8;    // cluster.B1
1578        else if (i == 28)     entry[i] = size>>0;       // size.B0
1579        else if (i == 29)     entry[i] = size>>8;       // size.B1
1580        else if (i == 30)     entry[i] = size>>16;      // size.B2
1581        else if (i == 31)     entry[i] = size>>24;      // size.B3
1582        else                  entry[i] = 0x00;
1583    }
1584
1585    // set ".." entry (32 bytes)
1586    cluster = parent->cluster;
1587    size    = parent->size;
1588    entry   = pdesc->buffer + 32;
1589
1590    for ( i = 0 ; i < 32 ; i++ )
1591    {
1592        if      (i <  2 )     entry[i] = 0x2E;          // SFN
1593        else if (i <  11)     entry[i] = 0x20;          // SFN
1594        else if (i == 11)     entry[i] = 0x10;          // ATTR == dir
1595        else if (i == 20)     entry[i] = cluster>>16;   // cluster.B2
1596        else if (i == 21)     entry[i] = cluster>>24;   // cluster.B3
1597        else if (i == 26)     entry[i] = cluster>>0;    // cluster.B0
1598        else if (i == 27)     entry[i] = cluster>>8;    // cluster.B1
1599        else if (i == 28)     entry[i] = size>>0;       // size.B0
1600        else if (i == 29)     entry[i] = size>>8;       // size.B1
1601        else if (i == 30)     entry[i] = size>>16;      // size.B2
1602        else if (i == 31)     entry[i] = size>>24;      // size.B3
1603        else                  entry[i] = 0x00;
1604    }
1605}  // end _add_special_directories
1606
1607
1608
1609////////////////////////////////////////////////////////////
1610static unsigned int _is_ancestor( fat_inode_t* a,
1611                                  fat_inode_t* b )
1612{
1613    while ( b )
1614    {
1615        if ( a == b )
1616            return 1;
1617
1618        b = b->parent;
1619    }
1620
1621    return 0;
1622} // _is_ancestor()
1623
1624
1625
1626////////////////////////////////////////////////////////////
1627static unsigned int _check_name_length( char* name,
1628                                        unsigned int* length,
1629                                        unsigned int* nb_lfn )
1630{
1631    unsigned int len = _strlen( name );
1632    if      ( len <= 13 )
1633    {
1634        *length  = len;
1635        *nb_lfn  = 1;
1636        return 0;
1637    }
1638    else if ( len <= 26 )
1639    {
1640        *length  = len;
1641        *nb_lfn  = 2;
1642        return 0;
1643    }
1644    else if ( len <= 31 )
1645    {
1646        *length  = len;
1647        *nb_lfn  = 3;
1648        return 0;
1649    }
1650    else
1651    {
1652        return 1;
1653    }
1654}  // _check_name_length()
1655
1656
1657
1658
1659///////////////////////////////////////////////////////////
1660static unsigned int _get_nb_entries( fat_inode_t*   inode,
1661                                     unsigned int*  nb_entries )
1662{
1663    // scan directory until "end of directory" with two embedded loops:
1664    // - scan the clusters allocated to this directory
1665    // - scan the entries to find NO_MORE_ENTRY
1666    fat_cache_desc_t*  pdesc;                      // pointer on buffer descriptor
1667    unsigned char*     buffer;                     // 4 Kbytes buffer (one cluster)
1668    unsigned int       ord;                        // ORD field in directory entry
1669    unsigned int       attr;                       // ATTR field in directory entry
1670    unsigned int       cluster_id = 0;             // cluster index in directory
1671    unsigned int       offset     = 0;             // position in scanned buffer
1672    unsigned int       found      = 0;             // NO_MORE_ENTRY found
1673    unsigned int       count      = 0;             // number of valid NORMAL entries
1674
1675    // loop on clusters allocated to directory
1676    while ( found == 0 )
1677    {
1678        // get one 4 Kytes buffer from File_Cache 
1679        if ( _get_buffer_from_cache( inode,
1680                                     cluster_id,
1681                                     &pdesc ) )   return 1;
1682        buffer = pdesc->buffer;
1683       
1684        // loop on directory entries in buffer
1685        while ( (offset < 4096) && (found == 0) )
1686        {
1687            attr = _read_entry( DIR_ATTR , buffer + offset , 0 );   
1688            ord  = _read_entry( LDIR_ORD , buffer + offset , 0 );
1689
1690            if ( ord == NO_MORE_ENTRY )
1691            {
1692                found = 1;
1693            } 
1694            else if ( ord == FREE_ENTRY )             // free entry => skip
1695            {
1696                offset = offset + 32;
1697            }
1698            else if ( attr == ATTR_LONG_NAME_MASK )   // LFN entry => skip
1699            {
1700                offset = offset + 32;
1701            }
1702            else                                      // NORMAL entry
1703            {
1704                offset = offset + 32;
1705                count++;
1706            }
1707        }  // end loop on directory entries
1708
1709        cluster_id++;
1710        offset = 0;
1711
1712    }  // end loop on clusters
1713
1714    // return nb_entries
1715    *nb_entries = count;
1716   
1717    return 0;
1718}  // end dir_not_empty()
1719
1720
1721
1722///////////////////////////////////////////////////////////
1723static unsigned int _add_dir_entry( fat_inode_t*   child,
1724                                    fat_inode_t*   parent )
1725{
1726    // get child attributes
1727    unsigned int      is_dir  = child->is_dir;     
1728    unsigned int      size    = child->size;
1729    unsigned int      cluster = child->cluster;
1730
1731    // compute number of required entries to store child->name
1732    // - Short name (less than 13 characters) require 3 entries:
1733    //   one LFN entry / one NORMAL entry / one NO_MORE_ENTRY entry.
1734    // - Longer names (up to 31 characters) can require 4 or 5 entries:
1735    //   2 or 3 LFN entries / one NORMAL entry / one NO_MORE entry.
1736    unsigned int length;
1737    unsigned int nb_lfn;
1738    if ( _check_name_length( child->name, 
1739                             &length,
1740                             &nb_lfn ) )  return 1;
1741
1742#if (GIET_DEBUG_FAT & 1)
1743if ( _get_proctime() > GIET_DEBUG_FAT )
1744_printf("\n[DEBUG FAT] _add_dir_entry() : try to add <%s> in <%s> / nb_lfn = %d\n", 
1745        child->name , parent->name, nb_lfn );
1746#endif
1747
1748    // Find end of directory : two embedded loops:
1749    // - scan the clusters allocated to this directory
1750    // - scan the entries to find NO_MORE_ENTRY
1751    fat_cache_desc_t*  pdesc;                      // pointer on buffer descriptor
1752    unsigned char*     buffer;                     // 4 Kbytes buffer (one cluster)
1753    unsigned int       cluster_id = 0;             // cluster index in directory
1754    unsigned int       offset     = 0;             // position in scanned buffer
1755    unsigned int       found      = 0;             // NO_MORE_ENTRY found
1756
1757    // loop on clusters allocated to directory
1758    while ( found == 0 )
1759    {
1760        // get one 4 Kytes buffer from File_Cache 
1761        if ( _get_buffer_from_cache( parent,
1762                                     cluster_id,
1763                                     &pdesc ) )   return 1;
1764
1765        buffer = pdesc->buffer;
1766       
1767        // loop on directory entries in buffer
1768        while ( (offset < 4096) && (found == 0) )
1769        {
1770            if ( _read_entry( LDIR_ORD , buffer + offset , 0 ) == NO_MORE_ENTRY )
1771            {
1772                found        = 1;
1773                pdesc->dirty = 1;
1774            } 
1775            else
1776            {
1777                offset = offset + 32;
1778            }
1779        }  // end loop on entries
1780        if ( found == 0 )
1781        {
1782            cluster_id++;
1783            offset = 0;
1784        }
1785    }  // end loop on clusters
1786
1787#if (GIET_DEBUG_FAT & 1)
1788if ( _get_proctime() > GIET_DEBUG_FAT )
1789_printf("\n[DEBUG FAT] _add_dir_entry() : get NO_MORE directory entry : "
1790        " buffer = %x / offset = %x / cluster_id = %d\n",
1791        (unsigned int)buffer , offset , cluster_id );
1792#endif
1793
1794    // enter FSM :
1795    // The new child requires to write 3, 4, or 5 directory entries.
1796    // To actually register the new child, we use a 5 steps FSM
1797    // (one state per entry to be written), that is traversed as:
1798    //    LFN3 -> LFN2 -> LFN1 -> NORMAL -> NOMORE
1799    // The buffer and first directory entry to be  written are identified
1800    // by the variables : buffer / cluster_id / offset
1801
1802    unsigned char* name  = (unsigned char*)child->name;
1803
1804    unsigned int step;          // FSM state
1805
1806    if      ( nb_lfn == 1 ) step = 3;
1807    else if ( nb_lfn == 2 ) step = 4;
1808    else if ( nb_lfn == 3 ) step = 5;
1809   
1810    unsigned int   i;           // byte index in 32 bytes directory
1811    unsigned int   c;           // character index in name
1812    unsigned char* entry;       // buffer + offset;
1813
1814    while ( step )   
1815    {
1816        // get another buffer if required
1817        if ( offset >= 4096 )  // new buffer required
1818        {
1819            if ( cluster_id == 63 )   // we need to increase depth of File-Cache
1820            {
1821                _printf("\n[FAT ERROR] in add_dir_entry() File Cache depth extension "
1822                        " not implemented\n" );
1823                _exit();  // TODO   
1824            }
1825            else
1826            {
1827                if ( _get_buffer_from_cache( parent,
1828                                             cluster_id + 1,
1829                                             &pdesc ) )      return 1;       
1830                buffer       = pdesc->buffer;
1831                pdesc->dirty = 1;
1832                offset       = 0;
1833            }
1834        }
1835
1836        // compute directory entry address
1837        entry = buffer + offset;
1838
1839#if (GIET_DEBUG_FAT & 1)
1840if ( _get_proctime() > GIET_DEBUG_FAT )
1841_printf("\n[DEBUG FAT] _add_dir_entry() : FSM step = %d /"
1842        " offset = %x / nb_lfn = %d\n", step, offset, nb_lfn );
1843#endif
1844
1845        // write one 32 bytes directory entry per iteration
1846        switch ( step )
1847        {
1848            case 5:   // write LFN3 entry
1849            {
1850                c = 26;
1851                // scan the 32 bytes in dir_entry
1852                for ( i = 0 ; i < 32 ; i++ )
1853                {
1854                    if (i == 0)
1855                    {
1856                        if ( nb_lfn == 3) entry[i] = 0x43;
1857                        else              entry[i] = 0x03;
1858                    }
1859                    else if ( ( ((i >= 1 ) && (i<=10) && ((i&1)==1))   ||
1860                                ((i >= 14) && (i<=25) && ((i&1)==0))   ||
1861                                ((i >= 28) && (i<=31) && ((i&1)==0)) ) &&
1862                              ( c < length ) )
1863                    {
1864                                          entry[i] = name[c];
1865                                          c++;
1866                    }
1867                    else if (i == 11)     entry[i] = 0x0F;
1868                    else if (i == 12)     entry[i] = 0xCA;
1869                    else                  entry[i] = 0x00;
1870                }
1871                step--;
1872                break;
1873            }
1874            case 4:   // write LFN2 entry 
1875            {
1876                c = 13;
1877                // scan the 32 bytes in dir_entry
1878                for ( i = 0 ; i < 32 ; i++ )
1879                {
1880                    if (i == 0)
1881                    {
1882                        if ( nb_lfn == 2) entry[i] = 0x42;
1883                        else              entry[i] = 0x02;
1884                    }
1885                    else if ( ( ((i >= 1 ) && (i<=10) && ((i&1)==1))   ||
1886                                ((i >= 14) && (i<=25) && ((i&1)==0))   ||
1887                                ((i >= 28) && (i<=31) && ((i&1)==0)) ) &&
1888                              ( c < length ) )
1889                    {
1890                                          entry[i] = name[c];
1891                                          c++;
1892                    }
1893                    else if (i == 11)     entry[i] = 0x0F;
1894                    else if (i == 12)     entry[i] = 0xCA;
1895                    else                  entry[i] = 0x00;
1896                }
1897                step--;
1898                break;
1899            }
1900            case 3:   // Write LFN1 entry   
1901            {
1902                c = 0;
1903                // scan the 32 bytes in dir_entry
1904                for ( i = 0 ; i < 32 ; i++ )
1905                {
1906                    if (i == 0)
1907                    {
1908                        if ( nb_lfn == 1) entry[i] = 0x41;
1909                        else              entry[i] = 0x01;
1910                    }
1911                    else if ( ( ((i >= 1 ) && (i<=10) && ((i&1)==1))   ||
1912                                ((i >= 14) && (i<=25) && ((i&1)==0))   ||
1913                                ((i >= 28) && (i<=31) && ((i&1)==0)) ) &&
1914                              ( c < length ) )
1915                    {
1916                                          entry[i] = name[c];
1917                                          c++;
1918                    }
1919                    else if (i == 11)     entry[i] = 0x0F;
1920                    else if (i == 12)     entry[i] = 0xCA;
1921                    else                  entry[i] = 0x00;
1922                }
1923                step--;
1924                break;
1925            }
1926            case 2:   // write NORMAL entry     
1927            {
1928                c = 0;
1929                // scan the 32 bytes in dir_entry
1930                for ( i = 0 ; i < 32 ; i++ )
1931                {
1932                    if      ( (i < 8) && (c < length) )             // SFN
1933                    {
1934                                          entry[i] = _to_upper( name[c] );
1935                                          c++;
1936                    }
1937                    else if (i <  11)     entry[i] = 0x20;          // EXT
1938                    else if (i == 11)                               // ATTR
1939                    {
1940                        if (is_dir)       entry[i] = 0x10;
1941                        else              entry[i] = 0x20;
1942                    }
1943                    else if (i == 20)     entry[i] = cluster>>16;   // cluster.B2
1944                    else if (i == 21)     entry[i] = cluster>>24;   // cluster.B3
1945                    else if (i == 26)     entry[i] = cluster>>0;    // cluster.B0
1946                    else if (i == 27)     entry[i] = cluster>>8;    // cluster.B1
1947                    else if (i == 28)     entry[i] = size>>0;       // size.B0
1948                    else if (i == 29)     entry[i] = size>>8;       // size.B1
1949                    else if (i == 30)     entry[i] = size>>16;      // size.B2
1950                    else if (i == 31)     entry[i] = size>>24;      // size.B3
1951                    else                  entry[i] = 0x00;
1952                }
1953
1954                // update the dentry field in child inode
1955                child->dentry = ((cluster_id<<12) + offset)>>5;
1956
1957                step--;
1958                break;
1959            }
1960            case 1:   // write NOMORE entry 
1961            {
1962                step--;
1963                entry [0] = 0x00;
1964                break;
1965            }
1966        } // end switch step
1967        offset += 32;
1968    } // exit while => exit FSM   
1969
1970#if (GIET_DEBUG_FAT & 1)
1971if ( _get_proctime() > GIET_DEBUG_FAT )
1972{
1973    _printf("\n[DEBUG FAT] _add_dir_entry() : <%s> successfully added in <%s>\n",
1974            child->name , parent->name );
1975}
1976#endif
1977
1978    return 0;       
1979} // end _add_dir_entry
1980
1981
1982
1983////////////////////////////////////////////////////////////
1984static unsigned int _remove_dir_entry( fat_inode_t*  inode )
1985{
1986    // compute number of LFN entries
1987    unsigned int length;
1988    unsigned int nb_lfn;
1989    if ( _check_name_length( inode->name, 
1990                             &length,
1991                             &nb_lfn ) )  return 1;
1992
1993    // get cluster_id and offset in parent directory cache
1994    unsigned int  dentry     = inode->dentry;
1995    unsigned int  cluster_id = dentry >> 7;
1996    unsigned int  offset     = (dentry & 0x7F)<<5;
1997
1998    // get buffer from parent directory cache
1999    unsigned char*     buffer;
2000    fat_cache_desc_t*  pdesc;
2001
2002    if ( _get_buffer_from_cache( inode->parent,
2003                                 cluster_id,
2004                                 &pdesc ) ) return 1;
2005    buffer       = pdesc->buffer;
2006    pdesc->dirty = 1;
2007
2008    // invalidate NORMAL entry in directory cache
2009    buffer[offset] = 0xE5;
2010
2011    // invalidate LFN entries
2012    while ( nb_lfn )
2013    {
2014        if (offset == 0)  // we must load buffer for (cluster_id - 1)
2015        {
2016            if ( cluster_id == 0 )
2017                break;
2018
2019            if ( _get_buffer_from_cache( inode->parent,
2020                                         cluster_id - 1,
2021                                         &pdesc ) )   return 1;
2022            buffer       = pdesc->buffer;
2023            pdesc->dirty = 1;
2024            offset       = 4096;
2025        }
2026
2027        offset = offset - 32;
2028
2029        // check for LFN entry
2030        if ( _read_entry( DIR_ATTR , buffer + offset , 0 ) != ATTR_LONG_NAME_MASK )
2031            break;
2032
2033        // invalidate LFN entry
2034        buffer[offset] = 0xE5;
2035
2036        nb_lfn--;
2037    }     
2038         
2039    return 0;
2040}  // end _remove_dir_entry
2041
2042
2043
2044
2045////////////////////////////////////////////////////////////
2046static unsigned int _update_dir_entry( fat_inode_t*  inode )
2047{ 
2048    // get Cache-File buffer containing the parent directory entry
2049    // 128 directories entries in one 4 Kbytes buffer
2050    fat_cache_desc_t*  pdesc;
2051    unsigned char*     buffer;   
2052    unsigned int       cluster_id = inode->dentry>>7;
2053    unsigned int       offset     = (inode->dentry & 0x7F)<<5;
2054
2055    if ( _get_buffer_from_cache( inode->parent,
2056                                 cluster_id,
2057                                 &pdesc ) )    return 1;
2058    buffer       = pdesc->buffer;
2059    pdesc->dirty = 1;
2060
2061    // update size field
2062    buffer[offset + 28] = inode->size>>0;       // size.B0
2063    buffer[offset + 29] = inode->size>>8;       // size.B1
2064    buffer[offset + 30] = inode->size>>16;      // size.B2
2065    buffer[offset + 31] = inode->size>>24;      // size.B3
2066
2067    // update cluster field
2068    buffer[offset + 26] = inode->cluster>>0;    // cluster.B0
2069    buffer[offset + 27] = inode->cluster>>8;    // cluster.B1
2070    buffer[offset + 20] = inode->cluster>>16;   // cluster.B2
2071    buffer[offset + 21] = inode->cluster>>24;   // cluster.B3
2072   
2073    return 0;
2074} // end _update_dir_entry()
2075
2076
2077
2078
2079//////////////////////////////////////////////////////////////////
2080static unsigned int _get_child_from_parent( fat_inode_t*   parent,
2081                                            char*          name, 
2082                                            fat_inode_t**  inode )
2083{
2084    fat_inode_t*   current;
2085
2086#if (GIET_DEBUG_FAT & 1)
2087if ( _get_proctime() > GIET_DEBUG_FAT )
2088_printf("\n[DEBUG FAT] _get_child_from_parent() : search <%s> in directory <%s>\n",
2089        name , parent->name );
2090#endif
2091   
2092    // scan inodes in the parent directory
2093    for ( current = parent->child ; current ; current = current->next )
2094    {
2095        if ( _strcmp( name , current->name ) == 0 )
2096        {
2097
2098#if (GIET_DEBUG_FAT & 1)
2099if ( _get_proctime() > GIET_DEBUG_FAT )
2100_printf("\n[DEBUG FAT] _get_child_from_parent() : found inode <%s> in directory <%s>\n", 
2101        name , parent->name );
2102#endif
2103            *inode = current;
2104            return 0;           // name found
2105        }
2106    }
2107
2108    // not found in Inode-Tree => access the parent directory
2109    // file_cache.  Two embedded loops:
2110    // - scan the clusters allocated to this directory
2111    // - scan the directory entries in each 4 Kbytes buffer
2112
2113    unsigned char*    buffer;           // pointer on one cache buffer
2114    char              cname[32];        // buffer for one full entry name
2115    char              lfn1[16];         // buffer for one partial name
2116    char              lfn2[16];         // buffer for one partial name
2117    char              lfn3[16];         // buffer for one partial name
2118    unsigned int      size;             // searched file/dir size (bytes)
2119    unsigned int      cluster;          // searched file/dir cluster index
2120    unsigned int      is_dir;           // searched file/dir type
2121    unsigned int      attr;             // directory entry ATTR field
2122    unsigned int      ord;              // directory entry ORD field
2123    unsigned int      lfn = 0;          // LFN entries number
2124    unsigned int      dentry;           // directory entry index
2125    unsigned int      offset     = 0;   // byte offset in buffer
2126    unsigned int      cluster_id = 0;   // cluster index in directory
2127    int               found      = 0;   // not found (0) / name found (1) / end of dir (-1)
2128
2129#if (GIET_DEBUG_FAT & 1)
2130if ( _get_proctime() > GIET_DEBUG_FAT )
2131_printf("\n[DEBUG FAT] _get_child_from_parent() : does not found inode <%s>"
2132        " in directory <%s> => search in cache\n", name , parent->name );
2133#endif
2134
2135    // scan the clusters allocated to parent directory
2136    while ( found == 0 )
2137    {
2138        // get one 4 Kytes buffer from parent File_Cache 
2139        fat_cache_desc_t*  pdesc;
2140        if ( _get_buffer_from_cache( parent,
2141                                     cluster_id,
2142                                     &pdesc ) )    return 2;
2143        buffer = pdesc->buffer;
2144
2145        // scan this buffer until end of directory, end of buffer, or name found
2146        while( (offset < 4096) && (found == 0) )
2147        {
2148
2149#if (GIET_DEBUG_FAT & 1)
2150if ( _get_proctime() > GIET_DEBUG_FAT )
2151_printf("\n[DEBUG FAT] _get_child_from_parent() : scan buffer %d for <%s>\n",
2152        cluster_id , name );
2153#endif
2154            attr = _read_entry( DIR_ATTR , buffer + offset , 0 );   
2155            ord  = _read_entry( LDIR_ORD , buffer + offset , 0 );
2156
2157            if (ord == NO_MORE_ENTRY)                 // no more entry in directory => break
2158            {
2159                found = -1;
2160            }
2161            else if ( ord == FREE_ENTRY )             // free entry => skip
2162            {
2163                offset = offset + 32;
2164            }
2165            else if ( attr == ATTR_LONG_NAME_MASK )   // LFN entry => get partial name
2166            {
2167                unsigned int seq = ord & 0x3;
2168                lfn = (seq > lfn) ? seq : lfn;   
2169                if      ( seq == 1 ) _get_name_from_long( buffer + offset, lfn1 );
2170                else if ( seq == 2 ) _get_name_from_long( buffer + offset, lfn2 );
2171                else if ( seq == 3 ) _get_name_from_long( buffer + offset, lfn3 );
2172                offset = offset + 32;
2173            }
2174            else                                 // NORMAL entry
2175            {
2176                // build the extracted name
2177                if      ( lfn == 0 )
2178                {
2179                    _get_name_from_short( buffer + offset , cname );
2180                }
2181                else if ( lfn == 1 )
2182                {
2183                    _strcpy( cname      , lfn1 );
2184                }   
2185                else if ( lfn == 2 ) 
2186                {
2187                    _strcpy( cname      , lfn1 );
2188                    _strcpy( cname + 13 , lfn2 );
2189                }
2190                else if ( lfn == 3 ) 
2191                {
2192                    _strcpy( cname      , lfn1 );
2193                    _strcpy( cname + 13 , lfn2 );
2194                    _strcpy( cname + 26 , lfn3 );
2195                }
2196                   
2197                // test if extracted name == searched name
2198                if ( _strcmp( name , cname ) == 0 )
2199                {
2200                    cluster = (_read_entry( DIR_FST_CLUS_HI , buffer + offset , 1 ) << 16) |
2201                              (_read_entry( DIR_FST_CLUS_LO , buffer + offset , 1 )      ) ;
2202                    dentry  = ((cluster_id<<12) + offset)>>5;
2203                    is_dir  = ((attr & ATTR_DIRECTORY) == ATTR_DIRECTORY);
2204                    size    = _read_entry( DIR_FILE_SIZE , buffer + offset , 1 );
2205                    found   = 1;
2206                }
2207                offset = offset + 32;
2208                lfn    = 0;
2209            }
2210        }  // end loop on directory entries
2211        cluster_id++;
2212        offset = 0;
2213    }  // end loop on buffers
2214
2215    if ( found == -1 )  // found end of directory in parent directory
2216    {
2217
2218#if (GIET_DEBUG_FAT & 1)
2219if ( _get_proctime() > GIET_DEBUG_FAT )
2220_printf("\n[DEBUG FAT] _get_child_from_parent() : found end of directory in <%s>\n",
2221        parent->name );
2222#endif
2223        *inode = NULL;
2224        return 1;
2225    }
2226    else               // found searched name in parent directory
2227    {
2228        // allocate a new inode and an empty Cache-File
2229        *inode = _allocate_one_inode( name,
2230                                      is_dir,
2231                                      cluster,
2232                                      size,
2233                                      0,             // count
2234                                      dentry,
2235                                      1 );           // cache_allocate
2236
2237        // introduce it in Inode-Tree
2238        _add_inode_in_tree( *inode , parent );
2239
2240#if (GIET_DEBUG_FAT & 1)
2241if ( _get_proctime() > GIET_DEBUG_FAT )
2242_printf("\n[DEBUG FAT] _get_child_from_parent() : found <%s> on device\n", name );
2243#endif
2244        return 0;
2245    }
2246}  // end _get_child_from_parent()
2247
2248
2249
2250
2251//////////////////////////////////////////////////////////////////
2252static unsigned int _get_inode_from_path( char*          pathname,
2253                                          fat_inode_t**  inode )
2254{
2255    char                 name[32];         // buffer for one name in pathname
2256    unsigned int         nb_read;              // number of characters written in name[]
2257    fat_inode_t*         parent;           // parent inode
2258    fat_inode_t*         child;            // child inode
2259    unsigned int         last;             // while exit condition
2260    unsigned int         code;             // return value
2261
2262#if (GIET_DEBUG_FAT & 1)
2263if ( _get_proctime() > GIET_DEBUG_FAT )
2264_printf("\n[DEBUG FAT] _get_inode_from_path() : enters for path <%s>\n", pathname );
2265#endif
2266
2267    // handle root directory case
2268    if ( _strcmp( pathname , "/" ) == 0 )
2269    {
2270
2271#if (GIET_DEBUG_FAT & 1)
2272if ( _get_proctime() > GIET_DEBUG_FAT )
2273_printf("\n[DEBUG FAT] _get_inode_from_path() : found root inode for <%s>\n", 
2274        pathname );
2275#endif
2276        *inode  = _fat.inode_tree_root;
2277        return 0;
2278    }
2279
2280    // If the pathname is not "/", we traverse the inode tree from the root.
2281    // We use _get_name_from_path() to scan pathname and extract inode names.
2282    // We use _get_child_from_parent() to scan each directory in the path.
2283
2284    last       = 0;
2285    nb_read    = 0;                      // number of characters analysed in path
2286    parent     = _fat.inode_tree_root;   // Inode-Tree root
2287   
2288    while ( !last )
2289    {
2290        // get searched file/dir name
2291        if ( _get_name_from_path( pathname, name, &nb_read ) )
2292        {
2293            return 3;   // error : name too long
2294        }
2295
2296        // compute last iteration condition
2297        last = (pathname[nb_read] == 0);
2298
2299#if (GIET_DEBUG_FAT & 1)
2300if ( _get_proctime() > GIET_DEBUG_FAT )
2301_printf("\n[DEBUG FAT] _get_inode_from_path() : got name <%s>\n", name );
2302#endif
2303
2304        if ( _strcmp( name, ".." ) == 0)
2305        {
2306            // found special name "..", try to go up
2307            code = 0;
2308            if ( parent->parent )
2309                child = parent->parent;
2310            else
2311                child = parent;
2312        }
2313        else if ( _strcmp( name, "." ) == 0 )
2314        {
2315            // found special name ".", stay on the same level
2316            code = 0;
2317            child = parent;
2318        }
2319        else
2320        {
2321            // get child inode from parent directory
2322            code = _get_child_from_parent( parent,
2323                                           name,
2324                                           &child );
2325
2326            // we need to find the child inode for all non terminal names
2327            if ( (code == 2) || ((code == 1 ) && !last) )
2328            {
2329
2330    #if (GIET_DEBUG_FAT & 1)
2331    if ( _get_proctime() > GIET_DEBUG_FAT )
2332    _printf("\n[DEBUG FAT] _get_inode_from_path() : neither parent, nor child found for <%s>\n",
2333            pathname );
2334    #endif
2335                return 2;  // error : parent inode not found
2336            }
2337        }
2338
2339        // update parent if not the last iteration
2340        if ( !last )
2341            parent = child;
2342    } // end while
2343
2344    // returns inode pointer
2345    if (code == 0 )
2346    {
2347
2348#if (GIET_DEBUG_FAT & 1)
2349if ( _get_proctime() > GIET_DEBUG_FAT )
2350_printf("\n[DEBUG FAT] _get_inode_from_path() : found inode for <%s>\n", 
2351        pathname );
2352#endif
2353        *inode  = child;
2354    }
2355    else
2356    {
2357
2358#if (GIET_DEBUG_FAT & 1)
2359if ( _get_proctime() > GIET_DEBUG_FAT )
2360_printf("\n[DEBUG FAT] _get_inode_from_path() : found only parent inode for <%s>\n",
2361        pathname );
2362#endif
2363        *inode  = parent;
2364    }
2365
2366    return code;                 // can be 0 (found) or 1 (not found)
2367
2368}  // end _get_inode_from_path()
2369
2370
2371
2372
2373//////////////////////////////////////////////////////////////
2374static unsigned int _remove_node_from_fs( fat_inode_t* inode )
2375{
2376    // check for root node
2377    if ( !inode->parent ) return 1;
2378
2379    // remove entry in parent directory
2380    if ( _remove_dir_entry( inode ) ) return 1;
2381
2382    // update parent directory on device
2383    if ( _update_device_from_cache( inode->parent->levels,
2384                                    inode->parent->cache,
2385                                    inode->parent->name ) ) return 1;
2386
2387    // release clusters allocated to file/dir in DATA region
2388    if ( _clusters_release( inode->cluster ) ) return 1;
2389
2390    // release File-Cache
2391    _release_cache_memory( inode->cache, inode->levels );
2392    _free ( inode->cache );
2393
2394    // remove inode from Inode-Tree
2395    _remove_inode_from_tree( inode );
2396
2397    // release inode
2398    _free ( inode );
2399
2400    return 0;
2401}  // end _remove_node_from_fs()
2402
2403
2404//////////////////////////////////////////////////////////////////
2405static unsigned int _next_cluster_no_cache( unsigned int   cluster,
2406                                            unsigned int*  next )
2407{
2408    // compute cluster_id and slot_id
2409    // each cluster contains 1024 slots (4 bytes per slot)
2410    unsigned int cluster_id  = cluster >> 10;
2411    unsigned int slot_id     = cluster & 0x3FF;
2412
2413    // compute lba of cluster identified by cluster_id
2414    unsigned int lba = _fat.fat_lba + (cluster_id << 3);
2415
2416    // get cluster containing the adressed FAT slot in FAT buffer
2417    if ( _fat_buffer_fat_lba != lba )
2418    {
2419        if ( _fat_ioc_access( 0,         // no descheduling
2420                              1,         // read
2421                              lba,
2422                              (unsigned int)_fat_buffer_fat,
2423                              8 ) )
2424        {
2425            _printf("\n[FAT ERROR] in _next_cluster_no_cache() : "
2426                    "cannot load lba = %x into fat_buffer\n", lba );
2427            return 1;
2428        }
2429
2430        _fat_buffer_fat_lba = lba;
2431    }
2432
2433    // return next cluster index
2434    unsigned int* buf = (unsigned int*)_fat_buffer_fat;
2435    *next = buf[slot_id];
2436    return 0;
2437   
2438}  // end _next_cluster_no_cache()
2439
2440
2441
2442
2443/////////////////////////////////////////////////////////////////
2444static unsigned int _file_info_no_cache( char*          pathname,
2445                                         unsigned int*  file_cluster,
2446                                         unsigned int*  file_size )
2447{
2448   
2449#if (GIET_DEBUG_FAT & 1)
2450if ( _get_proctime() > GIET_DEBUG_FAT )
2451_printf("\n[DEBUG FAT] _file_info_no_cache() : enters for path <%s>\n", pathname );
2452#endif
2453
2454    char            name[32];             // buffer for one name in the analysed pathname
2455    char            lfn1[16];             // buffer for a partial name in LFN entry
2456    char            lfn2[16];             // buffer for a partial name in LFN entry
2457    char            lfn3[16];             // buffer for a partial name in LFN entry
2458    char            cname[32];            // buffer for a full name in a directory entry
2459    unsigned int    nb_read;              // number of characters analysed in path
2460    unsigned int    parent_cluster;       // cluster index for the parent directory
2461    unsigned int    child_cluster = 0;    // cluster index for the searched file/dir
2462    unsigned int    child_size = 0;       // size of the searched file/dir
2463    unsigned int    child_is_dir;         // type of the searched file/dir
2464    unsigned int    offset;               // offset in a 4 Kbytes buffer
2465    unsigned int    ord;                  // ORD field in a directory entry
2466    unsigned int    attr;                 // ATTR field in a directory entry
2467    unsigned int    lfn = 0;              // number of lfn entries
2468    unsigned char*  buf;                  // pointer on a 4 Kbytes buffer
2469    unsigned int    found;                // name found in current directory entry
2470
2471    // Three embedded loops:
2472    // - scan pathname to extract file/dir names,
2473    // - for each name, scan the clusters of the parent directory
2474    // - for each cluster, scan the 4 Kbytes buffer to find the file/dir name
2475    // The starting point is the root directory (cluster 2)
2476
2477    nb_read        = 0;
2478    parent_cluster = 2; 
2479
2480    // scan pathname 
2481    while ( pathname[nb_read] != 0 )   
2482    {
2483        // get searched file/dir name
2484        if ( _get_name_from_path( pathname, name, &nb_read ) ) return 1;
2485
2486#if (GIET_DEBUG_FAT & 1)
2487if ( _get_proctime() > GIET_DEBUG_FAT )
2488_printf("\n[DEBUG FAT] _file_info_no_cache() : search name <%s>"
2489        " in cluster %x\n", name , parent_cluster );
2490#endif
2491        found  = 0;
2492
2493        // scan clusters containing the parent directory
2494        while ( found == 0 ) 
2495        {
2496            // compute lba
2497            unsigned int lba = _cluster_to_lba( parent_cluster );
2498
2499            // load one cluster of the parent directory into data_buffer
2500            if ( _fat_buffer_data_lba != lba )
2501            {
2502                if ( _fat_ioc_access( 0,         // no descheduling
2503                                      1,         // read
2504                                      lba,
2505                                      (unsigned int)_fat_buffer_data,
2506                                      8 ) )
2507                {
2508                    _printf("\n[FAT ERROR] in _file_info_no_cache() : "
2509                            "cannot load lba = %x into data_buffer\n", lba );
2510                    return 1;
2511                }
2512
2513                _fat_buffer_data_lba = lba;
2514            }
2515
2516            offset = 0;
2517
2518            // scan this 4 Kbytes buffer
2519            while ( (offset < 4096) && (found == 0) )
2520            {
2521                buf  = _fat_buffer_data + offset;
2522                attr = _read_entry( DIR_ATTR , buf , 0 );   
2523                ord  = _read_entry( LDIR_ORD , buf , 0 );
2524
2525                if (ord == NO_MORE_ENTRY)               // no more entry => break
2526                {
2527                    found = 2;
2528                }
2529                else if ( ord == FREE_ENTRY )           // free entry => skip
2530                {
2531                    offset = offset + 32;
2532                }
2533                else if ( attr == ATTR_LONG_NAME_MASK ) // LFN entry => get partial name
2534                {
2535                    unsigned int seq = ord & 0x3;
2536                    lfn = (seq > lfn) ? seq : lfn;   
2537                    if      ( seq == 1 ) _get_name_from_long( buf, lfn1 );
2538                    else if ( seq == 2 ) _get_name_from_long( buf, lfn2 );
2539                    else if ( seq == 3 ) _get_name_from_long( buf, lfn3 );
2540                    offset = offset + 32;
2541                }
2542                else                                    // NORMAL entry
2543                {
2544                    // build the full mame for current directory entry
2545                    if      ( lfn == 0 )
2546                    {
2547                        _get_name_from_short( buf , cname );
2548                    }
2549                    else if ( lfn == 1 )
2550                    {
2551                        _strcpy( cname      , lfn1 );
2552                    }   
2553                    else if ( lfn == 2 ) 
2554                    {
2555                        _strcpy( cname      , lfn1 );
2556                        _strcpy( cname + 13 , lfn2 );
2557                    }
2558                    else if ( lfn == 3 ) 
2559                    {
2560                        _strcpy( cname      , lfn1 );
2561                        _strcpy( cname + 13 , lfn2 );
2562                        _strcpy( cname + 26 , lfn3 );
2563                    }
2564                   
2565                    // test if extracted name == searched name
2566                    if ( _strcmp( name , cname ) == 0 )
2567                    {
2568                        child_cluster = (_read_entry( DIR_FST_CLUS_HI , buf , 1 ) << 16) |
2569                                        (_read_entry( DIR_FST_CLUS_LO , buf , 1 )      ) ;
2570                        child_is_dir  = ((attr & ATTR_DIRECTORY) == ATTR_DIRECTORY);
2571                        child_size    = _read_entry( DIR_FILE_SIZE , buf , 1 );
2572                        found         = 1;
2573                    }
2574                    offset = offset + 32;
2575                    lfn = 0;
2576                }
2577            }  // en loop on directory entries
2578           
2579            // compute next cluster index
2580            unsigned int next;
2581            if ( _next_cluster_no_cache ( parent_cluster , &next ) ) return 1;
2582            parent_cluster = next;
2583        } // end loop on clusters
2584
2585        if ( found == 2 )  // found end of directory => error
2586        { 
2587            _printf("\n[FAT ERROR] in _file_info_no_cache() : <%s> not found\n",
2588                    name );
2589            return 1;
2590        }
2591 
2592        // check type
2593        if ( ((pathname[nb_read] == 0) && (child_is_dir != 0)) ||
2594             ((pathname[nb_read] != 0) && (child_is_dir == 0)) )
2595        {
2596            _printf("\n[FAT ERROR] in _file_info_no_cache() : illegal type for <%s>\n", name );
2597            return 1;
2598        }
2599
2600        // update parent_cluster for next name
2601        parent_cluster = child_cluster;
2602
2603    }  // end loop on names
2604
2605#if (GIET_DEBUG_FAT & 1)
2606if ( _get_proctime() > GIET_DEBUG_FAT )
2607_printf("\n[DEBUG FAT] _file_info_no_cache() : success for <%s> / "
2608        "file_size = %x / file_cluster = %x\n", pathname, child_size, child_cluster );
2609#endif
2610
2611    // return file cluster and size
2612    *file_size    = child_size;
2613    *file_cluster = child_cluster;
2614    return 0;
2615
2616}  // end _file_info_no_cache()
2617
2618
2619
2620/////////////////////////////////////////////////////////////////////////////
2621/////////////////////////////////////////////////////////////////////////////
2622//             Extern functions                                               
2623/////////////////////////////////////////////////////////////////////////////
2624/////////////////////////////////////////////////////////////////////////////
2625
2626
2627/////////////////////////////////////////////////////////////////////////////
2628// This function initializes the FAT structures.
2629// - The Fat-Descriptor is always initialised.
2630// - The dynamically allocated structures (the Inode-Tre, the Fat_Cache,
2631//   and the File-Cache for the root directory) are only allocated
2632//   and initialised if the "kernel_mode" argument is set.
2633/////////////////////////////////////////////////////////////////////////////
2634// Implementation note:
2635// This function is called twice, by the boot-loader, and by the kernel_init.
2636// It does not use dynamic memory allocation from the distributed heap.
2637// It use informations found in the boot sector and FS-INFO sector.
2638// that are loaded in the Fat-Descriptor temporary block_buffer.
2639/////////////////////////////////////////////////////////////////////////////
2640// Returns 0 if success.
2641// Returns -1 if error.
2642/////////////////////////////////////////////////////////////////////////////
2643int _fat_init( unsigned int kernel_mode ) 
2644{
2645
2646#if GIET_DEBUG_FAT
2647if ( _get_proctime() > GIET_DEBUG_FAT )
2648_printf("\n[DEBUG FAT] _fat_init() : enters at cycle %d\n", _get_proctime() );
2649#endif
2650
2651    // FAT initialisation should be done only once
2652    if ( _fat.initialised == FAT_INITIALISED )
2653    {
2654        _printf("\n[FAT ERROR] in _fat_init() : FAT already initialised\n");
2655        return -1;
2656    }
2657
2658    // load Boot sector (VBR) into FAT buffer
2659    if ( _fat_ioc_access( 0,                                  // no descheduling
2660                          1,                                  // read
2661                          0,                                  // block index
2662                          (unsigned int)_fat.block_buffer,
2663                          1 ) )                               // one block
2664    {
2665        _printf("\n[FAT ERROR] in _fat_init() cannot load VBR\n");
2666        return -1;
2667    }
2668
2669    _fat.block_buffer_lba = 0;
2670   
2671#if GIET_DEBUG_FAT
2672if ( _get_proctime() > GIET_DEBUG_FAT )
2673{
2674    _printf("\n[DEBUG FAT] _fat_init() : Boot sector loaded\n");
2675    _display_one_block( _fat.block_buffer, "block device", _fat.block_buffer_lba );
2676}
2677#endif
2678
2679    // checking various FAT32 assuptions from boot sector
2680    if( _read_entry( BPB_BYTSPERSEC, _fat.block_buffer, 1 ) != 512 )
2681    {
2682        _printf("\n[FAT ERROR] The sector size must be 512 bytes\n");
2683        return -1;
2684    }
2685    if( _read_entry( BPB_SECPERCLUS, _fat.block_buffer, 1 ) != 8 )
2686    {
2687        _printf("\n[FAT ERROR] The cluster size must be 8 blocks\n");
2688        return -1;
2689    }
2690    if( _read_entry( BPB_NUMFATS, _fat.block_buffer, 1 ) != 1 )
2691    {
2692        _printf("\n[FAT ERROR] The number of FAT copies in FAT region must be 1\n");
2693        return -1;
2694    }
2695    if( (_read_entry( BPB_FAT32_FATSZ32, _fat.block_buffer, 1 ) & 0xF) != 0 )
2696    {
2697        _printf("\n[FAT ERROR] The FAT region must be multiple of 16 sectors\n");
2698        return -1;
2699    }
2700    if( _read_entry( BPB_FAT32_ROOTCLUS, _fat.block_buffer, 1 ) != 2 )
2701    {
2702        _printf("\n[FAT ERROR] The root directory must be at cluster 2\n");
2703        return -1;
2704    }
2705
2706    // initialise Fat-Descriptor from VBR
2707    _fat.sector_size         = 512;
2708    _fat.cluster_size        = 4096;
2709    _fat.fat_sectors         = _read_entry( BPB_FAT32_FATSZ32 , _fat.block_buffer , 1 );
2710    _fat.fat_lba             = _read_entry( BPB_RSVDSECCNT , _fat.block_buffer , 1 );
2711    _fat.data_sectors        = _fat.fat_sectors << 10;
2712    _fat.data_lba            = _fat.fat_lba + _fat.fat_sectors;
2713    _fat.fs_info_lba         = _read_entry( BPB_FAT32_FSINFO , _fat.block_buffer , 1 );
2714    _fat_buffer_fat_lba      = 0xFFFFFFFF;
2715    _fat_buffer_data_lba     = 0xFFFFFFFF;
2716    _fat.initialised         = FAT_INITIALISED;
2717
2718    // load FS_INFO sector into FAT buffer
2719    if ( _fat_ioc_access( 0,                                // no descheduling
2720                          1,                                // read
2721                          _fat.fs_info_lba,                 // lba
2722                          (unsigned int)_fat.block_buffer,
2723                          1 ) )                             // one block
2724    { 
2725        _printf("\n[FAT ERROR] in _fat_init() cannot load FS_INFO Sector\n"); 
2726        return -1;
2727    }
2728
2729    _fat.block_buffer_lba = _fat.fs_info_lba;
2730
2731#if GIET_DEBUG_FAT
2732if ( _get_proctime() > GIET_DEBUG_FAT )
2733{
2734    _printf("\n[DEBUG FAT] _fat_init() : FS-INFO sector loaded\n");
2735    _display_one_block( _fat.block_buffer, "block device", _fat.block_buffer_lba );
2736}
2737#endif
2738
2739    // initialise Fat-Descriptor from FS_INFO
2740    _fat.free_clusters_number   = _read_entry( FS_FREE_CLUSTERS    , _fat.block_buffer, 1);
2741    _fat.first_free_cluster     = _read_entry( FS_FREE_CLUSTER_HINT, _fat.block_buffer, 1);
2742
2743    // This is done only when the _fat_init() is called in kernel mode
2744
2745    if ( kernel_mode )
2746    {
2747        unsigned int i;
2748
2749        // create Inode-Tree root
2750        _fat.inode_tree_root = _allocate_one_inode("/", // dir name
2751                                                   1,   // directory
2752                                                   2,   // cluster id
2753                                                   0,   // no size
2754                                                   0,   // no children
2755                                                   0,   // no dentry
2756                                                   1);  // allocate cache
2757
2758        // initialize lock
2759        _spin_lock_init( &_fat.fat_lock );
2760
2761        // initialize File Descriptor Array
2762        for( i = 0 ; i < GIET_OPEN_FILES_MAX ; i++ ) _fat.fd[i].allocated = 0;
2763
2764        // initialize fat_cache root
2765        _fat.fat_cache_root   = _allocate_one_cache_node( NULL );
2766        _fat.fat_cache_levels = _get_levels_from_size( _fat.fat_sectors << 9 );
2767    }  // end if kernel_mode
2768
2769#if GIET_DEBUG_FAT
2770if ( _get_proctime() > GIET_DEBUG_FAT )
2771_display_fat_descriptor();
2772#endif
2773
2774    return 0;
2775}  // end _fat_init()
2776
2777
2778
2779
2780///////////////////////////////////////////////////////////////////////////////
2781// This function implements the giet_fat_open() system call.
2782// The semantic is similar to the UNIX open() function, but only the O_CREATE
2783// and O_RDONLY flags are supported. The UNIX access rights are not supported.
2784// If the file does not exist in the specified directory, it is created.
2785// If the specified directory does not exist, an error is returned.
2786// It allocates a file descriptor to the calling task, for the file identified
2787// by "pathname". If several tasks try to open the same file, each task 
2788// obtains a private file descriptor.
2789// A node name (file or directory) cannot be larger than 31 characters.
2790///////////////////////////////////////////////////////////////////////////////
2791// Returns file descriptor index if success
2792// Returns a negative value if error:
2793//   -1  :  "fat not initialised"
2794//   -2  :  "path to parent not found"
2795//   -3  :  "one name in path too long"
2796//   -4  :  "file not found"
2797//   -5  :  "Cannot update parent directory"
2798//   -6  :  "Cannot update DATA region"
2799//   -7  :  "Cannot update FAT region"
2800//   -8  :  "Cannot update FS_INFO sector"
2801//   -9  :  "file descriptor array full"
2802///////////////////////////////////////////////////////////////////////////////
2803int _fat_open( char*        pathname,     // absolute path from root
2804               unsigned int flags )       // O_CREATE and O_RDONLY
2805{
2806    unsigned int         fd_id;            // index in File-Descriptor-Array
2807    unsigned int         code;             // error code
2808    fat_inode_t*         inode;            // anonymous inode pointer
2809    fat_inode_t*         child;            // pointer on searched file inode
2810    fat_inode_t*         parent;           // pointer on parent directory inode
2811   
2812    // get flags
2813    unsigned int create    = ((flags & O_CREATE) != 0);
2814    unsigned int read_only = ((flags & O_RDONLY) != 0); 
2815
2816#if GIET_DEBUG_FAT
2817unsigned int procid  = _get_procid();
2818unsigned int x       = procid >> (Y_WIDTH + P_WIDTH);
2819unsigned int y       = (procid >> P_WIDTH) & ((1<<Y_WIDTH)-1);
2820unsigned int p       = procid & ((1<<P_WIDTH)-1);
2821if ( _get_proctime() > GIET_DEBUG_FAT )
2822_printf("\n[DEBUG FAT] _fat_open() : P[%d,%d,%d] enters for path <%s> / "
2823        " create = %d / read_only = %d\n",
2824        x, y, p, pathname , create , read_only );
2825#endif
2826
2827    // checking FAT initialised
2828    if( _fat.initialised != FAT_INITIALISED )
2829    {
2830        _printf("\n[FAT ERROR] in _fat_open() : FAT not initialised\n");
2831        return -1;
2832    }
2833
2834    // takes the lock
2835    _spin_lock_acquire( &_fat.fat_lock );
2836
2837    // get inode pointer
2838    code = _get_inode_from_path( pathname , &inode );
2839
2840    if ( code == 2 ) 
2841    {
2842        _spin_lock_release( &_fat.fat_lock );
2843        _printf("\n[FAT ERROR] in _fat_open() : path to parent not found"
2844                " for file <%s>\n", pathname );
2845        return -2;
2846    }
2847    else if ( code == 3 ) 
2848    {
2849        _spin_lock_release( &_fat.fat_lock );
2850        _printf("\n[FAT ERROR] in _fat_open() : one name in path too long"
2851                " for file <%s>\n", pathname );
2852        return -3;
2853    }
2854    else if ( (code == 1) && (create == 0) )   
2855    {
2856        _spin_lock_release( &_fat.fat_lock );
2857        _printf("\n[FAT ERROR] in _fat_open() : file not found"
2858                " for file <%s>\n", pathname );
2859        return -4;
2860    }
2861    else if ( (code == 1) && (create != 0) )   // file name not found => create
2862    {
2863        // set parent inode pointer
2864        parent = inode;
2865
2866#if GIET_DEBUG_FAT
2867if ( _get_proctime() > GIET_DEBUG_FAT )
2868_printf("\n[DEBUG FAT] _fat_open() : P[%d,%d,%d] create a new file <%s>\n",
2869        x , y , p , pathname );
2870#endif
2871
2872        // get new file name / error check already done by _get_inode_from_path()
2873        char name[32];       
2874        _get_last_name( pathname , name );
2875
2876        // allocate a new inode and an empty Cache-File
2877        child = _allocate_one_inode( name,
2878                                     0,                         // not a directory
2879                                     END_OF_CHAIN_CLUSTER_MAX,  // no cluster allocated
2880                                     0,                         // size : new file is empty
2881                                     0,                         // count incremented later
2882                                     0,                         // dentry set by add_dir_entry
2883                                     1 );                       // cache_allocate
2884
2885        // introduce inode into Inode-Tree
2886        _add_inode_in_tree( child , parent );
2887
2888        // add an entry in the parent directory Cache_file
2889        if ( _add_dir_entry( child , parent ) )
2890        {
2891            _spin_lock_release( &_fat.fat_lock );
2892            _printf("\n[FAT ERROR] in _fat_open() : cannot update parent directory"
2893                    " for file <%s>\n" , pathname );
2894            return -5;
2895        } 
2896
2897        // update DATA region on block device for parent directory
2898        if ( _update_device_from_cache( parent->levels,
2899                                        parent->cache,
2900                                        parent->name ) )
2901        {
2902            _spin_lock_release( &_fat.fat_lock );
2903            _printf("\n[FAT ERROR] in _fat_open() : cannot update DATA region "
2904                    " for parent of file <%s>\n", pathname );
2905            return -6;
2906        }
2907
2908        // update FAT region on block device
2909        if ( _update_device_from_cache( _fat.fat_cache_levels,
2910                                        _fat.fat_cache_root,
2911                                        "FAT" ) )
2912        {
2913            _spin_lock_release( &_fat.fat_lock );
2914            _printf("\n[FAT ERROR] in _fat_open() : cannot update FAT region"
2915                    " for file <%s>\n", pathname );
2916            return -7;
2917        }
2918
2919        // update FS_INFO sector
2920        if ( _update_fs_info() )
2921        {
2922            _spin_lock_release( &_fat.fat_lock );
2923            _printf("\n[FAT ERROR] in _fat_open() : cannot update FS-INFO"
2924                    " for file <%s>\n", pathname );
2925            return -8;
2926        }
2927    }
2928    else // code == 0
2929    {
2930        // set searched file inode pointer
2931        child = inode;
2932
2933#if GIET_DEBUG_FAT
2934if ( _get_proctime() > GIET_DEBUG_FAT )
2935_printf("\n[DEBUG FAT] _fat_open() : P[%d,%d,%d] found file <%s> on device : inode = %x\n",
2936        x , y , p , pathname , child );
2937#endif
2938
2939    }
2940
2941    // Search an empty slot in file descriptors array
2942    fd_id = 0;
2943    while ( (_fat.fd[fd_id].allocated) != 0 && (fd_id < GIET_OPEN_FILES_MAX) )
2944    {
2945        fd_id++;
2946    }
2947
2948    // set file descriptor if an empty slot has been found
2949    if ( fd_id < GIET_OPEN_FILES_MAX )
2950    {
2951        // update file descriptor
2952        _fat.fd[fd_id].allocated  = 1;
2953        _fat.fd[fd_id].seek       = 0;
2954        _fat.fd[fd_id].read_only  = read_only;
2955        _fat.fd[fd_id].inode      = child;
2956
2957        // increment the refcount
2958        child->count = child->count + 1;
2959
2960        // releases the lock
2961        _spin_lock_release( &_fat.fat_lock );
2962
2963#if GIET_DEBUG_FAT
2964if ( _get_proctime() > GIET_DEBUG_FAT )
2965_printf("\n[DEBUG FAT] _fat_open() : P[%d,%d,%d] got fd = %d for <%s> / "
2966        "read_only = %d\n",
2967        x , y , p , fd_id , pathname , read_only );
2968#endif
2969        return fd_id;
2970    }
2971    else
2972    {
2973        _spin_lock_release( &_fat.fat_lock );
2974        _printf("\n[FAT ERROR] in _fat_open() : File-Descriptors-Array full\n");
2975        return -9;
2976    }
2977} // end _fat_open()
2978
2979
2980
2981
2982/////////////////////////////////////////////////////////////////////////////////
2983// This function implements the "giet_fat_close()" system call.
2984// It decrements the inode reference count, and release the fd_id entry
2985// in the file descriptors array.
2986// If the reference count is zero, it writes all dirty clusters on block device,
2987// and releases the memory allocated to the File_Cache.
2988/////////////////////////////////////////////////////////////////////////////////
2989// Returns 0 on success.
2990// Returns negative value if error:
2991//  -1  : "FAT not initialised"
2992//  -2  : "Illegal file descriptor"
2993//  -3  : "File not open"
2994//  -4  : "Cannot update DATA regions"
2995/////////////////////////////////////////////////////////////////////////////////
2996int _fat_close( unsigned int fd_id )
2997{
2998    // checking FAT initialised
2999    if( _fat.initialised != FAT_INITIALISED )
3000    {
3001        _printf("\n[FAT ERROR] in _fat_close() : FAT not initialised\n");
3002        return -1;
3003    }
3004
3005    if( (fd_id >= GIET_OPEN_FILES_MAX) )
3006    {
3007        _printf("\n[FAT ERROR] in _fat_close() : illegal file descriptor index\n");
3008        return -2;
3009    } 
3010
3011    // takes lock
3012    _spin_lock_acquire( &_fat.fat_lock );
3013
3014    if( _fat.fd[fd_id].allocated == 0 )
3015    {
3016        _spin_lock_release( &_fat.fat_lock );
3017        _printf("\n[FAT ERROR] in _fat_close() : file not open\n");
3018        return -3;
3019    }
3020
3021    // get the inode pointer
3022    fat_inode_t*  inode = _fat.fd[fd_id].inode;
3023
3024    // decrement reference count
3025    inode->count = inode->count - 1;
3026   
3027#if GIET_DEBUG_FAT
3028if ( _get_proctime() > GIET_DEBUG_FAT )
3029_printf("\n[FAT DEBUG] _fat_close() for file <%s> : refcount = %d\n",
3030        inode->name , inode->count );
3031#endif
3032
3033    // update block device and release File-Cache if no more references
3034    if ( inode->count == 0 )
3035    {
3036        // update all dirty clusters for closed file
3037        if ( _update_device_from_cache( inode->levels, 
3038                                        inode->cache,
3039                                        inode->name ) ) 
3040        {
3041            _spin_lock_release( &_fat.fat_lock );
3042            _printf("\n[FAT ERROR] in _fat_close() : cannot write dirty clusters "
3043                    "for file <%s>\n", inode->name );
3044            return -4;
3045        }
3046
3047#if GIET_DEBUG_FAT
3048if ( _get_proctime() > GIET_DEBUG_FAT )
3049_printf("\n[FAT DEBUG] _fat_close() update device for file <%s>\n", inode->name );
3050#endif
3051
3052        // update directory dirty clusters for parent directory
3053        if ( inode->parent &&
3054             _update_device_from_cache( inode->parent->levels,
3055                                        inode->parent->cache,
3056                                        inode->parent->name ) )
3057        {
3058            _spin_lock_release( &_fat.fat_lock );
3059            _printf("\n[FAT ERROR] in _fat_close() : cannot write dirty clusters "
3060                    "for directory <%s>\n", inode->parent->name );
3061            return -4;
3062        }
3063
3064#if GIET_DEBUG_FAT
3065if ( _get_proctime() > GIET_DEBUG_FAT )
3066_printf("\n[FAT DEBUG] _fat_close() update device for parent directory <%s>\n",
3067        inode->parent->name );
3068#endif
3069
3070        // release memory allocated to File-Cache (keep cache root node)
3071        _release_cache_memory( inode->cache, inode->levels );
3072
3073#if GIET_DEBUG_FAT
3074if ( _get_proctime() > GIET_DEBUG_FAT )
3075_printf("\n[FAT DEBUG] _fat_close() release memory for File-Cache <%s>\n",
3076        inode->name );
3077#endif
3078
3079    }
3080
3081    // release fd_id entry in file descriptor array
3082    _fat.fd[fd_id].allocated = 0;
3083
3084    // release lock
3085    _spin_lock_release( &_fat.fat_lock );
3086
3087    return 0;
3088} // end fat_close()
3089
3090
3091
3092
3093/////////////////////////////////////////////////////////////////////////////////
3094// This function implements the giet_fat_file_info() system call.
3095// It returns the size, the current offset and the directory info for a file
3096// identified by the "fd_id" argument.
3097/////////////////////////////////////////////////////////////////////////////////
3098// Returns  0 if success.
3099// Returns negative value if error.
3100//  -1  : "FAT not initialised"
3101//  -2  : "Illegal file descriptor"
3102//  -3  : "File not open"
3103/////////////////////////////////////////////////////////////////////////////////
3104int _fat_file_info( unsigned int            fd_id,
3105                    struct fat_file_info_s* info )
3106{
3107    if ( _fat.initialised != FAT_INITIALISED )
3108    {
3109        _printf("\n[FAT ERROR] in _fat_file_info() : FAT not initialised\n");
3110        return -1;
3111    }
3112
3113    if ( fd_id >= GIET_OPEN_FILES_MAX )
3114    {
3115        _printf("\n[FAT ERROR] in _fat_file_info() : illegal file descriptor index\n");
3116        return -2;
3117    } 
3118
3119    if ( _fat.fd[fd_id].allocated == 0 )
3120    {
3121        _printf("\n[FAT ERROR] in _fat_file_info() : file not open\n");
3122        return -3;
3123    }
3124
3125    info->size   = _fat.fd[fd_id].inode->size;
3126    info->offset = _fat.fd[fd_id].seek;
3127    info->is_dir = _fat.fd[fd_id].inode->is_dir;
3128
3129    return 0;
3130} // end _fat_file_info()
3131
3132
3133
3134
3135/////////////////////////////////////////////////////////////////////////////////
3136// The following function implements the "giet_fat_read()" system call.
3137// It transfers "count" bytes from the File_Cache associated to the file
3138// identified by "fd_id", to the user "buffer", from the current file offset.
3139// In case of miss in the File_Cache, it loads all involved clusters into cache.
3140/////////////////////////////////////////////////////////////////////////////////
3141// Returns number of bytes actually transfered if success .
3142// Returns 0 if EOF encountered (offset + count > file_size).
3143// Returns a negative value if error:
3144//   -1 :  "fat not initialised"
3145//   -2 :  "illegal file descriptor"
3146//   -2 :  "file not open"
3147//   -3 :  "cannot load file from device"
3148/////////////////////////////////////////////////////////////////////////////////
3149int _fat_read( unsigned int fd_id,     // file descriptor index
3150               void*        buffer,    // destination buffer
3151               unsigned int count )    // number of bytes to read
3152{
3153    // checking FAT initialised
3154    if( _fat.initialised != FAT_INITIALISED )
3155    {
3156        _printf("\n[FAT ERROR] in _fat_write() : FAT not initialised\n");
3157        return -1;
3158    }
3159
3160    // check fd_id overflow
3161    if ( fd_id >= GIET_OPEN_FILES_MAX )
3162    {
3163        _printf("\n[FAT ERROR] in _fat_read() : illegal file descriptor\n");
3164        return -2;
3165    }
3166
3167    // check file is open
3168    if ( _fat.fd[fd_id].allocated == 0 )
3169    {
3170        _printf("\n[FAT ERROR] in _fat_read() : file not open\n");
3171        return -3;
3172    }
3173
3174    // takes lock
3175    _spin_lock_acquire( &_fat.fat_lock );
3176           
3177    // get file inode pointer and offset
3178    fat_inode_t* inode  = _fat.fd[fd_id].inode;
3179    unsigned int seek   = _fat.fd[fd_id].seek;
3180
3181    // check count & seek versus file size
3182    if ( count + seek > inode->size )
3183    {
3184        _spin_lock_release( &_fat.fat_lock );
3185        _printf("\n[FAT ERROR] in _fat_read() : file too small"
3186                " / seek = %x / count = %x / file_size = %x\n",
3187                seek , count , inode->size );
3188        return 0;
3189    }
3190
3191    // compute first_cluster_id and first_byte_to_move
3192    unsigned int first_cluster_id   = seek >> 12;
3193    unsigned int first_byte_to_move = seek & 0xFFF;   
3194
3195    // compute last_cluster and last_byte_to_move
3196    unsigned int last_cluster_id   = (seek + count - 1) >> 12;   
3197    unsigned int last_byte_to_move = (seek + count - 1) & 0xFFF;
3198
3199#if GIET_DEBUG_FAT
3200unsigned int procid  = _get_procid();
3201unsigned int x       = procid >> (Y_WIDTH + P_WIDTH);
3202unsigned int y       = (procid >> P_WIDTH) & ((1<<Y_WIDTH)-1);
3203unsigned int p       = procid & ((1<<P_WIDTH)-1);
3204if ( _get_proctime() > GIET_DEBUG_FAT )
3205_printf("\n[DEBUG FAT] _fat_read() : P[%d,%d,%d] enters for file <%s> "
3206        " / bytes = %x / offset = %x\n"
3207        "first_cluster_id = %x / first_byte_to_move = %x"
3208        " / last_cluster_id = %x / last_byte_to_move = %x\n",
3209        x , y , p , inode->name , count , seek ,
3210        first_cluster_id , first_byte_to_move , last_cluster_id , last_byte_to_move );
3211#endif
3212
3213    // loop on all cluster covering the requested transfer
3214    unsigned int cluster_id;
3215    unsigned int done = 0;
3216    for ( cluster_id = first_cluster_id ; cluster_id <= last_cluster_id ; cluster_id++ )
3217    {
3218        // get pointer on the cluster_id buffer in cache
3219        unsigned char*     cbuf;
3220        fat_cache_desc_t*  pdesc;
3221        if ( _get_buffer_from_cache( inode, 
3222                                     cluster_id,
3223                                     &pdesc ) )
3224        {
3225            _spin_lock_release( &_fat.fat_lock );
3226            _printf("\n[FAT ERROR] in _fat_read() : cannot load file <%s>\n",
3227                    inode->name );
3228            return -4;
3229        }
3230        cbuf = pdesc->buffer;
3231
3232#if GIET_DEBUG_FAT
3233if ( _get_proctime() > GIET_DEBUG_FAT )
3234_printf("\n[DEBUG FAT] _fat_read() : P[%d,%d,%d] moves cluster_id %d from Cache-File <%s>\n",
3235        x , y , p , cluster_id, inode->name );
3236#endif
3237
3238        // compute memcpy arguments
3239        unsigned char*  source;
3240        unsigned int    nbytes;
3241        unsigned char*  dest = (unsigned char*)buffer + done;
3242        if ( (cluster_id == first_cluster_id) && (cluster_id == last_cluster_id) )
3243        {
3244            source = cbuf + first_byte_to_move; 
3245            nbytes = last_byte_to_move - first_byte_to_move + 1;
3246        }
3247        else if ( cluster_id == first_cluster_id )
3248        {
3249            source = cbuf + first_byte_to_move; 
3250            nbytes = 4096 - first_byte_to_move;
3251        }
3252        else if ( cluster_id == last_cluster_id )
3253        {
3254            source = cbuf; 
3255            nbytes = last_byte_to_move + 1;
3256        }
3257        else  // not first / not last
3258        {
3259            source = cbuf; 
3260            nbytes = 4096;
3261        }
3262
3263        // move data
3264        memcpy( dest , source , nbytes );
3265        done = done + nbytes;
3266    }
3267
3268#if GIET_DEBUG_FAT
3269if ( _get_proctime() > GIET_DEBUG_FAT )
3270_printf("\n[DEBUG FAT] _fat_read() : P[%d,%d,%d] loaded file <%s> from Cache-File\n",
3271        x , y , p , inode->name );
3272#endif
3273
3274    // update seek
3275    _fat.fd[fd_id].seek += done;
3276
3277    // release lock
3278    _spin_lock_release( &_fat.fat_lock );
3279
3280    return done;
3281} // end _fat_read()
3282
3283
3284
3285
3286/////////////////////////////////////////////////////////////////////////////////
3287// The following function implements the "giet_fat_write()" system call.
3288// It transfers "count" bytes to the fat_cache associated to the file
3289// identified by "fd_id", from the user "buffer", using the current file offset.
3290// It increases the file size and allocate new clusters if (count + offset)
3291// is larger than the current file size. Then it loads and updates all
3292// involved clusters in the cache.
3293/////////////////////////////////////////////////////////////////////////////////
3294// Returns number of bytes actually written if success.
3295// Returns a negative value if error:
3296//   -1 :  "FAT not initialised"
3297//   -2 :  "Illegal file descriptor"
3298//   -3 :  "File not open"
3299//   -4 :  "File not writable"
3300//   -5 :  "No free clusters"
3301//   -6 :  "Cannot update parent directory entry"
3302//   -7 :  "Cannot access File-Cache"
3303/////////////////////////////////////////////////////////////////////////////////
3304int _fat_write( unsigned int fd_id,    // file descriptor index
3305                void*        buffer,   // source buffer
3306                unsigned int count )   // number of bytes to write
3307{
3308    // checking FAT initialised
3309    if( _fat.initialised != FAT_INITIALISED )
3310    {
3311        _printf("\n[FAT ERROR] in _fat_write() : FAT not initialised\n");
3312        return -1;
3313    }
3314
3315    // takes lock
3316    _spin_lock_acquire( &_fat.fat_lock );
3317           
3318    // check fd_id overflow
3319    if ( fd_id >= GIET_OPEN_FILES_MAX )
3320    {
3321        _spin_lock_release( &_fat.fat_lock );
3322        _printf("\n[FAT ERROR] in _fat_write() : illegal file descriptor\n");
3323        return -2;
3324    }
3325
3326    // check file open
3327    if ( _fat.fd[fd_id].allocated == 0 )
3328    {
3329        _spin_lock_release( &_fat.fat_lock );
3330        _printf("\n[FAT ERROR] in _fat_write() : file not open\n" );
3331        return -3;
3332    }
3333
3334    // check file writable
3335    if ( _fat.fd[fd_id].read_only )
3336    {
3337        _spin_lock_release( &_fat.fat_lock );
3338        _printf("\n[FAT ERROR] in _fat_write() : file <%s> is read-only\n",
3339                _fat.fd[fd_id].inode->name );
3340        return -4;
3341    }
3342
3343    // get file inode pointer and seek
3344    fat_inode_t* inode  = _fat.fd[fd_id].inode;
3345    unsigned int seek   = _fat.fd[fd_id].seek;
3346
3347#if GIET_DEBUG_FAT
3348unsigned int procid  = _get_procid();
3349unsigned int x       = procid >> (Y_WIDTH + P_WIDTH);
3350unsigned int y       = (procid >> P_WIDTH) & ((1<<Y_WIDTH)-1);
3351unsigned int p       = procid & ((1<<P_WIDTH)-1);
3352if ( _get_proctime() > GIET_DEBUG_FAT )
3353_printf("\n[DEBUG FAT] _fat_write() : P[%d,%d,%d] enters for file <%s> "
3354        " / bytes = %x / seek = %x\n",
3355        x , y , p , inode->name , count , seek );
3356#endif
3357
3358    // chek if file size must be incremented
3359    // and allocate new clusters from FAT if required
3360    unsigned int old_size = inode->size;
3361    unsigned int new_size = seek + count;
3362    if ( new_size > old_size )
3363    {
3364        // update size in inode
3365        inode->size = new_size;
3366 
3367        // compute current and required numbers of clusters
3368        unsigned old_clusters = old_size >> 12;
3369        if ( old_size & 0xFFF ) old_clusters++;
3370
3371        unsigned new_clusters = new_size >> 12;
3372        if ( new_size & 0xFFF ) new_clusters++;
3373
3374        // allocate new clusters from FAT if required
3375        if ( new_clusters > old_clusters )
3376        {
3377
3378#if GIET_DEBUG_FAT
3379if ( _get_proctime() > GIET_DEBUG_FAT )
3380_printf("\n[DEBUG FAT] _fat_write() : P[%d,%d,%d] allocates new clusters for file <%s>"
3381        " / current = %d / required = %d\n",
3382        x , y , p , inode->name , old_clusters , new_clusters );
3383#endif
3384            // allocate missing clusters
3385            if ( _clusters_allocate( inode,
3386                                     old_clusters,
3387                                     new_clusters - old_clusters ) )
3388            {
3389                _spin_lock_release( &_fat.fat_lock );
3390                _printf("\n[FAT ERROR] in _fat_write() : no free clusters"
3391                        " for file <%s>\n", _fat.fd[fd_id].inode->name );
3392                return -5;
3393            }
3394        }
3395         
3396        // update parent directory entry (size an cluster index)
3397        if ( _update_dir_entry( inode ) )
3398        {
3399            _spin_lock_release( &_fat.fat_lock );
3400            _printf("\n[FAT ERROR] in _fat_write() : cannot update parent directory entry"
3401                    " for file <%s>\n", _fat.fd[fd_id].inode->name );
3402            return -6;
3403        }
3404           
3405
3406#if GIET_DEBUG_FAT
3407if ( _get_proctime() > GIET_DEBUG_FAT )
3408_printf("\n[DEBUG FAT] _fat_write() : P[%d,%d,%d] updates size for file <%s> / size = %x\n",
3409        x , y , p , inode->name , (new_size - old_size) );
3410#endif
3411
3412    }
3413
3414    // compute first_cluster_id and first_byte_to_move
3415    unsigned int first_cluster_id   = seek >> 12;
3416    unsigned int first_byte_to_move = seek & 0xFFF;   
3417
3418    // compute last_cluster and last_byte_to_move
3419    unsigned int last_cluster_id   = (seek + count - 1) >> 12;   
3420    unsigned int last_byte_to_move = (seek + count - 1) & 0xFFF;
3421
3422#if GIET_DEBUG_FAT
3423if ( _get_proctime() > GIET_DEBUG_FAT )
3424_printf("\n[DEBUG FAT] _fat_write() : P[%d,%d,%d] starts loop on clusters for file <%s>\n"
3425        "  first_cluster_id = %d / first_byte_to_move = %x"
3426        " / last_cluster_id = %d / last_byte_to_move = %x\n",
3427        x , y , p , inode->name ,
3428        first_cluster_id , first_byte_to_move , last_cluster_id , last_byte_to_move );
3429#endif
3430
3431    // loop on all clusters covering the requested transfer
3432    unsigned int cluster_id;
3433    unsigned int done = 0;
3434    for ( cluster_id = first_cluster_id ; cluster_id <= last_cluster_id ; cluster_id++ )
3435    {
3436        // get pointer on one 4K buffer in File-Cache
3437        unsigned char*     cbuf;
3438        fat_cache_desc_t*  pdesc;
3439        if ( _get_buffer_from_cache( inode,   
3440                                     cluster_id, 
3441                                     &pdesc ) )   
3442        {
3443            _spin_lock_release( &_fat.fat_lock );
3444            _printf("\n[FAT ERROR] in _fat_write() : cannot load file <%s>\n",
3445                    inode->name );
3446            return -7;
3447        }
3448       
3449        cbuf         = pdesc->buffer;
3450        pdesc->dirty = 1;
3451   
3452#if GIET_DEBUG_FAT
3453if ( _get_proctime() > GIET_DEBUG_FAT )
3454_printf("\n[DEBUG FAT] _fat_write() : P[%d,%d,%d] move cluster_id %d to Cache-file <%s>\n",
3455        x , y , p , cluster_id, inode->name );
3456#endif
3457
3458        // compute memcpy arguments
3459        unsigned char* source = (unsigned char*)buffer + done;
3460        unsigned char* dest;
3461        unsigned int   nbytes;
3462        if ( (cluster_id == first_cluster_id) && (cluster_id == last_cluster_id) )
3463        {
3464            dest   = cbuf + first_byte_to_move; 
3465            nbytes = last_byte_to_move - first_byte_to_move + 1;
3466        }
3467        else if ( cluster_id == first_cluster_id )
3468        {
3469            dest   = cbuf + first_byte_to_move; 
3470            nbytes = 4096 - first_byte_to_move;
3471        }
3472        else if ( cluster_id == last_cluster_id )
3473        {
3474            dest   = cbuf; 
3475            nbytes = last_byte_to_move + 1;
3476        }
3477        else
3478        {
3479            dest   = cbuf; 
3480            nbytes = 4096;
3481        }
3482
3483        //move date
3484        memcpy( dest , source , nbytes ); 
3485        done = done + nbytes;
3486
3487    } // end for clusters
3488
3489    // update seek
3490    _fat.fd[fd_id].seek += done;
3491
3492#if GIET_DEBUG_FAT
3493if ( _get_proctime() > GIET_DEBUG_FAT )
3494_printf("\n[DEBUG FAT] _fat_write() : P[%d,%d,%d] store file <%s> into Cache-File\n",
3495        x , y , p , inode->name );
3496#endif
3497
3498    // release lock
3499    _spin_lock_release( &_fat.fat_lock );
3500
3501    return done;
3502} // end _fat_write()
3503
3504
3505
3506/////////////////////////////////////////////////////////////////////////////////
3507// The following function implements the "giet_fat_lseek()" system call.
3508// It repositions the seek in the file descriptor "fd_id", according to
3509// the "seek" and "whence" arguments.
3510// It has the same semantic as the UNIX lseek() function.
3511// Accepted values for whence are SEEK_SET and SEEK_CUR.
3512/////////////////////////////////////////////////////////////////////////////////
3513// Returns new seek value (bytes) if success.
3514// Returns negative value if error:
3515//   -1  : "FAT not initialised"
3516//   -2  : "Illegal file descriptor"
3517//   -3  : "File not open"
3518//   -4  : "Illegal whence argument"
3519/////////////////////////////////////////////////////////////////////////////////
3520int _fat_lseek( unsigned int fd_id,
3521                unsigned int seek,
3522                unsigned int whence )
3523{
3524    // checking FAT initialised
3525    if( _fat.initialised != FAT_INITIALISED )
3526    {
3527        _printf("\n[FAT ERROR] in _fat_lseek() : FAT not initialised\n");
3528        return -1;
3529    }
3530
3531    // check fd_id overflow
3532    if ( fd_id >= GIET_OPEN_FILES_MAX )
3533    {
3534        _printf("\n[FAT ERROR] in _fat_lseek() : illegal file descriptor\n");
3535        return -2;
3536    }
3537
3538    // takes lock
3539    _spin_lock_acquire( &_fat.fat_lock );
3540
3541    // check file open
3542    if ( _fat.fd[fd_id].allocated == 0 )
3543    {
3544        _spin_lock_release( &_fat.fat_lock );
3545        _printf("\n[FAT ERROR] in _fat_lseek() : file not open\n");
3546        return -3;
3547    }
3548
3549    unsigned int  new_seek;
3550
3551    // compute new seek
3552    if      ( whence == SEEK_CUR ) new_seek = _fat.fd[fd_id].seek + seek;
3553    else if ( whence == SEEK_SET ) new_seek = seek;
3554    else
3555    {
3556        _spin_lock_release( &_fat.fat_lock );
3557        _printf("\n[FAT ERROR] in _fat_user_lseek() : illegal whence valuel\n");
3558        return -4;
3559    }
3560
3561    // update file descriptor offset
3562    _fat.fd[fd_id].seek = new_seek;
3563
3564#if GIET_DEBUG_FAT
3565unsigned int procid  = _get_procid();
3566unsigned int x       = procid >> (Y_WIDTH + P_WIDTH);
3567unsigned int y       = (procid >> P_WIDTH) & ((1<<Y_WIDTH)-1);
3568unsigned int p       = procid & ((1<<P_WIDTH)-1);
3569if ( _get_proctime() > GIET_DEBUG_FAT )
3570_printf("\n[DEBUG FAT] _fat_lseek() : P[%d,%d,%d] set seek = %x for file <%s>\n",
3571        x , y , p , new_seek , _fat.fd[fd_id].inode->name );
3572#endif
3573
3574    // release lock
3575    _spin_lock_release( &_fat.fat_lock );
3576
3577    return new_seek;
3578}  // end _fat_lseek()
3579
3580
3581
3582/////////////////////////////////////////////////////////////////////////////////
3583// The following function implements the giet_fat_remove() system call.
3584// It deletes the file/directory identified by the "pathname" argument from
3585// the file system, if the remove condition is fulfilled (directory empty,
3586// or file not referenced).
3587// All clusters allocated in the block device DATA region are released.
3588// The FAT region is updated on the block device.
3589// The Inode-Tree is updated.
3590// The associated File_Cache is released.
3591// The Fat_Cache is updated.
3592/////////////////////////////////////////////////////////////////////////////////
3593// Returns 0 if success.
3594// Returns negative value if error
3595//   -1  : "FAT not initialised"
3596//   -2  : "File/Directory not found"
3597//   -3  : "Name too long in path"
3598//   -4  : "Has the wrong type"
3599//   -5  : "File still open"
3600//   -6  : "Cannot scan directory"
3601//   -7  : "Directory not empty"
3602//   -8  : "Cannot remove file/dir from FS"
3603/////////////////////////////////////////////////////////////////////////////////
3604int _fat_remove( char*        pathname,
3605                 unsigned int should_be_dir )
3606{
3607    fat_inode_t*  inode;            // searched file inode pointer
3608
3609#if GIET_DEBUG_FAT
3610unsigned int procid  = _get_procid();
3611unsigned int x       = procid >> (Y_WIDTH + P_WIDTH);
3612unsigned int y       = (procid >> P_WIDTH) & ((1<<Y_WIDTH)-1);
3613unsigned int p       = procid & ((1<<P_WIDTH)-1);
3614if ( _get_proctime() > GIET_DEBUG_FAT )
3615_printf("\n[DEBUG FAT] _fat_remove() : P[%d,%d,%d] enters for path <%s>\n",
3616        x, y, p, pathname );
3617#endif
3618
3619    // checking FAT initialised
3620    if( _fat.initialised != FAT_INITIALISED )
3621    {
3622        _printf("\n[FAT ERROR] in _fat_remove() : FAT not initialised\n");
3623        return -1;
3624    }
3625
3626    // take the lock
3627    _spin_lock_acquire( &_fat.fat_lock );
3628
3629    // get searched file inode
3630    unsigned int code = _get_inode_from_path( pathname , &inode );
3631
3632#if GIET_DEBUG_FAT
3633if ( _get_proctime() > GIET_DEBUG_FAT )
3634_printf("\n[DEBUG FAT] _fat_remove() : P[%d,%d,%d] found inode %x for <%s> / code = %d\n",
3635        x , y , p , (unsigned int)inode , pathname , code );
3636#endif
3637
3638    if ( (code == 1) || (code == 2) )
3639    {
3640        _spin_lock_release( &_fat.fat_lock );
3641        _printf("\n[FAT ERROR] in _fat_remove() : file <%s> not found\n", 
3642                pathname );
3643        return -2;
3644    }
3645    else if ( code == 3 )
3646    {
3647        _spin_lock_release( &_fat.fat_lock );
3648        _printf("\n[FAT ERROR] in _fat_remove() : name too long in <%s>\n",
3649                pathname );
3650        return -3;
3651    }
3652
3653    // check inode type
3654    if ( (inode->is_dir != 0) && (should_be_dir == 0) ) 
3655    {
3656        _spin_lock_release( &_fat.fat_lock );
3657        _printf("\n[FAT ERROR] in _fat_remove() : <%s> is a directory\n",
3658                pathname );
3659        return -4;
3660    }
3661    if ( (inode->is_dir == 0) && (should_be_dir != 0) )
3662    {
3663        _spin_lock_release( &_fat.fat_lock );
3664        _printf("\n[FAT ERROR] in _fat_remove() : <%s> is not a directory\n", 
3665                pathname );
3666        return -4;
3667    }
3668
3669#if GIET_DEBUG_FAT
3670if ( _get_proctime() > GIET_DEBUG_FAT )
3671_printf("\n[DEBUG FAT] _fat_remove() : P[%d,%d,%d] checked inode type for <%s>\n",
3672        x , y , p , pathname );
3673#endif
3674   
3675    // check references count for a file
3676    if ( (inode->is_dir == 0) && (inode->count != 0) )
3677    {
3678        _spin_lock_release( &_fat.fat_lock );
3679        _printf("\n[FAT ERROR] in _fat_remove() : file <%s> still referenced\n",
3680                pathname );
3681        return -5;
3682    }
3683
3684    //  check empty for a directory
3685    if ( inode->is_dir )
3686    {
3687        unsigned int entries;
3688        if ( _get_nb_entries( inode , &entries ) )
3689        {
3690            _spin_lock_release( &_fat.fat_lock );
3691            _printf("\n[FAT ERROR] in _fat_remove() : cannot scan directory <%s>\n", 
3692                    pathname );
3693            return -6;
3694        }
3695        else if ( entries > 2 )
3696        {
3697            _spin_lock_release( &_fat.fat_lock );
3698            _printf("\n[FAT ERROR] in _fat_remove() : directory <%s> not empty\n", 
3699                    pathname );
3700            return -7;
3701        }
3702    }
3703
3704#if GIET_DEBUG_FAT
3705if ( _get_proctime() > GIET_DEBUG_FAT )
3706_printf("\n[DEBUG FAT] _fat_remove() : P[%d,%d,%d] checked remove condition OK for <%s>\n",
3707        x , y , p , pathname );
3708#endif
3709   
3710    // remove the file or directory from the file system
3711    if ( _remove_node_from_fs( inode ) )
3712    {
3713        _spin_lock_release( &_fat.fat_lock );
3714        _printf("\n[FAT ERROR] in _fat_remove() : cannot remove <%s> from FS\n",
3715                pathname );
3716        return -8;
3717    }
3718
3719    // release lock and return success
3720    _spin_lock_release( &_fat.fat_lock );
3721
3722#if GIET_DEBUG_FAT
3723if ( _get_proctime() > GIET_DEBUG_FAT )
3724_printf("\n[DEBUG FAT] _fat_remove() : P[%d,%d,%d] removed  <%s> from FS\n",
3725        x, y, p, pathname );
3726#endif
3727   
3728    return 0;
3729       
3730}  // end _fat_remove()
3731
3732
3733
3734
3735
3736/////////////////////////////////////////////////////////////////////////////////
3737// This function implements the giet_fat_rename() system call.
3738// It moves an existing file or directory from one node (defined by "old_path"
3739// argument) to another node (defined by "new_path" argument) in the FS tree.
3740// The type (file/directory) and content are not modified.
3741// If the new_path file/dir exist, it is removed from the file system, but only 
3742// if the remove condition is respected (directory empty / file not referenced).
3743// The removed entry is only removed after the new entry is actually created.
3744/////////////////////////////////////////////////////////////////////////////////
3745// Returns 0 if success.
3746// Returns a negative value if error:
3747//  -1  : "FAT not initialised"
3748//  -2  : "old_path not found"
3749//  -3  : "new_path not found"
3750//  -4  : "cannot scan to_remove directory"
3751//  -5  : "to_remove directory not empty"
3752//  -6  : "to_remove file still referenced"
3753//  -7  : "cannot add new node to new_parent directory"
3754//  -8  : "cannot update new_parent directory on device"
3755//  -9  : "cannot remove old node from old_parent directory"
3756//  -10 : "cannot update old_parent directory on device"
3757//  -11 : "cannot remove to_remove node from FS"
3758//  -12 : "cannot move into its own subdirectory"
3759/////////////////////////////////////////////////////////////////////////////////
3760int _fat_rename( char*  old_path,
3761                 char*  new_path )
3762{
3763    fat_inode_t*  inode;        // anonymous inode pointer
3764    fat_inode_t*  old;          // inode identified by old_path      => to be deleted
3765    fat_inode_t*  new;          // inode identified by new_path      => to be created
3766    fat_inode_t*  old_parent;   // parent inode  in old_path         => to be modified
3767    fat_inode_t*  new_parent;   // parent inode  in new_path         => to be modified
3768    fat_inode_t*  to_remove;    // previouly identified by new_path  => to be removed
3769    unsigned int  code;
3770
3771#if GIET_DEBUG_FAT
3772unsigned int procid  = _get_procid();
3773unsigned int x       = procid >> (Y_WIDTH + P_WIDTH);
3774unsigned int y       = (procid >> P_WIDTH) & ((1<<Y_WIDTH)-1);
3775unsigned int p       = procid & ((1<<P_WIDTH)-1);
3776if ( _get_proctime() > GIET_DEBUG_FAT )
3777_printf("\n[DEBUG FAT] _fat_rename() : P[%d,%d,%d] enters to move <%s> to <%s>\n",
3778        x , y , p , old_path , new_path );
3779#endif
3780
3781    // checking FAT initialised
3782    if( _fat.initialised != FAT_INITIALISED )
3783    {
3784        _printf("\n[FAT ERROR] in _fat_rename() : FAT not initialised\n");
3785        return -1;
3786    }
3787
3788    // take the lock
3789    _spin_lock_acquire( &_fat.fat_lock );
3790
3791    // get "old" and "old_parent" inode pointers
3792    if ( _get_inode_from_path( old_path , &inode ) )
3793    {
3794        _spin_lock_release( &_fat.fat_lock );
3795        _printf("\n[FAT ERROR] in _fat_rename() : <%s> not found\n", old_path );
3796        return -2;
3797    }
3798    else
3799    {
3800        old        = inode;
3801        old_parent = inode->parent;
3802    }
3803
3804    // get "to_removed" and "new_parent" inode pointers
3805    code = _get_inode_from_path( new_path , &inode );
3806
3807    if ( code == 0 )       // new_path inode already exist
3808    {
3809        if ( inode == old )  // the file will replace itself, do nothing
3810        {
3811            _spin_lock_release( &_fat.fat_lock );
3812            return 0;
3813        }
3814
3815        to_remove        = inode;
3816        new_parent       = inode->parent;
3817    }
3818    else if ( code == 1 )  // to_remove does not exist but parent exist
3819    {
3820        to_remove        = NULL;
3821        new_parent       = inode;
3822    }
3823    else                   // parent directory in new_path not found
3824    {
3825        _spin_lock_release( &_fat.fat_lock );
3826        _printf("\n[FAT ERROR] in _fat_rename() : <%s> not found\n", new_path );
3827        return -3;
3828    }
3829
3830    // check for move into own subdirectory
3831    if ( _is_ancestor( old, new_parent ) )
3832    {
3833        _spin_lock_release( &_fat.fat_lock );
3834        _printf("\n[FAT ERROR] in _fat_rename() : can't move %s into its own subdirectory\n", old_path );
3835        return -12;
3836    }
3837
3838#if GIET_DEBUG_FAT
3839if ( _get_proctime() > GIET_DEBUG_FAT )
3840{
3841if ( to_remove )
3842_printf("\n[DEBUG FAT] _fat_rename() : old_parent = %s / old = %s / new_parent = %s "
3843        "/ to_remove = %s\n",
3844        old_parent->name , old->name , new_parent->name , to_remove->name );
3845else
3846_printf("\n[DEBUG FAT] _fat_rename() : old_parent = %s / old = %s / new_parent = %s "
3847        "/ no remove\n", 
3848        old_parent->name , old->name , new_parent->name );
3849}
3850#endif
3851
3852    // check remove condition for "to_remove" inode
3853    if ( to_remove )
3854    {
3855        if ( to_remove->is_dir )   // it's a directory
3856        {
3857            unsigned int entries;
3858            if ( _get_nb_entries( to_remove , &entries ) )
3859            {
3860                _spin_lock_release( &_fat.fat_lock );
3861                _printf("\n[FAT ERROR] in _fat_rename() : cannot scan directory <%s>\n", 
3862                        to_remove->name );
3863                return -4;
3864            }
3865            else if ( entries > 2 )
3866            {
3867                _spin_lock_release( &_fat.fat_lock );
3868                _printf("\n[FAT ERROR] in _fat_rename() : directory <%s> not empty\n", 
3869                        to_remove->name );
3870                return -5;
3871            }
3872        }
3873        else                       // it's a file
3874        {
3875            if ( to_remove->count ) 
3876            {
3877                _spin_lock_release( &_fat.fat_lock );
3878                _printf("\n[FAT ERROR] in _fat_rename() : file <%s> still referenced\n", 
3879                        to_remove->name );
3880                return -6;
3881            }
3882        }
3883    }
3884
3885#if GIET_DEBUG_FAT
3886if ( _get_proctime() > GIET_DEBUG_FAT )
3887_printf("\n[FAT DEBUG] _fat_rename() : P[%d,%d,%d] checked remove condition OK\n",
3888        x , y , p );
3889#endif
3890
3891    // get new last name / error checking already done by _get_inode_from_path()
3892    char  new_name[32];
3893    _get_last_name( new_path , new_name );
3894
3895    // allocate "new" inode
3896    new = _allocate_one_inode( new_name,
3897                               old->is_dir,
3898                               old->cluster,
3899                               old->size,
3900                               0,              // count
3901                               0,              // dentry
3902                               0 );            // no cache_allocate
3903 
3904    // give the "old" File-Cache to the "new inode
3905    new->levels = old->levels;
3906    new->cache  = old->cache;
3907
3908    // add "new" to "new_parent" directory File-Cache
3909    if ( _add_dir_entry( new , new_parent ) )
3910    {
3911        _spin_lock_release( &_fat.fat_lock );
3912        _printf("\n[FAT ERROR] in _fat_rename() : cannot add <%s> into <%s>\n",
3913                new->name , new_parent->name );
3914        return -7;
3915    }
3916
3917    // add "new" to "new_parent" directory in Inode-Tree
3918    _add_inode_in_tree( new , new_parent );
3919   
3920    // updates "new_parent" directory on device
3921    if ( _update_device_from_cache( new_parent->levels,
3922                                    new_parent->cache,
3923                                    new_parent->name ) )
3924    {
3925        _spin_lock_release( &_fat.fat_lock );
3926        _printf("\n[FAT ERROR] in _fat_rename() : cannot update <%s> on device\n",
3927                    new_parent->name );
3928        return -8;
3929    }
3930
3931    // remove "old" from "old_parent" File-Cache
3932    if ( _remove_dir_entry( old ) )
3933    {
3934        _spin_lock_release( &_fat.fat_lock );
3935        _printf("\n[FAT ERROR] in _fat_rename() : cannot remove <%s> from <%s>\n",
3936                old->name , old_parent->name );
3937        return -9;
3938    }
3939 
3940    // remove "old" inode from Inode-Tree
3941    _remove_inode_from_tree( old );
3942
3943    // release "old" inode
3944    _free( old );
3945
3946    // updates "old_parent" directory on device
3947    if ( _update_device_from_cache( old_parent->levels,
3948                                    old_parent->cache,
3949                                    old_parent->name ) )
3950    {
3951        _spin_lock_release( &_fat.fat_lock );
3952        _printf("\n[FAT ERROR] in _fat_rename() : cannot update <%s> on device\n",
3953                    old_parent->name );
3954        return -10;
3955    }
3956
3957    // remove "to_remove" from File System (if required)
3958    if ( to_remove )
3959    {
3960        if ( _remove_node_from_fs( to_remove ) )
3961        {
3962            _spin_lock_release( &_fat.fat_lock );
3963            _printf("\n[FAT ERROR] in _fat_rename() : cannot remove <%s> from FS\n",
3964                    to_remove->name );
3965            return -11;
3966        }
3967    }
3968
3969    // release lock
3970    _spin_lock_release( &_fat.fat_lock );
3971
3972    return 0;
3973}  // end _fat_rename()
3974
3975
3976
3977
3978/////////////////////////////////////////////////////////////////////////////////
3979// The following function implements the giet_fat_mkdir() system call.
3980// It creates in file system the directory specified by the "pathname" argument.
3981// The Inode-Tree is updated.
3982// One cluster is allocated to the new directory.
3983// The associated File-Cache is created.
3984// The FAT region on block device is updated.
3985// The DATA region on block device is updated.
3986/////////////////////////////////////////////////////////////////////////////////
3987// Returns 0 if success.
3988// Returns a negative value if error:
3989//   -1  : "Fat not initialised"
3990//   -2  : "Path to parent not found"
3991//   -3  : "One name in path too long"
3992//   -4  : "Directory already exist"
3993//   -5  : "No free cluster"
3994//   -6  : "Cannot update parent directory"
3995//   -7  : "Cannot update parent DATA region"
3996//   -8  : "Cannot update FAT region"
3997//   -9  : "Cannot update FS-INFO"
3998//   -10 : "Cannot update directory DATA region"
3999/////////////////////////////////////////////////////////////////////////////////
4000int _fat_mkdir( char* pathname )
4001{
4002    fat_inode_t*         inode;            // anonymous inode pointer
4003    fat_inode_t*         child;            // searched directory inode pointer
4004    fat_inode_t*         parent;           // parent directory inode pointer
4005
4006#if GIET_DEBUG_FAT
4007unsigned int procid  = _get_procid();
4008unsigned int x       = procid >> (Y_WIDTH + P_WIDTH);
4009unsigned int y       = (procid >> P_WIDTH) & ((1<<Y_WIDTH)-1);
4010unsigned int p       = procid & ((1<<P_WIDTH)-1);
4011if ( _get_proctime() > GIET_DEBUG_FAT )
4012_printf("\n[DEBUG FAT] _fat_mkdir() : P[%d,%d,%d] enters for path <%s>\n",
4013        x, y, p, pathname );
4014#endif
4015
4016    // checking FAT initialised
4017    if( _fat.initialised != FAT_INITIALISED )
4018    {
4019        _printf("\n[FAT ERROR] in _fat_mkdir() : FAT not initialised\n");
4020        return -1;
4021    }
4022
4023    // takes the lock
4024    _spin_lock_acquire( &_fat.fat_lock );
4025   
4026    // get inode
4027    unsigned int code = _get_inode_from_path( pathname , &inode );
4028
4029    if ( code == 2 ) 
4030    {
4031        _spin_lock_release( &_fat.fat_lock );
4032        _printf("\n[FAT ERROR] in _fat_mkdir() : path to parent not found"
4033                " for directory <%s>\n", pathname );
4034        return -2;
4035    }
4036    else if ( code == 3 ) 
4037    {
4038        _spin_lock_release( &_fat.fat_lock );
4039        _printf("\n[FAT ERROR] in _fat_mkdir() : one name in path too long"
4040                " for directory  <%s>\n", pathname );
4041        return -3;
4042    }
4043    else if ( code == 0 )
4044    {
4045        _spin_lock_release( &_fat.fat_lock );
4046        _printf("\n[FAT ERROR] in _fat_mkdir() : directory <%s> already exist\n",
4047                pathname );
4048        return -4;
4049    }
4050    else if ( code == 1 )   // directory not found => create
4051    {
4052        parent = inode;
4053
4054#if GIET_DEBUG_FAT
4055if ( _get_proctime() > GIET_DEBUG_FAT )
4056_printf("\n[DEBUG FAT] _fat_mkdir() : P[%d,%d,%d] create new directory <%s>\n",
4057        x , y , p , pathname );
4058#endif
4059
4060        // get directory name / error check already done by _get_inode_from_path()
4061        char name[32];       
4062        _get_last_name( pathname , name );
4063
4064        // allocate one cluster from FAT for the new directory
4065        unsigned int cluster;
4066        if ( _allocate_one_cluster( &cluster ) )
4067        {
4068            _spin_lock_release( &_fat.fat_lock );
4069            _printf("\n[FAT ERROR] in _fat_mkdir() : no free cluster"
4070                    " for directory <%s>\n" , pathname );
4071            return -5;
4072        }
4073
4074        // allocate a new inode and an empty Cache-File
4075        child = _allocate_one_inode( name,
4076                                     1,           // it's a directory
4077                                     cluster, 
4078                                     0,           // size not defined
4079                                     0,           // count
4080                                     0,           // dentry set by _add_dir_entry()
4081                                     1 );         // cache_allocate
4082
4083        // introduce inode in Inode-Tree
4084        _add_inode_in_tree( child , parent );
4085 
4086        // allocate and initialise one 4 Kbytes buffer and associated descriptor
4087        _allocate_one_buffer( child,
4088                              0,            // cluster_id,
4089                              cluster );
4090
4091        _add_special_directories( child, 
4092                                  parent );
4093
4094        // add an entry in the parent directory Cache_file
4095        if ( _add_dir_entry( child , parent ) )
4096        { 
4097            _spin_lock_release( &_fat.fat_lock );
4098            _printf("\n[FAT ERROR] in _fat_mkdir() : cannot update parent directory"
4099                    " for directory <%s>\n" , pathname );
4100            return -6;
4101        } 
4102
4103        // update DATA region on block device for parent directory
4104        if ( _update_device_from_cache( parent->levels,
4105                                        parent->cache,
4106                                        parent->name ) )
4107        {
4108            _spin_lock_release( &_fat.fat_lock );
4109            _printf("\n[FAT ERROR] in _fat_mkdir() : cannot update DATA region "
4110                    " for parent of directory <%s>\n", pathname );
4111            return -7;
4112        }
4113
4114        // update FAT region on block device
4115        if ( _update_device_from_cache( _fat.fat_cache_levels,
4116                                        _fat.fat_cache_root,
4117                                        "FAT" ) )
4118        {
4119            _spin_lock_release( &_fat.fat_lock );
4120            _printf("\n[FAT ERROR] in _fat_mkdir() : cannot update FAT region"
4121                    " for directory <%s>\n", pathname );
4122            return -8;
4123        }
4124
4125        // update FS_INFO sector
4126        if ( _update_fs_info() )
4127        {
4128            _spin_lock_release( &_fat.fat_lock );
4129            _printf("\n[FAT ERROR] in _fat_mkdir() : cannot update FS-INFO"
4130                    " for directory <%s>\n", pathname );
4131            return -9;
4132        }
4133
4134        // update DATA region on block device for the new directory
4135        if ( _update_device_from_cache( child->levels,   
4136                                        child->cache,
4137                                        child->name ) )
4138        {
4139            _spin_lock_release( &_fat.fat_lock );
4140            _printf("\n[FAT ERROR] in _fat_mkdir() : cannot update DATA region"
4141                    " for directory <%s>\n", pathname );
4142            return -10;
4143        }
4144    }  // end create directory
4145
4146    // release lock
4147    _spin_lock_release( &_fat.fat_lock );
4148
4149    return 0;
4150}  // end _fat_mkdir()
4151
4152
4153
4154
4155
4156/////////////////////////////////////////////////////////////////////////////////
4157// The following function implements the giet_fat_list() system call.
4158// It displays the content of a directory identified by the "pathname" argument.
4159// It returns an error code if the pathname is not a directory.
4160/////////////////////////////////////////////////////////////////////////////////
4161// Returns 0 if success.
4162// Returns a negative value if error:
4163//   -1  : "FAT not initialised
4164//   -2  : "Directory not found"
4165//   -3  : "Name in path too long
4166//   -4  : "Not a directory"
4167//   -5  : "Cannot access directory"
4168/////////////////////////////////////////////////////////////////////////////////
4169int _fat_list( char*  pathname )
4170{
4171    fat_inode_t*  inode;
4172
4173    // checking FAT initialised
4174    if( _fat.initialised != FAT_INITIALISED )
4175    {
4176        _printf("\n[FAT ERROR] in _fat_list() : FAT not initialised\n");
4177        return -1;
4178    }
4179
4180#if GIET_DEBUG_FAT
4181unsigned int procid  = _get_procid();
4182unsigned int x       = procid >> (Y_WIDTH + P_WIDTH);
4183unsigned int y       = (procid >> P_WIDTH) & ((1<<Y_WIDTH)-1);
4184unsigned int p       = procid & ((1<<P_WIDTH)-1);
4185if ( _get_proctime() > GIET_DEBUG_FAT )
4186_printf("\n[DEBUG FAT] _fat_list() : P[%d,%d,%d] enters for path <%s>\n",
4187        x, y, p, pathname );
4188#endif
4189
4190    // get inode
4191    unsigned int code = _get_inode_from_path( pathname , &inode );
4192
4193    if ( (code == 1) || (code == 2) ) 
4194    {
4195        _printf("\n[FAT ERROR] in _fat_list() : directory <%s> not found\n", pathname );
4196        return -2;
4197    }
4198    if ( code == 3 )
4199    {
4200        _printf("\n[FAT ERROR] in _fat_list() : name too long in path <%s>\n", pathname );
4201        return -3;
4202    }
4203
4204    // check found inode is a directory
4205    if ( inode->is_dir == 0 )
4206    {
4207        _printf("\n[FAT ERROR] in _fat_list() : <%s> is not a directory\n", pathname );
4208        return -4;
4209    }
4210
4211#if GIET_DEBUG_FAT
4212if ( _get_proctime() > GIET_DEBUG_FAT )
4213_printf("\n[DEBUG FAT] _fat_list() : P[%d,%d,%d] found inode for path <%s>\n",
4214        x, y, p, pathname );
4215#endif
4216
4217    // scan directory up to end of directory / two embedded loops :
4218    // - loop on the clusters allocated to the directory
4219    // - loop on the directory entries in each 4 Kbytes buffer
4220    unsigned char*     buffer; 
4221    fat_cache_desc_t*  pdesc;
4222    unsigned int       cluster_id = 0;     // cluster index in directory
4223    unsigned int       offset     = 0;     // position in scanned buffer
4224    unsigned int       lfn        = 0;     // number of lfn entries
4225    unsigned int       nb_entries = 0;     // number of directory entries
4226    unsigned int       done       = 0;     // end of directory found
4227    unsigned int       attr;               // ATTR field value
4228    unsigned int       ord;                // ORD field value
4229    char               lfn1[16];           // temporary buffer for string in LFN1
4230    char               lfn2[16];           // temporary buffer for string in LFN2
4231    char               lfn3[16];           // temporary buffer for string in LFN3
4232    char               name[36];           // directory entry full name
4233    unsigned int       cluster;            // directory entry cluster index
4234    unsigned int       size;               // directory entry size
4235    unsigned int       is_dir;             // directory entry is a directory
4236    unsigned int       is_vid;             // directory entry is volume_id
4237
4238    // TODO : define a method to transfer this information to user mode
4239    _printf("\n<%s>   cluster = %x / lba = %x\n", pathname ,
4240            inode->cluster , _cluster_to_lba( inode->cluster) );
4241
4242    while ( done == 0 )
4243    {
4244        // get one 4 Kytes buffer
4245        if ( _get_buffer_from_cache( inode,
4246                                     cluster_id,
4247                                     &pdesc ) ) 
4248        {
4249            _printf("\n[FAT ERROR] in _fat_list() : cannot access <%s>\n", pathname );
4250            return -5;
4251        }
4252        buffer = pdesc->buffer;
4253
4254        // scan this 4 Kbytes buffer
4255        while ( (offset < 4096)  && (done == 0) )
4256        {
4257            attr = _read_entry( DIR_ATTR , buffer + offset , 0 );   
4258            ord  = _read_entry( LDIR_ORD , buffer + offset , 0 );
4259
4260            if (ord == NO_MORE_ENTRY)                 // no more entry in directory => break
4261            {
4262                done = 1;
4263            }
4264            else if ( ord == FREE_ENTRY )             // free entry => skip
4265            {
4266                offset = offset + 32;
4267            }
4268            else if ( attr == ATTR_LONG_NAME_MASK )   // LFN entry => get partial names
4269            {
4270                unsigned int seq = ord & 0x3;
4271                lfn = (seq > lfn) ? seq : lfn;   
4272                if      ( seq == 1 ) _get_name_from_long( buffer + offset, lfn1 );
4273                else if ( seq == 2 ) _get_name_from_long( buffer + offset, lfn2 );
4274                else if ( seq == 3 ) _get_name_from_long( buffer + offset, lfn3 );
4275                offset = offset + 32;
4276            }
4277            else                                 // NORMAL entry
4278            {
4279                if      ( lfn == 0 )
4280                {
4281                    _get_name_from_short( buffer + offset , name );
4282                }
4283                else if ( lfn == 1 )
4284                {
4285                    _strcpy( name , lfn1 );
4286                }   
4287                else if ( lfn == 2 ) 
4288                {
4289                    _strcpy( name      , lfn1 );
4290                    _strcpy( name + 13 , lfn2 );
4291                }
4292                else if ( lfn == 3 ) 
4293                {
4294                    _strcpy( name      , lfn1 );
4295                    _strcpy( name + 13 , lfn2 );
4296                    _strcpy( name + 26 , lfn3 );
4297                }
4298                   
4299                is_dir  = ((attr & ATTR_DIRECTORY) == ATTR_DIRECTORY);
4300                is_vid  = ((attr & ATTR_VOLUME_ID) == ATTR_VOLUME_ID);
4301                size    = (_read_entry( DIR_FILE_SIZE   , buffer + offset , 1 )      ) ;
4302                cluster = (_read_entry( DIR_FST_CLUS_HI , buffer + offset , 1 ) << 16) |
4303                          (_read_entry( DIR_FST_CLUS_LO , buffer + offset , 1 )      ) ;
4304
4305                if ( is_vid == 0 )
4306                {
4307                    // TODO : define a method to transfer this information to user mode
4308                    if (is_dir) _printf("  DIR  | size = %X | cluster = %X | %s\n",
4309                                        size , cluster, name );
4310                    else        _printf("  FILE | size = %X | cluster = %X | %s\n",
4311                                        size , cluster, name );
4312                    nb_entries++;
4313                }
4314               
4315                offset = offset + 32;
4316                lfn    = 0;
4317            }
4318        }  // end loop on directory entries
4319
4320        if ( done == 0 )
4321        {
4322            cluster_id++;
4323            offset = 0;
4324        }
4325    }  // end loop on buffers
4326
4327    // TODO : define a method to transfer this information to user mode
4328    _printf("  total = %d entries\n", nb_entries );
4329
4330    return 0;
4331} // end _fat_list()
4332
4333
4334
4335
4336
4337///////////////////////////////////////////////////////////////////////////////
4338// This functiond load a file identified by the "pathname" argument into the
4339// memory buffer defined by the "buffer_vbase" and "buffer_size" arguments.
4340// It is intended to be called by the boot-loader, as it does not use the
4341// dynamically allocated FAT structures (Inode-Tree, Fat_Cache or File-Cache,
4342// File-Descriptor-Array).
4343// It uses only the 512 bytes buffer defined in the FAT descriptor.
4344///////////////////////////////////////////////////////////////////////////////
4345// Returns  0 if success.
4346// Returns negative value if error:
4347//  -1  : "FAT not initialised"
4348//  -2  : "File not found"
4349//  -3  : "Buffer too small"
4350//  -4  : "Cannot access block device"
4351//  -5  : "Cannot access FAT on block device"
4352///////////////////////////////////////////////////////////////////////////////
4353int _fat_load_no_cache( char*        pathname,
4354                        unsigned int buffer_vbase, 
4355                        unsigned int buffer_size ) 
4356{
4357    // checking FAT initialised
4358    if( _fat.initialised != FAT_INITIALISED )
4359    {
4360        _printf("\n[FAT ERROR] in _fat_load_no_cache() : FAT not initialised\n");
4361        return -1;
4362    }
4363
4364    unsigned int  file_size;
4365    unsigned int  cluster;
4366
4367#if GIET_DEBUG_FAT
4368unsigned int procid  = _get_procid();
4369unsigned int x       = procid >> (Y_WIDTH + P_WIDTH);
4370unsigned int y       = (procid >> P_WIDTH) & ((1<<Y_WIDTH)-1);
4371unsigned int p       = procid & ((1<<P_WIDTH)-1);
4372if ( _get_proctime() > GIET_DEBUG_FAT )
4373_printf("\n[DEBUG FAT] _fat_load_no_cache() : P[%d,%d,%d] enters for file <%s>\n",
4374        x , y , p , pathname );
4375#endif
4376
4377    // get file size, and cluster index in FAT
4378    if ( _file_info_no_cache( pathname,
4379                              &cluster,
4380                              &file_size ) )
4381    {
4382        _printf("\n[FAT ERROR] in _fat_load_no_cache() : file <%s> not found\n",
4383        pathname );
4384        return -2;
4385    }
4386
4387    // check buffer size
4388    if ( file_size > buffer_size )
4389    {
4390        _printf("\n[FAT ERROR] in _fat_load_no_cache() : buffer too small : "
4391                "file_size = %x / buffer_size = %x", file_size , buffer_size );
4392        return -3;
4393    }
4394
4395    // compute total number of clusters to read
4396    unsigned int nb_clusters = file_size >> 12;
4397    if ( file_size & 0xFFF ) nb_clusters++;
4398
4399    // initialise buffer address
4400    unsigned int dst = buffer_vbase;
4401
4402    // loop on the clusters containing the file
4403    while ( nb_clusters > 0 )
4404    {
4405        unsigned int lba = _cluster_to_lba( cluster );
4406
4407        if( _fat_ioc_access( 0,         // no descheduling
4408                             1,         // read
4409                             lba, 
4410                             dst, 
4411                             8 ) )      // 8 blocks
4412        {
4413            _printf("\n[FAT ERROR] in _fat_no _cache_read() : cannot load lba %x", lba );
4414            return -4;
4415        }
4416         
4417
4418        // compute next cluster index
4419        unsigned int next;
4420        if ( _next_cluster_no_cache( cluster , &next ) )
4421        {
4422            _printf("\n[FAT ERROR] in _fat_no _cache_read() : cannot get next cluster "
4423                    " for cluster = %x\n", cluster );
4424            return -5;
4425        }
4426       
4427        // update variables for next iteration
4428        nb_clusters = nb_clusters - 1;
4429        dst         = dst + 4096;
4430        cluster     = next;
4431    }
4432         
4433#if GIET_DEBUG_FAT
4434if ( _get_proctime() > GIET_DEBUG_FAT )
4435_printf("\n[DEBUG FAT] _fat_load_no_cache() : P[%d,%d,%d] loaded <%s> at vaddr = %x"
4436        " / size = %x\n", x , y , p , pathname , buffer_vbase , file_size );
4437#endif
4438
4439    return 0;
4440}  // end _fat_load_no_cache()
4441
4442
4443
4444// Local Variables:
4445// tab-width: 4
4446// c-basic-offset: 4
4447// c-file-offsets:((innamespace . 0)(inline-open . 0))
4448// indent-tabs-mode: nil
4449// End:
4450// vim: filetype=c:expandtab:shiftwidth=4:tabstop=4:softtabstop=4
4451
Note: See TracBrowser for help on using the repository browser.