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
|
// Copyright 2021 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 cgroupfs implements cgroupfs.
//
// A cgroup is a collection of tasks on the system, organized into a tree-like
// structure similar to a filesystem directory tree. In fact, each cgroup is
// represented by a directory on cgroupfs, and is manipulated through control
// files in the directory.
//
// All cgroups on a system are organized into hierarchies. Hierarchies are a
// distinct tree of cgroups, with a common set of controllers. One or more
// cgroupfs mounts may point to each hierarchy. These mounts provide a common
// view into the same tree of cgroups.
//
// A controller (also known as a "resource controller", or a cgroup "subsystem")
// determines the behaviour of each cgroup.
//
// In addition to cgroupfs, the kernel has a cgroup registry that tracks
// system-wide state related to cgroups such as active hierarchies and the
// controllers associated with them.
//
// Since cgroupfs doesn't allow hardlinks, there is a unique mapping between
// cgroupfs dentries and inodes. Thus, cgroupfs inodes don't need to be ref
// counted and exist until they're unlinked once or the FS is destroyed.
//
// # Synchronization
//
// Cgroup hierarchy creation and destruction is protected by the
// kernel.CgroupRegistry.mu. Once created, a hierarchy's set of controllers, the
// filesystem associated with it, and the root cgroup for the hierarchy are
// immutable.
//
// Membership of tasks within cgroups is protected by
// cgroupfs.filesystem.tasksMu. Tasks also maintain a set of all cgroups they're
// in, and this list is protected by Task.mu.
//
// Lock order:
//
// kernel.CgroupRegistry.mu
// kernfs.filesystem.mu
// kernel.TaskSet.mu
// kernel.Task.mu
// cgroupfs.filesystem.tasksMu.
// cgroupfs.dir.OrderedChildren.mu
package cgroupfs
import (
"fmt"
"sort"
"strconv"
"strings"
"gvisor.dev/gvisor/pkg/abi/linux"
"gvisor.dev/gvisor/pkg/context"
"gvisor.dev/gvisor/pkg/errors/linuxerr"
"gvisor.dev/gvisor/pkg/fspath"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs"
"gvisor.dev/gvisor/pkg/sentry/kernel"
"gvisor.dev/gvisor/pkg/sentry/kernel/auth"
"gvisor.dev/gvisor/pkg/sentry/vfs"
"gvisor.dev/gvisor/pkg/sync"
)
const (
// Name is the default filesystem name.
Name = "cgroup"
readonlyFileMode = linux.FileMode(0444)
writableFileMode = linux.FileMode(0644)
defaultMaxCachedDentries = uint64(1000)
)
const (
controllerCPU = kernel.CgroupControllerType("cpu")
controllerCPUAcct = kernel.CgroupControllerType("cpuacct")
controllerCPUSet = kernel.CgroupControllerType("cpuset")
controllerJob = kernel.CgroupControllerType("job")
controllerMemory = kernel.CgroupControllerType("memory")
)
var allControllers = []kernel.CgroupControllerType{
controllerCPU,
controllerCPUAcct,
controllerCPUSet,
controllerJob,
controllerMemory,
}
// SupportedMountOptions is the set of supported mount options for cgroupfs.
var SupportedMountOptions = []string{"all", "cpu", "cpuacct", "cpuset", "job", "memory"}
// FilesystemType implements vfs.FilesystemType.
//
// +stateify savable
type FilesystemType struct{}
// InternalData contains internal data passed in to the cgroupfs mount via
// vfs.GetFilesystemOptions.InternalData.
//
// +stateify savable
type InternalData struct {
DefaultControlValues map[string]int64
InitialCgroupPath string
}
// filesystem implements vfs.FilesystemImpl and kernel.cgroupFS.
//
// +stateify savable
type filesystem struct {
kernfs.Filesystem
devMinor uint32
// hierarchyID is the id the cgroup registry assigns to this hierarchy. Has
// the value kernel.InvalidCgroupHierarchyID until the FS is fully
// initialized.
//
// hierarchyID is immutable after initialization.
hierarchyID uint32
// controllers and kcontrollers are both the list of controllers attached to
// this cgroupfs. Both lists are the same set of controllers, but typecast
// to different interfaces for convenience. Both must stay in sync, and are
// immutable.
controllers []controller
kcontrollers []kernel.CgroupController
numCgroups uint64 // Protected by atomic ops.
root *kernfs.Dentry
// effectiveRoot is the initial cgroup new tasks are created in. Unless
// overwritten by internal mount options, root == effectiveRoot. If
// effectiveRoot != root, an extra reference is held on effectiveRoot for
// the lifetime of the filesystem.
effectiveRoot *kernfs.Dentry
// tasksMu serializes task membership changes across all cgroups within a
// filesystem.
tasksMu sync.RWMutex `state:"nosave"`
}
// InitializeHierarchyID implements kernel.cgroupFS.InitializeHierarchyID.
func (fs *filesystem) InitializeHierarchyID(hid uint32) {
fs.hierarchyID = hid
}
// 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) {
devMinor, err := vfsObj.GetAnonBlockDevMinor()
if err != nil {
return nil, nil, err
}
mopts := vfs.GenericParseMountOptions(opts.Data)
maxCachedDentries := defaultMaxCachedDentries
if str, ok := mopts["dentry_cache_limit"]; ok {
delete(mopts, "dentry_cache_limit")
maxCachedDentries, err = strconv.ParseUint(str, 10, 64)
if err != nil {
ctx.Warningf("sys.FilesystemType.GetFilesystem: invalid dentry cache limit: dentry_cache_limit=%s", str)
return nil, nil, linuxerr.EINVAL
}
}
var wantControllers []kernel.CgroupControllerType
if _, ok := mopts["cpu"]; ok {
delete(mopts, "cpu")
wantControllers = append(wantControllers, controllerCPU)
}
if _, ok := mopts["cpuacct"]; ok {
delete(mopts, "cpuacct")
wantControllers = append(wantControllers, controllerCPUAcct)
}
if _, ok := mopts["cpuset"]; ok {
delete(mopts, "cpuset")
wantControllers = append(wantControllers, controllerCPUSet)
}
if _, ok := mopts["job"]; ok {
delete(mopts, "job")
wantControllers = append(wantControllers, controllerJob)
}
if _, ok := mopts["memory"]; ok {
delete(mopts, "memory")
wantControllers = append(wantControllers, controllerMemory)
}
if _, ok := mopts["all"]; ok {
if len(wantControllers) > 0 {
ctx.Debugf("cgroupfs.FilesystemType.GetFilesystem: other controllers specified with all: %v", wantControllers)
return nil, nil, linuxerr.EINVAL
}
delete(mopts, "all")
wantControllers = allControllers
}
if len(wantControllers) == 0 {
// Specifying no controllers implies all controllers.
wantControllers = allControllers
}
if len(mopts) != 0 {
ctx.Debugf("cgroupfs.FilesystemType.GetFilesystem: unknown options: %v", mopts)
return nil, nil, linuxerr.EINVAL
}
k := kernel.KernelFromContext(ctx)
r := k.CgroupRegistry()
// "It is not possible to mount the same controller against multiple
// cgroup hierarchies. For example, it is not possible to mount both
// the cpu and cpuacct controllers against one hierarchy, and to mount
// the cpu controller alone against another hierarchy." - man cgroups(7)
//
// Is there a hierarchy available with all the controllers we want? If so,
// this mount is a view into the same hierarchy.
//
// Note: we're guaranteed to have at least one requested controller, since
// no explicit controller name implies all controllers.
if vfsfs := r.FindHierarchy(wantControllers); vfsfs != nil {
fs := vfsfs.Impl().(*filesystem)
ctx.Debugf("cgroupfs.FilesystemType.GetFilesystem: mounting new view to hierarchy %v", fs.hierarchyID)
fs.root.IncRef()
if fs.effectiveRoot != fs.root {
fs.effectiveRoot.IncRef()
}
return vfsfs, fs.root.VFSDentry(), nil
}
// No existing hierarchy with the exactly controllers found. Make a new
// one. Note that it's possible this mount creation is unsatisfiable, if one
// or more of the requested controllers are already on existing
// hierarchies. We'll find out about such collisions when we try to register
// the new hierarchy later.
fs := &filesystem{
devMinor: devMinor,
}
fs.MaxCachedDentries = maxCachedDentries
fs.VFSFilesystem().Init(vfsObj, &fsType, fs)
var defaults map[string]int64
if opts.InternalData != nil {
defaults = opts.InternalData.(*InternalData).DefaultControlValues
ctx.Debugf("cgroupfs.FilesystemType.GetFilesystem: default control values: %v", defaults)
}
for _, ty := range wantControllers {
var c controller
switch ty {
case controllerCPU:
c = newCPUController(fs, defaults)
case controllerCPUAcct:
c = newCPUAcctController(fs)
case controllerCPUSet:
c = newCPUSetController(fs)
case controllerJob:
c = newJobController(fs)
case controllerMemory:
c = newMemoryController(fs, defaults)
default:
panic(fmt.Sprintf("Unreachable: unknown cgroup controller %q", ty))
}
fs.controllers = append(fs.controllers, c)
}
if len(defaults) != 0 {
// Internal data is always provided at sentry startup and unused values
// indicate a problem with the sandbox config. Fail fast.
panic(fmt.Sprintf("cgroupfs.FilesystemType.GetFilesystem: unknown internal mount data: %v", defaults))
}
// Controllers usually appear in alphabetical order when displayed. Sort it
// here now, so it never needs to be sorted elsewhere.
sort.Slice(fs.controllers, func(i, j int) bool { return fs.controllers[i].Type() < fs.controllers[j].Type() })
fs.kcontrollers = make([]kernel.CgroupController, 0, len(fs.controllers))
for _, c := range fs.controllers {
fs.kcontrollers = append(fs.kcontrollers, c)
}
root := fs.newCgroupInode(ctx, creds)
var rootD kernfs.Dentry
rootD.InitRoot(&fs.Filesystem, root)
fs.root = &rootD
fs.effectiveRoot = fs.root
if err := fs.prepareInitialCgroup(ctx, vfsObj, opts); err != nil {
ctx.Warningf("cgroupfs.FilesystemType.GetFilesystem: failed to prepare initial cgroup: %v", err)
rootD.DecRef(ctx)
fs.VFSFilesystem().DecRef(ctx)
return nil, nil, err
}
// Register controllers. The registry may be modified concurrently, so if we
// get an error, we raced with someone else who registered the same
// controllers first.
if err := r.Register(fs.kcontrollers, fs); err != nil {
ctx.Infof("cgroupfs.FilesystemType.GetFilesystem: failed to register new hierarchy with controllers %v: %v", wantControllers, err)
rootD.DecRef(ctx)
fs.VFSFilesystem().DecRef(ctx)
return nil, nil, linuxerr.EBUSY
}
// Move all existing tasks to the root of the new hierarchy.
k.PopulateNewCgroupHierarchy(fs.rootCgroup())
return fs.VFSFilesystem(), rootD.VFSDentry(), nil
}
// prepareInitialCgroup creates the initial cgroup according to opts. An initial
// cgroup is optional, and if not specified, this function is a no-op.
func (fs *filesystem) prepareInitialCgroup(ctx context.Context, vfsObj *vfs.VirtualFilesystem, opts vfs.GetFilesystemOptions) error {
if opts.InternalData == nil {
return nil
}
initPathStr := opts.InternalData.(*InternalData).InitialCgroupPath
if initPathStr == "" {
return nil
}
ctx.Debugf("cgroupfs.FilesystemType.GetFilesystem: initial cgroup path: %v", initPathStr)
initPath := fspath.Parse(initPathStr)
if !initPath.Absolute || !initPath.HasComponents() {
ctx.Warningf("cgroupfs.FilesystemType.GetFilesystem: initial cgroup path invalid: %+v", initPath)
return linuxerr.EINVAL
}
// Have initial cgroup target, create the tree.
cgDir := fs.root.Inode().(*cgroupInode)
for pit := initPath.Begin; pit.Ok(); pit = pit.Next() {
cgDirI, err := cgDir.NewDir(ctx, pit.String(), vfs.MkdirOptions{})
if err != nil {
return err
}
cgDir = cgDirI.(*cgroupInode)
}
// Walk to target dentry.
initDentry, err := fs.root.WalkDentryTree(ctx, vfsObj, initPath)
if err != nil {
ctx.Warningf("cgroupfs.FilesystemType.GetFilesystem: initial cgroup dentry not found: %v", err)
return linuxerr.ENOENT
}
fs.effectiveRoot = initDentry // Reference from WalkDentryTree transferred here.
return nil
}
func (fs *filesystem) rootCgroup() kernel.Cgroup {
return kernel.Cgroup{
Dentry: fs.effectiveRoot,
CgroupImpl: fs.effectiveRoot.Inode().(kernel.CgroupImpl),
}
}
// Release implements vfs.FilesystemImpl.Release.
func (fs *filesystem) Release(ctx context.Context) {
k := kernel.KernelFromContext(ctx)
r := k.CgroupRegistry()
if fs.hierarchyID != kernel.InvalidCgroupHierarchyID {
k.ReleaseCgroupHierarchy(fs.hierarchyID)
r.Unregister(fs.hierarchyID)
}
if fs.root != fs.effectiveRoot {
fs.effectiveRoot.DecRef(ctx)
}
fs.Filesystem.VFSFilesystem().VirtualFilesystem().PutAnonBlockDevMinor(fs.devMinor)
fs.Filesystem.Release(ctx)
}
// MountOptions implements vfs.FilesystemImpl.MountOptions.
func (fs *filesystem) MountOptions() string {
var cnames []string
for _, c := range fs.controllers {
cnames = append(cnames, string(c.Type()))
}
return strings.Join(cnames, ",")
}
// +stateify savable
type implStatFS struct{}
// StatFS implements kernfs.Inode.StatFS.
func (*implStatFS) StatFS(context.Context, *vfs.Filesystem) (linux.Statfs, error) {
return vfs.GenericStatFS(linux.CGROUP_SUPER_MAGIC), nil
}
// dir implements kernfs.Inode for a generic cgroup resource controller
// directory. Specific controllers extend this to add their own functionality.
//
// +stateify savable
type dir struct {
kernfs.InodeNoopRefCount
kernfs.InodeAlwaysValid
kernfs.InodeAttrs
kernfs.InodeNotSymlink
kernfs.InodeDirectoryNoNewChildren
kernfs.OrderedChildren
implStatFS
locks vfs.FileLocks
fs *filesystem // Immutable.
cgi *cgroupInode // Immutable.
}
// Keep implements kernfs.Inode.Keep.
func (*dir) Keep() bool {
return true
}
// SetStat implements kernfs.Inode.SetStat not allowing inode attributes to be changed.
func (*dir) SetStat(context.Context, *vfs.Filesystem, *auth.Credentials, vfs.SetStatOptions) error {
return linuxerr.EPERM
}
// Open implements kernfs.Inode.Open.
func (d *dir) Open(ctx context.Context, rp *vfs.ResolvingPath, kd *kernfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {
fd, err := kernfs.NewGenericDirectoryFD(rp.Mount(), kd, &d.OrderedChildren, &d.locks, &opts, kernfs.GenericDirectoryFDOptions{
SeekEnd: kernfs.SeekEndStaticEntries,
})
if err != nil {
return nil, err
}
return fd.VFSFileDescription(), nil
}
// NewDir implements kernfs.Inode.NewDir.
func (d *dir) NewDir(ctx context.Context, name string, opts vfs.MkdirOptions) (kernfs.Inode, error) {
// "Do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable."
// -- Linux, kernel/cgroup.c:cgroup_mkdir().
if strings.Contains(name, "\n") {
return nil, linuxerr.EINVAL
}
return d.OrderedChildren.Inserter(name, func() kernfs.Inode {
d.IncLinks(1)
return d.fs.newCgroupInode(ctx, auth.CredentialsFromContext(ctx))
})
}
// Rename implements kernfs.Inode.Rename. Cgroupfs only allows renaming of
// cgroup directories, and the rename may only change the name within the same
// parent. See linux, kernel/cgroup.c:cgroup_rename().
func (d *dir) Rename(ctx context.Context, oldname, newname string, child, dst kernfs.Inode) error {
if _, ok := child.(*cgroupInode); !ok {
// Not a cgroup directory. Control files are backed by different types.
return linuxerr.ENOTDIR
}
dstCGInode, ok := dst.(*cgroupInode)
if !ok {
// Not a cgroup inode, so definitely can't be *this* inode.
return linuxerr.EIO
}
// Note: We're intentionally comparing addresses, since two different dirs
// could plausibly be identical in memory, but would occupy different
// locations in memory.
if d != &dstCGInode.dir {
// Destination dir is a different cgroup inode. Cross directory renames
// aren't allowed.
return linuxerr.EIO
}
// Rename moves oldname to newname within d. Proceed.
return d.OrderedChildren.Rename(ctx, oldname, newname, child, dst)
}
// Unlink implements kernfs.Inode.Unlink. Cgroupfs disallows unlink, as the only
// files in the filesystem are control files, which can't be deleted.
func (d *dir) Unlink(ctx context.Context, name string, child kernfs.Inode) error {
return linuxerr.EPERM
}
// hasChildrenLocked returns whether the cgroup dir contains any objects that
// prevent it from being deleted.
func (d *dir) hasChildrenLocked() bool {
// Subdirs take a link on the parent, so checks if there are any direct
// children cgroups. Exclude the dir's self link and the link from ".".
if d.InodeAttrs.Links()-2 > 0 {
return true
}
return len(d.cgi.ts) > 0
}
// HasChildren implements kernfs.Inode.HasChildren.
//
// The empty check for a cgroupfs directory is unlike a regular directory since
// a cgroupfs directory will always have control files. A cgroupfs directory can
// be deleted if cgroup contains no tasks and has no sub-cgroups.
func (d *dir) HasChildren() bool {
d.fs.tasksMu.RLock()
defer d.fs.tasksMu.RUnlock()
return d.hasChildrenLocked()
}
// RmDir implements kernfs.Inode.RmDir.
func (d *dir) RmDir(ctx context.Context, name string, child kernfs.Inode) error {
// Unlike a normal directory, we need to recheck if d is empty again, since
// vfs/kernfs can't stop tasks from entering or leaving the cgroup.
d.fs.tasksMu.RLock()
defer d.fs.tasksMu.RUnlock()
cgi, ok := child.(*cgroupInode)
if !ok {
return linuxerr.ENOTDIR
}
if cgi.dir.hasChildrenLocked() {
return linuxerr.ENOTEMPTY
}
// Disallow deletion of the effective root cgroup.
if cgi == d.fs.effectiveRoot.Inode().(*cgroupInode) {
ctx.Warningf("Cannot delete initial cgroup for new tasks %q", d.fs.effectiveRoot.FSLocalPath())
return linuxerr.EBUSY
}
err := d.OrderedChildren.RmDir(ctx, name, child)
if err == nil {
d.InodeAttrs.DecLinks()
}
return err
}
// controllerFile represents a generic control file that appears within a cgroup
// directory.
//
// +stateify savable
type controllerFile struct {
kernfs.DynamicBytesFile
}
func (fs *filesystem) newControllerFile(ctx context.Context, creds *auth.Credentials, data vfs.DynamicBytesSource) kernfs.Inode {
f := &controllerFile{}
f.Init(ctx, creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), data, readonlyFileMode)
return f
}
func (fs *filesystem) newControllerWritableFile(ctx context.Context, creds *auth.Credentials, data vfs.WritableDynamicBytesSource) kernfs.Inode {
f := &controllerFile{}
f.Init(ctx, creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), data, writableFileMode)
return f
}
// staticControllerFile represents a generic control file that appears within a
// cgroup directory which always returns the same data when read.
// staticControllerFiles are not writable.
//
// +stateify savable
type staticControllerFile struct {
kernfs.DynamicBytesFile
vfs.StaticData
}
// Note: We let the caller provide the mode so that static files may be used to
// fake both readable and writable control files. However, static files are
// effectively readonly, as attempting to write to them will return EIO
// regardless of the mode.
func (fs *filesystem) newStaticControllerFile(ctx context.Context, creds *auth.Credentials, mode linux.FileMode, data string) kernfs.Inode {
f := &staticControllerFile{StaticData: vfs.StaticData{Data: data}}
f.Init(ctx, creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), f, mode)
return f
}
|