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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
|
#include <u.h>
#include <libc.h>
#include <auth.h>
#include <fcall.h>
#include <thread.h>
#include <9p.h>
static char Ebad[] = "something bad happened";
static char Enomem[] = "no memory";
typedef struct Ramfile Ramfile;
struct Ramfile {
char *data;
int ndata;
};
void
fsread(Req *r)
{
Ramfile *rf;
vlong offset;
long count;
rf = r->fid->file->aux;
offset = r->ifcall.offset;
count = r->ifcall.count;
/*print("read %ld %lld\n", *count, offset); */
if(offset >= rf->ndata){
r->ofcall.count = 0;
respond(r, nil);
return;
}
if(offset+count >= rf->ndata)
count = rf->ndata - offset;
memmove(r->ofcall.data, rf->data+offset, count);
r->ofcall.count = count;
respond(r, nil);
}
void
fswrite(Req *r)
{
void *v;
Ramfile *rf;
vlong offset;
long count;
rf = r->fid->file->aux;
offset = r->ifcall.offset;
count = r->ifcall.count;
if(offset+count >= rf->ndata){
v = realloc(rf->data, offset+count);
if(v == nil){
respond(r, Enomem);
return;
}
rf->data = v;
rf->ndata = offset+count;
r->fid->file->length = rf->ndata;
}
memmove(rf->data+offset, r->ifcall.data, count);
r->ofcall.count = count;
respond(r, nil);
}
void
fscreate(Req *r)
{
Ramfile *rf;
File *f;
if(f = createfile(r->fid->file, r->ifcall.name, r->fid->uid, r->ifcall.perm, nil)){
rf = emalloc9p(sizeof *rf);
f->aux = rf;
r->fid->file = f;
r->ofcall.qid = f->qid;
respond(r, nil);
return;
}
respond(r, Ebad);
}
void
fsopen(Req *r)
{
Ramfile *rf;
rf = r->fid->file->aux;
if(rf && (r->ifcall.mode&OTRUNC)){
rf->ndata = 0;
r->fid->file->length = 0;
}
respond(r, nil);
}
void
fsdestroyfile(File *f)
{
Ramfile *rf;
/*fprint(2, "clunk\n"); */
rf = f->aux;
if(rf){
free(rf->data);
free(rf);
}
}
Srv fs = {
.open= fsopen,
.read= fsread,
.write= fswrite,
.create= fscreate,
};
void
usage(void)
{
fprint(2, "usage: ramfs [-D] [-s srvname] [-m mtpt]\n");
exits("usage");
}
void
main(int argc, char **argv)
{
char *srvname = nil;
char *mtpt = nil;
Qid q;
fs.tree = alloctree(nil, nil, DMDIR|0777, fsdestroyfile);
q = fs.tree->root->qid;
ARGBEGIN{
case 'D':
chatty9p++;
break;
case 's':
srvname = EARGF(usage());
break;
case 'm':
mtpt = EARGF(usage());
break;
default:
usage();
}ARGEND;
if(argc)
usage();
if(chatty9p)
fprint(2, "ramsrv.nopipe %d srvname %s mtpt %s\n", fs.nopipe, srvname, mtpt);
if(srvname == nil && mtpt == nil)
sysfatal("you should at least specify a -s or -m option");
postmountsrv(&fs, srvname, mtpt, MREPL|MCREATE);
exits(0);
}
|