File: simple_test.go

package info (click to toggle)
golang-github-hanwen-go-fuse 2.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,584 kB
  • sloc: cpp: 78; sh: 47; makefile: 16
file content (872 lines) | stat: -rw-r--r-- 20,668 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
// Copyright 2019 the Go-FUSE Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fs

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"runtime"
	"sort"
	"strings"
	"sync"
	"sync/atomic"
	"syscall"
	"testing"
	"time"

	"github.com/hanwen/go-fuse/v2/fuse"
	"github.com/hanwen/go-fuse/v2/internal/testutil"
	"github.com/hanwen/go-fuse/v2/posixtest"
	"github.com/kylelemons/godebug/pretty"
	"golang.org/x/sys/unix"
)

type testCase struct {
	*testing.T

	dir     string
	origDir string
	mntDir  string

	loopback InodeEmbedder
	rawFS    fuse.RawFileSystem
	server   *fuse.Server
}

// writeOrig writes a file into the backing directory of the loopback mount
func (tc *testCase) writeOrig(path, content string, mode os.FileMode) {
	if err := os.WriteFile(filepath.Join(tc.origDir, path), []byte(content), mode); err != nil {
		tc.Fatal(err)
	}
}

func (tc *testCase) clean() {
	if err := tc.server.Unmount(); err != nil {
		tc.Fatal(err)
	}
}

type testOptions struct {
	entryCache        bool
	enableLocks       bool
	attrCache         bool
	suppressDebug     bool
	testDir           string
	ro                bool
	directMount       bool // sets MountOptions.DirectMount
	directMountStrict bool // sets MountOptions.DirectMountStrict
	disableSplice     bool // sets MountOptions.DisableSplice
	idMappedMount     bool // sets MountOptions.IDMappedMount
}

// newTestCase creates the directories `orig` and `mnt` inside a temporary
// directory and mounts a loopback filesystem, backed by `orig`, on `mnt`.
func newTestCase(t *testing.T, opts *testOptions) *testCase {
	if opts == nil {
		opts = &testOptions{}
	}
	if opts.testDir == "" {
		opts.testDir = t.TempDir()
	}
	tc := &testCase{
		dir: opts.testDir,
		T:   t,
	}
	tc.origDir = tc.dir + "/orig"
	tc.mntDir = tc.dir + "/mnt"
	if err := os.Mkdir(tc.origDir, 0755); err != nil {
		t.Fatal(err)
	}
	if err := os.Mkdir(tc.mntDir, 0755); err != nil {
		t.Fatal(err)
	}

	var err error
	tc.loopback, err = NewLoopbackRoot(tc.origDir)
	if err != nil {
		t.Fatalf("NewLoopback: %v", err)
	}

	oneSec := time.Second

	attrDT := &oneSec
	if !opts.attrCache {
		attrDT = nil
	}
	entryDT := &oneSec
	if !opts.entryCache {
		entryDT = nil
	}
	tc.rawFS = NewNodeFS(tc.loopback, &Options{
		EntryTimeout: entryDT,
		AttrTimeout:  attrDT,
		Logger:       log.New(os.Stderr, "", 0),
	})

	mOpts := &fuse.MountOptions{
		DirectMount:       opts.directMount,
		DirectMountStrict: opts.directMountStrict,
		EnableLocks:       opts.enableLocks,
		DisableSplice:     opts.disableSplice,
		IDMappedMount:     opts.idMappedMount,
	}
	if !opts.suppressDebug {
		mOpts.Debug = testutil.VerboseTest()
	}
	if opts.ro {
		mOpts.Options = append(mOpts.Options, "ro")
	}
	if opts.idMappedMount {
		mOpts.Options = append(mOpts.Options, "default_permissions")
	}
	tc.server, err = fuse.NewServer(tc.rawFS, tc.mntDir, mOpts)
	if err != nil {
		t.Fatal(err)
	}

	go tc.server.Serve()
	if err := tc.server.WaitMount(); err != nil {
		t.Fatal(err)
	}
	t.Cleanup(tc.clean)

	return tc
}

func TestBasic(t *testing.T) {
	tc := newTestCase(t, &testOptions{attrCache: true, entryCache: true})

	tc.writeOrig("file", "hello", 0644)

	fn := tc.mntDir + "/file"
	fi, err := os.Lstat(fn)
	if err != nil {
		t.Fatalf("Lstat: %v", err)
	}

	if fi.Size() != 5 {
		t.Errorf("got size %d want 5", fi.Size())
	}

	stat := fuse.ToStatT(fi)
	if got, want := uint32(stat.Mode), uint32(fuse.S_IFREG|0644); got != want {
		t.Errorf("got mode %o, want %o", got, want)
	}

	if err := os.Remove(fn); err != nil {
		t.Errorf("Remove: %v", err)
	}

	if fi, err := os.Lstat(fn); err == nil {
		t.Errorf("Lstat after remove: got file %v", fi)
	}
}

func TestFileFdLeak(t *testing.T) {
	tc := newTestCase(t, &testOptions{
		suppressDebug: false,
		attrCache:     true,
		entryCache:    true,
	})

	posixtest.FdLeak(t, tc.mntDir)

	tc.clean()
	bridge := tc.rawFS.(*rawBridge)
	tc = nil

	// posixtest.FdLeak also uses 15 as a limit.
	if got, want := len(bridge.files), 15; got > want {
		t.Errorf("found %d used file handles, should be <= %d", got, want)
	}
}

func TestNotifyEntry(t *testing.T) {
	tc := newTestCase(t, &testOptions{attrCache: true, entryCache: true})

	orig := tc.origDir + "/file"
	fn := tc.mntDir + "/file"
	tc.writeOrig("file", "hello", 0644)

	st := syscall.Stat_t{}
	if err := syscall.Lstat(fn, &st); err != nil {
		t.Fatalf("Lstat before: %v", err)
	}

	if err := os.Remove(orig); err != nil {
		t.Fatalf("Remove: %v", err)
	}

	after := syscall.Stat_t{}
	if err := syscall.Lstat(fn, &after); err != nil {
		t.Fatalf("Lstat after: %v", err)
	} else if !reflect.DeepEqual(st, after) {
		t.Fatalf("got after %#v, want %#v", after, st)
	}

	if errno := tc.loopback.EmbeddedInode().NotifyEntry("file"); errno != 0 {
		t.Errorf("notify failed: %v", errno)
	}

	if err := syscall.Lstat(fn, &after); err != syscall.ENOENT {
		t.Fatalf("Lstat after: got %v, want ENOENT", err)
	}
}

func TestReadDirStress(t *testing.T) {
	tc := newTestCase(t, &testOptions{suppressDebug: true, attrCache: true, entryCache: true})

	// Create 110 entries
	for i := 0; i < 110; i++ {
		name := fmt.Sprintf("file%036x", i)
		if err := os.WriteFile(filepath.Join(tc.mntDir, name), []byte("hello"), 0644); err != nil {
			t.Fatalf("WriteFile %q: %v", name, err)
		}
	}

	var wg sync.WaitGroup
	stress := func(gr int) {
		defer wg.Done()
		for i := 1; i < 100; i++ {
			f, err := os.Open(tc.mntDir)
			if err != nil {
				t.Error(err)
				return
			}
			_, err = f.Readdirnames(-1)
			f.Close()
			if err != nil {
				t.Errorf("goroutine %d iteration %d: %v", gr, i, err)
				return
			}
		}
	}

	n := 3
	for i := 1; i <= n; i++ {
		wg.Add(1)
		go stress(i)
	}
	wg.Wait()

}

// This test is racy. If an external process consumes space while this
// runs, we may see spurious differences between the two statfs() calls.
func TestStatFs(t *testing.T) {
	tc := newTestCase(t, &testOptions{attrCache: true, entryCache: true})

	empty := syscall.Statfs_t{}
	orig := empty
	if err := syscall.Statfs(tc.origDir, &orig); err != nil {
		t.Fatal("statfs orig", err)
	}

	mnt := syscall.Statfs_t{}
	if err := syscall.Statfs(tc.mntDir, &mnt); err != nil {
		t.Fatal("statfs mnt", err)
	}

	var mntFuse, origFuse fuse.StatfsOut
	mntFuse.FromStatfsT(&mnt)
	origFuse.FromStatfsT(&orig)

	if !reflect.DeepEqual(mntFuse, origFuse) {
		t.Errorf("Got %#v, want %#v", mntFuse, origFuse)
	}
}

func TestGetAttrParallel(t *testing.T) {
	// We grab a file-handle to provide to the API so rename+fstat
	// can be handled correctly. Here, test that closing and
	// (f)stat in parallel don't lead to fstat on closed files.
	// We can only test that if we switch off caching
	tc := newTestCase(t, &testOptions{suppressDebug: true})

	N := 100

	var fds []int
	var fns []string
	for i := 0; i < N; i++ {
		fn := fmt.Sprintf("file%d", i)
		tc.writeOrig(fn, "ello", 0644)
		fn = filepath.Join(tc.mntDir, fn)
		fns = append(fns, fn)
		fd, err := syscall.Open(fn, syscall.O_RDONLY, 0)
		if err != nil {
			t.Fatalf("Open %d: %v", i, err)
		}

		fds = append(fds, fd)
	}

	var wg sync.WaitGroup
	wg.Add(2 * N)
	for i := 0; i < N; i++ {
		go func(i int) {
			if err := syscall.Close(fds[i]); err != nil {
				t.Errorf("close %d: %v", i, err)
			}
			wg.Done()
		}(i)
		go func(i int) {
			var st syscall.Stat_t
			if err := syscall.Lstat(fns[i], &st); err != nil {
				t.Errorf("lstat %d: %v", i, err)
			}
			wg.Done()
		}(i)
	}
	wg.Wait()
}

func TestMknod(t *testing.T) {
	tc := newTestCase(t, &testOptions{})

	modes := map[string]uint32{
		"regular": syscall.S_IFREG,
		"socket":  syscall.S_IFSOCK,
		"fifo":    syscall.S_IFIFO,
	}

	for nm, mode := range modes {
		t.Run(nm, func(t *testing.T) {
			p := filepath.Join(tc.mntDir, nm)
			err := syscall.Mknod(p, mode|0755, (8<<8)|0)
			if err != nil {
				t.Fatalf("mknod(%s): %v", nm, err)
			}

			var st syscall.Stat_t
			if err := syscall.Stat(p, &st); err != nil {
				got := st.Mode &^ 07777
				if want := uint(mode); want != uint(got) {
					t.Fatalf("stat(%s): got %o want %o", nm, got, want)
				}
			}

			// We could test if the files can be
			// read/written but: The kernel handles FIFOs
			// without talking to FUSE at all. Presumably,
			// this also holds for sockets.  Regular files
			// are tested extensively elsewhere.
		})
	}
}

func TestMknodNotSupported(t *testing.T) {
	mountPoint := t.TempDir()

	server, err := Mount(mountPoint, &Inode{}, nil)
	if err != nil {
		t.Fatalf("cannot mount: %v", err)
	}

	defer server.Unmount()

	name := filepath.Join(mountPoint, "foo")

	if got, want := syscall.Mknod(name, syscall.S_IFREG|0755, (8<<8)|0), syscall.ENOTSUP; got != want {
		t.Fatalf("mknod: got %v, want %v", got, want)
	}
}

func TestPosix(t *testing.T) {
	noisy := map[string]bool{
		"ParallelFileOpen": true,
		"ReadDir":          true,
	}

	for nm, fn := range posixtest.All {
		t.Run(nm, func(t *testing.T) {
			tc := newTestCase(t, &testOptions{
				suppressDebug: noisy[nm],
				attrCache:     true,
				entryCache:    true,
				enableLocks:   true,
			})

			fn(t, tc.mntDir)
		})
	}
}

func TestReadDisableSplice(t *testing.T) {
	tc := newTestCase(t, &testOptions{
		disableSplice: true,
	})

	posixtest.FileBasic(t, tc.mntDir)
}

func TestOpenDirectIO(t *testing.T) {
	// Apparently, tmpfs does not allow O_DIRECT, so try to create
	// a test temp directory in /var/tmp.
	ext4Dir, err := os.MkdirTemp("/var/tmp", "go-fuse.TestOpenDirectIO")
	if err != nil {
		t.Fatalf("MkdirAll: %v", err)
	}
	t.Cleanup(func() { os.RemoveAll(ext4Dir) })

	posixtest.DirectIO(t, ext4Dir)
	if t.Failed() {
		t.Skip("DirectIO failed on underlying FS")
	}

	opts := testOptions{
		testDir:    ext4Dir,
		attrCache:  true,
		entryCache: true,
	}

	tc := newTestCase(t, &opts)
	posixtest.DirectIO(t, tc.mntDir)
}

// TestFsstress is loosely modeled after xfstest's fsstress. It performs rapid
// parallel removes / creates / readdirs. Coupled with inode reuse, this test
// used to deadlock go-fuse quite quickly.
//
// Note: Run as
//
//	TMPDIR=/var/tmp go test -run TestFsstress
//
// to make sure the backing filesystem is ext4. /tmp is tmpfs on modern Linux
// distributions, and tmpfs does not reuse inode numbers, hiding the problem.
func TestFsstress(t *testing.T) {
	tc := newTestCase(t, &testOptions{suppressDebug: true, attrCache: true, entryCache: true})

	{
		old := runtime.GOMAXPROCS(100)
		defer runtime.GOMAXPROCS(old)
	}

	const concurrency = 10
	var wg sync.WaitGroup
	ctx, cancel := context.WithCancel(context.Background())

	// operations taking 1 path argument
	ops1 := map[string]func(string) error{
		"mkdir":      func(p string) error { return syscall.Mkdir(p, 0700) },
		"rmdir":      func(p string) error { return syscall.Rmdir(p) },
		"mknod_reg":  func(p string) error { return syscall.Mknod(p, 0700|syscall.S_IFREG, 0) },
		"remove":     os.Remove,
		"unlink":     syscall.Unlink,
		"mknod_sock": func(p string) error { return syscall.Mknod(p, 0700|syscall.S_IFSOCK, 0) },
		"mknod_fifo": func(p string) error { return syscall.Mknod(p, 0700|syscall.S_IFIFO, 0) },
		"mkfifo":     func(p string) error { return syscall.Mkfifo(p, 0700) },
		"symlink":    func(p string) error { return syscall.Symlink("foo", p) },
		"creat": func(p string) error {
			fd, err := syscall.Open(p, syscall.O_CREAT|syscall.O_EXCL, 0700)
			if err == nil {
				syscall.Close(fd)
			}
			return err
		},
	}
	// operations taking 2 path arguments
	ops2 := map[string]func(string, string) error{
		"rename": syscall.Rename,
		"link":   syscall.Link,
	}

	type opStats struct {
		ok   *int64
		fail *int64
		hung *int64
	}
	stats := make(map[string]opStats)

	// pathN() returns something like /var/tmp/TestFsstress/TestFsstress.4
	pathN := func(n int) string {
		return fmt.Sprintf("%s/%s.%d", tc.mntDir, t.Name(), n)
	}

	opLoop := func(k string, n int) {
		defer wg.Done()
		op := ops1[k]
		for {
			p := pathN(1)
			atomic.AddInt64(stats[k].hung, 1)
			err := op(p)
			atomic.AddInt64(stats[k].hung, -1)
			if err != nil {
				atomic.AddInt64(stats[k].fail, 1)
			} else {
				atomic.AddInt64(stats[k].ok, 1)
			}
			select {
			case <-ctx.Done():
				return
			default:
			}
		}
	}

	op2Loop := func(k string, n int) {
		defer wg.Done()
		op := ops2[k]
		n2 := (n + 1) % concurrency
		for {
			p1 := pathN(n)
			p2 := pathN(n2)
			atomic.AddInt64(stats[k].hung, 1)
			err := op(p1, p2)
			atomic.AddInt64(stats[k].hung, -1)
			if err != nil {
				atomic.AddInt64(stats[k].fail, 1)
			} else {
				atomic.AddInt64(stats[k].ok, 1)
			}
			select {
			case <-ctx.Done():
				return
			default:
			}
		}
	}

	readdirLoop := func(k string) {
		defer wg.Done()
		for {
			atomic.AddInt64(stats[k].hung, 1)
			f, err := os.Open(tc.mntDir)
			if err != nil {
				panic(err)
			}
			_, err = f.Readdir(0)
			if err != nil {
				atomic.AddInt64(stats[k].fail, 1)
			} else {
				atomic.AddInt64(stats[k].ok, 1)
			}
			f.Close()
			atomic.AddInt64(stats[k].hung, -1)
			select {
			case <-ctx.Done():
				return
			default:
			}
		}
	}

	// prepare stats map
	var allOps []string
	for k := range ops1 {
		allOps = append(allOps, k)
	}
	for k := range ops2 {
		allOps = append(allOps, k)
	}
	allOps = append(allOps, "readdir")
	for _, k := range allOps {
		var i1, i2, i3 int64
		stats[k] = opStats{ok: &i1, fail: &i2, hung: &i3}
	}

	// spawn worker goroutines
	for i := 0; i < concurrency; i++ {
		for k := range ops1 {
			wg.Add(1)
			go opLoop(k, i)
		}
		for k := range ops2 {
			wg.Add(1)
			go op2Loop(k, i)
		}
	}
	{
		k := "readdir"
		wg.Add(1)
		go readdirLoop(k)
	}

	// spawn ls loop
	//
	// An external "ls" loop has a destructive effect that I am unable to
	// reproduce through in-process operations.
	if strings.ContainsAny(tc.mntDir, "'\\") {
		// But let's not enable shell injection.
		log.Panicf("shell injection attempt? mntDir=%q", tc.mntDir)
	}
	// --color=always enables xattr lookups for extra stress
	cmd := exec.Command("bash", "-c", "while true ; do ls -l --color=always '"+tc.mntDir+"'; done")
	err := cmd.Start()
	if err != nil {
		t.Fatal(err)
	}
	wg.Add(1)
	go func() {
		cmd.Wait()
		wg.Done()
	}()

	defer cmd.Process.Kill()

	// Run the test for 1 second. If it deadlocks, it usually does within 20ms.
	time.Sleep(1 * time.Second)

	cancel()
	cmd.Process.Kill()

	// waitTimeout waits for the waitgroup for the specified max timeout.
	// Returns true if waiting timed out.
	waitTimeout := func(wg *sync.WaitGroup, timeout time.Duration) bool {
		c := make(chan struct{})
		go func() {
			defer close(c)
			wg.Wait()
		}()
		select {
		case <-c:
			return false // completed normally
		case <-time.After(timeout):
			return true // timed out
		}
	}

	if waitTimeout(&wg, time.Second) {
		t.Errorf("timeout waiting for goroutines to exit (deadlocked?)")
	}

	// Print operation statistics
	var keys []string
	for k := range stats {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	t.Logf("Operation statistics:")
	for _, k := range keys {
		v := stats[k]
		t.Logf("%10s: %5d ok, %6d fail, %2d hung", k, *v.ok, *v.fail, *v.hung)
	}
}

// TestStaleHardlinks creates a lot of hard links and deletes them again
// behind the back of the loopback fs. Then opens the original file.
//
// Fails at the moment. Core of the problem:
//
// 18:41:50.796468 rx 136: LOOKUP n1 ["link0"] 6b
// 18:41:50.796489 tx 136:     OK, {n2 g1 tE=0s tA=0s {M0100600 SZ=0 L=1 1026:1026 B0*4096 i0:269663 A 1616348510.793212 M 1616348510.793212 C 1616348510.795212}}
// 18:41:50.796535 rx 138: OPEN n2 {O_RDONLY,0x8000}
// 18:41:50.796557 tx 138:     2=no such file or directory, {Fh 0 }
func TestStaleHardlinks(t *testing.T) {
	// Disable all caches we can disable
	tc := newTestCase(t, &testOptions{attrCache: false, entryCache: false})

	// gvfsd-trash sets an inotify watch on mntDir and stat()s every file that is
	// created, racing with the test logic ( https://github.com/hanwen/go-fuse/issues/478 ).
	// Use a subdir to prevent that.
	if err := os.Mkdir(tc.mntDir+"/x", 0755); err != nil {
		t.Fatal(err)
	}

	// "link0" is original file
	link0 := tc.mntDir + "/x/link0"
	if fd, err := unix.Open(link0, unix.O_CREAT, 0600); err != nil {
		t.Fatal(err)
	} else {
		syscall.Close(fd)
	}
	// Create hardlinks via mntDir
	t.Logf("create link1...20, pid=%d", os.Getpid())
	for i := 1; i < 20; i++ {
		linki := fmt.Sprintf(tc.mntDir+"/x/link%d", i)
		if err := syscall.Link(link0, linki); err != nil {
			t.Fatal(err)
		}
	}
	// Delete hardlinks via origDir (behind loopback fs's back)
	t.Log("delete link1...20 behind loopback's back")
	for i := 1; i < 20; i++ {
		linki := fmt.Sprintf(tc.origDir+"/x/link%d", i)
		if err := syscall.Unlink(linki); err != nil {
			t.Fatal(err)
		}
	}
	// Try to open link0 via mntDir
	t.Log("open link0")
	fd, err := syscall.Open(link0, syscall.O_RDONLY, 0)
	if err != nil {
		t.Error(err)
	} else {
		syscall.Close(fd)
	}

}

func init() {
	syscall.Umask(0)
}

func testMountDir(dir string) error {
	opts := &Options{}
	opts.Debug = testutil.VerboseTest()
	server, err := Mount(dir, &Inode{}, opts)
	if err != nil {
		return err
	}

	server.Unmount()
	server.Wait()
	return nil
}

func TestParallelMount(t *testing.T) {
	before := runtime.GOMAXPROCS(1)
	defer runtime.GOMAXPROCS(before)
	// Per default, only 1000 FUSE mounts are allowed, then you get
	// > /usr/bin/fusermount3: too many FUSE filesystems mounted; mount_max=N can be set in /etc/fuse.conf
	// Let's stay well below 1000.
	N := 100
	todo := make(chan string, N)
	result := make(chan error, N)
	for i := 0; i < N; i++ {
		todo <- t.TempDir()
	}
	close(todo)

	P := 2
	for i := 0; i < P; i++ {
		go func() {
			for d := range todo {
				result <- testMountDir(d)
			}
		}()
	}

	for i := 0; i < N; i++ {
		e := <-result
		if e != nil {
			t.Error(e)
		}
	}
}

type handleLessCreateNode struct {
	Inode
}

var _ = (NodeCreater)((*handleLessCreateNode)(nil))

func (n *handleLessCreateNode) Create(ctx context.Context, name string, flags uint32, mode uint32, out *fuse.EntryOut) (node *Inode, fh FileHandle, fuseFlags uint32, errno syscall.Errno) {
	f := &MemRegularFile{
		Attr: fuse.Attr{
			Mode: mode,
		},
	}
	ch := n.NewPersistentInode(ctx, f, StableAttr{Mode: fuse.S_IFREG})
	n.AddChild(name, ch, true)
	return ch, nil, fuse.FOPEN_KEEP_CACHE, 0
}

func TestHandleLessCreate(t *testing.T) {
	hlcn := &handleLessCreateNode{}
	dir, _ := testMount(t, hlcn, nil)

	posixtest.FileBasic(t, dir)
}

func lstatxPath(p string) (*unix.Statx_t, error) {
	var r unix.Statx_t
	err := unix.Statx(unix.AT_FDCWD, p, unix.AT_SYMLINK_NOFOLLOW,
		(unix.STATX_BASIC_STATS | unix.STATX_BTIME |
			unix.STATX_MNT_ID), // unix.STATX_DIOALIGN
		&r)
	return &r, err
}

func clearStatx(st *unix.Statx_t, mask uint32) {
	st.Mask = mask
	if mask&(unix.STATX_TYPE|unix.STATX_MODE) == 0 {
		st.Mode = 0
	}
	if mask&(unix.STATX_NLINK) == 0 {
		st.Nlink = 0
	}
	if mask&(unix.STATX_INO) == 0 {
		st.Ino = 0
	}
	if mask&(unix.STATX_ATIME) == 0 {
		st.Atime = unix.StatxTimestamp{}
	}
	if mask&(unix.STATX_BTIME) == 0 {
		st.Btime = unix.StatxTimestamp{}
	}
	if mask&(unix.STATX_CTIME) == 0 {
		st.Ctime = unix.StatxTimestamp{}
	}
	if mask&(unix.STATX_MTIME) == 0 {
		st.Mtime = unix.StatxTimestamp{}
	}

	st.Dev_minor = 0
	st.Dev_major = 0
	st.Mnt_id = 0
	st.Attributes_mask = 0
}

func TestStatx(t *testing.T) {
	tc := newTestCase(t, &testOptions{attrCache: false, entryCache: false})
	if err := os.WriteFile(tc.origDir+"/file", []byte("blabla"), 0644); err != nil {
		t.Fatal(err)
	}

	oFile := tc.origDir + "/file"
	want, err := lstatxPath(oFile)
	if err != nil {
		t.Fatal(err)
	}
	mFile := tc.mntDir + "/file"
	got, err := lstatxPath(mFile)
	if err != nil {
		t.Fatal(err)
	}
	mask := got.Mask & want.Mask
	clearStatx(got, mask)
	clearStatx(want, mask)
	if diff := pretty.Compare(got, want); diff != "" {
		t.Errorf("got, want: %s", diff)
	}

	// the following works, but does not set Fh in StatxIn
	oFD, err := os.Open(oFile)
	if err != nil {
		t.Fatal(err)
	}
	defer oFD.Close()
	mFD, err := os.Open(mFile)
	if err != nil {
		t.Fatal(err)
	}
	defer mFD.Close()

	var osx, msx unix.Statx_t
	if err := unix.Statx(int(oFD.Fd()), "", unix.AT_EMPTY_PATH,
		(unix.STATX_BASIC_STATS | unix.STATX_BTIME |
			unix.STATX_MNT_ID), // unix.STATX_DIOALIGN
		&osx); err != nil {
		t.Fatal(err)
	}
	if err := unix.Statx(int(mFD.Fd()), "", unix.AT_EMPTY_PATH,
		(unix.STATX_BASIC_STATS | unix.STATX_BTIME |
			unix.STATX_MNT_ID), // unix.STATX_DIOALIGN
		&msx); err != nil {
		t.Fatal(err)
	}

	mask = msx.Mask & osx.Mask
	clearStatx(&msx, mask)
	clearStatx(&osx, mask)
	if diff := pretty.Compare(msx, osx); diff != "" {
		t.Errorf("got, want: %s", diff)
	}
}