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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include "types.h"
#include "param.h"
#include "fs.h"
int nblocks = 1009;
int ninodes = 100;
int fd;
struct superblock sb;
char zeroes[512];
uint freeblock;
void wsect(uint, void *);
void winode(uint, struct dinode *);
void rsect(uint sec, void *buf);
// convert to intel byte order
ushort
xshort(ushort x)
{
ushort y;
uchar *a = &y;
a[0] = x;
a[1] = x >> 8;
return y;
}
uint
xint(uint x)
{
uint y;
uchar *a = &y;
a[0] = x;
a[1] = x >> 8;
a[2] = x >> 16;
a[3] = x >> 24;
return y;
}
main(int argc, char *argv[])
{
int i;
struct dinode din;
char dbuf[512];
if(argc != 2){
fprintf(stderr, "Usage: mkfs fs.img\n");
exit(1);
}
if(sizeof(struct dinode) * IPB != 512){
fprintf(stderr, "sizeof(dinode) must divide 512\n");
exit(1);
}
fd = open(argv[1], O_RDWR|O_CREAT|O_TRUNC, 0666);
if(fd < 0){
perror(argv[1]);
exit(1);
}
sb.nblocks = xint(nblocks); // so whole disk is 1024 sectors
sb.ninodes = xint(ninodes);
freeblock = ninodes / IPB + 2;
for(i = 0; i < nblocks + (ninodes / IPB) + 3; i++)
wsect(i, zeroes);
wsect(1, &sb);
bzero(&din, sizeof(din));
din.type = xshort(T_DIR);
din.nlink = xshort(2);
din.size = xint(512);
din.addrs[0] = xint(freeblock++);
winode(1, &din);
bzero(dbuf, sizeof(dbuf));
((struct dirent *) dbuf)[0].inum = xshort(1);
strcpy(((struct dirent *) dbuf)[0].name, ".");
((struct dirent *) dbuf)[1].inum = xshort(1);
strcpy(((struct dirent *) dbuf)[1].name, "..");
wsect(din.addrs[0], dbuf);
exit(0);
}
void
wsect(uint sec, void *buf)
{
if(lseek(fd, sec * 512L, 0) != sec * 512L){
perror("lseek");
exit(1);
}
if(write(fd, buf, 512) != 512){
perror("write");
exit(1);
}
}
uint
i2b(uint inum)
{
return (inum / IPB) + 2;
}
void
winode(uint inum, struct dinode *ip)
{
char buf[512];
uint bn;
struct dinode *dip;
bn = i2b(inum);
rsect(bn, buf);
dip = ((struct dinode *) buf) + (inum % IPB);
*dip = *ip;
printf("bn %d off %d\n",
bn, (unsigned)dip - (unsigned) buf);
wsect(bn, buf);
}
void
rsect(uint sec, void *buf)
{
if(lseek(fd, sec * 512L, 0) != sec * 512L){
perror("lseek");
exit(1);
}
if(read(fd, buf, 512) != 512){
perror("read");
exit(1);
}
}
|