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 */
36 void fusedispatch(void*);
45 * The number of seconds that the kernel can cache
46 * returned file attributes. FUSE's default is 1.0.
47 * I haven't experimented with using 0.
49 double attrtimeout = 1.0;
52 * The number of seconds that the kernel can cache
53 * the returned entry nodeids returned by lookup.
54 * I haven't experimented with other values.
56 double entrytimeout = 1.0;
65 fprint(2, "usage: 9pfuse [-D] [-a attrtimeout] address mtpt\n");
69 void fusereader(void*);
72 threadmain(int argc, char **argv)
80 attrtimeout = atof(EARGF(usage()));
90 fmtinstall('F', fcallfmt);
91 fmtinstall('M', dirmodefmt);
92 fmtinstall('G', fusefmt);
94 setsid(); /* won't be able to use console, but can't be interrupted */
99 fusechan = chancreate(sizeof(void*), 0);
100 proccreate(fusedispatch, nil, STACK);
101 sendp(fusechan, nil); /* sync */
103 proccreate(fusereader, nil, STACK);
105 * Now that we're serving FUSE, we can wait
106 * for the mount to finish and exit back to the user.
117 while((m = readfusemsg()) != nil)
120 fusemtpt = nil; /* no need to unmount */
129 if((fd = dial(netmkaddr(addr, "tcp", "564"), nil, nil, nil)) < 0)
130 sysfatal("dial %s: %r", addr);
131 if((fsys = fsmount(fd, "")) == nil)
132 sysfatal("fsmount: %r");
133 fsysroot = fsroot(fsys);
137 * FUSE uses nodeids to refer to active "struct inodes"
138 * (9P's unopened fids). FUSE uses fhs to refer to active
139 * "struct fuse_files" (9P's opened fids). The choice of
140 * numbers is up to us except that nodeid 1 is the root directory.
141 * We use the same number space for both and call the
142 * bookkeeping structure a FuseFid.
144 * FUSE requires nodeids to have associated generation
145 * numbers. If we reuse a nodeid, we have to bump the
146 * generation number to guarantee that the nodeid,gen
147 * combination is never reused.
149 * There are also inode numbers returned in directory reads
150 * and file attributes, but these do NOT need to match the nodeids.
151 * We use a combination of qid.path and qid.type as the inode
155 * TO DO: reference count the fids.
157 typedef struct Fusefid Fusefid;
167 /* directory read state */
176 Fusefid *freefusefidlist;
183 if((f = freefusefidlist) == nil){
184 f = emalloc(sizeof *f);
185 fusefid = erealloc(fusefid, (nfusefid+1)*sizeof *fusefid);
190 freefusefidlist = f->next;
198 freefusefid(Fusefid *f)
212 f->next = freefusefidlist;
218 _alloc(CFid *fid, int isnodeid)
224 ff->isnodeid = isnodeid;
226 return ff->id+2; /* skip 0 and 1 */
232 return _alloc(fid, 0);
235 allocnodeid(CFid *fid)
237 return _alloc(fid, 1);
241 lookupfusefid(uvlong id, int isnodeid)
244 if(id < 2 || id >= nfusefid+2)
246 ff = fusefid[(int)id-2];
247 if(ff->isnodeid != isnodeid)
253 _lookupcfid(uvlong id, int isnodeid)
257 if((ff = lookupfusefid(id, isnodeid)) == nil)
265 return _lookupcfid(fh, 0);
269 nodeid2fid(uvlong nodeid)
273 return _lookupcfid(nodeid, 1);
279 return q.path | ((uvlong)q.type<<56);
283 dir2attr(Dir *d, struct fuse_attr *attr)
285 attr->ino = qid2inode(d->qid);
286 attr->size = d->length;
287 attr->blocks = (d->length+8191)/8192;
288 attr->atime = d->atime;
289 attr->mtime = d->mtime;
290 attr->ctime = d->mtime; /* not right */
294 attr->mode = d->mode&0777;
296 attr->mode |= S_IFDIR;
298 attr->mode |= S_IFREG;
299 attr->nlink = 1; /* works for directories! - see FUSE FAQ */
300 attr->uid = getuid();
301 attr->gid = getgid();
306 f2timeout(double f, __u64 *s, __u32 *ns)
309 *ns = (f - (int)f)*1e9;
313 dir2attrout(Dir *d, struct fuse_attr_out *out)
315 f2timeout(attrtimeout, &out->attr_valid, &out->attr_valid_nsec);
316 dir2attr(d, &out->attr);
320 * Lookup. Walk to the name given as the argument.
321 * The response is a fuse_entry_out giving full stat info.
324 fuselookup(FuseMsg *m)
330 struct fuse_entry_out out;
333 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
334 replyfuseerrno(m, ESTALE);
337 if(strchr(name, '/')){
338 replyfuseerrno(m, ENOENT);
341 if((newfid = fswalk(fid, name)) == nil){
345 if((d = fsdirfstat(newfid)) == nil){
350 out.nodeid = allocnodeid(newfid);
351 ff = lookupfusefid(out.nodeid, 1);
352 out.generation = ff->gen;
353 f2timeout(attrtimeout, &out.attr_valid, &out.attr_valid_nsec);
354 f2timeout(entrytimeout, &out.entry_valid, &out.entry_valid_nsec);
355 dir2attr(d, &out.attr);
357 replyfuse(m, &out, sizeof out);
361 * Forget. Reference-counted clunk for nodeids.
362 * Does not send a reply.
363 * Each lookup response gives the kernel an additional reference
364 * to the returned nodeid. Forget says "drop this many references
365 * to this nodeid". Our fuselookup, when presented with the same query,
366 * does not return the same results (it allocates a new nodeid for each
367 * call), but if that ever changes, fuseforget already handles the ref
371 fuseforget(FuseMsg *m)
373 struct fuse_forget_in *in;
377 if((ff = lookupfusefid(m->hdr->nodeid, 1)) == nil)
379 if(ff->ref > in->nlookup){
380 ff->ref -= in->nlookup;
383 if(ff->ref < in->nlookup)
384 fprint(2, "bad count in forget\n");
391 * Replies with a fuse_attr_out structure giving the
392 * attr for the requested nodeid in out.attr.
393 * Out.attr_valid and out.attr_valid_nsec give
394 * the amount of time that the attributes can
397 * Empirically, though, if I run ls -ld on the root
398 * twice back to back, I still get two getattrs,
399 * even with a one second attribute timeout!
402 fusegetattr(FuseMsg *m)
405 struct fuse_attr_out out;
408 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
409 replyfuseerrno(m, ESTALE);
412 if((d = fsdirfstat(fid)) == nil){
416 memset(&out, 0, sizeof out);
417 dir2attrout(d, &out);
419 replyfuse(m, &out, sizeof out);
424 * FUSE treats the many Unix attribute setting routines
425 * more or less like 9P does, with a single message.
428 fusesetattr(FuseMsg *m)
432 struct fuse_setattr_in *in;
433 struct fuse_attr_out out;
436 if(in->valid&FATTR_FH){
437 if((fid = fh2fid(in->fh)) == nil){
438 replyfuseerrno(m, ESTALE);
442 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
443 replyfuseerrno(m, ESTALE);
447 * Special case: Linux issues a size change to
448 * truncate a file before opening it OTRUNC.
449 * Synthetic file servers (e.g., plumber) honor
450 * open(OTRUNC) but not wstat.
452 if(in->valid == FATTR_SIZE && in->size == 0){
453 if((nfid = fswalk(fid, nil)) == nil){
457 if(fsfopen(nfid, OWRITE|OTRUNC) < 0){
468 if(in->valid&FATTR_SIZE)
470 if(in->valid&FATTR_ATIME)
472 if(in->valid&FATTR_MTIME)
474 if(in->valid&FATTR_MODE)
476 if((in->valid&FATTR_UID) || (in->valid&FATTR_GID)){
478 * I can't be bothered with these yet.
480 replyfuseerrno(m, EPERM);
483 if(fsdirfwstat(fid, &d) < 0){
488 if((dd = fsdirfstat(fid)) == nil){
492 memset(&out, 0, sizeof out);
493 dir2attrout(dd, &out);
495 replyfuse(m, &out, sizeof out);
499 _fuseopenfid(uvlong nodeid, int isdir, int openmode, int *err)
503 if((fid = nodeid2fid(nodeid)) == nil){
507 if(isdir && !(fsqid(fid).type&QTDIR)){
511 if(openmode != OREAD && fsqid(fid).type&QTDIR){
516 /* Clone fid to get one we can open. */
517 newfid = fswalk(fid, nil);
519 *err = errstr2errno();
523 if(fsfopen(newfid, openmode) < 0){
524 *err = errstr2errno();
534 * Argument is a struct fuse_open_in.
535 * The mode field is ignored (presumably permission bits)
536 * and flags is the open mode.
537 * Replies with a struct fuse_open_out.
540 _fuseopen(FuseMsg *m, int isdir)
542 struct fuse_open_in *in;
543 struct fuse_open_out out;
545 int openmode, flags, err;
551 flags &= ~(O_DIRECTORY|O_NONBLOCK|O_LARGEFILE);
557 * Could translate but not standard 9P:
558 * O_DIRECT -> ODIRECT
559 * O_NONBLOCK -> ONONBLOCK
560 * O_APPEND -> OAPPEND
563 fprint(2, "unexpected open flags %#uo", (uint)in->flags);
564 replyfuseerrno(m, EACCES);
567 if((fid = _fuseopenfid(m->hdr->nodeid, isdir, openmode, &err)) == nil){
568 replyfuseerrno(m, err);
571 out.fh = allocfh(fid);
572 out.open_flags = FOPEN_DIRECT_IO; /* no page cache */
573 replyfuse(m, &out, sizeof out);
583 fuseopendir(FuseMsg *m)
592 _fusecreate(uvlong nodeid, char *name, int perm, int ismkdir, int omode, struct fuse_entry_out *out, int *err)
594 CFid *fid, *newfid, *newfid2;
598 if((fid = nodeid2fid(nodeid)) == nil){
605 if(ismkdir && omode != OREAD){
609 if((newfid = fswalk(fid, nil)) == nil){
610 *err = errstr2errno();
613 if(fsfcreate(newfid, name, omode, perm) < 0){
614 *err = errstr2errno();
618 if((d = fsdirfstat(newfid)) == nil){
619 *err = errstr2errno();
624 * This fid is no good, because it's open.
625 * We need an unopened fid. Sigh.
627 if((newfid2 = fswalk(fid, name)) == nil){
628 *err = errstr2errno();
633 out->nodeid = allocnodeid(newfid2);
634 ff = lookupfusefid(out->nodeid, 1);
635 out->generation = ff->gen;
636 f2timeout(attrtimeout, &out->attr_valid, &out->attr_valid_nsec);
637 f2timeout(entrytimeout, &out->entry_valid, &out->entry_valid_nsec);
638 dir2attr(d, &out->attr);
644 fusemkdir(FuseMsg *m)
646 struct fuse_mkdir_in *in;
647 struct fuse_entry_out out;
653 name = (char*)(in+1);
654 if((fid = _fusecreate(m->hdr->nodeid, name, in->mode, 1, OREAD, &out, &err)) == nil){
655 replyfuseerrno(m, err);
658 /* Toss the open fid. */
660 replyfuse(m, &out, sizeof out);
664 fusecreate(FuseMsg *m)
666 struct fuse_open_in *in;
667 struct fuse_create_out out;
669 int err, openmode, flags;
674 openmode = in->flags&3;
676 flags &= ~(O_DIRECTORY|O_NONBLOCK|O_LARGEFILE);
677 flags &= ~(O_CREAT|O_TRUNC); /* huh? */
679 fprint(2, "bad mode %#uo\n", in->flags);
680 replyfuseerrno(m, EACCES);
683 name = (char*)(in+1);
684 if((fid = _fusecreate(m->hdr->nodeid, name, in->mode, 0, openmode, &out.e, &err)) == nil){
685 replyfuseerrno(m, err);
688 out.o.fh = allocfh(fid);
689 out.o.open_flags = FOPEN_DIRECT_IO; /* no page cache */
690 replyfuse(m, &out, sizeof out);
695 * Lib9pclient implements this just as Plan 9 does,
696 * by opening the file (or not) and then closing it.
699 fuseaccess(FuseMsg *m)
701 struct fuse_access_in *in;
716 if(in->mask >= nelem(a2o)){
717 replyfuseerrno(m, EINVAL);
720 omode = a2o[in->mask];
721 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
722 replyfuseerrno(m, ESTALE);
725 if(fsqid(fid).type&QTDIR)
727 if((fid = _fuseopenfid(m->hdr->nodeid, 0, omode, &err)) == nil){
728 replyfuseerrno(m, err);
732 replyfuse(m, nil, 0);
737 * Equivalent of clunk for file handles.
738 * in->flags is the open mode used in Open or Opendir.
741 fuserelease(FuseMsg *m)
743 struct fuse_release_in *in;
747 if((ff = lookupfusefid(in->fh, 0)) != nil)
750 fprint(2, "fuserelease: fh not found\n");
751 replyfuse(m, nil, 0);
755 fusereleasedir(FuseMsg *m)
762 * Read from file handle in->fh at offset in->offset for size in->size.
763 * We truncate size to maxwrite just to keep the buffer reasonable.
771 struct fuse_read_in *in;
774 if((fid = fh2fid(in->fh)) == nil){
775 replyfuseerrno(m, ESTALE);
782 n = fspread(fid, buf, n, in->offset);
787 replyfuse(m, buf, n);
793 * Read from file handle in->fh at offset in->offset for size in->size.
794 * We truncate size to maxwrite just to keep the buffer reasonable.
795 * We assume 9P directory read semantics: a read at offset 0 rewinds
796 * and a read at any other offset starts where we left off.
797 * If it became necessary, we could implement a crude seek
798 * or cache the entire list of directory entries.
799 * Directory entries read from 9P but not yet handed to FUSE
800 * are stored in m->d,nd,d0.
802 int canpack(Dir*, uvlong, uchar**, uchar*);
804 fusereaddir(FuseMsg *m)
806 struct fuse_read_in *in;
812 if((ff = lookupfusefid(in->fh, 0)) == nil){
813 replyfuseerrno(m, ESTALE);
817 fsseek(ff->fid, 0, 0);
831 if(!canpack(ff->d, ff->off, &p, ep))
840 if((ff->nd = fsdirread(ff->fid, &ff->d0)) < 0){
850 replyfuse(m, buf, p - buf);
855 canpack(Dir *d, uvlong off, uchar **pp, uchar *ep)
858 struct fuse_dirent *de;
862 size = FUSE_NAME_OFFSET + strlen(d->name);
866 if(size+pad > ep - p)
868 de = (struct fuse_dirent*)p;
869 de->ino = qid2inode(d->qid);
871 de->namelen = strlen(d->name);
872 memmove(de->name, d->name, de->namelen);
874 memset(de->name+de->namelen, 0, pad);
881 * Write from file handle in->fh at offset in->offset for size in->size.
882 * Don't know what in->write_flags means.
884 * Apparently implementations are allowed to buffer these writes
885 * and wait until Flush is sent, but FUSE docs say flush may be
886 * called zero, one, or even more times per close. So better do the
887 * actual writing here. Also, errors that happen during Flush just
888 * show up in the close() return status, which no one checks anyway.
891 fusewrite(FuseMsg *m)
893 struct fuse_write_in *in;
894 struct fuse_write_out out;
901 if((fid = fh2fid(in->fh)) == nil){
902 replyfuseerrno(m, ESTALE);
905 if(in->size > fusemaxwrite){
906 replyfuseerrno(m, EINVAL);
909 n = fspwrite(fid, a, in->size, in->offset);
915 replyfuse(m, &out, sizeof out);
919 * Flush. Supposed to flush any buffered writes. Don't use this.
921 * Flush is a total crock. It gets called on close() of a file descriptor
922 * associated with this open file. Some open files have multiple file
923 * descriptors and thus multiple closes of those file descriptors.
924 * In those cases, Flush is called multiple times. Some open files
925 * have file descriptors that are closed on process exit instead of
926 * closed explicitly. For those files, Flush is never called.
927 * Even more amusing, Flush gets called before close() of read-only
928 * file descriptors too!
930 * This is just a bad idea.
933 fuseflush(FuseMsg *m)
935 replyfuse(m, nil, 0);
942 _fuseremove(FuseMsg *m, int isdir)
948 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
949 replyfuseerrno(m, ESTALE);
952 if(strchr(name, '/')){
953 replyfuseerrno(m, ENOENT);
956 if((newfid = fswalk(fid, name)) == nil){
960 if(isdir && !(fsqid(newfid).type&QTDIR)){
961 replyfuseerrno(m, ENOTDIR);
965 if(!isdir && (fsqid(newfid).type&QTDIR)){
966 replyfuseerrno(m, EISDIR);
970 if(fsfremove(newfid) < 0){
974 replyfuse(m, nil, 0);
978 fuseunlink(FuseMsg *m)
984 fusermdir(FuseMsg *m)
992 * FUSE sends the nodeid for the source and destination
993 * directory and then the before and after names as strings.
994 * 9P can only do the rename if the source and destination
995 * are the same. If the same nodeid is used for source and
996 * destination, we're fine, but if FUSE gives us different nodeids
997 * that happen to correspond to the same directory, we have
998 * no way of figuring that out. Let's hope it doesn't happen too often.
1001 fuserename(FuseMsg *m)
1003 struct fuse_rename_in *in;
1004 char *before, *after;
1009 if(in->newdir != m->hdr->nodeid){
1010 replyfuseerrno(m, EXDEV);
1013 before = (char*)(in+1);
1014 after = before + strlen(before) + 1;
1015 if((fid = nodeid2fid(m->hdr->nodeid)) == nil){
1016 replyfuseerrno(m, ESTALE);
1019 if(strchr(before, '/') || strchr(after, '/')){
1020 replyfuseerrno(m, ENOENT);
1023 if((newfid = fswalk(fid, before)) == nil){
1029 if(fsdirfwstat(newfid, &d) < 0){
1035 replyfuse(m, nil, 0);
1039 * Fsync. Commit file info to stable storage.
1040 * Not sure what in->fsync_flags are.
1043 fusefsync(FuseMsg *m)
1045 struct fuse_fsync_in *in;
1050 if((fid = fh2fid(in->fh)) == nil){
1051 replyfuseerrno(m, ESTALE);
1055 if(fsdirfwstat(fid, &d) < 0){
1059 replyfuse(m, nil, 0);
1063 * Fsyncdir. Commit dir info to stable storage?
1066 fusefsyncdir(FuseMsg *m)
1072 * Statfs. Send back information about file system.
1073 * Not really worth implementing, except that if we
1074 * reply with ENOSYS, programs like df print messages like
1075 * df: `/tmp/z': Function not implemented
1076 * and that gets annoying. Returning all zeros excludes
1077 * us from df without appearing to cause any problems.
1080 fusestatfs(FuseMsg *m)
1082 struct fuse_statfs_out out;
1084 memset(&out, 0, sizeof out);
1085 replyfuse(m, &out, sizeof out);
1088 void (*fusehandlers[100])(FuseMsg*);
1092 void (*fn)(FuseMsg*);
1094 { FUSE_LOOKUP, fuselookup },
1095 { FUSE_FORGET, fuseforget },
1096 { FUSE_GETATTR, fusegetattr },
1097 { FUSE_SETATTR, fusesetattr },
1099 * FUSE_READLINK, FUSE_SYMLINK, FUSE_MKNOD are unimplemented.
1101 { FUSE_MKDIR, fusemkdir },
1102 { FUSE_UNLINK, fuseunlink },
1103 { FUSE_RMDIR, fusermdir },
1104 { FUSE_RENAME, fuserename },
1106 * FUSE_LINK is unimplemented.
1108 { FUSE_OPEN, fuseopen },
1109 { FUSE_READ, fuseread },
1110 { FUSE_WRITE, fusewrite },
1111 { FUSE_STATFS, fusestatfs },
1112 { FUSE_RELEASE, fuserelease },
1113 { FUSE_FSYNC, fusefsync },
1115 * FUSE_SETXATTR, FUSE_GETXATTR, FUSE_LISTXATTR, and
1116 * FUSE_REMOVEXATTR are unimplemented.
1117 * FUSE will stop sending these requests after getting
1118 * an -ENOSYS reply (see dispatch below).
1120 { FUSE_FLUSH, fuseflush },
1122 * FUSE_INIT is handled in initfuse and should not be seen again.
1124 { FUSE_OPENDIR, fuseopendir },
1125 { FUSE_READDIR, fusereaddir },
1126 { FUSE_RELEASEDIR, fusereleasedir },
1127 { FUSE_FSYNCDIR, fusefsyncdir },
1128 { FUSE_ACCESS, fuseaccess },
1129 { FUSE_CREATE, fusecreate },
1138 if((uint)m->hdr->opcode >= nelem(fusehandlers)
1139 || !fusehandlers[m->hdr->opcode]){
1140 replyfuseerrno(m, ENOSYS);
1143 fusehandlers[m->hdr->opcode](m);
1147 fusedispatch(void *v)
1152 eofkill9pclient = 1; /* threadexitsall on 9P eof */
1153 atexit(unmountatexit);
1155 recvp(fusechan); /* sync */
1157 for(i=0; i<nelem(fuselist); i++){
1158 if(fuselist[i].op >= nelem(fusehandlers))
1159 sysfatal("make fusehandlers bigger op=%d", fuselist[i].op);
1160 fusehandlers[fuselist[i].op] = fuselist[i].fn;
1163 while((m = recvp(fusechan)) != nil)
1164 threadcreate(fusethread, m, STACK);
1174 sysfatal("malloc(%d): %r", n);
1180 erealloc(void *p, uint n)
1184 sysfatal("realloc(..., %d): %r", n);
1194 sysfatal("strdup(%.20s): %r", p);