2 * 9P to FUSE translator. Acts as FUSE server, 9P client.
3 * Mounts 9P servers via FUSE kernel module.
5 * There are four procs in this threaded program
6 * (ignoring the one that runs main and then exits).
7 * The first proc reads FUSE requests from /dev/fuse.
8 * It sends the requests over a channel to a second proc,
9 * which serves the requests. Each request runs in a
10 * thread in that second proc. Those threads do write
11 * FUSE replies, which in theory might block, but in practice don't.
12 * The 9P interactions are handled by lib9pclient, which
13 * allocates two more procs, one for reading and one for
14 * writing the 9P connection. Thus the many threads in the
15 * request proc can do 9P interactions without blocking.
18 #define _GNU_SOURCE 1 /* for O_DIRECTORY on Linux */
26 #if defined(__linux__)
27 #define O_LARGEFILE 0100000 /* Sigh */
37 void fusedispatch(void*);
46 * The number of seconds that the kernel can cache
47 * returned file attributes. FUSE's default is 1.0.
48 * I haven't experimented with using 0.
50 double attrtimeout = 1.0;
53 * The number of seconds that the kernel can cache
54 * the returned entry nodeids returned by lookup.
55 * I haven't experimented with other values.
57 double entrytimeout = 1.0;
61 void init9p(char*, char*);
66 fprint(2, "usage: 9pfuse [-D] [-A attrtimeout] [-a aname] address mtpt\n");
70 void fusereader(void*);
73 threadmain(int argc, char **argv)
81 attrtimeout = atof(EARGF(usage()));
84 aname = EARGF(usage());
94 fmtinstall('F', fcallfmt);
95 fmtinstall('M', dirmodefmt);
96 fmtinstall('G', fusefmt);
98 setsid(); /* won't be able to use console, but can't be interrupted */
100 init9p(argv[0], aname);
103 fusechan = chancreate(sizeof(void*), 0);
104 proccreate(fusedispatch, nil, STACK);
105 sendp(fusechan, nil); /* sync */
107 proccreate(fusereader, nil, STACK);
109 * Now that we're serving FUSE, we can wait
110 * for the mount to finish and exit back to the user.
121 while((m = readfusemsg()) != nil)
124 fusemtpt = nil; /* no need to unmount */
129 init9p(char *addr, char *spec)
133 if((fd = dial(netmkaddr(addr, "tcp", "564"), nil, nil, nil)) < 0)
134 sysfatal("dial %s: %r", addr);
135 if((fsys = fsmount(fd, spec)) == nil)
136 sysfatal("fsmount: %r");
137 fsysroot = fsroot(fsys);
141 * FUSE uses nodeids to refer to active "struct inodes"
142 * (9P's unopened fids). FUSE uses fhs to refer to active
143 * "struct fuse_files" (9P's opened fids). The choice of
144 * numbers is up to us except that nodeid 1 is the root directory.
145 * We use the same number space for both and call the
146 * bookkeeping structure a FuseFid.
148 * FUSE requires nodeids to have associated generation
149 * numbers. If we reuse a nodeid, we have to bump the
150 * generation number to guarantee that the nodeid,gen
151 * combination is never reused.
153 * There are also inode numbers returned in directory reads
154 * and file attributes, but these do NOT need to match the nodeids.
155 * We use a combination of qid.path and qid.type as the inode
159 * TO DO: reference count the fids.
161 typedef struct Fusefid Fusefid;
171 /* directory read state */
180 Fusefid *freefusefidlist;
187 if((f = freefusefidlist) == nil){
188 f = emalloc(sizeof *f);
189 fusefid = erealloc(fusefid, (nfusefid+1)*sizeof *fusefid);
194 freefusefidlist = f->next;
202 freefusefid(Fusefid *f)
216 f->next = freefusefidlist;
222 _alloc(CFid *fid, int isnodeid)
228 ff->isnodeid = isnodeid;
230 return ff->id+2; /* skip 0 and 1 */
236 return _alloc(fid, 0);
239 allocnodeid(CFid *fid)
241 return _alloc(fid, 1);
245 lookupfusefid(uvlong id, int isnodeid)
248 if(id < 2 || id >= nfusefid+2)
250 ff = fusefid[(int)id-2];
251 if(ff->isnodeid != isnodeid)
257 _lookupcfid(uvlong id, int isnodeid)
261 if((ff = lookupfusefid(id, isnodeid)) == nil)
269 return _lookupcfid(fh, 0);
273 nodeid2fid(uvlong nodeid)
277 return _lookupcfid(nodeid, 1);
283 return q.path | ((uvlong)q.type<<56);
287 dir2attr(Dir *d, struct fuse_attr *attr)
289 attr->ino = qid2inode(d->qid);
290 attr->size = d->length;
291 attr->blocks = (d->length+8191)/8192;
292 attr->atime = d->atime;
293 attr->mtime = d->mtime;
294 attr->ctime = d->mtime; /* not right */
298 attr->mode = d->mode&0777;
300 attr->mode |= S_IFDIR;
302 attr->mode |= S_IFREG;
303 attr->nlink = 1; /* works for directories! - see FUSE FAQ */
304 attr->uid = getuid();
305 attr->gid = getgid();
310 f2timeout(double f, __u64 *s, __u32 *ns)
313 *ns = (f - (int)f)*1e9;
317 dir2attrout(Dir *d, struct fuse_attr_out *out)
319 f2timeout(attrtimeout, &out->attr_valid, &out->attr_valid_nsec);
320 dir2attr(d, &out->attr);
324 * Lookup. Walk to the name given as the argument.
325 * The response is a fuse_entry_out giving full stat info.
328 fuselookup(FuseMsg *m)
334 struct fuse_entry_out out;
337 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
338 replyfuseerrno(m, ESTALE);
341 if(strchr(name, '/')){
342 replyfuseerrno(m, ENOENT);
345 if((newfid = fswalk(fid, name)) == nil){
349 if((d = fsdirfstat(newfid)) == nil){
354 out.nodeid = allocnodeid(newfid);
355 ff = lookupfusefid(out.nodeid, 1);
356 out.generation = ff->gen;
357 f2timeout(attrtimeout, &out.attr_valid, &out.attr_valid_nsec);
358 f2timeout(entrytimeout, &out.entry_valid, &out.entry_valid_nsec);
359 dir2attr(d, &out.attr);
361 replyfuse(m, &out, sizeof out);
365 * Forget. Reference-counted clunk for nodeids.
366 * Does not send a reply.
367 * Each lookup response gives the kernel an additional reference
368 * to the returned nodeid. Forget says "drop this many references
369 * to this nodeid". Our fuselookup, when presented with the same query,
370 * does not return the same results (it allocates a new nodeid for each
371 * call), but if that ever changes, fuseforget already handles the ref
375 fuseforget(FuseMsg *m)
377 struct fuse_forget_in *in;
381 if((ff = lookupfusefid(m->hdr->nodeid, 1)) == nil)
383 if(ff->ref > in->nlookup){
384 ff->ref -= in->nlookup;
387 if(ff->ref < in->nlookup)
388 fprint(2, "bad count in forget\n");
395 * Replies with a fuse_attr_out structure giving the
396 * attr for the requested nodeid in out.attr.
397 * Out.attr_valid and out.attr_valid_nsec give
398 * the amount of time that the attributes can
401 * Empirically, though, if I run ls -ld on the root
402 * twice back to back, I still get two getattrs,
403 * even with a one second attribute timeout!
406 fusegetattr(FuseMsg *m)
409 struct fuse_attr_out out;
412 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
413 replyfuseerrno(m, ESTALE);
416 if((d = fsdirfstat(fid)) == nil){
420 memset(&out, 0, sizeof out);
421 dir2attrout(d, &out);
423 replyfuse(m, &out, sizeof out);
428 * FUSE treats the many Unix attribute setting routines
429 * more or less like 9P does, with a single message.
432 fusesetattr(FuseMsg *m)
436 struct fuse_setattr_in *in;
437 struct fuse_attr_out out;
440 if(in->valid&FATTR_FH){
441 if((fid = fh2fid(in->fh)) == nil){
442 replyfuseerrno(m, ESTALE);
446 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
447 replyfuseerrno(m, ESTALE);
451 * Special case: Linux issues a size change to
452 * truncate a file before opening it OTRUNC.
453 * Synthetic file servers (e.g., plumber) honor
454 * open(OTRUNC) but not wstat.
456 if(in->valid == FATTR_SIZE && in->size == 0){
457 if((nfid = fswalk(fid, nil)) == nil){
461 if(fsfopen(nfid, OWRITE|OTRUNC) < 0){
472 if(in->valid&FATTR_SIZE)
474 if(in->valid&FATTR_ATIME)
476 if(in->valid&FATTR_MTIME)
478 if(in->valid&FATTR_MODE)
480 if((in->valid&FATTR_UID) || (in->valid&FATTR_GID)){
482 * I can't be bothered with these yet.
484 replyfuseerrno(m, EPERM);
487 if(fsdirfwstat(fid, &d) < 0){
492 if((dd = fsdirfstat(fid)) == nil){
496 memset(&out, 0, sizeof out);
497 dir2attrout(dd, &out);
499 replyfuse(m, &out, sizeof out);
503 _fuseopenfid(uvlong nodeid, int isdir, int openmode, int *err)
507 if((fid = nodeid2fid(nodeid)) == nil){
511 if(isdir && !(fsqid(fid).type&QTDIR)){
515 if(openmode != OREAD && fsqid(fid).type&QTDIR){
520 /* Clone fid to get one we can open. */
521 newfid = fswalk(fid, nil);
523 *err = errstr2errno();
527 if(fsfopen(newfid, openmode) < 0){
528 *err = errstr2errno();
538 * Argument is a struct fuse_open_in.
539 * The mode field is ignored (presumably permission bits)
540 * and flags is the open mode.
541 * Replies with a struct fuse_open_out.
544 _fuseopen(FuseMsg *m, int isdir)
546 struct fuse_open_in *in;
547 struct fuse_open_out out;
549 int openmode, flags, err;
555 flags &= ~(O_DIRECTORY|O_NONBLOCK|O_LARGEFILE);
561 * Could translate but not standard 9P:
562 * O_DIRECT -> ODIRECT
563 * O_NONBLOCK -> ONONBLOCK
564 * O_APPEND -> OAPPEND
567 fprint(2, "unexpected open flags %#uo", (uint)in->flags);
568 replyfuseerrno(m, EACCES);
571 if((fid = _fuseopenfid(m->hdr->nodeid, isdir, openmode, &err)) == nil){
572 replyfuseerrno(m, err);
575 out.fh = allocfh(fid);
576 out.open_flags = FOPEN_DIRECT_IO; /* no page cache */
577 replyfuse(m, &out, sizeof out);
587 fuseopendir(FuseMsg *m)
596 _fusecreate(uvlong nodeid, char *name, int perm, int ismkdir, int omode, struct fuse_entry_out *out, int *err)
598 CFid *fid, *newfid, *newfid2;
602 if((fid = nodeid2fid(nodeid)) == nil){
609 if(ismkdir && omode != OREAD){
613 if((newfid = fswalk(fid, nil)) == nil){
614 *err = errstr2errno();
617 if(fsfcreate(newfid, name, omode, perm) < 0){
618 *err = errstr2errno();
622 if((d = fsdirfstat(newfid)) == nil){
623 *err = errstr2errno();
628 * This fid is no good, because it's open.
629 * We need an unopened fid. Sigh.
631 if((newfid2 = fswalk(fid, name)) == nil){
632 *err = errstr2errno();
637 out->nodeid = allocnodeid(newfid2);
638 ff = lookupfusefid(out->nodeid, 1);
639 out->generation = ff->gen;
640 f2timeout(attrtimeout, &out->attr_valid, &out->attr_valid_nsec);
641 f2timeout(entrytimeout, &out->entry_valid, &out->entry_valid_nsec);
642 dir2attr(d, &out->attr);
648 fusemkdir(FuseMsg *m)
650 struct fuse_mkdir_in *in;
651 struct fuse_entry_out out;
657 name = (char*)(in+1);
658 if((fid = _fusecreate(m->hdr->nodeid, name, in->mode, 1, OREAD, &out, &err)) == nil){
659 replyfuseerrno(m, err);
662 /* Toss the open fid. */
664 replyfuse(m, &out, sizeof out);
668 fusecreate(FuseMsg *m)
670 struct fuse_open_in *in;
671 struct fuse_create_out out;
673 int err, openmode, flags;
678 openmode = in->flags&3;
680 flags &= ~(O_DIRECTORY|O_NONBLOCK|O_LARGEFILE);
681 flags &= ~(O_CREAT|O_TRUNC); /* huh? */
683 fprint(2, "bad mode %#uo\n", in->flags);
684 replyfuseerrno(m, EACCES);
687 name = (char*)(in+1);
688 if((fid = _fusecreate(m->hdr->nodeid, name, in->mode, 0, openmode, &out.e, &err)) == nil){
689 replyfuseerrno(m, err);
692 out.o.fh = allocfh(fid);
693 out.o.open_flags = FOPEN_DIRECT_IO; /* no page cache */
694 replyfuse(m, &out, sizeof out);
699 * Lib9pclient implements this just as Plan 9 does,
700 * by opening the file (or not) and then closing it.
703 fuseaccess(FuseMsg *m)
705 struct fuse_access_in *in;
720 if(in->mask >= nelem(a2o)){
721 replyfuseerrno(m, EINVAL);
724 omode = a2o[in->mask];
725 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
726 replyfuseerrno(m, ESTALE);
729 if(fsqid(fid).type&QTDIR)
731 if((fid = _fuseopenfid(m->hdr->nodeid, 0, omode, &err)) == nil){
732 replyfuseerrno(m, err);
736 replyfuse(m, nil, 0);
741 * Equivalent of clunk for file handles.
742 * in->flags is the open mode used in Open or Opendir.
745 fuserelease(FuseMsg *m)
747 struct fuse_release_in *in;
751 if((ff = lookupfusefid(in->fh, 0)) != nil)
754 fprint(2, "fuserelease: fh not found\n");
755 replyfuse(m, nil, 0);
759 fusereleasedir(FuseMsg *m)
766 * Read from file handle in->fh at offset in->offset for size in->size.
767 * We truncate size to maxwrite just to keep the buffer reasonable.
775 struct fuse_read_in *in;
778 if((fid = fh2fid(in->fh)) == nil){
779 replyfuseerrno(m, ESTALE);
786 n = fspread(fid, buf, n, in->offset);
791 replyfuse(m, buf, n);
797 * Read from file handle in->fh at offset in->offset for size in->size.
798 * We truncate size to maxwrite just to keep the buffer reasonable.
799 * We assume 9P directory read semantics: a read at offset 0 rewinds
800 * and a read at any other offset starts where we left off.
801 * If it became necessary, we could implement a crude seek
802 * or cache the entire list of directory entries.
803 * Directory entries read from 9P but not yet handed to FUSE
804 * are stored in m->d,nd,d0.
806 int canpack(Dir*, uvlong, uchar**, uchar*);
808 fusereaddir(FuseMsg *m)
810 struct fuse_read_in *in;
816 if((ff = lookupfusefid(in->fh, 0)) == nil){
817 replyfuseerrno(m, ESTALE);
821 fsseek(ff->fid, 0, 0);
835 if(!canpack(ff->d, ff->off, &p, ep))
844 if((ff->nd = fsdirread(ff->fid, &ff->d0)) < 0){
854 replyfuse(m, buf, p - buf);
859 canpack(Dir *d, uvlong off, uchar **pp, uchar *ep)
862 struct fuse_dirent *de;
866 size = FUSE_NAME_OFFSET + strlen(d->name);
870 if(size+pad > ep - p)
872 de = (struct fuse_dirent*)p;
873 de->ino = qid2inode(d->qid);
875 de->namelen = strlen(d->name);
876 memmove(de->name, d->name, de->namelen);
878 memset(de->name+de->namelen, 0, pad);
885 * Write from file handle in->fh at offset in->offset for size in->size.
886 * Don't know what in->write_flags means.
888 * Apparently implementations are allowed to buffer these writes
889 * and wait until Flush is sent, but FUSE docs say flush may be
890 * called zero, one, or even more times per close. So better do the
891 * actual writing here. Also, errors that happen during Flush just
892 * show up in the close() return status, which no one checks anyway.
895 fusewrite(FuseMsg *m)
897 struct fuse_write_in *in;
898 struct fuse_write_out out;
905 if((fid = fh2fid(in->fh)) == nil){
906 replyfuseerrno(m, ESTALE);
909 if(in->size > fusemaxwrite){
910 replyfuseerrno(m, EINVAL);
913 n = fspwrite(fid, a, in->size, in->offset);
919 replyfuse(m, &out, sizeof out);
923 * Flush. Supposed to flush any buffered writes. Don't use this.
925 * Flush is a total crock. It gets called on close() of a file descriptor
926 * associated with this open file. Some open files have multiple file
927 * descriptors and thus multiple closes of those file descriptors.
928 * In those cases, Flush is called multiple times. Some open files
929 * have file descriptors that are closed on process exit instead of
930 * closed explicitly. For those files, Flush is never called.
931 * Even more amusing, Flush gets called before close() of read-only
932 * file descriptors too!
934 * This is just a bad idea.
937 fuseflush(FuseMsg *m)
939 replyfuse(m, nil, 0);
946 _fuseremove(FuseMsg *m, int isdir)
952 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
953 replyfuseerrno(m, ESTALE);
956 if(strchr(name, '/')){
957 replyfuseerrno(m, ENOENT);
960 if((newfid = fswalk(fid, name)) == nil){
964 if(isdir && !(fsqid(newfid).type&QTDIR)){
965 replyfuseerrno(m, ENOTDIR);
969 if(!isdir && (fsqid(newfid).type&QTDIR)){
970 replyfuseerrno(m, EISDIR);
974 if(fsfremove(newfid) < 0){
978 replyfuse(m, nil, 0);
982 fuseunlink(FuseMsg *m)
988 fusermdir(FuseMsg *m)
996 * FUSE sends the nodeid for the source and destination
997 * directory and then the before and after names as strings.
998 * 9P can only do the rename if the source and destination
999 * are the same. If the same nodeid is used for source and
1000 * destination, we're fine, but if FUSE gives us different nodeids
1001 * that happen to correspond to the same directory, we have
1002 * no way of figuring that out. Let's hope it doesn't happen too often.
1005 fuserename(FuseMsg *m)
1007 struct fuse_rename_in *in;
1008 char *before, *after;
1013 if(in->newdir != m->hdr->nodeid){
1014 replyfuseerrno(m, EXDEV);
1017 before = (char*)(in+1);
1018 after = before + strlen(before) + 1;
1019 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
1020 replyfuseerrno(m, ESTALE);
1023 if(strchr(before, '/') || strchr(after, '/')){
1024 replyfuseerrno(m, ENOENT);
1027 if((newfid = fswalk(fid, before)) == nil){
1033 if(fsdirfwstat(newfid, &d) < 0){
1039 replyfuse(m, nil, 0);
1043 * Fsync. Commit file info to stable storage.
1044 * Not sure what in->fsync_flags are.
1047 fusefsync(FuseMsg *m)
1049 struct fuse_fsync_in *in;
1054 if((fid = fh2fid(in->fh)) == nil){
1055 replyfuseerrno(m, ESTALE);
1059 if(fsdirfwstat(fid, &d) < 0){
1063 replyfuse(m, nil, 0);
1067 * Fsyncdir. Commit dir info to stable storage?
1070 fusefsyncdir(FuseMsg *m)
1076 * Statfs. Send back information about file system.
1077 * Not really worth implementing, except that if we
1078 * reply with ENOSYS, programs like df print messages like
1079 * df: `/tmp/z': Function not implemented
1080 * and that gets annoying. Returning all zeros excludes
1081 * us from df without appearing to cause any problems.
1084 fusestatfs(FuseMsg *m)
1086 struct fuse_statfs_out out;
1088 memset(&out, 0, sizeof out);
1089 replyfuse(m, &out, sizeof out);
1092 void (*fusehandlers[100])(FuseMsg*);
1096 void (*fn)(FuseMsg*);
1098 { FUSE_LOOKUP, fuselookup },
1099 { FUSE_FORGET, fuseforget },
1100 { FUSE_GETATTR, fusegetattr },
1101 { FUSE_SETATTR, fusesetattr },
1103 * FUSE_READLINK, FUSE_SYMLINK, FUSE_MKNOD are unimplemented.
1105 { FUSE_MKDIR, fusemkdir },
1106 { FUSE_UNLINK, fuseunlink },
1107 { FUSE_RMDIR, fusermdir },
1108 { FUSE_RENAME, fuserename },
1110 * FUSE_LINK is unimplemented.
1112 { FUSE_OPEN, fuseopen },
1113 { FUSE_READ, fuseread },
1114 { FUSE_WRITE, fusewrite },
1115 { FUSE_STATFS, fusestatfs },
1116 { FUSE_RELEASE, fuserelease },
1117 { FUSE_FSYNC, fusefsync },
1119 * FUSE_SETXATTR, FUSE_GETXATTR, FUSE_LISTXATTR, and
1120 * FUSE_REMOVEXATTR are unimplemented.
1121 * FUSE will stop sending these requests after getting
1122 * an -ENOSYS reply (see dispatch below).
1124 { FUSE_FLUSH, fuseflush },
1126 * FUSE_INIT is handled in initfuse and should not be seen again.
1128 { FUSE_OPENDIR, fuseopendir },
1129 { FUSE_READDIR, fusereaddir },
1130 { FUSE_RELEASEDIR, fusereleasedir },
1131 { FUSE_FSYNCDIR, fusefsyncdir },
1132 { FUSE_ACCESS, fuseaccess },
1133 { FUSE_CREATE, fusecreate },
1142 if((uint)m->hdr->opcode >= nelem(fusehandlers)
1143 || !fusehandlers[m->hdr->opcode]){
1144 replyfuseerrno(m, ENOSYS);
1147 fusehandlers[m->hdr->opcode](m);
1151 fusedispatch(void *v)
1156 eofkill9pclient = 1; /* threadexitsall on 9P eof */
1157 atexit(unmountatexit);
1159 recvp(fusechan); /* sync */
1161 for(i=0; i<nelem(fuselist); i++){
1162 if(fuselist[i].op >= nelem(fusehandlers))
1163 sysfatal("make fusehandlers bigger op=%d", fuselist[i].op);
1164 fusehandlers[fuselist[i].op] = fuselist[i].fn;
1167 while((m = recvp(fusechan)) != nil)
1168 threadcreate(fusethread, m, STACK);
1178 sysfatal("malloc(%d): %r", n);
1184 erealloc(void *p, uint n)
1188 sysfatal("realloc(..., %d): %r", n);
1198 sysfatal("strdup(%.20s): %r", p);