summaryrefslogtreecommitdiff
path: root/kernel/fs/buffer.c
blob: 99c3161a54468d5eae374d56c4ce34ccc94a0ff7 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <asm/interrupt.h>
#include <errno.h>
#include <kernel/con.h>
#include <kernel/fs.h>
#include <stdint.h>
#include <string.h>

/* memory dedicated to the block cache */
/* TODO: start buffers at kernel end not 512K */
#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) {
  struct buffer **p = &mru;
  struct buffer *b;

  if(!device)
    return NULL;

  /* check if the requested block is already in the cache */
  while(b = *p) {
    if(b->b_device != device || b->b_block != block)
      goto next;
    /* remove the buffer from the list */
    if(lru == b && b->b_next)   lru = b->b_next;
    if(b->b_next)               b->b_next->b_prev = b->b_prev;
    if(b->b_prev)               b->b_prev->b_next = b->b_next;
    /* put the buffer back at the MRU end of the list */
    b->b_next = NULL;
    b->b_prev = mru;
    if(mru != b)
      mru->b_next = b;
    mru = b;
    cli();
    /* if the buffer exists but isn't populated. wait on it */
    if(!b->b_present) {
      sleep_on(&b->b_wait);
      printk("[buf] Waiting for buffer %04x:%04x to be populated...\n", b->b_device, b->b_block);
    }
    sti();
    printk("[buf] Fetched block %04x:%04x from cache\n", b->b_device, b->b_block);
    return b->b_device ? b : NULL;
next:
    p = &b->b_prev;
  }

  /*
   * otherwise, iterate through the least recently used
   * buffers, to find a buffer that isn't pending an
   * I/O operation, and read into it.
   */

  p = &lru;
  while(b = *p) {
    if(b->b_present || !b->b_device)
      break;
    p = &(*p)->b_next;
  }

  if(!b)
    return NULL;

  b->b_device = device;
  b->b_block = block;
  b->b_present = 0;
  block_read(b);
  wake_up(&b->b_wait);
  printk("[buf] Called driver to read block %04x:%04x\n", b->b_device, b->b_block);
  return b->b_device ? b : NULL;
}

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);
}