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

/* memory dedicated to the block cache */
#define BSTART 0x80000
#define BEND 0xA0000

static struct buffer *lru;
static struct buffer *mru;

struct buffer *buffer_get_block(uint16_t device, uint16_t block);

void buffer_init(void) {
  int c = 0;
  struct buffer *last = NULL;
  struct buffer *b = (struct buffer*) BSTART;
  void *d = (void*) (BEND - BLOCK_SIZE);

  while(d > (void*) b) {
    memset(b, 0, sizeof(struct buffer));

    b->b_data = d;
    b->b_prev = last;

    if(last)
      last->b_next = b;

    last = b;

    b = (struct buffer*) ((void*) b + sizeof(struct buffer));
    d = (void*) (d - (void*) BLOCK_SIZE);

    c++;
  }

  lru = (struct buffer*) BSTART;
  mru = last;

  printk("[buf] Buffers initialized (0x%x buffers in pool)\n", c);
}

struct buffer *buffer_get_block(uint16_t device, uint16_t block) {
  int ret;
  struct buffer **p = &mru;
  struct buffer *b;

  /* check if the requested block is already in the cache */
  while(*p) {
    if((*p)->b_device == device && (*p)->b_block == block) {
      /* put the buffer back at the MRU end of the list */
      (*p)->b_next = NULL;
      (*p)->b_prev = mru;
      mru = *p;
      return *p;
    }
    p = &(*p)->b_prev;
  }

  /* find a buffer at the end of the LRU list */
  b = lru;
  lru = lru->b_next;
  lru->b_prev = NULL;
  ret = block_read(b->b_data, block);
  /* abort if we failed to read in the block */
  if(ret < 0) {
    /* release the allocated buffer to the pool */
    lru->b_prev = b;
    b->b_next = lru;
    b->b_prev = NULL;
    lru = b;
    return NULL;
  }
  b->b_device = device;
  b->b_block = block;
  /* put the buffer back at the MRU end of the list */
  b->b_next = NULL;
  b->b_prev = mru;
  mru = b;
  return b;
}