| 1 | #include <fs/fat.h> |
| 2 | #include <stdint.h> |
| 3 | |
| 4 | uint32_t fat_alloc_cluster(struct fat_fs *fs) { |
| 5 | uint32_t total_clusters = fs->total_clusters; |
| 6 | for (uint32_t cluster = 2; cluster < total_clusters + 2; cluster++) { |
| 7 | uint32_t entry = fat_read_fat_entry(fs, cluster); |
| 8 | if (entry == 0x00000000) { |
| 9 | fat_write_fat_entry(fs, cluster, value: fat_eoc(fs)); |
| 10 | fs->last_alloc_cluster = cluster; |
| 11 | |
| 12 | if (fs->free_clusters != 0xFFFFFFFF && fs->free_clusters > 0) |
| 13 | fs->free_clusters--; |
| 14 | |
| 15 | fat_write_fsinfo(fs); |
| 16 | return cluster; |
| 17 | } |
| 18 | } |
| 19 | return 0; |
| 20 | } |
| 21 | |
| 22 | void fat_free_chain(struct fat_fs *fs, uint32_t start_cluster) { |
| 23 | if (!start_cluster) |
| 24 | return; // no-op |
| 25 | |
| 26 | uint32_t cluster = start_cluster; |
| 27 | uint32_t freed = 0; |
| 28 | |
| 29 | while (!fat_is_eoc(fs, cluster)) { |
| 30 | uint32_t next = fat_read_fat_entry(fs, cluster); |
| 31 | fat_write_fat_entry(fs, cluster, value: 0x00000000); |
| 32 | freed++; |
| 33 | |
| 34 | if (next == cluster || fat_is_eoc(fs, cluster: next)) |
| 35 | break; |
| 36 | |
| 37 | cluster = next; |
| 38 | } |
| 39 | |
| 40 | fat_write_fat_entry(fs, cluster, value: 0x00000000); |
| 41 | |
| 42 | if (fs->free_clusters != 0xFFFFFFFF) |
| 43 | fs->free_clusters += freed; |
| 44 | |
| 45 | fat_write_fsinfo(fs); |
| 46 | } |
| 47 | |