summaryrefslogtreecommitdiff
path: root/src/kernel/fat.c
blob: e574da594ca170670d9d2931adbaf10f802df6c8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "fat.h"
#include "ata.h"
#include "panic.h"
#include "fs.h"

void load_fat() {
  read_sectors(FAT_INFO->reserved_sectors, FAT_INFO->sectors_per_fat, FAT);
}

bool check_fat_name(uint8_t *fname, uint8_t *sname) {
  panic("Not implemented (check_fat_name)");
}

bool check_fat_names(uint8_t *lname, uint8_t *rname) {
  return (* (uint32_t *)lname       ==  *(uint32_t *)rname) &&
         (*((uint32_t *)lname +  1) == *((uint32_t *)rname +  1)) &&
         (*((uint16_t *)lname +  4) == *((uint16_t *)rname +  4)) &&
         (*(            lname + 10) == *(            rname + 10));
}

struct directory_entry buffer[16];
uint16_t dir_start, buffer_from;


void load_root() {
  dir_start = FAT_INFO->reserved_sectors + FAT_INFO->sectors_per_fat;
}

struct directory_entry *load_subentry(uint8_t *name) {
  struct directory_entry *ptr = buffer;
  uint16_t dir_current = dir_start;
  do
    if (((ptr == buffer + 16) && !read_sectors(buffer_from = dir_current++, 1, ptr = buffer)) || !ptr->name[0])
      return 0;
  while (!check_fat_name(ptr->name, name));
  return ptr;
}

bool load_subdir(uint8_t *name) {
  struct directory_entry *e = load_subentry(name);
  if (!e)
    return true;
  dir_start = e->first_cluster;
  return false;
}

struct directory_entry *load_entry(uint8_t *path) {
  load_root();
  for (uint8_t *ptr = path; ptr; ++ptr)
    if (*ptr = '/') {
      *ptr = 0;
      if (load_subdir(path))
        return 0;
      path = ptr + 1;
    }
  return load_subentry(path);
}

bool get_entry(uint8_t *path, struct directory_entry *at) {
  struct directory_entry *e = load_entry(path);
  if (!e)
    return true;
  *at = *e;
  return false;
}

bool update_entry(uint8_t *path, struct directory_entry *value) {
  struct directory_entry *e = load_entry(path);
  if (!e)
    return true;
  *e = *value;
  write_sectors(buffer_from, 1, buffer);
  return false;
}

bool create_entry(uint8_t *dir_path, struct directory_entry *value) {
  fs_handle h = fs_open(dir_path);
  struct directory_entry *check;
  while (fs_read(h, 32, check))
    if (check_fat_names(check->name, value->name)) {
      fs_close(h);
      return true;
    }
  fs_write(h, 32, value);
  fs_close(h);
  return false;
}