summaryrefslogtreecommitdiff
path: root/bio.c
blob: 49b52c983999ca2976a2caee9ec0343e870851a0 (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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include "types.h"
#include "param.h"
#include "x86.h"
#include "mmu.h"
#include "proc.h"
#include "defs.h"
#include "spinlock.h"
#include "buf.h"

struct buf buf[NBUF];
struct spinlock buf_table_lock;

// linked list of all buffers, through prev/next.
// bufhead->next is most recently used.
// bufhead->tail is least recently used.
struct buf bufhead;

void
binit(void)
{
  struct buf *b;

  initlock(&buf_table_lock, "buf_table");

  bufhead.prev = &bufhead;
  bufhead.next = &bufhead;
  for(b = buf; b < buf+NBUF; b++){
    b->next = bufhead.next;
    b->prev = &bufhead;
    bufhead.next->prev = b;
    bufhead.next = b;
  }
}

struct buf *
getblk(uint dev, uint sector)
{
  struct buf *b;

  acquire(&buf_table_lock);

  while(1){
    for(b = bufhead.next; b != &bufhead; b = b->next)
      if((b->flags & (B_BUSY|B_VALID)) && b->dev == dev && b->sector == sector)
        break;

    if(b != &bufhead){
      if(b->flags & B_BUSY){
        sleep(buf, &buf_table_lock);
      } else {
        b->flags |= B_BUSY;
        release(&buf_table_lock);
        return b;
      }
    } else {
      for(b = bufhead.prev; b != &bufhead; b = b->prev){
        if((b->flags & B_BUSY) == 0){
          b->flags = B_BUSY;
          b->dev = dev;
          b->sector = sector;
          release(&buf_table_lock);
          return b;
        }
      }
      panic("getblk: no buffers");
    }
  }
}

struct buf *
bread(uint dev, uint sector)
{
  void *c;
  struct buf *b;
  extern struct spinlock ide_lock;

  b = getblk(dev, sector);
  if(b->flags & B_VALID)
    return b;

  acquire(&ide_lock);
  c = ide_start_rw(dev & 0xff, sector, b->data, 1, 1);
  sleep (c, &ide_lock);
  ide_finish(c);
  b->flags |= B_VALID;
  release(&ide_lock);

  return b;
}

void
bwrite(struct buf *b, uint sector)
{
  void *c;
  extern struct spinlock ide_lock;

  acquire(&ide_lock);
  c = ide_start_rw(b->dev & 0xff, sector, b->data, 1, 0);
  sleep (c, &ide_lock);
  ide_finish(c);
  b->flags |= B_VALID;
  release(&ide_lock);
}

void
brelse(struct buf *b)
{
  if((b->flags & B_BUSY) == 0)
    panic("brelse");
  
  acquire(&buf_table_lock);

  b->next->prev = b->prev;
  b->prev->next = b->next;
  b->next = bufhead.next;
  b->prev = &bufhead;
  bufhead.next->prev = b;
  bufhead.next = b;

  b->flags &= ~B_BUSY;
  wakeup(buf);

  release(&buf_table_lock);
}