Imported Upstream version 2.9.0
[platform/upstream/fuse.git] / lib / fuse.c
1 /*
2   FUSE: Filesystem in Userspace
3   Copyright (C) 2001-2007  Miklos Szeredi <miklos@szeredi.hu>
4
5   This program can be distributed under the terms of the GNU LGPLv2.
6   See the file COPYING.LIB
7 */
8
9
10 /* For pthread_rwlock_t */
11 #define _GNU_SOURCE
12
13 #include "fuse_i.h"
14 #include "fuse_lowlevel.h"
15 #include "fuse_opt.h"
16 #include "fuse_misc.h"
17 #include "fuse_common_compat.h"
18 #include "fuse_compat.h"
19 #include "fuse_kernel.h"
20
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <stddef.h>
25 #include <unistd.h>
26 #include <time.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <errno.h>
30 #include <signal.h>
31 #include <dlfcn.h>
32 #include <assert.h>
33 #include <poll.h>
34 #include <sys/param.h>
35 #include <sys/uio.h>
36 #include <sys/time.h>
37 #include <sys/mman.h>
38
39 #define FUSE_NODE_SLAB 1
40
41 #ifndef MAP_ANONYMOUS
42 #undef FUSE_NODE_SLAB
43 #endif
44
45 #define FUSE_DEFAULT_INTR_SIGNAL SIGUSR1
46
47 #define FUSE_UNKNOWN_INO 0xffffffff
48 #define OFFSET_MAX 0x7fffffffffffffffLL
49
50 #define NODE_TABLE_MIN_SIZE 8192
51
52 struct fuse_config {
53         unsigned int uid;
54         unsigned int gid;
55         unsigned int  umask;
56         double entry_timeout;
57         double negative_timeout;
58         double attr_timeout;
59         double ac_attr_timeout;
60         int ac_attr_timeout_set;
61         int remember;
62         int nopath;
63         int debug;
64         int hard_remove;
65         int use_ino;
66         int readdir_ino;
67         int set_mode;
68         int set_uid;
69         int set_gid;
70         int direct_io;
71         int kernel_cache;
72         int auto_cache;
73         int intr;
74         int intr_signal;
75         int help;
76         char *modules;
77 };
78
79 struct fuse_fs {
80         struct fuse_operations op;
81         struct fuse_module *m;
82         void *user_data;
83         int compat;
84         int debug;
85 };
86
87 struct fusemod_so {
88         void *handle;
89         int ctr;
90 };
91
92 struct lock_queue_element {
93        struct lock_queue_element *next;
94        pthread_cond_t cond;
95 };
96
97 struct node_table {
98         struct node **array;
99         size_t use;
100         size_t size;
101         size_t split;
102 };
103
104 #define container_of(ptr, type, member) ({                              \
105                         const typeof( ((type *)0)->member ) *__mptr = (ptr); \
106                         (type *)( (char *)__mptr - offsetof(type,member) );})
107
108 #define list_entry(ptr, type, member)           \
109         container_of(ptr, type, member)
110
111 struct list_head {
112         struct list_head *next;
113         struct list_head *prev;
114 };
115
116 struct node_slab {
117         struct list_head list;  /* must be the first member */
118         struct list_head freelist;
119         int used;
120 };
121
122 struct fuse {
123         struct fuse_session *se;
124         struct node_table name_table;
125         struct node_table id_table;
126         struct list_head lru_table;
127         fuse_ino_t ctr;
128         unsigned int generation;
129         unsigned int hidectr;
130         pthread_mutex_t lock;
131         struct fuse_config conf;
132         int intr_installed;
133         struct fuse_fs *fs;
134         int nullpath_ok;
135         int utime_omit_ok;
136         int curr_ticket;
137         struct lock_queue_element *lockq;
138         int pagesize;
139         struct list_head partial_slabs;
140         struct list_head full_slabs;
141         pthread_t prune_thread;
142 };
143
144 struct lock {
145         int type;
146         off_t start;
147         off_t end;
148         pid_t pid;
149         uint64_t owner;
150         struct lock *next;
151 };
152
153 struct node {
154         struct node *name_next;
155         struct node *id_next;
156         fuse_ino_t nodeid;
157         unsigned int generation;
158         int refctr;
159         struct node *parent;
160         char *name;
161         uint64_t nlookup;
162         int open_count;
163         struct timespec stat_updated;
164         struct timespec mtime;
165         off_t size;
166         struct lock *locks;
167         unsigned int is_hidden : 1;
168         unsigned int cache_valid : 1;
169         int treelock;
170         int ticket;
171         char inline_name[32];
172 };
173
174 struct node_lru {
175         struct node node;
176         struct list_head lru;
177         struct timespec forget_time;
178 };
179
180 struct fuse_dh {
181         pthread_mutex_t lock;
182         struct fuse *fuse;
183         fuse_req_t req;
184         char *contents;
185         int allocated;
186         unsigned len;
187         unsigned size;
188         unsigned needlen;
189         int filled;
190         uint64_t fh;
191         int error;
192         fuse_ino_t nodeid;
193 };
194
195 /* old dir handle */
196 struct fuse_dirhandle {
197         fuse_fill_dir_t filler;
198         void *buf;
199 };
200
201 struct fuse_context_i {
202         struct fuse_context ctx;
203         fuse_req_t req;
204 };
205
206 static pthread_key_t fuse_context_key;
207 static pthread_mutex_t fuse_context_lock = PTHREAD_MUTEX_INITIALIZER;
208 static int fuse_context_ref;
209 static struct fusemod_so *fuse_current_so;
210 static struct fuse_module *fuse_modules;
211
212 static int fuse_load_so_name(const char *soname)
213 {
214         struct fusemod_so *so;
215
216         so = calloc(1, sizeof(struct fusemod_so));
217         if (!so) {
218                 fprintf(stderr, "fuse: memory allocation failed\n");
219                 return -1;
220         }
221
222         fuse_current_so = so;
223         so->handle = dlopen(soname, RTLD_NOW);
224         fuse_current_so = NULL;
225         if (!so->handle) {
226                 fprintf(stderr, "fuse: %s\n", dlerror());
227                 goto err;
228         }
229         if (!so->ctr) {
230                 fprintf(stderr, "fuse: %s did not register any modules\n",
231                         soname);
232                 goto err;
233         }
234         return 0;
235
236 err:
237         if (so->handle)
238                 dlclose(so->handle);
239         free(so);
240         return -1;
241 }
242
243 static int fuse_load_so_module(const char *module)
244 {
245         int res;
246         char *soname = malloc(strlen(module) + 64);
247         if (!soname) {
248                 fprintf(stderr, "fuse: memory allocation failed\n");
249                 return -1;
250         }
251         sprintf(soname, "libfusemod_%s.so", module);
252         res = fuse_load_so_name(soname);
253         free(soname);
254         return res;
255 }
256
257 static struct fuse_module *fuse_find_module(const char *module)
258 {
259         struct fuse_module *m;
260         for (m = fuse_modules; m; m = m->next) {
261                 if (strcmp(module, m->name) == 0) {
262                         m->ctr++;
263                         break;
264                 }
265         }
266         return m;
267 }
268
269 static struct fuse_module *fuse_get_module(const char *module)
270 {
271         struct fuse_module *m;
272
273         pthread_mutex_lock(&fuse_context_lock);
274         m = fuse_find_module(module);
275         if (!m) {
276                 int err = fuse_load_so_module(module);
277                 if (!err)
278                         m = fuse_find_module(module);
279         }
280         pthread_mutex_unlock(&fuse_context_lock);
281         return m;
282 }
283
284 static void fuse_put_module(struct fuse_module *m)
285 {
286         pthread_mutex_lock(&fuse_context_lock);
287         assert(m->ctr > 0);
288         m->ctr--;
289         if (!m->ctr && m->so) {
290                 struct fusemod_so *so = m->so;
291                 assert(so->ctr > 0);
292                 so->ctr--;
293                 if (!so->ctr) {
294                         struct fuse_module **mp;
295                         for (mp = &fuse_modules; *mp;) {
296                                 if ((*mp)->so == so)
297                                         *mp = (*mp)->next;
298                                 else
299                                         mp = &(*mp)->next;
300                         }
301                         dlclose(so->handle);
302                         free(so);
303                 }
304         }
305         pthread_mutex_unlock(&fuse_context_lock);
306 }
307
308 static void init_list_head(struct list_head *list)
309 {
310         list->next = list;
311         list->prev = list;
312 }
313
314 static int list_empty(const struct list_head *head)
315 {
316         return head->next == head;
317 }
318
319 static void list_add(struct list_head *new, struct list_head *prev,
320                      struct list_head *next)
321 {
322         next->prev = new;
323         new->next = next;
324         new->prev = prev;
325         prev->next = new;
326 }
327
328 static void list_add_head(struct list_head *new, struct list_head *head)
329 {
330         list_add(new, head, head->next);
331 }
332
333 static void list_add_tail(struct list_head *new, struct list_head *head)
334 {
335         list_add(new, head->prev, head);
336 }
337
338 static inline void list_del(struct list_head *entry)
339 {
340         struct list_head *prev = entry->prev;
341         struct list_head *next = entry->next;
342
343         next->prev = prev;
344         prev->next = next;
345 }
346
347 static inline int lru_enabled(struct fuse *f)
348 {
349         return f->conf.remember > 0;
350 }
351
352 static struct node_lru *node_lru(struct node *node)
353 {
354         return (struct node_lru *) node;
355 }
356
357 static size_t get_node_size(struct fuse *f)
358 {
359         if (lru_enabled(f))
360                 return sizeof(struct node_lru);
361         else
362                 return sizeof(struct node);
363 }
364
365 #ifdef FUSE_NODE_SLAB
366 static struct node_slab *list_to_slab(struct list_head *head)
367 {
368         return (struct node_slab *) head;
369 }
370
371 static struct node_slab *node_to_slab(struct fuse *f, struct node *node)
372 {
373         return (struct node_slab *) (((uintptr_t) node) & ~((uintptr_t) f->pagesize - 1));
374 }
375
376 static int alloc_slab(struct fuse *f)
377 {
378         void *mem;
379         struct node_slab *slab;
380         char *start;
381         size_t num;
382         size_t i;
383         size_t node_size = get_node_size(f);
384
385         mem = mmap(NULL, f->pagesize, PROT_READ | PROT_WRITE,
386                    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
387
388         if (mem == MAP_FAILED)
389                 return -1;
390
391         slab = mem;
392         init_list_head(&slab->freelist);
393         slab->used = 0;
394         num = (f->pagesize - sizeof(struct node_slab)) / node_size;
395
396         start = (char *) mem + f->pagesize - num * node_size;
397         for (i = 0; i < num; i++) {
398                 struct list_head *n;
399
400                 n = (struct list_head *) (start + i * node_size);
401                 list_add_tail(n, &slab->freelist);
402         }
403         list_add_tail(&slab->list, &f->partial_slabs);
404
405         return 0;
406 }
407
408 static struct node *alloc_node(struct fuse *f)
409 {
410         struct node_slab *slab;
411         struct list_head *node;
412
413         if (list_empty(&f->partial_slabs)) {
414                 int res = alloc_slab(f);
415                 if (res != 0)
416                         return NULL;
417         }
418         slab = list_to_slab(f->partial_slabs.next);
419         slab->used++;
420         node = slab->freelist.next;
421         list_del(node);
422         if (list_empty(&slab->freelist)) {
423                 list_del(&slab->list);
424                 list_add_tail(&slab->list, &f->full_slabs);
425         }
426
427         return (struct node *) node;
428 }
429
430 static void free_slab(struct fuse *f, struct node_slab *slab)
431 {
432         int res;
433
434         list_del(&slab->list);
435         res = munmap(slab, f->pagesize);
436         if (res == -1)
437                 fprintf(stderr, "fuse warning: munmap(%p) failed\n", slab);
438 }
439
440 static void free_node_mem(struct fuse *f, struct node *node)
441 {
442         struct node_slab *slab = node_to_slab(f, node);
443         struct list_head *n = (struct list_head *) node;
444
445         slab->used--;
446         if (slab->used) {
447                 if (list_empty(&slab->freelist)) {
448                         list_del(&slab->list);
449                         list_add_tail(&slab->list, &f->partial_slabs);
450                 }
451                 list_add_head(n, &slab->freelist);
452         } else {
453                 free_slab(f, slab);
454         }
455 }
456 #else
457 static struct node *alloc_node(struct fuse *f)
458 {
459         return (struct node *) calloc(1, get_node_size(f));
460 }
461
462 static void free_node_mem(struct fuse *f, struct node *node)
463 {
464         (void) f;
465         free(node);
466 }
467 #endif
468
469 static size_t id_hash(struct fuse *f, fuse_ino_t ino)
470 {
471         uint64_t hash = ((uint32_t) ino * 2654435761U) % f->id_table.size;
472         uint64_t oldhash = hash % (f->id_table.size / 2);
473
474         if (oldhash >= f->id_table.split)
475                 return oldhash;
476         else
477                 return hash;
478 }
479
480 static struct node *get_node_nocheck(struct fuse *f, fuse_ino_t nodeid)
481 {
482         size_t hash = id_hash(f, nodeid);
483         struct node *node;
484
485         for (node = f->id_table.array[hash]; node != NULL; node = node->id_next)
486                 if (node->nodeid == nodeid)
487                         return node;
488
489         return NULL;
490 }
491
492 static struct node *get_node(struct fuse *f, fuse_ino_t nodeid)
493 {
494         struct node *node = get_node_nocheck(f, nodeid);
495         if (!node) {
496                 fprintf(stderr, "fuse internal error: node %llu not found\n",
497                         (unsigned long long) nodeid);
498                 abort();
499         }
500         return node;
501 }
502
503 static void curr_time(struct timespec *now);
504 static double diff_timespec(const struct timespec *t1,
505                            const struct timespec *t2);
506
507 static void remove_node_lru(struct node *node)
508 {
509         struct node_lru *lnode = node_lru(node);
510         list_del(&lnode->lru);
511         init_list_head(&lnode->lru);
512 }
513
514 static void set_forget_time(struct fuse *f, struct node *node)
515 {
516         struct node_lru *lnode = node_lru(node);
517
518         list_del(&lnode->lru);
519         list_add_tail(&lnode->lru, &f->lru_table);
520         curr_time(&lnode->forget_time);
521 }
522
523 static void free_node(struct fuse *f, struct node *node)
524 {
525         if (node->name != node->inline_name)
526                 free(node->name);
527         free_node_mem(f, node);
528 }
529
530 static void node_table_reduce(struct node_table *t)
531 {
532         size_t newsize = t->size / 2;
533         void *newarray;
534
535         if (newsize < NODE_TABLE_MIN_SIZE)
536                 return;
537
538         newarray = realloc(t->array, sizeof(struct node *) * newsize);
539         if (newarray != NULL)
540                 t->array = newarray;
541
542         t->size = newsize;
543         t->split = t->size / 2;
544 }
545
546 static void remerge_id(struct fuse *f)
547 {
548         struct node_table *t = &f->id_table;
549         int iter;
550
551         if (t->split == 0)
552                 node_table_reduce(t);
553
554         for (iter = 8; t->split > 0 && iter; iter--) {
555                 struct node **upper;
556
557                 t->split--;
558                 upper = &t->array[t->split + t->size / 2];
559                 if (*upper) {
560                         struct node **nodep;
561
562                         for (nodep = &t->array[t->split]; *nodep;
563                              nodep = &(*nodep)->id_next);
564
565                         *nodep = *upper;
566                         *upper = NULL;
567                         break;
568                 }
569         }
570 }
571
572 static void unhash_id(struct fuse *f, struct node *node)
573 {
574         struct node **nodep = &f->id_table.array[id_hash(f, node->nodeid)];
575
576         for (; *nodep != NULL; nodep = &(*nodep)->id_next)
577                 if (*nodep == node) {
578                         *nodep = node->id_next;
579                         f->id_table.use--;
580
581                         if(f->id_table.use < f->id_table.size / 4)
582                                 remerge_id(f);
583                         return;
584                 }
585 }
586
587 static int node_table_resize(struct node_table *t)
588 {
589         size_t newsize = t->size * 2;
590         void *newarray;
591
592         newarray = realloc(t->array, sizeof(struct node *) * newsize);
593         if (newarray == NULL)
594                 return -1;
595
596         t->array = newarray;
597         memset(t->array + t->size, 0, t->size * sizeof(struct node *));
598         t->size = newsize;
599         t->split = 0;
600
601         return 0;
602 }
603
604 static void rehash_id(struct fuse *f)
605 {
606         struct node_table *t = &f->id_table;
607         struct node **nodep;
608         struct node **next;
609         size_t hash;
610
611         if (t->split == t->size / 2)
612                 return;
613
614         hash = t->split;
615         t->split++;
616         for (nodep = &t->array[hash]; *nodep != NULL; nodep = next) {
617                 struct node *node = *nodep;
618                 size_t newhash = id_hash(f, node->nodeid);
619
620                 if (newhash != hash) {
621                         next = nodep;
622                         *nodep = node->id_next;
623                         node->id_next = t->array[newhash];
624                         t->array[newhash] = node;
625                 } else {
626                         next = &node->id_next;
627                 }
628         }
629         if (t->split == t->size / 2)
630                 node_table_resize(t);
631 }
632
633 static void hash_id(struct fuse *f, struct node *node)
634 {
635         size_t hash = id_hash(f, node->nodeid);
636         node->id_next = f->id_table.array[hash];
637         f->id_table.array[hash] = node;
638         f->id_table.use++;
639
640         if (f->id_table.use >= f->id_table.size / 2)
641                 rehash_id(f);
642 }
643
644 static size_t name_hash(struct fuse *f, fuse_ino_t parent,
645                         const char *name)
646 {
647         uint64_t hash = parent;
648         uint64_t oldhash;
649
650         for (; *name; name++)
651                 hash = hash * 31 + (unsigned char) *name;
652
653         hash %= f->name_table.size;
654         oldhash = hash % (f->name_table.size / 2);
655         if (oldhash >= f->name_table.split)
656                 return oldhash;
657         else
658                 return hash;
659 }
660
661 static void unref_node(struct fuse *f, struct node *node);
662
663 static void remerge_name(struct fuse *f)
664 {
665         struct node_table *t = &f->name_table;
666         int iter;
667
668         if (t->split == 0)
669                 node_table_reduce(t);
670
671         for (iter = 8; t->split > 0 && iter; iter--) {
672                 struct node **upper;
673
674                 t->split--;
675                 upper = &t->array[t->split + t->size / 2];
676                 if (*upper) {
677                         struct node **nodep;
678
679                         for (nodep = &t->array[t->split]; *nodep;
680                              nodep = &(*nodep)->name_next);
681
682                         *nodep = *upper;
683                         *upper = NULL;
684                         break;
685                 }
686         }
687 }
688
689 static void unhash_name(struct fuse *f, struct node *node)
690 {
691         if (node->name) {
692                 size_t hash = name_hash(f, node->parent->nodeid, node->name);
693                 struct node **nodep = &f->name_table.array[hash];
694
695                 for (; *nodep != NULL; nodep = &(*nodep)->name_next)
696                         if (*nodep == node) {
697                                 *nodep = node->name_next;
698                                 node->name_next = NULL;
699                                 unref_node(f, node->parent);
700                                 if (node->name != node->inline_name)
701                                         free(node->name);
702                                 node->name = NULL;
703                                 node->parent = NULL;
704                                 f->name_table.use--;
705
706                                 if (f->name_table.use < f->name_table.size / 4)
707                                         remerge_name(f);
708                                 return;
709                         }
710                 fprintf(stderr,
711                         "fuse internal error: unable to unhash node: %llu\n",
712                         (unsigned long long) node->nodeid);
713                 abort();
714         }
715 }
716
717 static void rehash_name(struct fuse *f)
718 {
719         struct node_table *t = &f->name_table;
720         struct node **nodep;
721         struct node **next;
722         size_t hash;
723
724         if (t->split == t->size / 2)
725                 return;
726
727         hash = t->split;
728         t->split++;
729         for (nodep = &t->array[hash]; *nodep != NULL; nodep = next) {
730                 struct node *node = *nodep;
731                 size_t newhash = name_hash(f, node->parent->nodeid, node->name);
732
733                 if (newhash != hash) {
734                         next = nodep;
735                         *nodep = node->name_next;
736                         node->name_next = t->array[newhash];
737                         t->array[newhash] = node;
738                 } else {
739                         next = &node->name_next;
740                 }
741         }
742         if (t->split == t->size / 2)
743                 node_table_resize(t);
744 }
745
746 static int hash_name(struct fuse *f, struct node *node, fuse_ino_t parentid,
747                      const char *name)
748 {
749         size_t hash = name_hash(f, parentid, name);
750         struct node *parent = get_node(f, parentid);
751         if (strlen(name) < sizeof(node->inline_name)) {
752                 strcpy(node->inline_name, name);
753                 node->name = node->inline_name;
754         } else {
755                 node->name = strdup(name);
756                 if (node->name == NULL)
757                         return -1;
758         }
759
760         parent->refctr ++;
761         node->parent = parent;
762         node->name_next = f->name_table.array[hash];
763         f->name_table.array[hash] = node;
764         f->name_table.use++;
765
766         if (f->name_table.use >= f->name_table.size / 2)
767                 rehash_name(f);
768
769         return 0;
770 }
771
772 static void delete_node(struct fuse *f, struct node *node)
773 {
774         if (f->conf.debug)
775                 fprintf(stderr, "DELETE: %llu\n",
776                         (unsigned long long) node->nodeid);
777
778         assert(node->treelock == 0);
779         unhash_name(f, node);
780         if (lru_enabled(f))
781                 remove_node_lru(node);
782         unhash_id(f, node);
783         free_node(f, node);
784 }
785
786 static void unref_node(struct fuse *f, struct node *node)
787 {
788         assert(node->refctr > 0);
789         node->refctr --;
790         if (!node->refctr)
791                 delete_node(f, node);
792 }
793
794 static fuse_ino_t next_id(struct fuse *f)
795 {
796         do {
797                 f->ctr = (f->ctr + 1) & 0xffffffff;
798                 if (!f->ctr)
799                         f->generation ++;
800         } while (f->ctr == 0 || f->ctr == FUSE_UNKNOWN_INO ||
801                  get_node_nocheck(f, f->ctr) != NULL);
802         return f->ctr;
803 }
804
805 static struct node *lookup_node(struct fuse *f, fuse_ino_t parent,
806                                 const char *name)
807 {
808         size_t hash = name_hash(f, parent, name);
809         struct node *node;
810
811         for (node = f->name_table.array[hash]; node != NULL; node = node->name_next)
812                 if (node->parent->nodeid == parent &&
813                     strcmp(node->name, name) == 0)
814                         return node;
815
816         return NULL;
817 }
818
819 static struct node *find_node(struct fuse *f, fuse_ino_t parent,
820                               const char *name)
821 {
822         struct node *node;
823
824         pthread_mutex_lock(&f->lock);
825         if (!name)
826                 node = get_node(f, parent);
827         else
828                 node = lookup_node(f, parent, name);
829         if (node == NULL) {
830                 node = alloc_node(f);
831                 if (node == NULL)
832                         goto out_err;
833
834                 if (f->conf.remember)
835                         node->nlookup = 1;
836                 node->refctr = 1;
837                 node->nodeid = next_id(f);
838                 node->generation = f->generation;
839                 node->open_count = 0;
840                 node->is_hidden = 0;
841                 node->treelock = 0;
842                 node->ticket = 0;
843                 if (hash_name(f, node, parent, name) == -1) {
844                         free_node(f, node);
845                         node = NULL;
846                         goto out_err;
847                 }
848                 hash_id(f, node);
849                 if (lru_enabled(f)) {
850                         struct node_lru *lnode = node_lru(node);
851                         init_list_head(&lnode->lru);
852                 }
853         } else if (lru_enabled(f) && node->nlookup == 1) {
854                 remove_node_lru(node);
855         }
856         node->nlookup ++;
857 out_err:
858         pthread_mutex_unlock(&f->lock);
859         return node;
860 }
861
862 static char *add_name(char **buf, unsigned *bufsize, char *s, const char *name)
863 {
864         size_t len = strlen(name);
865
866         if (s - len <= *buf) {
867                 unsigned pathlen = *bufsize - (s - *buf);
868                 unsigned newbufsize = *bufsize;
869                 char *newbuf;
870
871                 while (newbufsize < pathlen + len + 1) {
872                         if (newbufsize >= 0x80000000)
873                                 newbufsize = 0xffffffff;
874                         else
875                                 newbufsize *= 2;
876                 }
877
878                 newbuf = realloc(*buf, newbufsize);
879                 if (newbuf == NULL)
880                         return NULL;
881
882                 *buf = newbuf;
883                 s = newbuf + newbufsize - pathlen;
884                 memmove(s, newbuf + *bufsize - pathlen, pathlen);
885                 *bufsize = newbufsize;
886         }
887         s -= len;
888         strncpy(s, name, len);
889         s--;
890         *s = '/';
891
892         return s;
893 }
894
895 static void unlock_path(struct fuse *f, fuse_ino_t nodeid, struct node *wnode,
896                         struct node *end, int ticket)
897 {
898         struct node *node;
899
900         if (wnode) {
901                 assert(wnode->treelock == -1);
902                 wnode->treelock = 0;
903                 if (!wnode->ticket)
904                         wnode->ticket = ticket;
905         }
906
907         for (node = get_node(f, nodeid);
908              node != end && node->nodeid != FUSE_ROOT_ID; node = node->parent) {
909                 assert(node->treelock > 0);
910                 node->treelock--;
911                 if (!node->ticket)
912                         node->ticket = ticket;
913         }
914 }
915
916 static void release_tickets(struct fuse *f, fuse_ino_t nodeid,
917                             struct node *wnode, int ticket)
918 {
919         struct node *node;
920
921         if (wnode) {
922                 if (wnode->ticket != ticket)
923                         return;
924
925                 wnode->ticket = 0;
926         }
927
928         for (node = get_node(f, nodeid);
929              node->nodeid != FUSE_ROOT_ID; node = node->parent) {
930                 if (node->ticket != ticket)
931                         return;
932                 node->ticket = 0;
933         }
934 }
935
936 static int try_get_path(struct fuse *f, fuse_ino_t nodeid, const char *name,
937                         char **path, struct node **wnodep, int ticket)
938 {
939         unsigned bufsize = 256;
940         char *buf;
941         char *s;
942         struct node *node;
943         struct node *wnode = NULL;
944         int err;
945
946         *path = NULL;
947
948         err = -ENOMEM;
949         buf = malloc(bufsize);
950         if (buf == NULL)
951                 goto out_err;
952
953         s = buf + bufsize - 1;
954         *s = '\0';
955
956         if (name != NULL) {
957                 s = add_name(&buf, &bufsize, s, name);
958                 err = -ENOMEM;
959                 if (s == NULL)
960                         goto out_free;
961         }
962
963         if (wnodep) {
964                 assert(ticket);
965                 wnode = lookup_node(f, nodeid, name);
966                 if (wnode) {
967                         if (wnode->treelock != 0 ||
968                             (wnode->ticket && wnode->ticket != ticket)) {
969                                 if (!wnode->ticket)
970                                         wnode->ticket = ticket;
971                                 err = -EAGAIN;
972                                 goto out_free;
973                         }
974                         wnode->treelock = -1;
975                         wnode->ticket = 0;
976                 }
977         }
978
979         for (node = get_node(f, nodeid); node->nodeid != FUSE_ROOT_ID;
980              node = node->parent) {
981                 err = -ENOENT;
982                 if (node->name == NULL || node->parent == NULL)
983                         goto out_unlock;
984
985                 err = -ENOMEM;
986                 s = add_name(&buf, &bufsize, s, node->name);
987                 if (s == NULL)
988                         goto out_unlock;
989
990                 if (ticket) {
991                         err = -EAGAIN;
992                         if (node->treelock == -1 ||
993                             (node->ticket && node->ticket != ticket))
994                                 goto out_unlock;
995
996                         node->treelock++;
997                         node->ticket = 0;
998                 }
999         }
1000
1001         if (s[0])
1002                 memmove(buf, s, bufsize - (s - buf));
1003         else
1004                 strcpy(buf, "/");
1005
1006         *path = buf;
1007         if (wnodep)
1008                 *wnodep = wnode;
1009
1010         return 0;
1011
1012  out_unlock:
1013         if (ticket)
1014                 unlock_path(f, nodeid, wnode, node, ticket);
1015  out_free:
1016         free(buf);
1017
1018  out_err:
1019         if (ticket && err != -EAGAIN)
1020                 release_tickets(f, nodeid, wnode, ticket);
1021
1022         return err;
1023 }
1024
1025 static void wake_up_first(struct fuse *f)
1026 {
1027         if (f->lockq)
1028                 pthread_cond_signal(&f->lockq->cond);
1029 }
1030
1031 static void wake_up_next(struct lock_queue_element *qe)
1032 {
1033         if (qe->next)
1034                 pthread_cond_signal(&qe->next->cond);
1035 }
1036
1037 static int get_ticket(struct fuse *f)
1038 {
1039         do f->curr_ticket++;
1040         while (f->curr_ticket == 0);
1041
1042         return f->curr_ticket;
1043 }
1044
1045 static void debug_path(struct fuse *f, const char *msg, fuse_ino_t nodeid,
1046                        const char *name, int wr)
1047 {
1048         if (f->conf.debug) {
1049                 struct node *wnode = NULL;
1050
1051                 if (wr)
1052                         wnode = lookup_node(f, nodeid, name);
1053
1054                 if (wnode)
1055                         fprintf(stderr, "%s %li (w)\n", msg, wnode->nodeid);
1056                 else
1057                         fprintf(stderr, "%s %li\n", msg, nodeid);
1058         }
1059 }
1060
1061 static void queue_path(struct fuse *f, struct lock_queue_element *qe,
1062                        fuse_ino_t nodeid, const char *name, int wr)
1063 {
1064         struct lock_queue_element **qp;
1065
1066         debug_path(f, "QUEUE PATH", nodeid, name, wr);
1067         pthread_cond_init(&qe->cond, NULL);
1068         qe->next = NULL;
1069         for (qp = &f->lockq; *qp != NULL; qp = &(*qp)->next);
1070         *qp = qe;
1071 }
1072
1073 static void dequeue_path(struct fuse *f, struct lock_queue_element *qe,
1074                          fuse_ino_t nodeid, const char *name, int wr)
1075 {
1076         struct lock_queue_element **qp;
1077
1078         debug_path(f, "DEQUEUE PATH", nodeid, name, wr);
1079         pthread_cond_destroy(&qe->cond);
1080         for (qp = &f->lockq; *qp != qe; qp = &(*qp)->next);
1081         *qp = qe->next;
1082 }
1083
1084 static void wait_on_path(struct fuse *f, struct lock_queue_element *qe,
1085                          fuse_ino_t nodeid, const char *name, int wr)
1086 {
1087         debug_path(f, "WAIT ON PATH", nodeid, name, wr);
1088         pthread_cond_wait(&qe->cond, &f->lock);
1089 }
1090
1091 static int get_path_common(struct fuse *f, fuse_ino_t nodeid, const char *name,
1092                            char **path, struct node **wnode)
1093 {
1094         int err;
1095         int ticket;
1096
1097         pthread_mutex_lock(&f->lock);
1098         ticket = get_ticket(f);
1099         err = try_get_path(f, nodeid, name, path, wnode, ticket);
1100         if (err == -EAGAIN) {
1101                 struct lock_queue_element qe;
1102
1103                 queue_path(f, &qe, nodeid, name, !!wnode);
1104                 do {
1105                         wait_on_path(f, &qe, nodeid, name, !!wnode);
1106                         err = try_get_path(f, nodeid, name, path, wnode,
1107                                            ticket);
1108                         wake_up_next(&qe);
1109                 } while (err == -EAGAIN);
1110                 dequeue_path(f, &qe, nodeid, name, !!wnode);
1111         }
1112         pthread_mutex_unlock(&f->lock);
1113
1114         return err;
1115 }
1116
1117 static int get_path(struct fuse *f, fuse_ino_t nodeid, char **path)
1118 {
1119         return get_path_common(f, nodeid, NULL, path, NULL);
1120 }
1121
1122 static int get_path_nullok(struct fuse *f, fuse_ino_t nodeid, char **path)
1123 {
1124         int err = 0;
1125
1126         if (f->conf.nopath) {
1127                 *path = NULL;
1128         } else {
1129                 err = get_path_common(f, nodeid, NULL, path, NULL);
1130                 if (err == -ENOENT && f->nullpath_ok)
1131                         err = 0;
1132         }
1133
1134         return err;
1135 }
1136
1137 static int get_path_name(struct fuse *f, fuse_ino_t nodeid, const char *name,
1138                          char **path)
1139 {
1140         return get_path_common(f, nodeid, name, path, NULL);
1141 }
1142
1143 static int get_path_wrlock(struct fuse *f, fuse_ino_t nodeid, const char *name,
1144                            char **path, struct node **wnode)
1145 {
1146         return get_path_common(f, nodeid, name, path, wnode);
1147 }
1148
1149 static int try_get_path2(struct fuse *f, fuse_ino_t nodeid1, const char *name1,
1150                          fuse_ino_t nodeid2, const char *name2,
1151                          char **path1, char **path2,
1152                          struct node **wnode1, struct node **wnode2,
1153                          int ticket)
1154 {
1155         int err;
1156
1157         /* FIXME: locking two paths needs deadlock checking */
1158         err = try_get_path(f, nodeid1, name1, path1, wnode1, ticket);
1159         if (!err) {
1160                 err = try_get_path(f, nodeid2, name2, path2, wnode2, ticket);
1161                 if (err) {
1162                         struct node *wn1 = wnode1 ? *wnode1 : NULL;
1163
1164                         unlock_path(f, nodeid1, wn1, NULL, ticket);
1165                         free(path1);
1166                         if (ticket && err != -EAGAIN)
1167                                 release_tickets(f, nodeid1, wn1, ticket);
1168                 }
1169         }
1170         return err;
1171 }
1172
1173 static int get_path2(struct fuse *f, fuse_ino_t nodeid1, const char *name1,
1174                      fuse_ino_t nodeid2, const char *name2,
1175                      char **path1, char **path2,
1176                      struct node **wnode1, struct node **wnode2)
1177 {
1178         int err;
1179         int ticket;
1180
1181         pthread_mutex_lock(&f->lock);
1182         ticket = get_ticket(f);
1183         err = try_get_path2(f, nodeid1, name1, nodeid2, name2,
1184                             path1, path2, wnode1, wnode2, ticket);
1185         if (err == -EAGAIN) {
1186                 struct lock_queue_element qe;
1187
1188                 queue_path(f, &qe, nodeid1, name1, !!wnode1);
1189                 debug_path(f, "      path2", nodeid2, name2, !!wnode2);
1190                 do {
1191                         wait_on_path(f, &qe, nodeid1, name1, !!wnode1);
1192                         debug_path(f, "        path2", nodeid2, name2, !!wnode2);
1193                         err = try_get_path2(f, nodeid1, name1, nodeid2, name2,
1194                                             path1, path2, wnode1, wnode2,
1195                                             ticket);
1196                         wake_up_next(&qe);
1197                 } while (err == -EAGAIN);
1198                 dequeue_path(f, &qe, nodeid1, name1, !!wnode1);
1199                 debug_path(f, "        path2", nodeid2, name2, !!wnode2);
1200         }
1201         pthread_mutex_unlock(&f->lock);
1202
1203         return err;
1204 }
1205
1206 static void free_path_wrlock(struct fuse *f, fuse_ino_t nodeid,
1207                              struct node *wnode, char *path)
1208 {
1209         pthread_mutex_lock(&f->lock);
1210         unlock_path(f, nodeid, wnode, NULL, 0);
1211         wake_up_first(f);
1212         pthread_mutex_unlock(&f->lock);
1213         free(path);
1214 }
1215
1216 static void free_path(struct fuse *f, fuse_ino_t nodeid, char *path)
1217 {
1218         if (path)
1219                 free_path_wrlock(f, nodeid, NULL, path);
1220 }
1221
1222 static void free_path2(struct fuse *f, fuse_ino_t nodeid1, fuse_ino_t nodeid2,
1223                        struct node *wnode1, struct node *wnode2,
1224                        char *path1, char *path2)
1225 {
1226         pthread_mutex_lock(&f->lock);
1227         unlock_path(f, nodeid1, wnode1, NULL, 0);
1228         unlock_path(f, nodeid2, wnode2, NULL, 0);
1229         wake_up_first(f);
1230         pthread_mutex_unlock(&f->lock);
1231         free(path1);
1232         free(path2);
1233 }
1234
1235 static void forget_node(struct fuse *f, fuse_ino_t nodeid, uint64_t nlookup)
1236 {
1237         struct node *node;
1238         if (nodeid == FUSE_ROOT_ID)
1239                 return;
1240         pthread_mutex_lock(&f->lock);
1241         node = get_node(f, nodeid);
1242
1243         /*
1244          * Node may still be locked due to interrupt idiocy in open,
1245          * create and opendir
1246          */
1247         while (node->nlookup == nlookup && node->treelock) {
1248                 struct lock_queue_element qe;
1249
1250                 queue_path(f, &qe, node->nodeid, NULL, 0);
1251                 do {
1252                         wait_on_path(f, &qe, node->nodeid, NULL, 0);
1253                         wake_up_next(&qe);
1254
1255                 } while (node->nlookup == nlookup && node->treelock);
1256                 dequeue_path(f, &qe, node->nodeid, NULL, 0);
1257         }
1258
1259         assert(node->nlookup >= nlookup);
1260         node->nlookup -= nlookup;
1261         if (!node->nlookup) {
1262                 unref_node(f, node);
1263         } else if (lru_enabled(f) && node->nlookup == 1) {
1264                 set_forget_time(f, node);
1265         }
1266         pthread_mutex_unlock(&f->lock);
1267 }
1268
1269 static void unlink_node(struct fuse *f, struct node *node)
1270 {
1271         if (f->conf.remember) {
1272                 assert(node->nlookup > 1);
1273                 node->nlookup--;
1274         }
1275         unhash_name(f, node);
1276 }
1277
1278 static void remove_node(struct fuse *f, fuse_ino_t dir, const char *name)
1279 {
1280         struct node *node;
1281
1282         pthread_mutex_lock(&f->lock);
1283         node = lookup_node(f, dir, name);
1284         if (node != NULL)
1285                 unlink_node(f, node);
1286         pthread_mutex_unlock(&f->lock);
1287 }
1288
1289 static int rename_node(struct fuse *f, fuse_ino_t olddir, const char *oldname,
1290                        fuse_ino_t newdir, const char *newname, int hide)
1291 {
1292         struct node *node;
1293         struct node *newnode;
1294         int err = 0;
1295
1296         pthread_mutex_lock(&f->lock);
1297         node  = lookup_node(f, olddir, oldname);
1298         newnode  = lookup_node(f, newdir, newname);
1299         if (node == NULL)
1300                 goto out;
1301
1302         if (newnode != NULL) {
1303                 if (hide) {
1304                         fprintf(stderr, "fuse: hidden file got created during hiding\n");
1305                         err = -EBUSY;
1306                         goto out;
1307                 }
1308                 unlink_node(f, newnode);
1309         }
1310
1311         unhash_name(f, node);
1312         if (hash_name(f, node, newdir, newname) == -1) {
1313                 err = -ENOMEM;
1314                 goto out;
1315         }
1316
1317         if (hide)
1318                 node->is_hidden = 1;
1319
1320 out:
1321         pthread_mutex_unlock(&f->lock);
1322         return err;
1323 }
1324
1325 static void set_stat(struct fuse *f, fuse_ino_t nodeid, struct stat *stbuf)
1326 {
1327         if (!f->conf.use_ino)
1328                 stbuf->st_ino = nodeid;
1329         if (f->conf.set_mode)
1330                 stbuf->st_mode = (stbuf->st_mode & S_IFMT) |
1331                                  (0777 & ~f->conf.umask);
1332         if (f->conf.set_uid)
1333                 stbuf->st_uid = f->conf.uid;
1334         if (f->conf.set_gid)
1335                 stbuf->st_gid = f->conf.gid;
1336 }
1337
1338 static struct fuse *req_fuse(fuse_req_t req)
1339 {
1340         return (struct fuse *) fuse_req_userdata(req);
1341 }
1342
1343 static void fuse_intr_sighandler(int sig)
1344 {
1345         (void) sig;
1346         /* Nothing to do */
1347 }
1348
1349 struct fuse_intr_data {
1350         pthread_t id;
1351         pthread_cond_t cond;
1352         int finished;
1353 };
1354
1355 static void fuse_interrupt(fuse_req_t req, void *d_)
1356 {
1357         struct fuse_intr_data *d = d_;
1358         struct fuse *f = req_fuse(req);
1359
1360         if (d->id == pthread_self())
1361                 return;
1362
1363         pthread_mutex_lock(&f->lock);
1364         while (!d->finished) {
1365                 struct timeval now;
1366                 struct timespec timeout;
1367
1368                 pthread_kill(d->id, f->conf.intr_signal);
1369                 gettimeofday(&now, NULL);
1370                 timeout.tv_sec = now.tv_sec + 1;
1371                 timeout.tv_nsec = now.tv_usec * 1000;
1372                 pthread_cond_timedwait(&d->cond, &f->lock, &timeout);
1373         }
1374         pthread_mutex_unlock(&f->lock);
1375 }
1376
1377 static void fuse_do_finish_interrupt(struct fuse *f, fuse_req_t req,
1378                                      struct fuse_intr_data *d)
1379 {
1380         pthread_mutex_lock(&f->lock);
1381         d->finished = 1;
1382         pthread_cond_broadcast(&d->cond);
1383         pthread_mutex_unlock(&f->lock);
1384         fuse_req_interrupt_func(req, NULL, NULL);
1385         pthread_cond_destroy(&d->cond);
1386 }
1387
1388 static void fuse_do_prepare_interrupt(fuse_req_t req, struct fuse_intr_data *d)
1389 {
1390         d->id = pthread_self();
1391         pthread_cond_init(&d->cond, NULL);
1392         d->finished = 0;
1393         fuse_req_interrupt_func(req, fuse_interrupt, d);
1394 }
1395
1396 static inline void fuse_finish_interrupt(struct fuse *f, fuse_req_t req,
1397                                          struct fuse_intr_data *d)
1398 {
1399         if (f->conf.intr)
1400                 fuse_do_finish_interrupt(f, req, d);
1401 }
1402
1403 static inline void fuse_prepare_interrupt(struct fuse *f, fuse_req_t req,
1404                                           struct fuse_intr_data *d)
1405 {
1406         if (f->conf.intr)
1407                 fuse_do_prepare_interrupt(req, d);
1408 }
1409
1410 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
1411
1412 static int fuse_compat_open(struct fuse_fs *fs, const char *path,
1413                             struct fuse_file_info *fi)
1414 {
1415         int err;
1416         if (!fs->compat || fs->compat >= 25)
1417                 err = fs->op.open(path, fi);
1418         else if (fs->compat == 22) {
1419                 struct fuse_file_info_compat tmp;
1420                 memcpy(&tmp, fi, sizeof(tmp));
1421                 err = ((struct fuse_operations_compat22 *) &fs->op)->open(path,
1422                                                                           &tmp);
1423                 memcpy(fi, &tmp, sizeof(tmp));
1424                 fi->fh = tmp.fh;
1425         } else
1426                 err = ((struct fuse_operations_compat2 *) &fs->op)
1427                         ->open(path, fi->flags);
1428         return err;
1429 }
1430
1431 static int fuse_compat_release(struct fuse_fs *fs, const char *path,
1432                                struct fuse_file_info *fi)
1433 {
1434         if (!fs->compat || fs->compat >= 22)
1435                 return fs->op.release(path, fi);
1436         else
1437                 return ((struct fuse_operations_compat2 *) &fs->op)
1438                         ->release(path, fi->flags);
1439 }
1440
1441 static int fuse_compat_opendir(struct fuse_fs *fs, const char *path,
1442                                struct fuse_file_info *fi)
1443 {
1444         if (!fs->compat || fs->compat >= 25)
1445                 return fs->op.opendir(path, fi);
1446         else {
1447                 int err;
1448                 struct fuse_file_info_compat tmp;
1449                 memcpy(&tmp, fi, sizeof(tmp));
1450                 err = ((struct fuse_operations_compat22 *) &fs->op)
1451                         ->opendir(path, &tmp);
1452                 memcpy(fi, &tmp, sizeof(tmp));
1453                 fi->fh = tmp.fh;
1454                 return err;
1455         }
1456 }
1457
1458 static void convert_statfs_compat(struct fuse_statfs_compat1 *compatbuf,
1459                                   struct statvfs *stbuf)
1460 {
1461         stbuf->f_bsize   = compatbuf->block_size;
1462         stbuf->f_blocks  = compatbuf->blocks;
1463         stbuf->f_bfree   = compatbuf->blocks_free;
1464         stbuf->f_bavail  = compatbuf->blocks_free;
1465         stbuf->f_files   = compatbuf->files;
1466         stbuf->f_ffree   = compatbuf->files_free;
1467         stbuf->f_namemax = compatbuf->namelen;
1468 }
1469
1470 static void convert_statfs_old(struct statfs *oldbuf, struct statvfs *stbuf)
1471 {
1472         stbuf->f_bsize   = oldbuf->f_bsize;
1473         stbuf->f_blocks  = oldbuf->f_blocks;
1474         stbuf->f_bfree   = oldbuf->f_bfree;
1475         stbuf->f_bavail  = oldbuf->f_bavail;
1476         stbuf->f_files   = oldbuf->f_files;
1477         stbuf->f_ffree   = oldbuf->f_ffree;
1478         stbuf->f_namemax = oldbuf->f_namelen;
1479 }
1480
1481 static int fuse_compat_statfs(struct fuse_fs *fs, const char *path,
1482                               struct statvfs *buf)
1483 {
1484         int err;
1485
1486         if (!fs->compat || fs->compat >= 25) {
1487                 err = fs->op.statfs(fs->compat == 25 ? "/" : path, buf);
1488         } else if (fs->compat > 11) {
1489                 struct statfs oldbuf;
1490                 err = ((struct fuse_operations_compat22 *) &fs->op)
1491                         ->statfs("/", &oldbuf);
1492                 if (!err)
1493                         convert_statfs_old(&oldbuf, buf);
1494         } else {
1495                 struct fuse_statfs_compat1 compatbuf;
1496                 memset(&compatbuf, 0, sizeof(struct fuse_statfs_compat1));
1497                 err = ((struct fuse_operations_compat1 *) &fs->op)
1498                         ->statfs(&compatbuf);
1499                 if (!err)
1500                         convert_statfs_compat(&compatbuf, buf);
1501         }
1502         return err;
1503 }
1504
1505 #else /* __FreeBSD__ || __NetBSD__ */
1506
1507 static inline int fuse_compat_open(struct fuse_fs *fs, char *path,
1508                                    struct fuse_file_info *fi)
1509 {
1510         return fs->op.open(path, fi);
1511 }
1512
1513 static inline int fuse_compat_release(struct fuse_fs *fs, const char *path,
1514                                       struct fuse_file_info *fi)
1515 {
1516         return fs->op.release(path, fi);
1517 }
1518
1519 static inline int fuse_compat_opendir(struct fuse_fs *fs, const char *path,
1520                                       struct fuse_file_info *fi)
1521 {
1522         return fs->op.opendir(path, fi);
1523 }
1524
1525 static inline int fuse_compat_statfs(struct fuse_fs *fs, const char *path,
1526                                      struct statvfs *buf)
1527 {
1528         return fs->op.statfs(fs->compat == 25 ? "/" : path, buf);
1529 }
1530
1531 #endif /* __FreeBSD__ || __NetBSD__ */
1532
1533 int fuse_fs_getattr(struct fuse_fs *fs, const char *path, struct stat *buf)
1534 {
1535         fuse_get_context()->private_data = fs->user_data;
1536         if (fs->op.getattr) {
1537                 if (fs->debug)
1538                         fprintf(stderr, "getattr %s\n", path);
1539
1540                 return fs->op.getattr(path, buf);
1541         } else {
1542                 return -ENOSYS;
1543         }
1544 }
1545
1546 int fuse_fs_fgetattr(struct fuse_fs *fs, const char *path, struct stat *buf,
1547                      struct fuse_file_info *fi)
1548 {
1549         fuse_get_context()->private_data = fs->user_data;
1550         if (fs->op.fgetattr) {
1551                 if (fs->debug)
1552                         fprintf(stderr, "fgetattr[%llu] %s\n",
1553                                 (unsigned long long) fi->fh, path);
1554
1555                 return fs->op.fgetattr(path, buf, fi);
1556         } else if (path && fs->op.getattr) {
1557                 if (fs->debug)
1558                         fprintf(stderr, "getattr %s\n", path);
1559
1560                 return fs->op.getattr(path, buf);
1561         } else {
1562                 return -ENOSYS;
1563         }
1564 }
1565
1566 int fuse_fs_rename(struct fuse_fs *fs, const char *oldpath,
1567                    const char *newpath)
1568 {
1569         fuse_get_context()->private_data = fs->user_data;
1570         if (fs->op.rename) {
1571                 if (fs->debug)
1572                         fprintf(stderr, "rename %s %s\n", oldpath, newpath);
1573
1574                 return fs->op.rename(oldpath, newpath);
1575         } else {
1576                 return -ENOSYS;
1577         }
1578 }
1579
1580 int fuse_fs_unlink(struct fuse_fs *fs, const char *path)
1581 {
1582         fuse_get_context()->private_data = fs->user_data;
1583         if (fs->op.unlink) {
1584                 if (fs->debug)
1585                         fprintf(stderr, "unlink %s\n", path);
1586
1587                 return fs->op.unlink(path);
1588         } else {
1589                 return -ENOSYS;
1590         }
1591 }
1592
1593 int fuse_fs_rmdir(struct fuse_fs *fs, const char *path)
1594 {
1595         fuse_get_context()->private_data = fs->user_data;
1596         if (fs->op.rmdir) {
1597                 if (fs->debug)
1598                         fprintf(stderr, "rmdir %s\n", path);
1599
1600                 return fs->op.rmdir(path);
1601         } else {
1602                 return -ENOSYS;
1603         }
1604 }
1605
1606 int fuse_fs_symlink(struct fuse_fs *fs, const char *linkname, const char *path)
1607 {
1608         fuse_get_context()->private_data = fs->user_data;
1609         if (fs->op.symlink) {
1610                 if (fs->debug)
1611                         fprintf(stderr, "symlink %s %s\n", linkname, path);
1612
1613                 return fs->op.symlink(linkname, path);
1614         } else {
1615                 return -ENOSYS;
1616         }
1617 }
1618
1619 int fuse_fs_link(struct fuse_fs *fs, const char *oldpath, const char *newpath)
1620 {
1621         fuse_get_context()->private_data = fs->user_data;
1622         if (fs->op.link) {
1623                 if (fs->debug)
1624                         fprintf(stderr, "link %s %s\n", oldpath, newpath);
1625
1626                 return fs->op.link(oldpath, newpath);
1627         } else {
1628                 return -ENOSYS;
1629         }
1630 }
1631
1632 int fuse_fs_release(struct fuse_fs *fs,  const char *path,
1633                     struct fuse_file_info *fi)
1634 {
1635         fuse_get_context()->private_data = fs->user_data;
1636         if (fs->op.release) {
1637                 if (fs->debug)
1638                         fprintf(stderr, "release%s[%llu] flags: 0x%x\n",
1639                                 fi->flush ? "+flush" : "",
1640                                 (unsigned long long) fi->fh, fi->flags);
1641
1642                 return fuse_compat_release(fs, path, fi);
1643         } else {
1644                 return 0;
1645         }
1646 }
1647
1648 int fuse_fs_opendir(struct fuse_fs *fs, const char *path,
1649                     struct fuse_file_info *fi)
1650 {
1651         fuse_get_context()->private_data = fs->user_data;
1652         if (fs->op.opendir) {
1653                 int err;
1654
1655                 if (fs->debug)
1656                         fprintf(stderr, "opendir flags: 0x%x %s\n", fi->flags,
1657                                 path);
1658
1659                 err = fuse_compat_opendir(fs, path, fi);
1660
1661                 if (fs->debug && !err)
1662                         fprintf(stderr, "   opendir[%lli] flags: 0x%x %s\n",
1663                                 (unsigned long long) fi->fh, fi->flags, path);
1664
1665                 return err;
1666         } else {
1667                 return 0;
1668         }
1669 }
1670
1671 int fuse_fs_open(struct fuse_fs *fs, const char *path,
1672                  struct fuse_file_info *fi)
1673 {
1674         fuse_get_context()->private_data = fs->user_data;
1675         if (fs->op.open) {
1676                 int err;
1677
1678                 if (fs->debug)
1679                         fprintf(stderr, "open flags: 0x%x %s\n", fi->flags,
1680                                 path);
1681
1682                 err = fuse_compat_open(fs, path, fi);
1683
1684                 if (fs->debug && !err)
1685                         fprintf(stderr, "   open[%lli] flags: 0x%x %s\n",
1686                                 (unsigned long long) fi->fh, fi->flags, path);
1687
1688                 return err;
1689         } else {
1690                 return 0;
1691         }
1692 }
1693
1694 static void fuse_free_buf(struct fuse_bufvec *buf)
1695 {
1696         if (buf != NULL) {
1697                 size_t i;
1698
1699                 for (i = 0; i < buf->count; i++)
1700                         free(buf->buf[i].mem);
1701                 free(buf);
1702         }
1703 }
1704
1705 int fuse_fs_read_buf(struct fuse_fs *fs, const char *path,
1706                      struct fuse_bufvec **bufp, size_t size, off_t off,
1707                      struct fuse_file_info *fi)
1708 {
1709         fuse_get_context()->private_data = fs->user_data;
1710         if (fs->op.read || fs->op.read_buf) {
1711                 int res;
1712
1713                 if (fs->debug)
1714                         fprintf(stderr,
1715                                 "read[%llu] %zu bytes from %llu flags: 0x%x\n",
1716                                 (unsigned long long) fi->fh,
1717                                 size, (unsigned long long) off, fi->flags);
1718
1719                 if (fs->op.read_buf) {
1720                         res = fs->op.read_buf(path, bufp, size, off, fi);
1721                 } else {
1722                         struct fuse_bufvec *buf;
1723                         void *mem;
1724
1725                         buf = malloc(sizeof(struct fuse_bufvec));
1726                         if (buf == NULL)
1727                                 return -ENOMEM;
1728
1729                         mem = malloc(size);
1730                         if (mem == NULL) {
1731                                 free(buf);
1732                                 return -ENOMEM;
1733                         }
1734                         *buf = FUSE_BUFVEC_INIT(size);
1735                         buf->buf[0].mem = mem;
1736                         *bufp = buf;
1737
1738                         res = fs->op.read(path, mem, size, off, fi);
1739                         if (res >= 0)
1740                                 buf->buf[0].size = res;
1741                 }
1742
1743                 if (fs->debug && res >= 0)
1744                         fprintf(stderr, "   read[%llu] %zu bytes from %llu\n",
1745                                 (unsigned long long) fi->fh,
1746                                 fuse_buf_size(*bufp),
1747                                 (unsigned long long) off);
1748                 if (res >= 0 && fuse_buf_size(*bufp) > (int) size)
1749                         fprintf(stderr, "fuse: read too many bytes\n");
1750
1751                 if (res < 0)
1752                         return res;
1753
1754                 return 0;
1755         } else {
1756                 return -ENOSYS;
1757         }
1758 }
1759
1760 int fuse_fs_read(struct fuse_fs *fs, const char *path, char *mem, size_t size,
1761                  off_t off, struct fuse_file_info *fi)
1762 {
1763         int res;
1764         struct fuse_bufvec *buf = NULL;
1765
1766         res = fuse_fs_read_buf(fs, path, &buf, size, off, fi);
1767         if (res == 0) {
1768                 struct fuse_bufvec dst = FUSE_BUFVEC_INIT(size);
1769
1770                 dst.buf[0].mem = mem;
1771                 res = fuse_buf_copy(&dst, buf, 0);
1772         }
1773         fuse_free_buf(buf);
1774
1775         return res;
1776 }
1777
1778 int fuse_fs_write_buf(struct fuse_fs *fs, const char *path,
1779                       struct fuse_bufvec *buf, off_t off,
1780                       struct fuse_file_info *fi)
1781 {
1782         fuse_get_context()->private_data = fs->user_data;
1783         if (fs->op.write_buf || fs->op.write) {
1784                 int res;
1785                 size_t size = fuse_buf_size(buf);
1786
1787                 assert(buf->idx == 0 && buf->off == 0);
1788                 if (fs->debug)
1789                         fprintf(stderr,
1790                                 "write%s[%llu] %zu bytes to %llu flags: 0x%x\n",
1791                                 fi->writepage ? "page" : "",
1792                                 (unsigned long long) fi->fh,
1793                                 size,
1794                                 (unsigned long long) off,
1795                                 fi->flags);
1796
1797                 if (fs->op.write_buf) {
1798                         res = fs->op.write_buf(path, buf, off, fi);
1799                 } else {
1800                         void *mem = NULL;
1801                         struct fuse_buf *flatbuf;
1802                         struct fuse_bufvec tmp = FUSE_BUFVEC_INIT(size);
1803
1804                         if (buf->count == 1 &&
1805                             !(buf->buf[0].flags & FUSE_BUF_IS_FD)) {
1806                                 flatbuf = &buf->buf[0];
1807                         } else {
1808                                 res = -ENOMEM;
1809                                 mem = malloc(size);
1810                                 if (mem == NULL)
1811                                         goto out;
1812
1813                                 tmp.buf[0].mem = mem;
1814                                 res = fuse_buf_copy(&tmp, buf, 0);
1815                                 if (res <= 0)
1816                                         goto out_free;
1817
1818                                 tmp.buf[0].size = res;
1819                                 flatbuf = &tmp.buf[0];
1820                         }
1821
1822                         res = fs->op.write(path, flatbuf->mem, flatbuf->size,
1823                                            off, fi);
1824 out_free:
1825                         free(mem);
1826                 }
1827 out:
1828                 if (fs->debug && res >= 0)
1829                         fprintf(stderr, "   write%s[%llu] %u bytes to %llu\n",
1830                                 fi->writepage ? "page" : "",
1831                                 (unsigned long long) fi->fh, res,
1832                                 (unsigned long long) off);
1833                 if (res > (int) size)
1834                         fprintf(stderr, "fuse: wrote too many bytes\n");
1835
1836                 return res;
1837         } else {
1838                 return -ENOSYS;
1839         }
1840 }
1841
1842 int fuse_fs_write(struct fuse_fs *fs, const char *path, const char *mem,
1843                   size_t size, off_t off, struct fuse_file_info *fi)
1844 {
1845         struct fuse_bufvec bufv = FUSE_BUFVEC_INIT(size);
1846
1847         bufv.buf[0].mem = (void *) mem;
1848
1849         return fuse_fs_write_buf(fs, path, &bufv, off, fi);
1850 }
1851
1852 int fuse_fs_fsync(struct fuse_fs *fs, const char *path, int datasync,
1853                   struct fuse_file_info *fi)
1854 {
1855         fuse_get_context()->private_data = fs->user_data;
1856         if (fs->op.fsync) {
1857                 if (fs->debug)
1858                         fprintf(stderr, "fsync[%llu] datasync: %i\n",
1859                                 (unsigned long long) fi->fh, datasync);
1860
1861                 return fs->op.fsync(path, datasync, fi);
1862         } else {
1863                 return -ENOSYS;
1864         }
1865 }
1866
1867 int fuse_fs_fsyncdir(struct fuse_fs *fs, const char *path, int datasync,
1868                      struct fuse_file_info *fi)
1869 {
1870         fuse_get_context()->private_data = fs->user_data;
1871         if (fs->op.fsyncdir) {
1872                 if (fs->debug)
1873                         fprintf(stderr, "fsyncdir[%llu] datasync: %i\n",
1874                                 (unsigned long long) fi->fh, datasync);
1875
1876                 return fs->op.fsyncdir(path, datasync, fi);
1877         } else {
1878                 return -ENOSYS;
1879         }
1880 }
1881
1882 int fuse_fs_flush(struct fuse_fs *fs, const char *path,
1883                   struct fuse_file_info *fi)
1884 {
1885         fuse_get_context()->private_data = fs->user_data;
1886         if (fs->op.flush) {
1887                 if (fs->debug)
1888                         fprintf(stderr, "flush[%llu]\n",
1889                                 (unsigned long long) fi->fh);
1890
1891                 return fs->op.flush(path, fi);
1892         } else {
1893                 return -ENOSYS;
1894         }
1895 }
1896
1897 int fuse_fs_statfs(struct fuse_fs *fs, const char *path, struct statvfs *buf)
1898 {
1899         fuse_get_context()->private_data = fs->user_data;
1900         if (fs->op.statfs) {
1901                 if (fs->debug)
1902                         fprintf(stderr, "statfs %s\n", path);
1903
1904                 return fuse_compat_statfs(fs, path, buf);
1905         } else {
1906                 buf->f_namemax = 255;
1907                 buf->f_bsize = 512;
1908                 return 0;
1909         }
1910 }
1911
1912 int fuse_fs_releasedir(struct fuse_fs *fs, const char *path,
1913                        struct fuse_file_info *fi)
1914 {
1915         fuse_get_context()->private_data = fs->user_data;
1916         if (fs->op.releasedir) {
1917                 if (fs->debug)
1918                         fprintf(stderr, "releasedir[%llu] flags: 0x%x\n",
1919                                 (unsigned long long) fi->fh, fi->flags);
1920
1921                 return fs->op.releasedir(path, fi);
1922         } else {
1923                 return 0;
1924         }
1925 }
1926
1927 static int fill_dir_old(struct fuse_dirhandle *dh, const char *name, int type,
1928                         ino_t ino)
1929 {
1930         int res;
1931         struct stat stbuf;
1932
1933         memset(&stbuf, 0, sizeof(stbuf));
1934         stbuf.st_mode = type << 12;
1935         stbuf.st_ino = ino;
1936
1937         res = dh->filler(dh->buf, name, &stbuf, 0);
1938         return res ? -ENOMEM : 0;
1939 }
1940
1941 int fuse_fs_readdir(struct fuse_fs *fs, const char *path, void *buf,
1942                     fuse_fill_dir_t filler, off_t off,
1943                     struct fuse_file_info *fi)
1944 {
1945         fuse_get_context()->private_data = fs->user_data;
1946         if (fs->op.readdir) {
1947                 if (fs->debug)
1948                         fprintf(stderr, "readdir[%llu] from %llu\n",
1949                                 (unsigned long long) fi->fh,
1950                                 (unsigned long long) off);
1951
1952                 return fs->op.readdir(path, buf, filler, off, fi);
1953         } else if (fs->op.getdir) {
1954                 struct fuse_dirhandle dh;
1955
1956                 if (fs->debug)
1957                         fprintf(stderr, "getdir[%llu]\n",
1958                                 (unsigned long long) fi->fh);
1959
1960                 dh.filler = filler;
1961                 dh.buf = buf;
1962                 return fs->op.getdir(path, &dh, fill_dir_old);
1963         } else {
1964                 return -ENOSYS;
1965         }
1966 }
1967
1968 int fuse_fs_create(struct fuse_fs *fs, const char *path, mode_t mode,
1969                    struct fuse_file_info *fi)
1970 {
1971         fuse_get_context()->private_data = fs->user_data;
1972         if (fs->op.create) {
1973                 int err;
1974
1975                 if (fs->debug)
1976                         fprintf(stderr,
1977                                 "create flags: 0x%x %s 0%o umask=0%03o\n",
1978                                 fi->flags, path, mode,
1979                                 fuse_get_context()->umask);
1980
1981                 err = fs->op.create(path, mode, fi);
1982
1983                 if (fs->debug && !err)
1984                         fprintf(stderr, "   create[%llu] flags: 0x%x %s\n",
1985                                 (unsigned long long) fi->fh, fi->flags, path);
1986
1987                 return err;
1988         } else {
1989                 return -ENOSYS;
1990         }
1991 }
1992
1993 int fuse_fs_lock(struct fuse_fs *fs, const char *path,
1994                  struct fuse_file_info *fi, int cmd, struct flock *lock)
1995 {
1996         fuse_get_context()->private_data = fs->user_data;
1997         if (fs->op.lock) {
1998                 if (fs->debug)
1999                         fprintf(stderr, "lock[%llu] %s %s start: %llu len: %llu pid: %llu\n",
2000                                 (unsigned long long) fi->fh,
2001                                 (cmd == F_GETLK ? "F_GETLK" :
2002                                  (cmd == F_SETLK ? "F_SETLK" :
2003                                   (cmd == F_SETLKW ? "F_SETLKW" : "???"))),
2004                                 (lock->l_type == F_RDLCK ? "F_RDLCK" :
2005                                  (lock->l_type == F_WRLCK ? "F_WRLCK" :
2006                                   (lock->l_type == F_UNLCK ? "F_UNLCK" :
2007                                    "???"))),
2008                                 (unsigned long long) lock->l_start,
2009                                 (unsigned long long) lock->l_len,
2010                                 (unsigned long long) lock->l_pid);
2011
2012                 return fs->op.lock(path, fi, cmd, lock);
2013         } else {
2014                 return -ENOSYS;
2015         }
2016 }
2017
2018 int fuse_fs_flock(struct fuse_fs *fs, const char *path,
2019                   struct fuse_file_info *fi, int op)
2020 {
2021         fuse_get_context()->private_data = fs->user_data;
2022         if (fs->op.flock) {
2023                 if (fs->debug) {
2024                         int xop = op & ~LOCK_NB;
2025
2026                         fprintf(stderr, "lock[%llu] %s%s\n",
2027                                 (unsigned long long) fi->fh,
2028                                 xop == LOCK_SH ? "LOCK_SH" :
2029                                 (xop == LOCK_EX ? "LOCK_EX" :
2030                                  (xop == LOCK_UN ? "LOCK_UN" : "???")),
2031                                 (op & LOCK_NB) ? "|LOCK_NB" : "");
2032                 }
2033                 return fs->op.flock(path, fi, op);
2034         } else {
2035                 return -ENOSYS;
2036         }
2037 }
2038
2039 int fuse_fs_chown(struct fuse_fs *fs, const char *path, uid_t uid, gid_t gid)
2040 {
2041         fuse_get_context()->private_data = fs->user_data;
2042         if (fs->op.chown) {
2043                 if (fs->debug)
2044                         fprintf(stderr, "chown %s %lu %lu\n", path,
2045                                 (unsigned long) uid, (unsigned long) gid);
2046
2047                 return fs->op.chown(path, uid, gid);
2048         } else {
2049                 return -ENOSYS;
2050         }
2051 }
2052
2053 int fuse_fs_truncate(struct fuse_fs *fs, const char *path, off_t size)
2054 {
2055         fuse_get_context()->private_data = fs->user_data;
2056         if (fs->op.truncate) {
2057                 if (fs->debug)
2058                         fprintf(stderr, "truncate %s %llu\n", path,
2059                                 (unsigned long long) size);
2060
2061                 return fs->op.truncate(path, size);
2062         } else {
2063                 return -ENOSYS;
2064         }
2065 }
2066
2067 int fuse_fs_ftruncate(struct fuse_fs *fs, const char *path, off_t size,
2068                       struct fuse_file_info *fi)
2069 {
2070         fuse_get_context()->private_data = fs->user_data;
2071         if (fs->op.ftruncate) {
2072                 if (fs->debug)
2073                         fprintf(stderr, "ftruncate[%llu] %llu\n",
2074                                 (unsigned long long) fi->fh,
2075                                 (unsigned long long) size);
2076
2077                 return fs->op.ftruncate(path, size, fi);
2078         } else if (path && fs->op.truncate) {
2079                 if (fs->debug)
2080                         fprintf(stderr, "truncate %s %llu\n", path,
2081                                 (unsigned long long) size);
2082
2083                 return fs->op.truncate(path, size);
2084         } else {
2085                 return -ENOSYS;
2086         }
2087 }
2088
2089 int fuse_fs_utimens(struct fuse_fs *fs, const char *path,
2090                     const struct timespec tv[2])
2091 {
2092         fuse_get_context()->private_data = fs->user_data;
2093         if (fs->op.utimens) {
2094                 if (fs->debug)
2095                         fprintf(stderr, "utimens %s %li.%09lu %li.%09lu\n",
2096                                 path, tv[0].tv_sec, tv[0].tv_nsec,
2097                                 tv[1].tv_sec, tv[1].tv_nsec);
2098
2099                 return fs->op.utimens(path, tv);
2100         } else if(fs->op.utime) {
2101                 struct utimbuf buf;
2102
2103                 if (fs->debug)
2104                         fprintf(stderr, "utime %s %li %li\n", path,
2105                                 tv[0].tv_sec, tv[1].tv_sec);
2106
2107                 buf.actime = tv[0].tv_sec;
2108                 buf.modtime = tv[1].tv_sec;
2109                 return fs->op.utime(path, &buf);
2110         } else {
2111                 return -ENOSYS;
2112         }
2113 }
2114
2115 int fuse_fs_access(struct fuse_fs *fs, const char *path, int mask)
2116 {
2117         fuse_get_context()->private_data = fs->user_data;
2118         if (fs->op.access) {
2119                 if (fs->debug)
2120                         fprintf(stderr, "access %s 0%o\n", path, mask);
2121
2122                 return fs->op.access(path, mask);
2123         } else {
2124                 return -ENOSYS;
2125         }
2126 }
2127
2128 int fuse_fs_readlink(struct fuse_fs *fs, const char *path, char *buf,
2129                      size_t len)
2130 {
2131         fuse_get_context()->private_data = fs->user_data;
2132         if (fs->op.readlink) {
2133                 if (fs->debug)
2134                         fprintf(stderr, "readlink %s %lu\n", path,
2135                                 (unsigned long) len);
2136
2137                 return fs->op.readlink(path, buf, len);
2138         } else {
2139                 return -ENOSYS;
2140         }
2141 }
2142
2143 int fuse_fs_mknod(struct fuse_fs *fs, const char *path, mode_t mode,
2144                   dev_t rdev)
2145 {
2146         fuse_get_context()->private_data = fs->user_data;
2147         if (fs->op.mknod) {
2148                 if (fs->debug)
2149                         fprintf(stderr, "mknod %s 0%o 0x%llx umask=0%03o\n",
2150                                 path, mode, (unsigned long long) rdev,
2151                                 fuse_get_context()->umask);
2152
2153                 return fs->op.mknod(path, mode, rdev);
2154         } else {
2155                 return -ENOSYS;
2156         }
2157 }
2158
2159 int fuse_fs_mkdir(struct fuse_fs *fs, const char *path, mode_t mode)
2160 {
2161         fuse_get_context()->private_data = fs->user_data;
2162         if (fs->op.mkdir) {
2163                 if (fs->debug)
2164                         fprintf(stderr, "mkdir %s 0%o umask=0%03o\n",
2165                                 path, mode, fuse_get_context()->umask);
2166
2167                 return fs->op.mkdir(path, mode);
2168         } else {
2169                 return -ENOSYS;
2170         }
2171 }
2172
2173 int fuse_fs_setxattr(struct fuse_fs *fs, const char *path, const char *name,
2174                      const char *value, size_t size, int flags)
2175 {
2176         fuse_get_context()->private_data = fs->user_data;
2177         if (fs->op.setxattr) {
2178                 if (fs->debug)
2179                         fprintf(stderr, "setxattr %s %s %lu 0x%x\n",
2180                                 path, name, (unsigned long) size, flags);
2181
2182                 return fs->op.setxattr(path, name, value, size, flags);
2183         } else {
2184                 return -ENOSYS;
2185         }
2186 }
2187
2188 int fuse_fs_getxattr(struct fuse_fs *fs, const char *path, const char *name,
2189                      char *value, size_t size)
2190 {
2191         fuse_get_context()->private_data = fs->user_data;
2192         if (fs->op.getxattr) {
2193                 if (fs->debug)
2194                         fprintf(stderr, "getxattr %s %s %lu\n",
2195                                 path, name, (unsigned long) size);
2196
2197                 return fs->op.getxattr(path, name, value, size);
2198         } else {
2199                 return -ENOSYS;
2200         }
2201 }
2202
2203 int fuse_fs_listxattr(struct fuse_fs *fs, const char *path, char *list,
2204                       size_t size)
2205 {
2206         fuse_get_context()->private_data = fs->user_data;
2207         if (fs->op.listxattr) {
2208                 if (fs->debug)
2209                         fprintf(stderr, "listxattr %s %lu\n",
2210                                 path, (unsigned long) size);
2211
2212                 return fs->op.listxattr(path, list, size);
2213         } else {
2214                 return -ENOSYS;
2215         }
2216 }
2217
2218 int fuse_fs_bmap(struct fuse_fs *fs, const char *path, size_t blocksize,
2219                  uint64_t *idx)
2220 {
2221         fuse_get_context()->private_data = fs->user_data;
2222         if (fs->op.bmap) {
2223                 if (fs->debug)
2224                         fprintf(stderr, "bmap %s blocksize: %lu index: %llu\n",
2225                                 path, (unsigned long) blocksize,
2226                                 (unsigned long long) *idx);
2227
2228                 return fs->op.bmap(path, blocksize, idx);
2229         } else {
2230                 return -ENOSYS;
2231         }
2232 }
2233
2234 int fuse_fs_removexattr(struct fuse_fs *fs, const char *path, const char *name)
2235 {
2236         fuse_get_context()->private_data = fs->user_data;
2237         if (fs->op.removexattr) {
2238                 if (fs->debug)
2239                         fprintf(stderr, "removexattr %s %s\n", path, name);
2240
2241                 return fs->op.removexattr(path, name);
2242         } else {
2243                 return -ENOSYS;
2244         }
2245 }
2246
2247 int fuse_fs_ioctl(struct fuse_fs *fs, const char *path, int cmd, void *arg,
2248                   struct fuse_file_info *fi, unsigned int flags, void *data)
2249 {
2250         fuse_get_context()->private_data = fs->user_data;
2251         if (fs->op.ioctl) {
2252                 if (fs->debug)
2253                         fprintf(stderr, "ioctl[%llu] 0x%x flags: 0x%x\n",
2254                                 (unsigned long long) fi->fh, cmd, flags);
2255
2256                 return fs->op.ioctl(path, cmd, arg, fi, flags, data);
2257         } else
2258                 return -ENOSYS;
2259 }
2260
2261 int fuse_fs_poll(struct fuse_fs *fs, const char *path,
2262                  struct fuse_file_info *fi, struct fuse_pollhandle *ph,
2263                  unsigned *reventsp)
2264 {
2265         fuse_get_context()->private_data = fs->user_data;
2266         if (fs->op.poll) {
2267                 int res;
2268
2269                 if (fs->debug)
2270                         fprintf(stderr, "poll[%llu] ph: %p\n",
2271                                 (unsigned long long) fi->fh, ph);
2272
2273                 res = fs->op.poll(path, fi, ph, reventsp);
2274
2275                 if (fs->debug && !res)
2276                         fprintf(stderr, "   poll[%llu] revents: 0x%x\n",
2277                                 (unsigned long long) fi->fh, *reventsp);
2278
2279                 return res;
2280         } else
2281                 return -ENOSYS;
2282 }
2283
2284 static int is_open(struct fuse *f, fuse_ino_t dir, const char *name)
2285 {
2286         struct node *node;
2287         int isopen = 0;
2288         pthread_mutex_lock(&f->lock);
2289         node = lookup_node(f, dir, name);
2290         if (node && node->open_count > 0)
2291                 isopen = 1;
2292         pthread_mutex_unlock(&f->lock);
2293         return isopen;
2294 }
2295
2296 static char *hidden_name(struct fuse *f, fuse_ino_t dir, const char *oldname,
2297                          char *newname, size_t bufsize)
2298 {
2299         struct stat buf;
2300         struct node *node;
2301         struct node *newnode;
2302         char *newpath;
2303         int res;
2304         int failctr = 10;
2305
2306         do {
2307                 pthread_mutex_lock(&f->lock);
2308                 node = lookup_node(f, dir, oldname);
2309                 if (node == NULL) {
2310                         pthread_mutex_unlock(&f->lock);
2311                         return NULL;
2312                 }
2313                 do {
2314                         f->hidectr ++;
2315                         snprintf(newname, bufsize, ".fuse_hidden%08x%08x",
2316                                  (unsigned int) node->nodeid, f->hidectr);
2317                         newnode = lookup_node(f, dir, newname);
2318                 } while(newnode);
2319
2320                 res = try_get_path(f, dir, newname, &newpath, NULL, 0);
2321                 pthread_mutex_unlock(&f->lock);
2322                 if (res)
2323                         break;
2324
2325                 res = fuse_fs_getattr(f->fs, newpath, &buf);
2326                 if (res == -ENOENT)
2327                         break;
2328                 free(newpath);
2329                 newpath = NULL;
2330         } while(res == 0 && --failctr);
2331
2332         return newpath;
2333 }
2334
2335 static int hide_node(struct fuse *f, const char *oldpath,
2336                      fuse_ino_t dir, const char *oldname)
2337 {
2338         char newname[64];
2339         char *newpath;
2340         int err = -EBUSY;
2341
2342         newpath = hidden_name(f, dir, oldname, newname, sizeof(newname));
2343         if (newpath) {
2344                 err = fuse_fs_rename(f->fs, oldpath, newpath);
2345                 if (!err)
2346                         err = rename_node(f, dir, oldname, dir, newname, 1);
2347                 free(newpath);
2348         }
2349         return err;
2350 }
2351
2352 static int mtime_eq(const struct stat *stbuf, const struct timespec *ts)
2353 {
2354         return stbuf->st_mtime == ts->tv_sec &&
2355                 ST_MTIM_NSEC(stbuf) == ts->tv_nsec;
2356 }
2357
2358 #ifndef CLOCK_MONOTONIC
2359 #define CLOCK_MONOTONIC CLOCK_REALTIME
2360 #endif
2361
2362 static void curr_time(struct timespec *now)
2363 {
2364         static clockid_t clockid = CLOCK_MONOTONIC;
2365         int res = clock_gettime(clockid, now);
2366         if (res == -1 && errno == EINVAL) {
2367                 clockid = CLOCK_REALTIME;
2368                 res = clock_gettime(clockid, now);
2369         }
2370         if (res == -1) {
2371                 perror("fuse: clock_gettime");
2372                 abort();
2373         }
2374 }
2375
2376 static void update_stat(struct node *node, const struct stat *stbuf)
2377 {
2378         if (node->cache_valid && (!mtime_eq(stbuf, &node->mtime) ||
2379                                   stbuf->st_size != node->size))
2380                 node->cache_valid = 0;
2381         node->mtime.tv_sec = stbuf->st_mtime;
2382         node->mtime.tv_nsec = ST_MTIM_NSEC(stbuf);
2383         node->size = stbuf->st_size;
2384         curr_time(&node->stat_updated);
2385 }
2386
2387 static int lookup_path(struct fuse *f, fuse_ino_t nodeid,
2388                        const char *name, const char *path,
2389                        struct fuse_entry_param *e, struct fuse_file_info *fi)
2390 {
2391         int res;
2392
2393         memset(e, 0, sizeof(struct fuse_entry_param));
2394         if (fi)
2395                 res = fuse_fs_fgetattr(f->fs, path, &e->attr, fi);
2396         else
2397                 res = fuse_fs_getattr(f->fs, path, &e->attr);
2398         if (res == 0) {
2399                 struct node *node;
2400
2401                 node = find_node(f, nodeid, name);
2402                 if (node == NULL)
2403                         res = -ENOMEM;
2404                 else {
2405                         e->ino = node->nodeid;
2406                         e->generation = node->generation;
2407                         e->entry_timeout = f->conf.entry_timeout;
2408                         e->attr_timeout = f->conf.attr_timeout;
2409                         if (f->conf.auto_cache) {
2410                                 pthread_mutex_lock(&f->lock);
2411                                 update_stat(node, &e->attr);
2412                                 pthread_mutex_unlock(&f->lock);
2413                         }
2414                         set_stat(f, e->ino, &e->attr);
2415                         if (f->conf.debug)
2416                                 fprintf(stderr, "   NODEID: %lu\n",
2417                                         (unsigned long) e->ino);
2418                 }
2419         }
2420         return res;
2421 }
2422
2423 static struct fuse_context_i *fuse_get_context_internal(void)
2424 {
2425         struct fuse_context_i *c;
2426
2427         c = (struct fuse_context_i *) pthread_getspecific(fuse_context_key);
2428         if (c == NULL) {
2429                 c = (struct fuse_context_i *)
2430                         calloc(1, sizeof(struct fuse_context_i));
2431                 if (c == NULL) {
2432                         /* This is hard to deal with properly, so just
2433                            abort.  If memory is so low that the
2434                            context cannot be allocated, there's not
2435                            much hope for the filesystem anyway */
2436                         fprintf(stderr, "fuse: failed to allocate thread specific data\n");
2437                         abort();
2438                 }
2439                 pthread_setspecific(fuse_context_key, c);
2440         }
2441         return c;
2442 }
2443
2444 static void fuse_freecontext(void *data)
2445 {
2446         free(data);
2447 }
2448
2449 static int fuse_create_context_key(void)
2450 {
2451         int err = 0;
2452         pthread_mutex_lock(&fuse_context_lock);
2453         if (!fuse_context_ref) {
2454                 err = pthread_key_create(&fuse_context_key, fuse_freecontext);
2455                 if (err) {
2456                         fprintf(stderr, "fuse: failed to create thread specific key: %s\n",
2457                                 strerror(err));
2458                         pthread_mutex_unlock(&fuse_context_lock);
2459                         return -1;
2460                 }
2461         }
2462         fuse_context_ref++;
2463         pthread_mutex_unlock(&fuse_context_lock);
2464         return 0;
2465 }
2466
2467 static void fuse_delete_context_key(void)
2468 {
2469         pthread_mutex_lock(&fuse_context_lock);
2470         fuse_context_ref--;
2471         if (!fuse_context_ref) {
2472                 free(pthread_getspecific(fuse_context_key));
2473                 pthread_key_delete(fuse_context_key);
2474         }
2475         pthread_mutex_unlock(&fuse_context_lock);
2476 }
2477
2478 static struct fuse *req_fuse_prepare(fuse_req_t req)
2479 {
2480         struct fuse_context_i *c = fuse_get_context_internal();
2481         const struct fuse_ctx *ctx = fuse_req_ctx(req);
2482         c->req = req;
2483         c->ctx.fuse = req_fuse(req);
2484         c->ctx.uid = ctx->uid;
2485         c->ctx.gid = ctx->gid;
2486         c->ctx.pid = ctx->pid;
2487         c->ctx.umask = ctx->umask;
2488         return c->ctx.fuse;
2489 }
2490
2491 static inline void reply_err(fuse_req_t req, int err)
2492 {
2493         /* fuse_reply_err() uses non-negated errno values */
2494         fuse_reply_err(req, -err);
2495 }
2496
2497 static void reply_entry(fuse_req_t req, const struct fuse_entry_param *e,
2498                         int err)
2499 {
2500         if (!err) {
2501                 struct fuse *f = req_fuse(req);
2502                 if (fuse_reply_entry(req, e) == -ENOENT) {
2503                         /* Skip forget for negative result */
2504                         if  (e->ino != 0)
2505                                 forget_node(f, e->ino, 1);
2506                 }
2507         } else
2508                 reply_err(req, err);
2509 }
2510
2511 void fuse_fs_init(struct fuse_fs *fs, struct fuse_conn_info *conn)
2512 {
2513         fuse_get_context()->private_data = fs->user_data;
2514         if (!fs->op.write_buf)
2515                 conn->want &= ~FUSE_CAP_SPLICE_READ;
2516         if (!fs->op.lock)
2517                 conn->want &= ~FUSE_CAP_POSIX_LOCKS;
2518         if (!fs->op.flock)
2519                 conn->want &= ~FUSE_CAP_FLOCK_LOCKS;
2520         if (fs->op.init)
2521                 fs->user_data = fs->op.init(conn);
2522 }
2523
2524 static void fuse_lib_init(void *data, struct fuse_conn_info *conn)
2525 {
2526         struct fuse *f = (struct fuse *) data;
2527         struct fuse_context_i *c = fuse_get_context_internal();
2528
2529         memset(c, 0, sizeof(*c));
2530         c->ctx.fuse = f;
2531         conn->want |= FUSE_CAP_EXPORT_SUPPORT;
2532         fuse_fs_init(f->fs, conn);
2533 }
2534
2535 void fuse_fs_destroy(struct fuse_fs *fs)
2536 {
2537         fuse_get_context()->private_data = fs->user_data;
2538         if (fs->op.destroy)
2539                 fs->op.destroy(fs->user_data);
2540         if (fs->m)
2541                 fuse_put_module(fs->m);
2542         free(fs);
2543 }
2544
2545 static void fuse_lib_destroy(void *data)
2546 {
2547         struct fuse *f = (struct fuse *) data;
2548         struct fuse_context_i *c = fuse_get_context_internal();
2549
2550         memset(c, 0, sizeof(*c));
2551         c->ctx.fuse = f;
2552         fuse_fs_destroy(f->fs);
2553         f->fs = NULL;
2554 }
2555
2556 static void fuse_lib_lookup(fuse_req_t req, fuse_ino_t parent,
2557                             const char *name)
2558 {
2559         struct fuse *f = req_fuse_prepare(req);
2560         struct fuse_entry_param e;
2561         char *path;
2562         int err;
2563         struct node *dot = NULL;
2564
2565         if (name[0] == '.') {
2566                 int len = strlen(name);
2567
2568                 if (len == 1 || (name[1] == '.' && len == 2)) {
2569                         pthread_mutex_lock(&f->lock);
2570                         if (len == 1) {
2571                                 if (f->conf.debug)
2572                                         fprintf(stderr, "LOOKUP-DOT\n");
2573                                 dot = get_node_nocheck(f, parent);
2574                                 if (dot == NULL) {
2575                                         pthread_mutex_unlock(&f->lock);
2576                                         reply_entry(req, &e, -ESTALE);
2577                                         return;
2578                                 }
2579                                 dot->refctr++;
2580                         } else {
2581                                 if (f->conf.debug)
2582                                         fprintf(stderr, "LOOKUP-DOTDOT\n");
2583                                 parent = get_node(f, parent)->parent->nodeid;
2584                         }
2585                         pthread_mutex_unlock(&f->lock);
2586                         name = NULL;
2587                 }
2588         }
2589
2590         err = get_path_name(f, parent, name, &path);
2591         if (!err) {
2592                 struct fuse_intr_data d;
2593                 if (f->conf.debug)
2594                         fprintf(stderr, "LOOKUP %s\n", path);
2595                 fuse_prepare_interrupt(f, req, &d);
2596                 err = lookup_path(f, parent, name, path, &e, NULL);
2597                 if (err == -ENOENT && f->conf.negative_timeout != 0.0) {
2598                         e.ino = 0;
2599                         e.entry_timeout = f->conf.negative_timeout;
2600                         err = 0;
2601                 }
2602                 fuse_finish_interrupt(f, req, &d);
2603                 free_path(f, parent, path);
2604         }
2605         if (dot) {
2606                 pthread_mutex_lock(&f->lock);
2607                 unref_node(f, dot);
2608                 pthread_mutex_unlock(&f->lock);
2609         }
2610         reply_entry(req, &e, err);
2611 }
2612
2613 static void do_forget(struct fuse *f, fuse_ino_t ino, uint64_t nlookup)
2614 {
2615         if (f->conf.debug)
2616                 fprintf(stderr, "FORGET %llu/%llu\n", (unsigned long long)ino,
2617                         (unsigned long long) nlookup);
2618         forget_node(f, ino, nlookup);
2619 }
2620
2621 static void fuse_lib_forget(fuse_req_t req, fuse_ino_t ino,
2622                             unsigned long nlookup)
2623 {
2624         do_forget(req_fuse(req), ino, nlookup);
2625         fuse_reply_none(req);
2626 }
2627
2628 static void fuse_lib_forget_multi(fuse_req_t req, size_t count,
2629                                   struct fuse_forget_data *forgets)
2630 {
2631         struct fuse *f = req_fuse(req);
2632         size_t i;
2633
2634         for (i = 0; i < count; i++)
2635                 do_forget(f, forgets[i].ino, forgets[i].nlookup);
2636
2637         fuse_reply_none(req);
2638 }
2639
2640
2641 static void fuse_lib_getattr(fuse_req_t req, fuse_ino_t ino,
2642                              struct fuse_file_info *fi)
2643 {
2644         struct fuse *f = req_fuse_prepare(req);
2645         struct stat buf;
2646         char *path;
2647         int err;
2648
2649         memset(&buf, 0, sizeof(buf));
2650
2651         if (fi != NULL && f->fs->op.fgetattr)
2652                 err = get_path_nullok(f, ino, &path);
2653         else
2654                 err = get_path(f, ino, &path);
2655         if (!err) {
2656                 struct fuse_intr_data d;
2657                 fuse_prepare_interrupt(f, req, &d);
2658                 if (fi)
2659                         err = fuse_fs_fgetattr(f->fs, path, &buf, fi);
2660                 else
2661                         err = fuse_fs_getattr(f->fs, path, &buf);
2662                 fuse_finish_interrupt(f, req, &d);
2663                 free_path(f, ino, path);
2664         }
2665         if (!err) {
2666                 struct node *node;
2667
2668                 pthread_mutex_lock(&f->lock);
2669                 node = get_node(f, ino);
2670                 if (node->is_hidden && buf.st_nlink > 0)
2671                         buf.st_nlink--;
2672                 if (f->conf.auto_cache)
2673                         update_stat(node, &buf);
2674                 pthread_mutex_unlock(&f->lock);
2675                 set_stat(f, ino, &buf);
2676                 fuse_reply_attr(req, &buf, f->conf.attr_timeout);
2677         } else
2678                 reply_err(req, err);
2679 }
2680
2681 int fuse_fs_chmod(struct fuse_fs *fs, const char *path, mode_t mode)
2682 {
2683         fuse_get_context()->private_data = fs->user_data;
2684         if (fs->op.chmod)
2685                 return fs->op.chmod(path, mode);
2686         else
2687                 return -ENOSYS;
2688 }
2689
2690 static void fuse_lib_setattr(fuse_req_t req, fuse_ino_t ino, struct stat *attr,
2691                              int valid, struct fuse_file_info *fi)
2692 {
2693         struct fuse *f = req_fuse_prepare(req);
2694         struct stat buf;
2695         char *path;
2696         int err;
2697
2698         if (valid == FUSE_SET_ATTR_SIZE && fi != NULL &&
2699             f->fs->op.ftruncate && f->fs->op.fgetattr)
2700                 err = get_path_nullok(f, ino, &path);
2701         else
2702                 err = get_path(f, ino, &path);
2703         if (!err) {
2704                 struct fuse_intr_data d;
2705                 fuse_prepare_interrupt(f, req, &d);
2706                 err = 0;
2707                 if (!err && (valid & FUSE_SET_ATTR_MODE))
2708                         err = fuse_fs_chmod(f->fs, path, attr->st_mode);
2709                 if (!err && (valid & (FUSE_SET_ATTR_UID | FUSE_SET_ATTR_GID))) {
2710                         uid_t uid = (valid & FUSE_SET_ATTR_UID) ?
2711                                 attr->st_uid : (uid_t) -1;
2712                         gid_t gid = (valid & FUSE_SET_ATTR_GID) ?
2713                                 attr->st_gid : (gid_t) -1;
2714                         err = fuse_fs_chown(f->fs, path, uid, gid);
2715                 }
2716                 if (!err && (valid & FUSE_SET_ATTR_SIZE)) {
2717                         if (fi)
2718                                 err = fuse_fs_ftruncate(f->fs, path,
2719                                                         attr->st_size, fi);
2720                         else
2721                                 err = fuse_fs_truncate(f->fs, path,
2722                                                        attr->st_size);
2723                 }
2724 #ifdef HAVE_UTIMENSAT
2725                 if (!err && f->utime_omit_ok &&
2726                     (valid & (FUSE_SET_ATTR_ATIME | FUSE_SET_ATTR_MTIME))) {
2727                         struct timespec tv[2];
2728
2729                         tv[0].tv_sec = 0;
2730                         tv[1].tv_sec = 0;
2731                         tv[0].tv_nsec = UTIME_OMIT;
2732                         tv[1].tv_nsec = UTIME_OMIT;
2733
2734                         if (valid & FUSE_SET_ATTR_ATIME_NOW)
2735                                 tv[0].tv_nsec = UTIME_NOW;
2736                         else if (valid & FUSE_SET_ATTR_ATIME)
2737                                 tv[0] = attr->st_atim;
2738
2739                         if (valid & FUSE_SET_ATTR_MTIME_NOW)
2740                                 tv[1].tv_nsec = UTIME_NOW;
2741                         else if (valid & FUSE_SET_ATTR_MTIME)
2742                                 tv[1] = attr->st_mtim;
2743
2744                         err = fuse_fs_utimens(f->fs, path, tv);
2745                 } else
2746 #endif
2747                 if (!err &&
2748                     (valid & (FUSE_SET_ATTR_ATIME | FUSE_SET_ATTR_MTIME)) ==
2749                     (FUSE_SET_ATTR_ATIME | FUSE_SET_ATTR_MTIME)) {
2750                         struct timespec tv[2];
2751                         tv[0].tv_sec = attr->st_atime;
2752                         tv[0].tv_nsec = ST_ATIM_NSEC(attr);
2753                         tv[1].tv_sec = attr->st_mtime;
2754                         tv[1].tv_nsec = ST_MTIM_NSEC(attr);
2755                         err = fuse_fs_utimens(f->fs, path, tv);
2756                 }
2757                 if (!err) {
2758                         if (fi)
2759                                 err = fuse_fs_fgetattr(f->fs, path, &buf, fi);
2760                         else
2761                                 err = fuse_fs_getattr(f->fs, path, &buf);
2762                 }
2763                 fuse_finish_interrupt(f, req, &d);
2764                 free_path(f, ino, path);
2765         }
2766         if (!err) {
2767                 if (f->conf.auto_cache) {
2768                         pthread_mutex_lock(&f->lock);
2769                         update_stat(get_node(f, ino), &buf);
2770                         pthread_mutex_unlock(&f->lock);
2771                 }
2772                 set_stat(f, ino, &buf);
2773                 fuse_reply_attr(req, &buf, f->conf.attr_timeout);
2774         } else
2775                 reply_err(req, err);
2776 }
2777
2778 static void fuse_lib_access(fuse_req_t req, fuse_ino_t ino, int mask)
2779 {
2780         struct fuse *f = req_fuse_prepare(req);
2781         char *path;
2782         int err;
2783
2784         err = get_path(f, ino, &path);
2785         if (!err) {
2786                 struct fuse_intr_data d;
2787
2788                 fuse_prepare_interrupt(f, req, &d);
2789                 err = fuse_fs_access(f->fs, path, mask);
2790                 fuse_finish_interrupt(f, req, &d);
2791                 free_path(f, ino, path);
2792         }
2793         reply_err(req, err);
2794 }
2795
2796 static void fuse_lib_readlink(fuse_req_t req, fuse_ino_t ino)
2797 {
2798         struct fuse *f = req_fuse_prepare(req);
2799         char linkname[PATH_MAX + 1];
2800         char *path;
2801         int err;
2802
2803         err = get_path(f, ino, &path);
2804         if (!err) {
2805                 struct fuse_intr_data d;
2806                 fuse_prepare_interrupt(f, req, &d);
2807                 err = fuse_fs_readlink(f->fs, path, linkname, sizeof(linkname));
2808                 fuse_finish_interrupt(f, req, &d);
2809                 free_path(f, ino, path);
2810         }
2811         if (!err) {
2812                 linkname[PATH_MAX] = '\0';
2813                 fuse_reply_readlink(req, linkname);
2814         } else
2815                 reply_err(req, err);
2816 }
2817
2818 static void fuse_lib_mknod(fuse_req_t req, fuse_ino_t parent, const char *name,
2819                            mode_t mode, dev_t rdev)
2820 {
2821         struct fuse *f = req_fuse_prepare(req);
2822         struct fuse_entry_param e;
2823         char *path;
2824         int err;
2825
2826         err = get_path_name(f, parent, name, &path);
2827         if (!err) {
2828                 struct fuse_intr_data d;
2829
2830                 fuse_prepare_interrupt(f, req, &d);
2831                 err = -ENOSYS;
2832                 if (S_ISREG(mode)) {
2833                         struct fuse_file_info fi;
2834
2835                         memset(&fi, 0, sizeof(fi));
2836                         fi.flags = O_CREAT | O_EXCL | O_WRONLY;
2837                         err = fuse_fs_create(f->fs, path, mode, &fi);
2838                         if (!err) {
2839                                 err = lookup_path(f, parent, name, path, &e,
2840                                                   &fi);
2841                                 fuse_fs_release(f->fs, path, &fi);
2842                         }
2843                 }
2844                 if (err == -ENOSYS) {
2845                         err = fuse_fs_mknod(f->fs, path, mode, rdev);
2846                         if (!err)
2847                                 err = lookup_path(f, parent, name, path, &e,
2848                                                   NULL);
2849                 }
2850                 fuse_finish_interrupt(f, req, &d);
2851                 free_path(f, parent, path);
2852         }
2853         reply_entry(req, &e, err);
2854 }
2855
2856 static void fuse_lib_mkdir(fuse_req_t req, fuse_ino_t parent, const char *name,
2857                            mode_t mode)
2858 {
2859         struct fuse *f = req_fuse_prepare(req);
2860         struct fuse_entry_param e;
2861         char *path;
2862         int err;
2863
2864         err = get_path_name(f, parent, name, &path);
2865         if (!err) {
2866                 struct fuse_intr_data d;
2867
2868                 fuse_prepare_interrupt(f, req, &d);
2869                 err = fuse_fs_mkdir(f->fs, path, mode);
2870                 if (!err)
2871                         err = lookup_path(f, parent, name, path, &e, NULL);
2872                 fuse_finish_interrupt(f, req, &d);
2873                 free_path(f, parent, path);
2874         }
2875         reply_entry(req, &e, err);
2876 }
2877
2878 static void fuse_lib_unlink(fuse_req_t req, fuse_ino_t parent,
2879                             const char *name)
2880 {
2881         struct fuse *f = req_fuse_prepare(req);
2882         struct node *wnode;
2883         char *path;
2884         int err;
2885
2886         err = get_path_wrlock(f, parent, name, &path, &wnode);
2887         if (!err) {
2888                 struct fuse_intr_data d;
2889
2890                 fuse_prepare_interrupt(f, req, &d);
2891                 if (!f->conf.hard_remove && is_open(f, parent, name)) {
2892                         err = hide_node(f, path, parent, name);
2893                 } else {
2894                         err = fuse_fs_unlink(f->fs, path);
2895                         if (!err)
2896                                 remove_node(f, parent, name);
2897                 }
2898                 fuse_finish_interrupt(f, req, &d);
2899                 free_path_wrlock(f, parent, wnode, path);
2900         }
2901         reply_err(req, err);
2902 }
2903
2904 static void fuse_lib_rmdir(fuse_req_t req, fuse_ino_t parent, const char *name)
2905 {
2906         struct fuse *f = req_fuse_prepare(req);
2907         struct node *wnode;
2908         char *path;
2909         int err;
2910
2911         err = get_path_wrlock(f, parent, name, &path, &wnode);
2912         if (!err) {
2913                 struct fuse_intr_data d;
2914
2915                 fuse_prepare_interrupt(f, req, &d);
2916                 err = fuse_fs_rmdir(f->fs, path);
2917                 fuse_finish_interrupt(f, req, &d);
2918                 if (!err)
2919                         remove_node(f, parent, name);
2920                 free_path_wrlock(f, parent, wnode, path);
2921         }
2922         reply_err(req, err);
2923 }
2924
2925 static void fuse_lib_symlink(fuse_req_t req, const char *linkname,
2926                              fuse_ino_t parent, const char *name)
2927 {
2928         struct fuse *f = req_fuse_prepare(req);
2929         struct fuse_entry_param e;
2930         char *path;
2931         int err;
2932
2933         err = get_path_name(f, parent, name, &path);
2934         if (!err) {
2935                 struct fuse_intr_data d;
2936
2937                 fuse_prepare_interrupt(f, req, &d);
2938                 err = fuse_fs_symlink(f->fs, linkname, path);
2939                 if (!err)
2940                         err = lookup_path(f, parent, name, path, &e, NULL);
2941                 fuse_finish_interrupt(f, req, &d);
2942                 free_path(f, parent, path);
2943         }
2944         reply_entry(req, &e, err);
2945 }
2946
2947 static void fuse_lib_rename(fuse_req_t req, fuse_ino_t olddir,
2948                             const char *oldname, fuse_ino_t newdir,
2949                             const char *newname)
2950 {
2951         struct fuse *f = req_fuse_prepare(req);
2952         char *oldpath;
2953         char *newpath;
2954         struct node *wnode1;
2955         struct node *wnode2;
2956         int err;
2957
2958         err = get_path2(f, olddir, oldname, newdir, newname,
2959                         &oldpath, &newpath, &wnode1, &wnode2);
2960         if (!err) {
2961                 struct fuse_intr_data d;
2962                 err = 0;
2963                 fuse_prepare_interrupt(f, req, &d);
2964                 if (!f->conf.hard_remove && is_open(f, newdir, newname))
2965                         err = hide_node(f, newpath, newdir, newname);
2966                 if (!err) {
2967                         err = fuse_fs_rename(f->fs, oldpath, newpath);
2968                         if (!err)
2969                                 err = rename_node(f, olddir, oldname, newdir,
2970                                                   newname, 0);
2971                 }
2972                 fuse_finish_interrupt(f, req, &d);
2973                 free_path2(f, olddir, newdir, wnode1, wnode2, oldpath, newpath);
2974         }
2975         reply_err(req, err);
2976 }
2977
2978 static void fuse_lib_link(fuse_req_t req, fuse_ino_t ino, fuse_ino_t newparent,
2979                           const char *newname)
2980 {
2981         struct fuse *f = req_fuse_prepare(req);
2982         struct fuse_entry_param e;
2983         char *oldpath;
2984         char *newpath;
2985         int err;
2986
2987         err = get_path2(f, ino, NULL, newparent, newname,
2988                         &oldpath, &newpath, NULL, NULL);
2989         if (!err) {
2990                 struct fuse_intr_data d;
2991
2992                 fuse_prepare_interrupt(f, req, &d);
2993                 err = fuse_fs_link(f->fs, oldpath, newpath);
2994                 if (!err)
2995                         err = lookup_path(f, newparent, newname, newpath,
2996                                           &e, NULL);
2997                 fuse_finish_interrupt(f, req, &d);
2998                 free_path2(f, ino, newparent, NULL, NULL, oldpath, newpath);
2999         }
3000         reply_entry(req, &e, err);
3001 }
3002
3003 static void fuse_do_release(struct fuse *f, fuse_ino_t ino, const char *path,
3004                             struct fuse_file_info *fi)
3005 {
3006         struct node *node;
3007         int unlink_hidden = 0;
3008         const char *compatpath;
3009
3010         if (path != NULL || f->nullpath_ok || f->conf.nopath)
3011                 compatpath = path;
3012         else
3013                 compatpath = "-";
3014
3015         fuse_fs_release(f->fs, compatpath, fi);
3016
3017         pthread_mutex_lock(&f->lock);
3018         node = get_node(f, ino);
3019         assert(node->open_count > 0);
3020         --node->open_count;
3021         if (node->is_hidden && !node->open_count) {
3022                 unlink_hidden = 1;
3023                 node->is_hidden = 0;
3024         }
3025         pthread_mutex_unlock(&f->lock);
3026
3027         if(unlink_hidden) {
3028                 if (path) {
3029                         fuse_fs_unlink(f->fs, path);
3030                 } else if (f->conf.nopath) {
3031                         char *unlinkpath;
3032
3033                         if (get_path(f, ino, &unlinkpath) == 0)
3034                                 fuse_fs_unlink(f->fs, unlinkpath);
3035
3036                         free_path(f, ino, unlinkpath);
3037                 }
3038         }
3039 }
3040
3041 static void fuse_lib_create(fuse_req_t req, fuse_ino_t parent,
3042                             const char *name, mode_t mode,
3043                             struct fuse_file_info *fi)
3044 {
3045         struct fuse *f = req_fuse_prepare(req);
3046         struct fuse_intr_data d;
3047         struct fuse_entry_param e;
3048         char *path;
3049         int err;
3050
3051         err = get_path_name(f, parent, name, &path);
3052         if (!err) {
3053                 fuse_prepare_interrupt(f, req, &d);
3054                 err = fuse_fs_create(f->fs, path, mode, fi);
3055                 if (!err) {
3056                         err = lookup_path(f, parent, name, path, &e, fi);
3057                         if (err)
3058                                 fuse_fs_release(f->fs, path, fi);
3059                         else if (!S_ISREG(e.attr.st_mode)) {
3060                                 err = -EIO;
3061                                 fuse_fs_release(f->fs, path, fi);
3062                                 forget_node(f, e.ino, 1);
3063                         } else {
3064                                 if (f->conf.direct_io)
3065                                         fi->direct_io = 1;
3066                                 if (f->conf.kernel_cache)
3067                                         fi->keep_cache = 1;
3068
3069                         }
3070                 }
3071                 fuse_finish_interrupt(f, req, &d);
3072         }
3073         if (!err) {
3074                 pthread_mutex_lock(&f->lock);
3075                 get_node(f, e.ino)->open_count++;
3076                 pthread_mutex_unlock(&f->lock);
3077                 if (fuse_reply_create(req, &e, fi) == -ENOENT) {
3078                         /* The open syscall was interrupted, so it
3079                            must be cancelled */
3080                         fuse_do_release(f, e.ino, path, fi);
3081                         forget_node(f, e.ino, 1);
3082                 }
3083         } else {
3084                 reply_err(req, err);
3085         }
3086
3087         free_path(f, parent, path);
3088 }
3089
3090 static double diff_timespec(const struct timespec *t1,
3091                             const struct timespec *t2)
3092 {
3093         return (t1->tv_sec - t2->tv_sec) +
3094                 ((double) t1->tv_nsec - (double) t2->tv_nsec) / 1000000000.0;
3095 }
3096
3097 static void open_auto_cache(struct fuse *f, fuse_ino_t ino, const char *path,
3098                             struct fuse_file_info *fi)
3099 {
3100         struct node *node;
3101
3102         pthread_mutex_lock(&f->lock);
3103         node = get_node(f, ino);
3104         if (node->cache_valid) {
3105                 struct timespec now;
3106
3107                 curr_time(&now);
3108                 if (diff_timespec(&now, &node->stat_updated) >
3109                     f->conf.ac_attr_timeout) {
3110                         struct stat stbuf;
3111                         int err;
3112                         pthread_mutex_unlock(&f->lock);
3113                         err = fuse_fs_fgetattr(f->fs, path, &stbuf, fi);
3114                         pthread_mutex_lock(&f->lock);
3115                         if (!err)
3116                                 update_stat(node, &stbuf);
3117                         else
3118                                 node->cache_valid = 0;
3119                 }
3120         }
3121         if (node->cache_valid)
3122                 fi->keep_cache = 1;
3123
3124         node->cache_valid = 1;
3125         pthread_mutex_unlock(&f->lock);
3126 }
3127
3128 static void fuse_lib_open(fuse_req_t req, fuse_ino_t ino,
3129                           struct fuse_file_info *fi)
3130 {
3131         struct fuse *f = req_fuse_prepare(req);
3132         struct fuse_intr_data d;
3133         char *path;
3134         int err;
3135
3136         err = get_path(f, ino, &path);
3137         if (!err) {
3138                 fuse_prepare_interrupt(f, req, &d);
3139                 err = fuse_fs_open(f->fs, path, fi);
3140                 if (!err) {
3141                         if (f->conf.direct_io)
3142                                 fi->direct_io = 1;
3143                         if (f->conf.kernel_cache)
3144                                 fi->keep_cache = 1;
3145
3146                         if (f->conf.auto_cache)
3147                                 open_auto_cache(f, ino, path, fi);
3148                 }
3149                 fuse_finish_interrupt(f, req, &d);
3150         }
3151         if (!err) {
3152                 pthread_mutex_lock(&f->lock);
3153                 get_node(f, ino)->open_count++;
3154                 pthread_mutex_unlock(&f->lock);
3155                 if (fuse_reply_open(req, fi) == -ENOENT) {
3156                         /* The open syscall was interrupted, so it
3157                            must be cancelled */
3158                         fuse_do_release(f, ino, path, fi);
3159                 }
3160         } else
3161                 reply_err(req, err);
3162
3163         free_path(f, ino, path);
3164 }
3165
3166 static void fuse_lib_read(fuse_req_t req, fuse_ino_t ino, size_t size,
3167                           off_t off, struct fuse_file_info *fi)
3168 {
3169         struct fuse *f = req_fuse_prepare(req);
3170         struct fuse_bufvec *buf = NULL;
3171         char *path;
3172         int res;
3173
3174         res = get_path_nullok(f, ino, &path);
3175         if (res == 0) {
3176                 struct fuse_intr_data d;
3177
3178                 fuse_prepare_interrupt(f, req, &d);
3179                 res = fuse_fs_read_buf(f->fs, path, &buf, size, off, fi);
3180                 fuse_finish_interrupt(f, req, &d);
3181                 free_path(f, ino, path);
3182         }
3183
3184         if (res == 0)
3185                 fuse_reply_data(req, buf, FUSE_BUF_SPLICE_MOVE);
3186         else
3187                 reply_err(req, res);
3188
3189         fuse_free_buf(buf);
3190 }
3191
3192 static void fuse_lib_write_buf(fuse_req_t req, fuse_ino_t ino,
3193                                struct fuse_bufvec *buf, off_t off,
3194                                struct fuse_file_info *fi)
3195 {
3196         struct fuse *f = req_fuse_prepare(req);
3197         char *path;
3198         int res;
3199
3200         res = get_path_nullok(f, ino, &path);
3201         if (res == 0) {
3202                 struct fuse_intr_data d;
3203
3204                 fuse_prepare_interrupt(f, req, &d);
3205                 res = fuse_fs_write_buf(f->fs, path, buf, off, fi);
3206                 fuse_finish_interrupt(f, req, &d);
3207                 free_path(f, ino, path);
3208         }
3209
3210         if (res >= 0)
3211                 fuse_reply_write(req, res);
3212         else
3213                 reply_err(req, res);
3214 }
3215
3216 static void fuse_lib_fsync(fuse_req_t req, fuse_ino_t ino, int datasync,
3217                            struct fuse_file_info *fi)
3218 {
3219         struct fuse *f = req_fuse_prepare(req);
3220         char *path;
3221         int err;
3222
3223         err = get_path_nullok(f, ino, &path);
3224         if (!err) {
3225                 struct fuse_intr_data d;
3226
3227                 fuse_prepare_interrupt(f, req, &d);
3228                 err = fuse_fs_fsync(f->fs, path, datasync, fi);
3229                 fuse_finish_interrupt(f, req, &d);
3230                 free_path(f, ino, path);
3231         }
3232         reply_err(req, err);
3233 }
3234
3235 static struct fuse_dh *get_dirhandle(const struct fuse_file_info *llfi,
3236                                      struct fuse_file_info *fi)
3237 {
3238         struct fuse_dh *dh = (struct fuse_dh *) (uintptr_t) llfi->fh;
3239         memset(fi, 0, sizeof(struct fuse_file_info));
3240         fi->fh = dh->fh;
3241         fi->fh_old = dh->fh;
3242         return dh;
3243 }
3244
3245 static void fuse_lib_opendir(fuse_req_t req, fuse_ino_t ino,
3246                              struct fuse_file_info *llfi)
3247 {
3248         struct fuse *f = req_fuse_prepare(req);
3249         struct fuse_intr_data d;
3250         struct fuse_dh *dh;
3251         struct fuse_file_info fi;
3252         char *path;
3253         int err;
3254
3255         dh = (struct fuse_dh *) malloc(sizeof(struct fuse_dh));
3256         if (dh == NULL) {
3257                 reply_err(req, -ENOMEM);
3258                 return;
3259         }
3260         memset(dh, 0, sizeof(struct fuse_dh));
3261         dh->fuse = f;
3262         dh->contents = NULL;
3263         dh->len = 0;
3264         dh->filled = 0;
3265         dh->nodeid = ino;
3266         fuse_mutex_init(&dh->lock);
3267
3268         llfi->fh = (uintptr_t) dh;
3269
3270         memset(&fi, 0, sizeof(fi));
3271         fi.flags = llfi->flags;
3272
3273         err = get_path(f, ino, &path);
3274         if (!err) {
3275                 fuse_prepare_interrupt(f, req, &d);
3276                 err = fuse_fs_opendir(f->fs, path, &fi);
3277                 fuse_finish_interrupt(f, req, &d);
3278                 dh->fh = fi.fh;
3279         }
3280         if (!err) {
3281                 if (fuse_reply_open(req, llfi) == -ENOENT) {
3282                         /* The opendir syscall was interrupted, so it
3283                            must be cancelled */
3284                         fuse_fs_releasedir(f->fs, path, &fi);
3285                         pthread_mutex_destroy(&dh->lock);
3286                         free(dh);
3287                 }
3288         } else {
3289                 reply_err(req, err);
3290                 pthread_mutex_destroy(&dh->lock);
3291                 free(dh);
3292         }
3293         free_path(f, ino, path);
3294 }
3295
3296 static int extend_contents(struct fuse_dh *dh, unsigned minsize)
3297 {
3298         if (minsize > dh->size) {
3299                 char *newptr;
3300                 unsigned newsize = dh->size;
3301                 if (!newsize)
3302                         newsize = 1024;
3303                 while (newsize < minsize) {
3304                         if (newsize >= 0x80000000)
3305                                 newsize = 0xffffffff;
3306                         else
3307                                 newsize *= 2;
3308                 }
3309
3310                 newptr = (char *) realloc(dh->contents, newsize);
3311                 if (!newptr) {
3312                         dh->error = -ENOMEM;
3313                         return -1;
3314                 }
3315                 dh->contents = newptr;
3316                 dh->size = newsize;
3317         }
3318         return 0;
3319 }
3320
3321 static int fill_dir(void *dh_, const char *name, const struct stat *statp,
3322                     off_t off)
3323 {
3324         struct fuse_dh *dh = (struct fuse_dh *) dh_;
3325         struct stat stbuf;
3326         size_t newlen;
3327
3328         if (statp)
3329                 stbuf = *statp;
3330         else {
3331                 memset(&stbuf, 0, sizeof(stbuf));
3332                 stbuf.st_ino = FUSE_UNKNOWN_INO;
3333         }
3334
3335         if (!dh->fuse->conf.use_ino) {
3336                 stbuf.st_ino = FUSE_UNKNOWN_INO;
3337                 if (dh->fuse->conf.readdir_ino) {
3338                         struct node *node;
3339                         pthread_mutex_lock(&dh->fuse->lock);
3340                         node = lookup_node(dh->fuse, dh->nodeid, name);
3341                         if (node)
3342                                 stbuf.st_ino  = (ino_t) node->nodeid;
3343                         pthread_mutex_unlock(&dh->fuse->lock);
3344                 }
3345         }
3346
3347         if (off) {
3348                 if (extend_contents(dh, dh->needlen) == -1)
3349                         return 1;
3350
3351                 dh->filled = 0;
3352                 newlen = dh->len +
3353                         fuse_add_direntry(dh->req, dh->contents + dh->len,
3354                                           dh->needlen - dh->len, name,
3355                                           &stbuf, off);
3356                 if (newlen > dh->needlen)
3357                         return 1;
3358         } else {
3359                 newlen = dh->len +
3360                         fuse_add_direntry(dh->req, NULL, 0, name, NULL, 0);
3361                 if (extend_contents(dh, newlen) == -1)
3362                         return 1;
3363
3364                 fuse_add_direntry(dh->req, dh->contents + dh->len,
3365                                   dh->size - dh->len, name, &stbuf, newlen);
3366         }
3367         dh->len = newlen;
3368         return 0;
3369 }
3370
3371 static int readdir_fill(struct fuse *f, fuse_req_t req, fuse_ino_t ino,
3372                         size_t size, off_t off, struct fuse_dh *dh,
3373                         struct fuse_file_info *fi)
3374 {
3375         char *path;
3376         int err;
3377
3378         if (f->fs->op.readdir)
3379                 err = get_path_nullok(f, ino, &path);
3380         else
3381                 err = get_path(f, ino, &path);
3382         if (!err) {
3383                 struct fuse_intr_data d;
3384
3385                 dh->len = 0;
3386                 dh->error = 0;
3387                 dh->needlen = size;
3388                 dh->filled = 1;
3389                 dh->req = req;
3390                 fuse_prepare_interrupt(f, req, &d);
3391                 err = fuse_fs_readdir(f->fs, path, dh, fill_dir, off, fi);
3392                 fuse_finish_interrupt(f, req, &d);
3393                 dh->req = NULL;
3394                 if (!err)
3395                         err = dh->error;
3396                 if (err)
3397                         dh->filled = 0;
3398                 free_path(f, ino, path);
3399         }
3400         return err;
3401 }
3402
3403 static void fuse_lib_readdir(fuse_req_t req, fuse_ino_t ino, size_t size,
3404                              off_t off, struct fuse_file_info *llfi)
3405 {
3406         struct fuse *f = req_fuse_prepare(req);
3407         struct fuse_file_info fi;
3408         struct fuse_dh *dh = get_dirhandle(llfi, &fi);
3409
3410         pthread_mutex_lock(&dh->lock);
3411         /* According to SUS, directory contents need to be refreshed on
3412            rewinddir() */
3413         if (!off)
3414                 dh->filled = 0;
3415
3416         if (!dh->filled) {
3417                 int err = readdir_fill(f, req, ino, size, off, dh, &fi);
3418                 if (err) {
3419                         reply_err(req, err);
3420                         goto out;
3421                 }
3422         }
3423         if (dh->filled) {
3424                 if (off < dh->len) {
3425                         if (off + size > dh->len)
3426                                 size = dh->len - off;
3427                 } else
3428                         size = 0;
3429         } else {
3430                 size = dh->len;
3431                 off = 0;
3432         }
3433         fuse_reply_buf(req, dh->contents + off, size);
3434 out:
3435         pthread_mutex_unlock(&dh->lock);
3436 }
3437
3438 static void fuse_lib_releasedir(fuse_req_t req, fuse_ino_t ino,
3439                                 struct fuse_file_info *llfi)
3440 {
3441         struct fuse *f = req_fuse_prepare(req);
3442         struct fuse_intr_data d;
3443         struct fuse_file_info fi;
3444         struct fuse_dh *dh = get_dirhandle(llfi, &fi);
3445         char *path;
3446         const char *compatpath;
3447
3448         get_path_nullok(f, ino, &path);
3449         if (path != NULL || f->nullpath_ok || f->conf.nopath)
3450                 compatpath = path;
3451         else
3452                 compatpath = "-";
3453
3454         fuse_prepare_interrupt(f, req, &d);
3455         fuse_fs_releasedir(f->fs, compatpath, &fi);
3456         fuse_finish_interrupt(f, req, &d);
3457         free_path(f, ino, path);
3458
3459         pthread_mutex_lock(&dh->lock);
3460         pthread_mutex_unlock(&dh->lock);
3461         pthread_mutex_destroy(&dh->lock);
3462         free(dh->contents);
3463         free(dh);
3464         reply_err(req, 0);
3465 }
3466
3467 static void fuse_lib_fsyncdir(fuse_req_t req, fuse_ino_t ino, int datasync,
3468                               struct fuse_file_info *llfi)
3469 {
3470         struct fuse *f = req_fuse_prepare(req);
3471         struct fuse_file_info fi;
3472         char *path;
3473         int err;
3474
3475         get_dirhandle(llfi, &fi);
3476
3477         err = get_path_nullok(f, ino, &path);
3478         if (!err) {
3479                 struct fuse_intr_data d;
3480                 fuse_prepare_interrupt(f, req, &d);
3481                 err = fuse_fs_fsyncdir(f->fs, path, datasync, &fi);
3482                 fuse_finish_interrupt(f, req, &d);
3483                 free_path(f, ino, path);
3484         }
3485         reply_err(req, err);
3486 }
3487
3488 static void fuse_lib_statfs(fuse_req_t req, fuse_ino_t ino)
3489 {
3490         struct fuse *f = req_fuse_prepare(req);
3491         struct statvfs buf;
3492         char *path = NULL;
3493         int err = 0;
3494
3495         memset(&buf, 0, sizeof(buf));
3496         if (ino)
3497                 err = get_path(f, ino, &path);
3498
3499         if (!err) {
3500                 struct fuse_intr_data d;
3501                 fuse_prepare_interrupt(f, req, &d);
3502                 err = fuse_fs_statfs(f->fs, path ? path : "/", &buf);
3503                 fuse_finish_interrupt(f, req, &d);
3504                 free_path(f, ino, path);
3505         }
3506
3507         if (!err)
3508                 fuse_reply_statfs(req, &buf);
3509         else
3510                 reply_err(req, err);
3511 }
3512
3513 static void fuse_lib_setxattr(fuse_req_t req, fuse_ino_t ino, const char *name,
3514                               const char *value, size_t size, int flags)
3515 {
3516         struct fuse *f = req_fuse_prepare(req);
3517         char *path;
3518         int err;
3519
3520         err = get_path(f, ino, &path);
3521         if (!err) {
3522                 struct fuse_intr_data d;
3523                 fuse_prepare_interrupt(f, req, &d);
3524                 err = fuse_fs_setxattr(f->fs, path, name, value, size, flags);
3525                 fuse_finish_interrupt(f, req, &d);
3526                 free_path(f, ino, path);
3527         }
3528         reply_err(req, err);
3529 }
3530
3531 static int common_getxattr(struct fuse *f, fuse_req_t req, fuse_ino_t ino,
3532                            const char *name, char *value, size_t size)
3533 {
3534         int err;
3535         char *path;
3536
3537         err = get_path(f, ino, &path);
3538         if (!err) {
3539                 struct fuse_intr_data d;
3540                 fuse_prepare_interrupt(f, req, &d);
3541                 err = fuse_fs_getxattr(f->fs, path, name, value, size);
3542                 fuse_finish_interrupt(f, req, &d);
3543                 free_path(f, ino, path);
3544         }
3545         return err;
3546 }
3547
3548 static void fuse_lib_getxattr(fuse_req_t req, fuse_ino_t ino, const char *name,
3549                               size_t size)
3550 {
3551         struct fuse *f = req_fuse_prepare(req);
3552         int res;
3553
3554         if (size) {
3555                 char *value = (char *) malloc(size);
3556                 if (value == NULL) {
3557                         reply_err(req, -ENOMEM);
3558                         return;
3559                 }
3560                 res = common_getxattr(f, req, ino, name, value, size);
3561                 if (res > 0)
3562                         fuse_reply_buf(req, value, res);
3563                 else
3564                         reply_err(req, res);
3565                 free(value);
3566         } else {
3567                 res = common_getxattr(f, req, ino, name, NULL, 0);
3568                 if (res >= 0)
3569                         fuse_reply_xattr(req, res);
3570                 else
3571                         reply_err(req, res);
3572         }
3573 }
3574
3575 static int common_listxattr(struct fuse *f, fuse_req_t req, fuse_ino_t ino,
3576                             char *list, size_t size)
3577 {
3578         char *path;
3579         int err;
3580
3581         err = get_path(f, ino, &path);
3582         if (!err) {
3583                 struct fuse_intr_data d;
3584                 fuse_prepare_interrupt(f, req, &d);
3585                 err = fuse_fs_listxattr(f->fs, path, list, size);
3586                 fuse_finish_interrupt(f, req, &d);
3587                 free_path(f, ino, path);
3588         }
3589         return err;
3590 }
3591
3592 static void fuse_lib_listxattr(fuse_req_t req, fuse_ino_t ino, size_t size)
3593 {
3594         struct fuse *f = req_fuse_prepare(req);
3595         int res;
3596
3597         if (size) {
3598                 char *list = (char *) malloc(size);
3599                 if (list == NULL) {
3600                         reply_err(req, -ENOMEM);
3601                         return;
3602                 }
3603                 res = common_listxattr(f, req, ino, list, size);
3604                 if (res > 0)
3605                         fuse_reply_buf(req, list, res);
3606                 else
3607                         reply_err(req, res);
3608                 free(list);
3609         } else {
3610                 res = common_listxattr(f, req, ino, NULL, 0);
3611                 if (res >= 0)
3612                         fuse_reply_xattr(req, res);
3613                 else
3614                         reply_err(req, res);
3615         }
3616 }
3617
3618 static void fuse_lib_removexattr(fuse_req_t req, fuse_ino_t ino,
3619                                  const char *name)
3620 {
3621         struct fuse *f = req_fuse_prepare(req);
3622         char *path;
3623         int err;
3624
3625         err = get_path(f, ino, &path);
3626         if (!err) {
3627                 struct fuse_intr_data d;
3628                 fuse_prepare_interrupt(f, req, &d);
3629                 err = fuse_fs_removexattr(f->fs, path, name);
3630                 fuse_finish_interrupt(f, req, &d);
3631                 free_path(f, ino, path);
3632         }
3633         reply_err(req, err);
3634 }
3635
3636 static struct lock *locks_conflict(struct node *node, const struct lock *lock)
3637 {
3638         struct lock *l;
3639
3640         for (l = node->locks; l; l = l->next)
3641                 if (l->owner != lock->owner &&
3642                     lock->start <= l->end && l->start <= lock->end &&
3643                     (l->type == F_WRLCK || lock->type == F_WRLCK))
3644                         break;
3645
3646         return l;
3647 }
3648
3649 static void delete_lock(struct lock **lockp)
3650 {
3651         struct lock *l = *lockp;
3652         *lockp = l->next;
3653         free(l);
3654 }
3655
3656 static void insert_lock(struct lock **pos, struct lock *lock)
3657 {
3658         lock->next = *pos;
3659         *pos = lock;
3660 }
3661
3662 static int locks_insert(struct node *node, struct lock *lock)
3663 {
3664         struct lock **lp;
3665         struct lock *newl1 = NULL;
3666         struct lock *newl2 = NULL;
3667
3668         if (lock->type != F_UNLCK || lock->start != 0 ||
3669             lock->end != OFFSET_MAX) {
3670                 newl1 = malloc(sizeof(struct lock));
3671                 newl2 = malloc(sizeof(struct lock));
3672
3673                 if (!newl1 || !newl2) {
3674                         free(newl1);
3675                         free(newl2);
3676                         return -ENOLCK;
3677                 }
3678         }
3679
3680         for (lp = &node->locks; *lp;) {
3681                 struct lock *l = *lp;
3682                 if (l->owner != lock->owner)
3683                         goto skip;
3684
3685                 if (lock->type == l->type) {
3686                         if (l->end < lock->start - 1)
3687                                 goto skip;
3688                         if (lock->end < l->start - 1)
3689                                 break;
3690                         if (l->start <= lock->start && lock->end <= l->end)
3691                                 goto out;
3692                         if (l->start < lock->start)
3693                                 lock->start = l->start;
3694                         if (lock->end < l->end)
3695                                 lock->end = l->end;
3696                         goto delete;
3697                 } else {
3698                         if (l->end < lock->start)
3699                                 goto skip;
3700                         if (lock->end < l->start)
3701                                 break;
3702                         if (lock->start <= l->start && l->end <= lock->end)
3703                                 goto delete;
3704                         if (l->end <= lock->end) {
3705                                 l->end = lock->start - 1;
3706                                 goto skip;
3707                         }
3708                         if (lock->start <= l->start) {
3709                                 l->start = lock->end + 1;
3710                                 break;
3711                         }
3712                         *newl2 = *l;
3713                         newl2->start = lock->end + 1;
3714                         l->end = lock->start - 1;
3715                         insert_lock(&l->next, newl2);
3716                         newl2 = NULL;
3717                 }
3718         skip:
3719                 lp = &l->next;
3720                 continue;
3721
3722         delete:
3723                 delete_lock(lp);
3724         }
3725         if (lock->type != F_UNLCK) {
3726                 *newl1 = *lock;
3727                 insert_lock(lp, newl1);
3728                 newl1 = NULL;
3729         }
3730 out:
3731         free(newl1);
3732         free(newl2);
3733         return 0;
3734 }
3735
3736 static void flock_to_lock(struct flock *flock, struct lock *lock)
3737 {
3738         memset(lock, 0, sizeof(struct lock));
3739         lock->type = flock->l_type;
3740         lock->start = flock->l_start;
3741         lock->end =
3742                 flock->l_len ? flock->l_start + flock->l_len - 1 : OFFSET_MAX;
3743         lock->pid = flock->l_pid;
3744 }
3745
3746 static void lock_to_flock(struct lock *lock, struct flock *flock)
3747 {
3748         flock->l_type = lock->type;
3749         flock->l_start = lock->start;
3750         flock->l_len =
3751                 (lock->end == OFFSET_MAX) ? 0 : lock->end - lock->start + 1;
3752         flock->l_pid = lock->pid;
3753 }
3754
3755 static int fuse_flush_common(struct fuse *f, fuse_req_t req, fuse_ino_t ino,
3756                              const char *path, struct fuse_file_info *fi)
3757 {
3758         struct fuse_intr_data d;
3759         struct flock lock;
3760         struct lock l;
3761         int err;
3762         int errlock;
3763
3764         fuse_prepare_interrupt(f, req, &d);
3765         memset(&lock, 0, sizeof(lock));
3766         lock.l_type = F_UNLCK;
3767         lock.l_whence = SEEK_SET;
3768         err = fuse_fs_flush(f->fs, path, fi);
3769         errlock = fuse_fs_lock(f->fs, path, fi, F_SETLK, &lock);
3770         fuse_finish_interrupt(f, req, &d);
3771
3772         if (errlock != -ENOSYS) {
3773                 flock_to_lock(&lock, &l);
3774                 l.owner = fi->lock_owner;
3775                 pthread_mutex_lock(&f->lock);
3776                 locks_insert(get_node(f, ino), &l);
3777                 pthread_mutex_unlock(&f->lock);
3778
3779                 /* if op.lock() is defined FLUSH is needed regardless
3780                    of op.flush() */
3781                 if (err == -ENOSYS)
3782                         err = 0;
3783         }
3784         return err;
3785 }
3786
3787 static void fuse_lib_release(fuse_req_t req, fuse_ino_t ino,
3788                              struct fuse_file_info *fi)
3789 {
3790         struct fuse *f = req_fuse_prepare(req);
3791         struct fuse_intr_data d;
3792         char *path;
3793         int err = 0;
3794
3795         get_path_nullok(f, ino, &path);
3796         if (fi->flush) {
3797                 err = fuse_flush_common(f, req, ino, path, fi);
3798                 if (err == -ENOSYS)
3799                         err = 0;
3800         }
3801
3802         fuse_prepare_interrupt(f, req, &d);
3803         fuse_do_release(f, ino, path, fi);
3804         fuse_finish_interrupt(f, req, &d);
3805         free_path(f, ino, path);
3806
3807         reply_err(req, err);
3808 }
3809
3810 static void fuse_lib_flush(fuse_req_t req, fuse_ino_t ino,
3811                            struct fuse_file_info *fi)
3812 {
3813         struct fuse *f = req_fuse_prepare(req);
3814         char *path;
3815         int err;
3816
3817         get_path_nullok(f, ino, &path);
3818         err = fuse_flush_common(f, req, ino, path, fi);
3819         free_path(f, ino, path);
3820
3821         reply_err(req, err);
3822 }
3823
3824 static int fuse_lock_common(fuse_req_t req, fuse_ino_t ino,
3825                             struct fuse_file_info *fi, struct flock *lock,
3826                             int cmd)
3827 {
3828         struct fuse *f = req_fuse_prepare(req);
3829         char *path;
3830         int err;
3831
3832         err = get_path_nullok(f, ino, &path);
3833         if (!err) {
3834                 struct fuse_intr_data d;
3835                 fuse_prepare_interrupt(f, req, &d);
3836                 err = fuse_fs_lock(f->fs, path, fi, cmd, lock);
3837                 fuse_finish_interrupt(f, req, &d);
3838                 free_path(f, ino, path);
3839         }
3840         return err;
3841 }
3842
3843 static void fuse_lib_getlk(fuse_req_t req, fuse_ino_t ino,
3844                            struct fuse_file_info *fi, struct flock *lock)
3845 {
3846         int err;
3847         struct lock l;
3848         struct lock *conflict;
3849         struct fuse *f = req_fuse(req);
3850
3851         flock_to_lock(lock, &l);
3852         l.owner = fi->lock_owner;
3853         pthread_mutex_lock(&f->lock);
3854         conflict = locks_conflict(get_node(f, ino), &l);
3855         if (conflict)
3856                 lock_to_flock(conflict, lock);
3857         pthread_mutex_unlock(&f->lock);
3858         if (!conflict)
3859                 err = fuse_lock_common(req, ino, fi, lock, F_GETLK);
3860         else
3861                 err = 0;
3862
3863         if (!err)
3864                 fuse_reply_lock(req, lock);
3865         else
3866                 reply_err(req, err);
3867 }
3868
3869 static void fuse_lib_setlk(fuse_req_t req, fuse_ino_t ino,
3870                            struct fuse_file_info *fi, struct flock *lock,
3871                            int sleep)
3872 {
3873         int err = fuse_lock_common(req, ino, fi, lock,
3874                                    sleep ? F_SETLKW : F_SETLK);
3875         if (!err) {
3876                 struct fuse *f = req_fuse(req);
3877                 struct lock l;
3878                 flock_to_lock(lock, &l);
3879                 l.owner = fi->lock_owner;
3880                 pthread_mutex_lock(&f->lock);
3881                 locks_insert(get_node(f, ino), &l);
3882                 pthread_mutex_unlock(&f->lock);
3883         }
3884         reply_err(req, err);
3885 }
3886
3887 static void fuse_lib_flock(fuse_req_t req, fuse_ino_t ino,
3888                            struct fuse_file_info *fi, int op)
3889 {
3890         struct fuse *f = req_fuse_prepare(req);
3891         char *path;
3892         int err;
3893
3894         err = get_path_nullok(f, ino, &path);
3895         if (err == 0) {
3896                 struct fuse_intr_data d;
3897                 fuse_prepare_interrupt(f, req, &d);
3898                 err = fuse_fs_flock(f->fs, path, fi, op);
3899                 fuse_finish_interrupt(f, req, &d);
3900                 free_path(f, ino, path);
3901         }
3902         reply_err(req, err);
3903 }
3904
3905 static void fuse_lib_bmap(fuse_req_t req, fuse_ino_t ino, size_t blocksize,
3906                           uint64_t idx)
3907 {
3908         struct fuse *f = req_fuse_prepare(req);
3909         struct fuse_intr_data d;
3910         char *path;
3911         int err;
3912
3913         err = get_path(f, ino, &path);
3914         if (!err) {
3915                 fuse_prepare_interrupt(f, req, &d);
3916                 err = fuse_fs_bmap(f->fs, path, blocksize, &idx);
3917                 fuse_finish_interrupt(f, req, &d);
3918                 free_path(f, ino, path);
3919         }
3920         if (!err)
3921                 fuse_reply_bmap(req, idx);
3922         else
3923                 reply_err(req, err);
3924 }
3925
3926 static void fuse_lib_ioctl(fuse_req_t req, fuse_ino_t ino, int cmd, void *arg,
3927                            struct fuse_file_info *fi, unsigned int flags,
3928                            const void *in_buf, size_t in_bufsz,
3929                            size_t out_bufsz)
3930 {
3931         struct fuse *f = req_fuse_prepare(req);
3932         struct fuse_intr_data d;
3933         char *path, *out_buf = NULL;
3934         int err;
3935
3936         err = -EPERM;
3937         if (flags & FUSE_IOCTL_UNRESTRICTED)
3938                 goto err;
3939
3940         if (out_bufsz) {
3941                 err = -ENOMEM;
3942                 out_buf = malloc(out_bufsz);
3943                 if (!out_buf)
3944                         goto err;
3945         }
3946
3947         assert(!in_bufsz || !out_bufsz || in_bufsz == out_bufsz);
3948         if (out_buf)
3949                 memcpy(out_buf, in_buf, in_bufsz);
3950
3951         err = get_path_nullok(f, ino, &path);
3952         if (err)
3953                 goto err;
3954
3955         fuse_prepare_interrupt(f, req, &d);
3956
3957         err = fuse_fs_ioctl(f->fs, path, cmd, arg, fi, flags,
3958                             out_buf ?: (void *)in_buf);
3959
3960         fuse_finish_interrupt(f, req, &d);
3961         free_path(f, ino, path);
3962
3963         fuse_reply_ioctl(req, err, out_buf, out_bufsz);
3964         goto out;
3965 err:
3966         reply_err(req, err);
3967 out:
3968         free(out_buf);
3969 }
3970
3971 static void fuse_lib_poll(fuse_req_t req, fuse_ino_t ino,
3972                           struct fuse_file_info *fi, struct fuse_pollhandle *ph)
3973 {
3974         struct fuse *f = req_fuse_prepare(req);
3975         struct fuse_intr_data d;
3976         char *path;
3977         int err;
3978         unsigned revents = 0;
3979
3980         err = get_path_nullok(f, ino, &path);
3981         if (!err) {
3982                 fuse_prepare_interrupt(f, req, &d);
3983                 err = fuse_fs_poll(f->fs, path, fi, ph, &revents);
3984                 fuse_finish_interrupt(f, req, &d);
3985                 free_path(f, ino, path);
3986         }
3987         if (!err)
3988                 fuse_reply_poll(req, revents);
3989         else
3990                 reply_err(req, err);
3991 }
3992
3993 static int clean_delay(struct fuse *f)
3994 {
3995         /*
3996          * This is calculating the delay between clean runs.  To
3997          * reduce the number of cleans we are doing them 10 times
3998          * within the remember window.
3999          */
4000         int min_sleep = 60;
4001         int max_sleep = 3600;
4002         int sleep_time = f->conf.remember / 10;
4003
4004         if (sleep_time > max_sleep)
4005                 return max_sleep;
4006         if (sleep_time < min_sleep)
4007                 return min_sleep;
4008         return sleep_time;
4009 }
4010
4011 int fuse_clean_cache(struct fuse *f)
4012 {
4013         struct node_lru *lnode;
4014         struct list_head *curr, *next;
4015         struct node *node;
4016         struct timespec now;
4017
4018         pthread_mutex_lock(&f->lock);
4019
4020         curr_time(&now);
4021
4022         for (curr = f->lru_table.next; curr != &f->lru_table; curr = next) {
4023                 double age;
4024
4025                 next = curr->next;
4026                 lnode = list_entry(curr, struct node_lru, lru);
4027                 node = &lnode->node;
4028
4029                 age = diff_timespec(&now, &lnode->forget_time);
4030                 if (age <= f->conf.remember)
4031                         break;
4032
4033                 assert(node->nlookup == 1);
4034
4035                 /* Don't forget active directories */
4036                 if (node->refctr > 1)
4037                         continue;
4038
4039                 node->nlookup = 0;
4040                 unhash_name(f, node);
4041                 unref_node(f, node);
4042         }
4043         pthread_mutex_unlock(&f->lock);
4044
4045         return clean_delay(f);
4046 }
4047
4048 static struct fuse_lowlevel_ops fuse_path_ops = {
4049         .init = fuse_lib_init,
4050         .destroy = fuse_lib_destroy,
4051         .lookup = fuse_lib_lookup,
4052         .forget = fuse_lib_forget,
4053         .forget_multi = fuse_lib_forget_multi,
4054         .getattr = fuse_lib_getattr,
4055         .setattr = fuse_lib_setattr,
4056         .access = fuse_lib_access,
4057         .readlink = fuse_lib_readlink,
4058         .mknod = fuse_lib_mknod,
4059         .mkdir = fuse_lib_mkdir,
4060         .unlink = fuse_lib_unlink,
4061         .rmdir = fuse_lib_rmdir,
4062         .symlink = fuse_lib_symlink,
4063         .rename = fuse_lib_rename,
4064         .link = fuse_lib_link,
4065         .create = fuse_lib_create,
4066         .open = fuse_lib_open,
4067         .read = fuse_lib_read,
4068         .write_buf = fuse_lib_write_buf,
4069         .flush = fuse_lib_flush,
4070         .release = fuse_lib_release,
4071         .fsync = fuse_lib_fsync,
4072         .opendir = fuse_lib_opendir,
4073         .readdir = fuse_lib_readdir,
4074         .releasedir = fuse_lib_releasedir,
4075         .fsyncdir = fuse_lib_fsyncdir,
4076         .statfs = fuse_lib_statfs,
4077         .setxattr = fuse_lib_setxattr,
4078         .getxattr = fuse_lib_getxattr,
4079         .listxattr = fuse_lib_listxattr,
4080         .removexattr = fuse_lib_removexattr,
4081         .getlk = fuse_lib_getlk,
4082         .setlk = fuse_lib_setlk,
4083         .flock = fuse_lib_flock,
4084         .bmap = fuse_lib_bmap,
4085         .ioctl = fuse_lib_ioctl,
4086         .poll = fuse_lib_poll,
4087 };
4088
4089 int fuse_notify_poll(struct fuse_pollhandle *ph)
4090 {
4091         return fuse_lowlevel_notify_poll(ph);
4092 }
4093
4094 static void free_cmd(struct fuse_cmd *cmd)
4095 {
4096         free(cmd->buf);
4097         free(cmd);
4098 }
4099
4100 void fuse_process_cmd(struct fuse *f, struct fuse_cmd *cmd)
4101 {
4102         fuse_session_process(f->se, cmd->buf, cmd->buflen, cmd->ch);
4103         free_cmd(cmd);
4104 }
4105
4106 int fuse_exited(struct fuse *f)
4107 {
4108         return fuse_session_exited(f->se);
4109 }
4110
4111 struct fuse_session *fuse_get_session(struct fuse *f)
4112 {
4113         return f->se;
4114 }
4115
4116 static struct fuse_cmd *fuse_alloc_cmd(size_t bufsize)
4117 {
4118         struct fuse_cmd *cmd = (struct fuse_cmd *) malloc(sizeof(*cmd));
4119         if (cmd == NULL) {
4120                 fprintf(stderr, "fuse: failed to allocate cmd\n");
4121                 return NULL;
4122         }
4123         cmd->buf = (char *) malloc(bufsize);
4124         if (cmd->buf == NULL) {
4125                 fprintf(stderr, "fuse: failed to allocate read buffer\n");
4126                 free(cmd);
4127                 return NULL;
4128         }
4129         return cmd;
4130 }
4131
4132 struct fuse_cmd *fuse_read_cmd(struct fuse *f)
4133 {
4134         struct fuse_chan *ch = fuse_session_next_chan(f->se, NULL);
4135         size_t bufsize = fuse_chan_bufsize(ch);
4136         struct fuse_cmd *cmd = fuse_alloc_cmd(bufsize);
4137         if (cmd != NULL) {
4138                 int res = fuse_chan_recv(&ch, cmd->buf, bufsize);
4139                 if (res <= 0) {
4140                         free_cmd(cmd);
4141                         if (res < 0 && res != -EINTR && res != -EAGAIN)
4142                                 fuse_exit(f);
4143                         return NULL;
4144                 }
4145                 cmd->buflen = res;
4146                 cmd->ch = ch;
4147         }
4148         return cmd;
4149 }
4150
4151 static int fuse_session_loop_remember(struct fuse *f)
4152 {
4153         struct fuse_session *se = f->se;
4154         int res = 0;
4155         struct timespec now;
4156         time_t next_clean;
4157         struct fuse_chan *ch = fuse_session_next_chan(se, NULL);
4158         size_t bufsize = fuse_chan_bufsize(ch);
4159         char *buf = (char *) malloc(bufsize);
4160         struct pollfd fds = {
4161                 .fd = fuse_chan_fd(ch),
4162                 .events = POLLIN
4163         };
4164
4165         if (!buf) {
4166                 fprintf(stderr, "fuse: failed to allocate read buffer\n");
4167                 return -1;
4168         }
4169
4170         curr_time(&now);
4171         next_clean = now.tv_sec;
4172         while (!fuse_session_exited(se)) {
4173                 struct fuse_chan *tmpch = ch;
4174                 struct fuse_buf fbuf = {
4175                         .mem = buf,
4176                         .size = bufsize,
4177                 };
4178                 unsigned timeout;
4179
4180                 curr_time(&now);
4181                 if (now.tv_sec < next_clean)
4182                         timeout = next_clean - now.tv_sec;
4183                 else
4184                         timeout = 0;
4185
4186                 res = poll(&fds, 1, timeout * 1000);
4187                 if (res == -1) {
4188                         if (errno == -EINTR)
4189                                 continue;
4190                         else
4191                                 break;
4192                 } else if (res > 0) {
4193                         res = fuse_session_receive_buf(se, &fbuf, &tmpch);
4194
4195                         if (res == -EINTR)
4196                                 continue;
4197                         if (res <= 0)
4198                                 break;
4199
4200                         fuse_session_process_buf(se, &fbuf, tmpch);
4201                 } else {
4202                         timeout = fuse_clean_cache(f);
4203                         curr_time(&now);
4204                         next_clean = now.tv_sec + timeout;
4205                 }
4206         }
4207
4208         free(buf);
4209         fuse_session_reset(se);
4210         return res < 0 ? -1 : 0;
4211 }
4212
4213 int fuse_loop(struct fuse *f)
4214 {
4215         if (!f)
4216                 return -1;
4217
4218         if (lru_enabled(f))
4219                 return fuse_session_loop_remember(f);
4220
4221         return fuse_session_loop(f->se);
4222 }
4223
4224 int fuse_invalidate(struct fuse *f, const char *path)
4225 {
4226         (void) f;
4227         (void) path;
4228         return -EINVAL;
4229 }
4230
4231 void fuse_exit(struct fuse *f)
4232 {
4233         fuse_session_exit(f->se);
4234 }
4235
4236 struct fuse_context *fuse_get_context(void)
4237 {
4238         return &fuse_get_context_internal()->ctx;
4239 }
4240
4241 /*
4242  * The size of fuse_context got extended, so need to be careful about
4243  * incompatibility (i.e. a new binary cannot work with an old
4244  * library).
4245  */
4246 struct fuse_context *fuse_get_context_compat22(void);
4247 struct fuse_context *fuse_get_context_compat22(void)
4248 {
4249         return &fuse_get_context_internal()->ctx;
4250 }
4251 FUSE_SYMVER(".symver fuse_get_context_compat22,fuse_get_context@FUSE_2.2");
4252
4253 int fuse_getgroups(int size, gid_t list[])
4254 {
4255         fuse_req_t req = fuse_get_context_internal()->req;
4256         return fuse_req_getgroups(req, size, list);
4257 }
4258
4259 int fuse_interrupted(void)
4260 {
4261         return fuse_req_interrupted(fuse_get_context_internal()->req);
4262 }
4263
4264 void fuse_set_getcontext_func(struct fuse_context *(*func)(void))
4265 {
4266         (void) func;
4267         /* no-op */
4268 }
4269
4270 enum {
4271         KEY_HELP,
4272 };
4273
4274 #define FUSE_LIB_OPT(t, p, v) { t, offsetof(struct fuse_config, p), v }
4275
4276 static const struct fuse_opt fuse_lib_opts[] = {
4277         FUSE_OPT_KEY("-h",                    KEY_HELP),
4278         FUSE_OPT_KEY("--help",                KEY_HELP),
4279         FUSE_OPT_KEY("debug",                 FUSE_OPT_KEY_KEEP),
4280         FUSE_OPT_KEY("-d",                    FUSE_OPT_KEY_KEEP),
4281         FUSE_LIB_OPT("debug",                 debug, 1),
4282         FUSE_LIB_OPT("-d",                    debug, 1),
4283         FUSE_LIB_OPT("hard_remove",           hard_remove, 1),
4284         FUSE_LIB_OPT("use_ino",               use_ino, 1),
4285         FUSE_LIB_OPT("readdir_ino",           readdir_ino, 1),
4286         FUSE_LIB_OPT("direct_io",             direct_io, 1),
4287         FUSE_LIB_OPT("kernel_cache",          kernel_cache, 1),
4288         FUSE_LIB_OPT("auto_cache",            auto_cache, 1),
4289         FUSE_LIB_OPT("noauto_cache",          auto_cache, 0),
4290         FUSE_LIB_OPT("umask=",                set_mode, 1),
4291         FUSE_LIB_OPT("umask=%o",              umask, 0),
4292         FUSE_LIB_OPT("uid=",                  set_uid, 1),
4293         FUSE_LIB_OPT("uid=%d",                uid, 0),
4294         FUSE_LIB_OPT("gid=",                  set_gid, 1),
4295         FUSE_LIB_OPT("gid=%d",                gid, 0),
4296         FUSE_LIB_OPT("entry_timeout=%lf",     entry_timeout, 0),
4297         FUSE_LIB_OPT("attr_timeout=%lf",      attr_timeout, 0),
4298         FUSE_LIB_OPT("ac_attr_timeout=%lf",   ac_attr_timeout, 0),
4299         FUSE_LIB_OPT("ac_attr_timeout=",      ac_attr_timeout_set, 1),
4300         FUSE_LIB_OPT("negative_timeout=%lf",  negative_timeout, 0),
4301         FUSE_LIB_OPT("noforget",              remember, -1),
4302         FUSE_LIB_OPT("remember=%u",           remember, 0),
4303         FUSE_LIB_OPT("nopath",                nopath, 1),
4304         FUSE_LIB_OPT("intr",                  intr, 1),
4305         FUSE_LIB_OPT("intr_signal=%d",        intr_signal, 0),
4306         FUSE_LIB_OPT("modules=%s",            modules, 0),
4307         FUSE_OPT_END
4308 };
4309
4310 static void fuse_lib_help(void)
4311 {
4312         fprintf(stderr,
4313 "    -o hard_remove         immediate removal (don't hide files)\n"
4314 "    -o use_ino             let filesystem set inode numbers\n"
4315 "    -o readdir_ino         try to fill in d_ino in readdir\n"
4316 "    -o direct_io           use direct I/O\n"
4317 "    -o kernel_cache        cache files in kernel\n"
4318 "    -o [no]auto_cache      enable caching based on modification times (off)\n"
4319 "    -o umask=M             set file permissions (octal)\n"
4320 "    -o uid=N               set file owner\n"
4321 "    -o gid=N               set file group\n"
4322 "    -o entry_timeout=T     cache timeout for names (1.0s)\n"
4323 "    -o negative_timeout=T  cache timeout for deleted names (0.0s)\n"
4324 "    -o attr_timeout=T      cache timeout for attributes (1.0s)\n"
4325 "    -o ac_attr_timeout=T   auto cache timeout for attributes (attr_timeout)\n"
4326 "    -o noforget            never forget cached inodes\n"
4327 "    -o remember=T          remember cached inodes for T seconds (0s)\n"
4328 "    -o intr                allow requests to be interrupted\n"
4329 "    -o intr_signal=NUM     signal to send on interrupt (%i)\n"
4330 "    -o modules=M1[:M2...]  names of modules to push onto filesystem stack\n"
4331 "\n", FUSE_DEFAULT_INTR_SIGNAL);
4332 }
4333
4334 static void fuse_lib_help_modules(void)
4335 {
4336         struct fuse_module *m;
4337         fprintf(stderr, "\nModule options:\n");
4338         pthread_mutex_lock(&fuse_context_lock);
4339         for (m = fuse_modules; m; m = m->next) {
4340                 struct fuse_fs *fs = NULL;
4341                 struct fuse_fs *newfs;
4342                 struct fuse_args args = FUSE_ARGS_INIT(0, NULL);
4343                 if (fuse_opt_add_arg(&args, "") != -1 &&
4344                     fuse_opt_add_arg(&args, "-h") != -1) {
4345                         fprintf(stderr, "\n[%s]\n", m->name);
4346                         newfs = m->factory(&args, &fs);
4347                         assert(newfs == NULL);
4348                 }
4349                 fuse_opt_free_args(&args);
4350         }
4351         pthread_mutex_unlock(&fuse_context_lock);
4352 }
4353
4354 static int fuse_lib_opt_proc(void *data, const char *arg, int key,
4355                              struct fuse_args *outargs)
4356 {
4357         (void) arg; (void) outargs;
4358
4359         if (key == KEY_HELP) {
4360                 struct fuse_config *conf = (struct fuse_config *) data;
4361                 fuse_lib_help();
4362                 conf->help = 1;
4363         }
4364
4365         return 1;
4366 }
4367
4368 int fuse_is_lib_option(const char *opt)
4369 {
4370         return fuse_lowlevel_is_lib_option(opt) ||
4371                 fuse_opt_match(fuse_lib_opts, opt);
4372 }
4373
4374 static int fuse_init_intr_signal(int signum, int *installed)
4375 {
4376         struct sigaction old_sa;
4377
4378         if (sigaction(signum, NULL, &old_sa) == -1) {
4379                 perror("fuse: cannot get old signal handler");
4380                 return -1;
4381         }
4382
4383         if (old_sa.sa_handler == SIG_DFL) {
4384                 struct sigaction sa;
4385
4386                 memset(&sa, 0, sizeof(struct sigaction));
4387                 sa.sa_handler = fuse_intr_sighandler;
4388                 sigemptyset(&sa.sa_mask);
4389
4390                 if (sigaction(signum, &sa, NULL) == -1) {
4391                         perror("fuse: cannot set interrupt signal handler");
4392                         return -1;
4393                 }
4394                 *installed = 1;
4395         }
4396         return 0;
4397 }
4398
4399 static void fuse_restore_intr_signal(int signum)
4400 {
4401         struct sigaction sa;
4402
4403         memset(&sa, 0, sizeof(struct sigaction));
4404         sa.sa_handler = SIG_DFL;
4405         sigaction(signum, &sa, NULL);
4406 }
4407
4408
4409 static int fuse_push_module(struct fuse *f, const char *module,
4410                             struct fuse_args *args)
4411 {
4412         struct fuse_fs *fs[2] = { f->fs, NULL };
4413         struct fuse_fs *newfs;
4414         struct fuse_module *m = fuse_get_module(module);
4415
4416         if (!m)
4417                 return -1;
4418
4419         newfs = m->factory(args, fs);
4420         if (!newfs) {
4421                 fuse_put_module(m);
4422                 return -1;
4423         }
4424         newfs->m = m;
4425         f->fs = newfs;
4426         f->nullpath_ok = newfs->op.flag_nullpath_ok && f->nullpath_ok;
4427         f->conf.nopath = newfs->op.flag_nopath && f->conf.nopath;
4428         f->utime_omit_ok = newfs->op.flag_utime_omit_ok && f->utime_omit_ok;
4429         return 0;
4430 }
4431
4432 struct fuse_fs *fuse_fs_new(const struct fuse_operations *op, size_t op_size,
4433                             void *user_data)
4434 {
4435         struct fuse_fs *fs;
4436
4437         if (sizeof(struct fuse_operations) < op_size) {
4438                 fprintf(stderr, "fuse: warning: library too old, some operations may not not work\n");
4439                 op_size = sizeof(struct fuse_operations);
4440         }
4441
4442         fs = (struct fuse_fs *) calloc(1, sizeof(struct fuse_fs));
4443         if (!fs) {
4444                 fprintf(stderr, "fuse: failed to allocate fuse_fs object\n");
4445                 return NULL;
4446         }
4447
4448         fs->user_data = user_data;
4449         if (op)
4450                 memcpy(&fs->op, op, op_size);
4451         return fs;
4452 }
4453
4454 static int node_table_init(struct node_table *t)
4455 {
4456         t->size = NODE_TABLE_MIN_SIZE;
4457         t->array = (struct node **) calloc(1, sizeof(struct node *) * t->size);
4458         if (t->array == NULL) {
4459                 fprintf(stderr, "fuse: memory allocation failed\n");
4460                 return -1;
4461         }
4462         t->use = 0;
4463         t->split = 0;
4464
4465         return 0;
4466 }
4467
4468 static void *fuse_prune_nodes(void *fuse)
4469 {
4470         struct fuse *f = fuse;
4471         int sleep_time;
4472
4473         while(1) {
4474                 sleep_time = fuse_clean_cache(f);
4475                 sleep(sleep_time);
4476         }
4477         return NULL;
4478 }
4479
4480 int fuse_start_cleanup_thread(struct fuse *f)
4481 {
4482         if (lru_enabled(f))
4483                 return fuse_start_thread(&f->prune_thread, fuse_prune_nodes, f);
4484
4485         return 0;
4486 }
4487
4488 void fuse_stop_cleanup_thread(struct fuse *f)
4489 {
4490         if (lru_enabled(f)) {
4491                 pthread_mutex_lock(&f->lock);
4492                 pthread_cancel(f->prune_thread);
4493                 pthread_mutex_unlock(&f->lock);
4494                 pthread_join(f->prune_thread, NULL);
4495         }
4496 }
4497
4498 struct fuse *fuse_new_common(struct fuse_chan *ch, struct fuse_args *args,
4499                              const struct fuse_operations *op,
4500                              size_t op_size, void *user_data, int compat)
4501 {
4502         struct fuse *f;
4503         struct node *root;
4504         struct fuse_fs *fs;
4505         struct fuse_lowlevel_ops llop = fuse_path_ops;
4506
4507         if (fuse_create_context_key() == -1)
4508                 goto out;
4509
4510         f = (struct fuse *) calloc(1, sizeof(struct fuse));
4511         if (f == NULL) {
4512                 fprintf(stderr, "fuse: failed to allocate fuse object\n");
4513                 goto out_delete_context_key;
4514         }
4515
4516         fs = fuse_fs_new(op, op_size, user_data);
4517         if (!fs)
4518                 goto out_free;
4519
4520         fs->compat = compat;
4521         f->fs = fs;
4522         f->nullpath_ok = fs->op.flag_nullpath_ok;
4523         f->conf.nopath = fs->op.flag_nopath;
4524         f->utime_omit_ok = fs->op.flag_utime_omit_ok;
4525
4526         /* Oh f**k, this is ugly! */
4527         if (!fs->op.lock) {
4528                 llop.getlk = NULL;
4529                 llop.setlk = NULL;
4530         }
4531
4532         f->conf.entry_timeout = 1.0;
4533         f->conf.attr_timeout = 1.0;
4534         f->conf.negative_timeout = 0.0;
4535         f->conf.intr_signal = FUSE_DEFAULT_INTR_SIGNAL;
4536
4537         f->pagesize = getpagesize();
4538         init_list_head(&f->partial_slabs);
4539         init_list_head(&f->full_slabs);
4540         init_list_head(&f->lru_table);
4541
4542         if (fuse_opt_parse(args, &f->conf, fuse_lib_opts,
4543                            fuse_lib_opt_proc) == -1)
4544                 goto out_free_fs;
4545
4546         if (f->conf.modules) {
4547                 char *module;
4548                 char *next;
4549
4550                 for (module = f->conf.modules; module; module = next) {
4551                         char *p;
4552                         for (p = module; *p && *p != ':'; p++);
4553                         next = *p ? p + 1 : NULL;
4554                         *p = '\0';
4555                         if (module[0] &&
4556                             fuse_push_module(f, module, args) == -1)
4557                                 goto out_free_fs;
4558                 }
4559         }
4560
4561         if (!f->conf.ac_attr_timeout_set)
4562                 f->conf.ac_attr_timeout = f->conf.attr_timeout;
4563
4564 #if defined(__FreeBSD__) || defined(__NetBSD__)
4565         /*
4566          * In FreeBSD, we always use these settings as inode numbers
4567          * are needed to make getcwd(3) work.
4568          */
4569         f->conf.readdir_ino = 1;
4570 #endif
4571
4572         if (compat && compat <= 25) {
4573                 if (fuse_sync_compat_args(args) == -1)
4574                         goto out_free_fs;
4575         }
4576
4577         f->se = fuse_lowlevel_new_common(args, &llop, sizeof(llop), f);
4578         if (f->se == NULL) {
4579                 if (f->conf.help)
4580                         fuse_lib_help_modules();
4581                 goto out_free_fs;
4582         }
4583
4584         fuse_session_add_chan(f->se, ch);
4585
4586         if (f->conf.debug) {
4587                 fprintf(stderr, "nullpath_ok: %i\n", f->nullpath_ok);
4588                 fprintf(stderr, "nopath: %i\n", f->conf.nopath);
4589                 fprintf(stderr, "utime_omit_ok: %i\n", f->utime_omit_ok);
4590         }
4591
4592         /* Trace topmost layer by default */
4593         f->fs->debug = f->conf.debug;
4594         f->ctr = 0;
4595         f->generation = 0;
4596         if (node_table_init(&f->name_table) == -1)
4597                 goto out_free_session;
4598
4599         if (node_table_init(&f->id_table) == -1)
4600                 goto out_free_name_table;
4601
4602         fuse_mutex_init(&f->lock);
4603
4604         root = alloc_node(f);
4605         if (root == NULL) {
4606                 fprintf(stderr, "fuse: memory allocation failed\n");
4607                 goto out_free_id_table;
4608         }
4609
4610         strcpy(root->inline_name, "/");
4611         root->name = root->inline_name;
4612
4613         if (f->conf.intr &&
4614             fuse_init_intr_signal(f->conf.intr_signal,
4615                                   &f->intr_installed) == -1)
4616                 goto out_free_root;
4617
4618         root->parent = NULL;
4619         root->nodeid = FUSE_ROOT_ID;
4620         root->generation = 0;
4621         root->refctr = 1;
4622         root->nlookup = 1;
4623         hash_id(f, root);
4624
4625         return f;
4626
4627 out_free_root:
4628         free(root);
4629 out_free_id_table:
4630         free(f->id_table.array);
4631 out_free_name_table:
4632         free(f->name_table.array);
4633 out_free_session:
4634         fuse_session_destroy(f->se);
4635 out_free_fs:
4636         /* Horrible compatibility hack to stop the destructor from being
4637            called on the filesystem without init being called first */
4638         fs->op.destroy = NULL;
4639         fuse_fs_destroy(f->fs);
4640         free(f->conf.modules);
4641 out_free:
4642         free(f);
4643 out_delete_context_key:
4644         fuse_delete_context_key();
4645 out:
4646         return NULL;
4647 }
4648
4649 struct fuse *fuse_new(struct fuse_chan *ch, struct fuse_args *args,
4650                       const struct fuse_operations *op, size_t op_size,
4651                       void *user_data)
4652 {
4653         return fuse_new_common(ch, args, op, op_size, user_data, 0);
4654 }
4655
4656 void fuse_destroy(struct fuse *f)
4657 {
4658         size_t i;
4659
4660         if (f->conf.intr && f->intr_installed)
4661                 fuse_restore_intr_signal(f->conf.intr_signal);
4662
4663         if (f->fs) {
4664                 struct fuse_context_i *c = fuse_get_context_internal();
4665
4666                 memset(c, 0, sizeof(*c));
4667                 c->ctx.fuse = f;
4668
4669                 for (i = 0; i < f->id_table.size; i++) {
4670                         struct node *node;
4671
4672                         for (node = f->id_table.array[i]; node != NULL;
4673                              node = node->id_next) {
4674                                 if (node->is_hidden) {
4675                                         char *path;
4676                                         if (try_get_path(f, node->nodeid, NULL, &path, NULL, 0) == 0) {
4677                                                 fuse_fs_unlink(f->fs, path);
4678                                                 free(path);
4679                                         }
4680                                 }
4681                         }
4682                 }
4683         }
4684         for (i = 0; i < f->id_table.size; i++) {
4685                 struct node *node;
4686                 struct node *next;
4687
4688                 for (node = f->id_table.array[i]; node != NULL; node = next) {
4689                         next = node->id_next;
4690                         free_node(f, node);
4691                         f->id_table.use--;
4692                 }
4693         }
4694         assert(list_empty(&f->partial_slabs));
4695         assert(list_empty(&f->full_slabs));
4696
4697         free(f->id_table.array);
4698         free(f->name_table.array);
4699         pthread_mutex_destroy(&f->lock);
4700         fuse_session_destroy(f->se);
4701         free(f->conf.modules);
4702         free(f);
4703         fuse_delete_context_key();
4704 }
4705
4706 static struct fuse *fuse_new_common_compat25(int fd, struct fuse_args *args,
4707                                              const struct fuse_operations *op,
4708                                              size_t op_size, int compat)
4709 {
4710         struct fuse *f = NULL;
4711         struct fuse_chan *ch = fuse_kern_chan_new(fd);
4712
4713         if (ch)
4714                 f = fuse_new_common(ch, args, op, op_size, NULL, compat);
4715
4716         return f;
4717 }
4718
4719 /* called with fuse_context_lock held or during initialization (before
4720    main() has been called) */
4721 void fuse_register_module(struct fuse_module *mod)
4722 {
4723         mod->ctr = 0;
4724         mod->so = fuse_current_so;
4725         if (mod->so)
4726                 mod->so->ctr++;
4727         mod->next = fuse_modules;
4728         fuse_modules = mod;
4729 }
4730
4731 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
4732
4733 static struct fuse *fuse_new_common_compat(int fd, const char *opts,
4734                                            const struct fuse_operations *op,
4735                                            size_t op_size, int compat)
4736 {
4737         struct fuse *f;
4738         struct fuse_args args = FUSE_ARGS_INIT(0, NULL);
4739
4740         if (fuse_opt_add_arg(&args, "") == -1)
4741                 return NULL;
4742         if (opts &&
4743             (fuse_opt_add_arg(&args, "-o") == -1 ||
4744              fuse_opt_add_arg(&args, opts) == -1)) {
4745                 fuse_opt_free_args(&args);
4746                 return NULL;
4747         }
4748         f = fuse_new_common_compat25(fd, &args, op, op_size, compat);
4749         fuse_opt_free_args(&args);
4750
4751         return f;
4752 }
4753
4754 struct fuse *fuse_new_compat22(int fd, const char *opts,
4755                                const struct fuse_operations_compat22 *op,
4756                                size_t op_size)
4757 {
4758         return fuse_new_common_compat(fd, opts, (struct fuse_operations *) op,
4759                                       op_size, 22);
4760 }
4761
4762 struct fuse *fuse_new_compat2(int fd, const char *opts,
4763                               const struct fuse_operations_compat2 *op)
4764 {
4765         return fuse_new_common_compat(fd, opts, (struct fuse_operations *) op,
4766                                       sizeof(struct fuse_operations_compat2),
4767                                       21);
4768 }
4769
4770 struct fuse *fuse_new_compat1(int fd, int flags,
4771                               const struct fuse_operations_compat1 *op)
4772 {
4773         const char *opts = NULL;
4774         if (flags & FUSE_DEBUG_COMPAT1)
4775                 opts = "debug";
4776         return fuse_new_common_compat(fd, opts, (struct fuse_operations *) op,
4777                                       sizeof(struct fuse_operations_compat1),
4778                                       11);
4779 }
4780
4781 FUSE_SYMVER(".symver fuse_exited,__fuse_exited@");
4782 FUSE_SYMVER(".symver fuse_process_cmd,__fuse_process_cmd@");
4783 FUSE_SYMVER(".symver fuse_read_cmd,__fuse_read_cmd@");
4784 FUSE_SYMVER(".symver fuse_set_getcontext_func,__fuse_set_getcontext_func@");
4785 FUSE_SYMVER(".symver fuse_new_compat2,fuse_new@");
4786 FUSE_SYMVER(".symver fuse_new_compat22,fuse_new@FUSE_2.2");
4787
4788 #endif /* __FreeBSD__ || __NetBSD__  */
4789
4790 struct fuse *fuse_new_compat25(int fd, struct fuse_args *args,
4791                                const struct fuse_operations_compat25 *op,
4792                                size_t op_size)
4793 {
4794         return fuse_new_common_compat25(fd, args, (struct fuse_operations *) op,
4795                                         op_size, 25);
4796 }
4797
4798 FUSE_SYMVER(".symver fuse_new_compat25,fuse_new@FUSE_2.5");