forked from MetaCubeX/gvisor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gofer.go
2249 lines (2028 loc) · 75 KB
/
gofer.go
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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package gofer provides a filesystem implementation that is backed by a 9p
// server, interchangably referred to as "gofers" throughout this package.
//
// Lock order:
//
// regularFileFD/directoryFD.mu
// filesystem.renameMu
// dentry.cachingMu
// dentryCache.mu
// dentry.opMu
// dentry.childrenMu
// filesystem.syncMu
// dentry.metadataMu
// *** "memmap.Mappable locks" below this point
// dentry.mapsMu
// *** "memmap.Mappable locks taken by Translate" below this point
// dentry.handleMu
// dentry.dataMu
// filesystem.inoMu
// specialFileFD.mu
// specialFileFD.bufMu
//
// Locking dentry.opMu and dentry.metadataMu in multiple dentries requires that
// either ancestor dentries are locked before descendant dentries, or that
// filesystem.renameMu is locked for writing.
package gofer
import (
"fmt"
"path"
"strconv"
"strings"
"golang.org/x/sys/unix"
"github.com/MerlinKodo/gvisor/pkg/abi/linux"
"github.com/MerlinKodo/gvisor/pkg/atomicbitops"
"github.com/MerlinKodo/gvisor/pkg/cleanup"
"github.com/MerlinKodo/gvisor/pkg/context"
"github.com/MerlinKodo/gvisor/pkg/errors/linuxerr"
"github.com/MerlinKodo/gvisor/pkg/hostarch"
"github.com/MerlinKodo/gvisor/pkg/lisafs"
"github.com/MerlinKodo/gvisor/pkg/log"
"github.com/MerlinKodo/gvisor/pkg/refs"
fslock "github.com/MerlinKodo/gvisor/pkg/sentry/fsimpl/lock"
"github.com/MerlinKodo/gvisor/pkg/sentry/fsutil"
"github.com/MerlinKodo/gvisor/pkg/sentry/kernel/auth"
"github.com/MerlinKodo/gvisor/pkg/sentry/kernel/pipe"
ktime "github.com/MerlinKodo/gvisor/pkg/sentry/kernel/time"
"github.com/MerlinKodo/gvisor/pkg/sentry/memmap"
"github.com/MerlinKodo/gvisor/pkg/sentry/pgalloc"
"github.com/MerlinKodo/gvisor/pkg/sentry/socket/unix/transport"
"github.com/MerlinKodo/gvisor/pkg/sentry/vfs"
"github.com/MerlinKodo/gvisor/pkg/sync"
"github.com/MerlinKodo/gvisor/pkg/unet"
)
// Name is the default filesystem name.
const Name = "9p"
// Mount option names for goferfs.
const (
moptTransport = "trans"
moptReadFD = "rfdno"
moptWriteFD = "wfdno"
moptAname = "aname"
moptDfltUID = "dfltuid"
moptDfltGID = "dfltgid"
moptCache = "cache"
moptForcePageCache = "force_page_cache"
moptLimitHostFDTranslation = "limit_host_fd_translation"
moptOverlayfsStaleRead = "overlayfs_stale_read"
moptDisableFileHandleSharing = "disable_file_handle_sharing"
moptDisableFifoOpen = "disable_fifo_open"
// Directfs options.
moptDirectfs = "directfs"
)
// Valid values for the "cache" mount option.
const (
cacheFSCache = "fscache"
cacheFSCacheWritethrough = "fscache_writethrough"
cacheRemoteRevalidating = "remote_revalidating"
)
const (
defaultMaxCachedDentries = 1000
maxCachedNegativeChildren = 1000
)
// stringFixedCache is a fixed sized cache, once initialized,
// its size never changes.
//
// +stateify savable
type stringFixedCache struct {
// namesList stores negative names with fifo list.
// name stored in namesList only means it used to be negative
// at the moment you pushed it to the list.
namesList stringList
size uint64
}
func (cache *stringFixedCache) isInited() bool {
return cache.size != 0
}
func (cache *stringFixedCache) init(size uint64) {
elements := make([]stringListElem, size)
for i := uint64(0); i < size; i++ {
cache.namesList.PushFront(&elements[i])
}
cache.size = size
}
// Update will push name to the front of the list,
// and pop the tail value.
func (cache *stringFixedCache) add(name string) string {
tail := cache.namesList.Back()
victimName := tail.str
tail.str = name
cache.namesList.Remove(tail)
cache.namesList.PushFront(tail)
return victimName
}
// +stateify savable
type dentryCache struct {
// mu protects the below fields.
mu sync.Mutex `state:"nosave"`
// dentries contains all dentries with 0 references. Due to race conditions,
// it may also contain dentries with non-zero references.
dentries dentryList
// dentriesLen is the number of dentries in dentries.
dentriesLen uint64
// maxCachedDentries is the maximum number of cachable dentries.
maxCachedDentries uint64
}
// SetDentryCacheSize sets the size of the global gofer dentry cache.
func SetDentryCacheSize(size int) {
if size < 0 {
return
}
if globalDentryCache != nil {
log.Warningf("Global dentry cache has already been initialized. Ignoring subsequent attempt.")
return
}
globalDentryCache = &dentryCache{maxCachedDentries: uint64(size)}
}
// globalDentryCache is a global cache of dentries across all gofers.
var globalDentryCache *dentryCache
// Valid values for "trans" mount option.
const transportModeFD = "fd"
// FilesystemType implements vfs.FilesystemType.
//
// +stateify savable
type FilesystemType struct{}
// filesystem implements vfs.FilesystemImpl.
//
// +stateify savable
type filesystem struct {
vfsfs vfs.Filesystem
// mfp is used to allocate memory that caches regular file contents. mfp is
// immutable.
mfp pgalloc.MemoryFileProvider
// Immutable options.
opts filesystemOptions
iopts InternalFilesystemOptions
// client is the LISAFS client used for communicating with the server. client
// is immutable.
client *lisafs.Client `state:"nosave"`
// clock is a realtime clock used to set timestamps in file operations.
clock ktime.Clock
// devMinor is the filesystem's minor device number. devMinor is immutable.
devMinor uint32
// root is the root dentry. root is immutable.
root *dentry
// renameMu serves two purposes:
//
// - It synchronizes path resolution with renaming initiated by this
// client.
//
// - It is held by path resolution to ensure that reachable dentries remain
// valid. A dentry is reachable by path resolution if it has a non-zero
// reference count (such that it is usable as vfs.ResolvingPath.Start() or
// is reachable from its children), or if it is a child dentry (such that
// it is reachable from its parent).
renameMu sync.RWMutex `state:"nosave"`
dentryCache *dentryCache
// syncableDentries contains all non-synthetic dentries. specialFileFDs
// contains all open specialFileFDs. These fields are protected by syncMu.
syncMu sync.Mutex `state:"nosave"`
syncableDentries dentryList
specialFileFDs specialFDList
// inoByKey maps previously-observed device ID and host inode numbers to
// internal inode numbers assigned to those files. inoByKey is not preserved
// across checkpoint/restore because inode numbers may be reused between
// different gofer processes, so inode numbers may be repeated for different
// files across checkpoint/restore. inoByKey is protected by inoMu.
inoMu sync.Mutex `state:"nosave"`
inoByKey map[inoKey]uint64 `state:"nosave"`
// lastIno is the last inode number assigned to a file. lastIno is accessed
// using atomic memory operations.
lastIno atomicbitops.Uint64
// savedDentryRW records open read/write handles during save/restore.
savedDentryRW map[*dentry]savedDentryRW
// released is nonzero once filesystem.Release has been called.
released atomicbitops.Int32
}
// +stateify savable
type filesystemOptions struct {
fd int
aname string
interop InteropMode // derived from the "cache" mount option
dfltuid auth.KUID
dfltgid auth.KGID
// If forcePageCache is true, host FDs may not be used for application
// memory mappings even if available; instead, the client must perform its
// own caching of regular file pages. This is primarily useful for testing.
forcePageCache bool
// If limitHostFDTranslation is true, apply maxFillRange() constraints to
// host FD mappings returned by dentry.(memmap.Mappable).Translate(). This
// makes memory accounting behavior more consistent between cases where
// host FDs are / are not available, but may increase the frequency of
// sentry-handled page faults on files for which a host FD is available.
limitHostFDTranslation bool
// If overlayfsStaleRead is true, O_RDONLY host FDs provided by the remote
// filesystem may not be coherent with writable host FDs opened later, so
// all uses of the former must be replaced by uses of the latter. This is
// usually only the case when the remote filesystem is a Linux overlayfs
// mount. (Prior to Linux 4.18, patch series centered on commit
// d1d04ef8572b "ovl: stack file ops", both I/O and memory mappings were
// incoherent between pre-copy-up and post-copy-up FDs; after that patch
// series, only memory mappings are incoherent.)
overlayfsStaleRead bool
// If regularFilesUseSpecialFileFD is true, application FDs representing
// regular files will use distinct file handles for each FD, in the same
// way that application FDs representing "special files" such as sockets
// do. Note that this disables client caching for regular files. This option
// may regress performance due to excessive Open RPCs. This option is not
// supported with overlayfsStaleRead for now.
regularFilesUseSpecialFileFD bool
// If disableFifoOpen is true, application attempts to open(2) a host FIFO
// are disallowed.
disableFifoOpen bool
// directfs holds options for directfs mode.
directfs directfsOpts
}
// +stateify savable
type directfsOpts struct {
// If directfs is enabled, the gofer client does not make RPCs to the gofer
// process. Instead, it makes host syscalls to perform file operations.
enabled bool
}
// InteropMode controls the client's interaction with other remote filesystem
// users.
//
// +stateify savable
type InteropMode uint32
const (
// InteropModeExclusive is appropriate when the filesystem client is the
// only user of the remote filesystem.
//
// - The client may cache arbitrary filesystem state (file data, metadata,
// filesystem structure, etc.).
//
// - Client changes to filesystem state may be sent to the remote
// filesystem asynchronously, except when server permission checks are
// necessary.
//
// - File timestamps are based on client clocks. This ensures that users of
// the client observe timestamps that are coherent with their own clocks
// and consistent with Linux's semantics (in particular, it is not always
// possible for clients to set arbitrary atimes and mtimes depending on the
// remote filesystem implementation, and never possible for clients to set
// arbitrary ctimes.)
InteropModeExclusive InteropMode = iota
// InteropModeWritethrough is appropriate when there are read-only users of
// the remote filesystem that expect to observe changes made by the
// filesystem client.
//
// - The client may cache arbitrary filesystem state.
//
// - Client changes to filesystem state must be sent to the remote
// filesystem synchronously.
//
// - File timestamps are based on client clocks. As a corollary, access
// timestamp changes from other remote filesystem users will not be visible
// to the client.
InteropModeWritethrough
// InteropModeShared is appropriate when there are users of the remote
// filesystem that may mutate its state other than the client.
//
// - The client must verify ("revalidate") cached filesystem state before
// using it.
//
// - Client changes to filesystem state must be sent to the remote
// filesystem synchronously.
//
// - File timestamps are based on server clocks. This is necessary to
// ensure that timestamp changes are synchronized between remote filesystem
// users.
//
// Note that the correctness of InteropModeShared depends on the server
// correctly implementing 9P fids (i.e. each fid immutably represents a
// single filesystem object), even in the presence of remote filesystem
// mutations from other users. If this is violated, the behavior of the
// client is undefined.
InteropModeShared
)
// InternalFilesystemOptions may be passed as
// vfs.GetFilesystemOptions.InternalData to FilesystemType.GetFilesystem.
//
// +stateify savable
type InternalFilesystemOptions struct {
// If UniqueID is non-empty, it is an opaque string used to reassociate the
// filesystem with a new server FD during restoration from checkpoint.
UniqueID string
// If LeakConnection is true, do not close the connection to the server
// when the Filesystem is released. This is necessary for deployments in
// which servers can handle only a single client and report failure if that
// client disconnects.
LeakConnection bool
// If OpenSocketsByConnecting is true, silently translate attempts to open
// files identifying as sockets to connect RPCs.
OpenSocketsByConnecting bool
}
// _V9FS_DEFUID and _V9FS_DEFGID (from Linux's fs/9p/v9fs.h) are the default
// UIDs and GIDs used for files that do not provide a specific owner or group
// respectively.
const (
// uint32(-2) doesn't work in Go.
_V9FS_DEFUID = auth.KUID(4294967294)
_V9FS_DEFGID = auth.KGID(4294967294)
)
// Name implements vfs.FilesystemType.Name.
func (FilesystemType) Name() string {
return Name
}
// Release implements vfs.FilesystemType.Release.
func (FilesystemType) Release(ctx context.Context) {}
// GetFilesystem implements vfs.FilesystemType.GetFilesystem.
func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *auth.Credentials, source string, opts vfs.GetFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {
mfp := pgalloc.MemoryFileProviderFromContext(ctx)
if mfp == nil {
ctx.Warningf("gofer.FilesystemType.GetFilesystem: context does not provide a pgalloc.MemoryFileProvider")
return nil, nil, linuxerr.EINVAL
}
mopts := vfs.GenericParseMountOptions(opts.Data)
var fsopts filesystemOptions
fd, err := getFDFromMountOptionsMap(ctx, mopts)
if err != nil {
return nil, nil, err
}
fsopts.fd = fd
// Get the attach name.
fsopts.aname = "/"
if aname, ok := mopts[moptAname]; ok {
delete(mopts, moptAname)
if !path.IsAbs(aname) {
ctx.Warningf("gofer.FilesystemType.GetFilesystem: aname is not absolute: %s=%s", moptAname, aname)
return nil, nil, linuxerr.EINVAL
}
fsopts.aname = path.Clean(aname)
}
// Parse the cache policy. For historical reasons, this defaults to the
// least generally-applicable option, InteropModeExclusive.
fsopts.interop = InteropModeExclusive
if cache, ok := mopts[moptCache]; ok {
delete(mopts, moptCache)
switch cache {
case cacheFSCache:
fsopts.interop = InteropModeExclusive
case cacheFSCacheWritethrough:
fsopts.interop = InteropModeWritethrough
case cacheRemoteRevalidating:
fsopts.interop = InteropModeShared
default:
ctx.Warningf("gofer.FilesystemType.GetFilesystem: invalid cache policy: %s=%s", moptCache, cache)
return nil, nil, linuxerr.EINVAL
}
}
// Parse the default UID and GID.
fsopts.dfltuid = _V9FS_DEFUID
if dfltuidstr, ok := mopts[moptDfltUID]; ok {
delete(mopts, moptDfltUID)
dfltuid, err := strconv.ParseUint(dfltuidstr, 10, 32)
if err != nil {
ctx.Warningf("gofer.FilesystemType.GetFilesystem: invalid default UID: %s=%s", moptDfltUID, dfltuidstr)
return nil, nil, linuxerr.EINVAL
}
// In Linux, dfltuid is interpreted as a UID and is converted to a KUID
// in the caller's user namespace, but goferfs isn't
// application-mountable.
fsopts.dfltuid = auth.KUID(dfltuid)
}
fsopts.dfltgid = _V9FS_DEFGID
if dfltgidstr, ok := mopts[moptDfltGID]; ok {
delete(mopts, moptDfltGID)
dfltgid, err := strconv.ParseUint(dfltgidstr, 10, 32)
if err != nil {
ctx.Warningf("gofer.FilesystemType.GetFilesystem: invalid default UID: %s=%s", moptDfltGID, dfltgidstr)
return nil, nil, linuxerr.EINVAL
}
fsopts.dfltgid = auth.KGID(dfltgid)
}
// Handle simple flags.
if _, ok := mopts[moptDisableFileHandleSharing]; ok {
delete(mopts, moptDisableFileHandleSharing)
fsopts.regularFilesUseSpecialFileFD = true
}
if _, ok := mopts[moptDisableFifoOpen]; ok {
delete(mopts, moptDisableFifoOpen)
fsopts.disableFifoOpen = true
}
if _, ok := mopts[moptForcePageCache]; ok {
delete(mopts, moptForcePageCache)
fsopts.forcePageCache = true
}
if _, ok := mopts[moptLimitHostFDTranslation]; ok {
delete(mopts, moptLimitHostFDTranslation)
fsopts.limitHostFDTranslation = true
}
if _, ok := mopts[moptOverlayfsStaleRead]; ok {
delete(mopts, moptOverlayfsStaleRead)
fsopts.overlayfsStaleRead = true
}
if _, ok := mopts[moptDirectfs]; ok {
delete(mopts, moptDirectfs)
fsopts.directfs.enabled = true
}
// fsopts.regularFilesUseSpecialFileFD can only be enabled by specifying
// "cache=none".
// Check for unparsed options.
if len(mopts) != 0 {
ctx.Warningf("gofer.FilesystemType.GetFilesystem: unknown options: %v", mopts)
return nil, nil, linuxerr.EINVAL
}
// Validation.
if fsopts.regularFilesUseSpecialFileFD && fsopts.overlayfsStaleRead {
// These options are not supported together. To support this, when a dentry
// is opened writably for the first time, we need to iterate over all the
// specialFileFDs of that dentry that represent a regular file and call
// fd.hostFileMapper.RegenerateMappings(writable_fd).
ctx.Warningf("gofer.FilesystemType.GetFilesystem: regularFilesUseSpecialFileFD and overlayfsStaleRead options are not supported together.")
return nil, nil, linuxerr.EINVAL
}
// Handle internal options.
iopts, ok := opts.InternalData.(InternalFilesystemOptions)
if opts.InternalData != nil && !ok {
ctx.Warningf("gofer.FilesystemType.GetFilesystem: GetFilesystemOptions.InternalData has type %T, wanted gofer.InternalFilesystemOptions", opts.InternalData)
return nil, nil, linuxerr.EINVAL
}
// If !ok, iopts being the zero value is correct.
// Construct the filesystem object.
devMinor, err := vfsObj.GetAnonBlockDevMinor()
if err != nil {
return nil, nil, err
}
fs := &filesystem{
mfp: mfp,
opts: fsopts,
iopts: iopts,
clock: ktime.RealtimeClockFromContext(ctx),
devMinor: devMinor,
inoByKey: make(map[inoKey]uint64),
}
// Did the user configure a global dentry cache?
if globalDentryCache != nil {
fs.dentryCache = globalDentryCache
} else {
fs.dentryCache = &dentryCache{maxCachedDentries: defaultMaxCachedDentries}
}
fs.vfsfs.Init(vfsObj, &fstype, fs)
rootInode, rootHostFD, err := fs.initClientAndGetRoot(ctx)
if err != nil {
fs.vfsfs.DecRef(ctx)
return nil, nil, err
}
if fs.opts.directfs.enabled {
fs.root, err = fs.getDirectfsRootDentry(ctx, rootHostFD, fs.client.NewFD(rootInode.ControlFD))
} else {
fs.root, err = fs.newLisafsDentry(ctx, &rootInode)
}
if err != nil {
fs.vfsfs.DecRef(ctx)
return nil, nil, err
}
// Set the root's reference count to 2. One reference is returned to the
// caller, and the other is held by fs to prevent the root from being "cached"
// and subsequently evicted.
fs.root.refs = atomicbitops.FromInt64(2)
return &fs.vfsfs, &fs.root.vfsd, nil
}
// initClientAndGetRoot initializes fs.client and returns the root inode for
// this mount point. It handles the attach point (fs.opts.aname) resolution.
func (fs *filesystem) initClientAndGetRoot(ctx context.Context) (lisafs.Inode, int, error) {
sock, err := unet.NewSocket(fs.opts.fd)
if err != nil {
return lisafs.Inode{}, -1, err
}
ctx.UninterruptibleSleepStart(false)
defer ctx.UninterruptibleSleepFinish(false)
var (
rootInode lisafs.Inode
rootHostFD int
)
fs.client, rootInode, rootHostFD, err = lisafs.NewClient(sock)
if err != nil {
return lisafs.Inode{}, -1, err
}
cu := cleanup.Make(func() {
if rootHostFD >= 0 {
_ = unix.Close(rootHostFD)
}
rootControlFD := fs.client.NewFD(rootInode.ControlFD)
rootControlFD.Close(ctx, false /* flush */)
})
defer cu.Clean()
if fs.opts.directfs.enabled {
if fs.opts.aname != "/" {
log.Warningf("directfs does not support aname filesystem option: aname=%q", fs.opts.aname)
return lisafs.Inode{}, -1, unix.EINVAL
}
if rootHostFD < 0 {
log.Warningf("Mount RPC did not return host FD to mount point with directfs enabled")
return lisafs.Inode{}, -1, unix.EINVAL
}
} else {
if rootHostFD >= 0 {
log.Warningf("Mount RPC returned a host FD to mount point without directfs, we didn't ask for it")
_ = unix.Close(rootHostFD)
rootHostFD = -1
}
// Use flipcall channels with lisafs because it makes a lot of RPCs.
if err := fs.client.StartChannels(); err != nil {
return lisafs.Inode{}, -1, err
}
rootInode, err = fs.handleAnameLisafs(ctx, rootInode)
if err != nil {
return lisafs.Inode{}, -1, err
}
}
cu.Release()
return rootInode, rootHostFD, nil
}
func getFDFromMountOptionsMap(ctx context.Context, mopts map[string]string) (int, error) {
// Check that the transport is "fd".
trans, ok := mopts[moptTransport]
if !ok || trans != transportModeFD {
ctx.Warningf("gofer.getFDFromMountOptionsMap: transport must be specified as '%s=%s'", moptTransport, transportModeFD)
return -1, linuxerr.EINVAL
}
delete(mopts, moptTransport)
// Check that read and write FDs are provided and identical.
rfdstr, ok := mopts[moptReadFD]
if !ok {
ctx.Warningf("gofer.getFDFromMountOptionsMap: read FD must be specified as '%s=<file descriptor>'", moptReadFD)
return -1, linuxerr.EINVAL
}
delete(mopts, moptReadFD)
rfd, err := strconv.Atoi(rfdstr)
if err != nil {
ctx.Warningf("gofer.getFDFromMountOptionsMap: invalid read FD: %s=%s", moptReadFD, rfdstr)
return -1, linuxerr.EINVAL
}
wfdstr, ok := mopts[moptWriteFD]
if !ok {
ctx.Warningf("gofer.getFDFromMountOptionsMap: write FD must be specified as '%s=<file descriptor>'", moptWriteFD)
return -1, linuxerr.EINVAL
}
delete(mopts, moptWriteFD)
wfd, err := strconv.Atoi(wfdstr)
if err != nil {
ctx.Warningf("gofer.getFDFromMountOptionsMap: invalid write FD: %s=%s", moptWriteFD, wfdstr)
return -1, linuxerr.EINVAL
}
if rfd != wfd {
ctx.Warningf("gofer.getFDFromMountOptionsMap: read FD (%d) and write FD (%d) must be equal", rfd, wfd)
return -1, linuxerr.EINVAL
}
return rfd, nil
}
// Release implements vfs.FilesystemImpl.Release.
func (fs *filesystem) Release(ctx context.Context) {
fs.released.Store(1)
mf := fs.mfp.MemoryFile()
fs.syncMu.Lock()
for elem := fs.syncableDentries.Front(); elem != nil; elem = elem.Next() {
d := elem.d
d.handleMu.Lock()
d.dataMu.Lock()
if d.isWriteHandleOk() {
// Write dirty cached data to the remote file.
h := d.writeHandle()
if err := fsutil.SyncDirtyAll(ctx, &d.cache, &d.dirty, d.size.Load(), mf, h.writeFromBlocksAt); err != nil {
log.Warningf("gofer.filesystem.Release: failed to flush dentry: %v", err)
}
// TODO(jamieliu): Do we need to flushf/fsync d?
}
// Discard cached pages.
d.cache.DropAll(mf)
d.dirty.RemoveAll()
d.dataMu.Unlock()
// Close host FDs if they exist. We can use RacyLoad() because d.handleMu
// is locked.
if d.readFD.RacyLoad() >= 0 {
_ = unix.Close(int(d.readFD.RacyLoad()))
}
if d.writeFD.RacyLoad() >= 0 && d.readFD.RacyLoad() != d.writeFD.RacyLoad() {
_ = unix.Close(int(d.writeFD.RacyLoad()))
}
d.readFD = atomicbitops.FromInt32(-1)
d.writeFD = atomicbitops.FromInt32(-1)
d.mmapFD = atomicbitops.FromInt32(-1)
d.handleMu.Unlock()
}
// There can't be any specialFileFDs still using fs, since each such
// FileDescription would hold a reference on a Mount holding a reference on
// fs.
fs.syncMu.Unlock()
// If leak checking is enabled, release all outstanding references in the
// filesystem. We deliberately avoid doing this outside of leak checking; we
// have released all external resources above rather than relying on dentry
// destructors. fs.root may be nil if creating the client or initializing the
// root dentry failed in GetFilesystem.
if refs.GetLeakMode() != refs.NoLeakChecking && fs.root != nil {
fs.renameMu.Lock()
fs.root.releaseSyntheticRecursiveLocked(ctx)
fs.evictAllCachedDentriesLocked(ctx)
fs.renameMu.Unlock()
// An extra reference was held by the filesystem on the root to prevent it from
// being cached/evicted.
fs.root.DecRef(ctx)
}
if !fs.iopts.LeakConnection {
// Close the connection to the server. This implicitly closes all FDs.
if fs.client != nil {
fs.client.Close()
}
}
fs.vfsfs.VirtualFilesystem().PutAnonBlockDevMinor(fs.devMinor)
}
// releaseSyntheticRecursiveLocked traverses the tree with root d and decrements
// the reference count on every synthetic dentry. Synthetic dentries have one
// reference for existence that should be dropped during filesystem.Release.
//
// Precondition: d.fs.renameMu is locked for writing.
func (d *dentry) releaseSyntheticRecursiveLocked(ctx context.Context) {
if d.isSynthetic() {
d.decRefNoCaching()
d.checkCachingLocked(ctx, true /* renameMuWriteLocked */)
}
if d.isDir() {
var children []*dentry
d.childrenMu.Lock()
for _, child := range d.children {
children = append(children, child)
}
d.childrenMu.Unlock()
for _, child := range children {
if child != nil {
child.releaseSyntheticRecursiveLocked(ctx)
}
}
}
}
// inoKey is the key used to identify the inode backed by this dentry.
//
// +stateify savable
type inoKey struct {
ino uint64
devMinor uint32
devMajor uint32
}
func inoKeyFromStatx(stat *linux.Statx) inoKey {
return inoKey{
ino: stat.Ino,
devMinor: stat.DevMinor,
devMajor: stat.DevMajor,
}
}
func inoKeyFromStat(stat *unix.Stat_t) inoKey {
return inoKey{
ino: stat.Ino,
devMinor: unix.Minor(stat.Dev),
devMajor: unix.Major(stat.Dev),
}
}
// dentry implements vfs.DentryImpl.
//
// +stateify savable
type dentry struct {
vfsd vfs.Dentry
// refs is the reference count. Each dentry holds a reference on its
// parent, even if disowned. An additional reference is held on all
// synthetic dentries until they are unlinked or invalidated. When refs
// reaches 0, the dentry may be added to the cache or destroyed. If refs ==
// -1, the dentry has already been destroyed. refs is accessed using atomic
// memory operations.
refs atomicbitops.Int64
// fs is the owning filesystem. fs is immutable.
fs *filesystem
// parent is this dentry's parent directory. Each dentry holds a reference
// on its parent. If this dentry is a filesystem root, parent is nil.
// parent is protected by filesystem.renameMu.
parent *dentry
// name is the name of this dentry in its parent. If this dentry is a
// filesystem root, name is the empty string. name is protected by
// filesystem.renameMu.
name string
// inoKey is used to identify this dentry's inode.
inoKey inoKey
// If deleted is non-zero, the file represented by this dentry has been
// deleted is accessed using atomic memory operations.
deleted atomicbitops.Uint32
// cachingMu is used to synchronize concurrent dentry caching attempts on
// this dentry.
cachingMu sync.Mutex `state:"nosave"`
// If cached is true, this dentry is part of filesystem.dentryCache. cached
// is protected by cachingMu.
cached bool
// cacheEntry links dentry into filesystem.dentryCache.dentries. It is
// protected by filesystem.dentryCache.mu.
cacheEntry dentryListElem
// syncableListEntry links dentry into filesystem.syncableDentries. It is
// protected by filesystem.syncMu.
syncableListEntry dentryListElem
// opMu synchronizes operations on this dentry. Operations that mutate
// the dentry tree must hold this lock for writing. Operations that
// only read the tree must hold for reading.
opMu sync.RWMutex `state:"nosave"`
// childrenMu protects the cached children data for this dentry.
childrenMu sync.Mutex `state:"nosave"`
// If this dentry represents a directory, children contains:
//
// - Mappings of child filenames to dentries representing those children.
//
// - Mappings of child filenames that are known not to exist to nil
// dentries (only if InteropModeShared is not in effect and the directory
// is not synthetic).
//
// +checklocks:childrenMu
children map[string]*dentry
// If this dentry represents a directory, negativeChildrenCache cache
// names of negative children.
//
// +checklocks:childrenMu
negativeChildrenCache stringFixedCache
// If this dentry represents a directory, negativeChildren is the number
// of negative children cached in dentry.children
//
// +checklocks:childrenMu
negativeChildren int
// If this dentry represents a directory, syntheticChildren is the number
// of child dentries for which dentry.isSynthetic() == true.
//
// +checklocks:childrenMu
syntheticChildren int
// If this dentry represents a directory,
// dentry.cachedMetadataAuthoritative() == true, and dirents is not
// nil, then dirents is a cache of all entries in the directory, in the
// order they were returned by the server. childrenSet just stores the
// `Name` field of all dirents in a set for fast query. dirents and
// childrenSet share the same lifecycle.
//
// +checklocks:childrenMu
dirents []vfs.Dirent
// +checklocks:childrenMu
childrenSet map[string]struct{}
// Cached metadata; protected by metadataMu.
// To access:
// - In situations where consistency is not required (like stat), these
// can be accessed using atomic operations only (without locking).
// - Lock metadataMu and can access without atomic operations.
// To mutate:
// - Lock metadataMu and use atomic operations to update because we might
// have atomic readers that don't hold the lock.
metadataMu sync.Mutex `state:"nosave"`
ino uint64 // immutable
mode atomicbitops.Uint32 // type is immutable, perms are mutable
uid atomicbitops.Uint32 // auth.KUID, but stored as raw uint32 for sync/atomic
gid atomicbitops.Uint32 // auth.KGID, but ...
blockSize atomicbitops.Uint32 // 0 if unknown
// Timestamps, all nsecs from the Unix epoch.
atime atomicbitops.Int64
mtime atomicbitops.Int64
ctime atomicbitops.Int64
btime atomicbitops.Int64
// File size, which differs from other metadata in two ways:
//
// - We make a best-effort attempt to keep it up to date even if
// !dentry.cachedMetadataAuthoritative() for the sake of O_APPEND writes.
//
// - size is protected by both metadataMu and dataMu (i.e. both must be
// locked to mutate it; locking either is sufficient to access it).
size atomicbitops.Uint64
// If this dentry does not represent a synthetic file, deleted is 0, and
// atimeDirty/mtimeDirty are non-zero, atime/mtime may have diverged from the
// remote file's timestamps, which should be updated when this dentry is
// evicted.
atimeDirty atomicbitops.Uint32
mtimeDirty atomicbitops.Uint32
// nlink counts the number of hard links to this dentry. It's updated and
// accessed using atomic operations. It's not protected by metadataMu like the
// other metadata fields.
nlink atomicbitops.Uint32
mapsMu sync.Mutex `state:"nosave"`
// If this dentry represents a regular file, mappings tracks mappings of
// the file into memmap.MappingSpaces. mappings is protected by mapsMu.
mappings memmap.MappingSet
// - If this dentry represents a regular file or directory, readFD (if not
// -1) is a host FD used for reads by all regularFileFDs/directoryFDs
// representing this dentry.
//
// - If this dentry represents a regular file, writeFD (if not -1) is a host
// FD used for writes by all regularFileFDs representing this dentry.
//
// - If this dentry represents a regular file, mmapFD is the host FD used
// for memory mappings. If mmapFD is -1, no such FD is available, and the
// internal page cache implementation is used for memory mappings instead.
//
// These fields are protected by handleMu. readFD, writeFD, and mmapFD are
// additionally written using atomic memory operations, allowing them to be
// read (albeit racily) with atomic.LoadInt32() without locking handleMu.
//
// readFD and writeFD may or may not be the same file descriptor. Once either
// transitions from closed (-1) to open, it may be mutated with handleMu
// locked, but cannot be closed until the dentry is destroyed.
//
// readFD and writeFD may or may not be the same file descriptor. mmapFD is
// always either -1 or equal to readFD; if the file has been opened for
// writing, it is additionally either -1 or equal to writeFD.
handleMu sync.RWMutex `state:"nosave"`
readFD atomicbitops.Int32 `state:"nosave"`
writeFD atomicbitops.Int32 `state:"nosave"`
mmapFD atomicbitops.Int32 `state:"nosave"`
dataMu sync.RWMutex `state:"nosave"`
// If this dentry represents a regular file that is client-cached, cache
// maps offsets into the cached file to offsets into
// filesystem.mfp.MemoryFile() that store the file's data. cache is
// protected by dataMu.
cache fsutil.FileRangeSet
// If this dentry represents a regular file that is client-cached, dirty
// tracks dirty segments in cache. dirty is protected by dataMu.
dirty fsutil.DirtySet
// pf implements memmap.File for mappings of hostFD.
pf dentryPlatformFile
// If this dentry represents a symbolic link, InteropModeShared is not in
// effect, and haveTarget is true, target is the symlink target. haveTarget
// and target are protected by dataMu.
haveTarget bool
target string
// If this dentry represents a synthetic socket file, endpoint is the
// transport endpoint bound to this file.
endpoint transport.BoundEndpoint
// If this dentry represents a synthetic named pipe, pipe is the pipe
// endpoint bound to this file.
pipe *pipe.VFSPipe
locks vfs.FileLocks
// Inotify watches for this dentry.
//
// Note that inotify may behave unexpectedly in the presence of hard links,
// because dentries corresponding to the same file have separate inotify
// watches when they should share the same set. This is the case because it is
// impossible for us to know for sure whether two dentries correspond to the
// same underlying file (see the gofer filesystem section fo vfs/inotify.md for
// a more in-depth discussion on this matter).
watches vfs.Watches
// impl is the specific dentry implementation for non-synthetic dentries.
// impl is immutable.
//
// If impl is nil, this dentry represents a synthetic file, i.e. a
// file that does not exist on the host filesystem. As of this writing, the
// only files that can be synthetic are sockets, pipes, and directories.
impl any
}
// +stateify savable
type stringListElem struct {
// str is the string that this elem represents.
str string
stringEntry
}
// +stateify savable
type dentryListElem struct {
// d is the dentry that this elem represents.