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
|
// 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 (
"bytes"
"fmt"
"sort"
"strconv"
"strings"
"gvisor.dev/gvisor/pkg/abi/linux"
"gvisor.dev/gvisor/pkg/atomicbitops"
"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/usermem"
)
const (
// Name is the default filesystem name.
Name = "cgroup"
readonlyFileMode = linux.FileMode(0444)
writableFileMode = linux.FileMode(0644)
defaultDirMode = linux.FileMode(0555) | linux.ModeDirectory
defaultMaxCachedDentries = uint64(1000)
)
var allControllers = []kernel.CgroupControllerType{
kernel.CgroupControllerCPU,
kernel.CgroupControllerCPUAcct,
kernel.CgroupControllerCPUSet,
kernel.CgroupControllerDevices,
kernel.CgroupControllerJob,
kernel.CgroupControllerMemory,
kernel.CgroupControllerPIDs,
}
// SupportedMountOptions is the set of supported mount options for cgroupfs.
var SupportedMountOptions = []string{"all", "cpu", "cpuacct", "cpuset", "devices", "job", "memory", "pids"}
// FilesystemType implements vfs.FilesystemType.
//
// +stateify savable
type FilesystemType struct{}
// InitialCgroup specifies properties of the cgroup for the init task.
//
// +stateify savable
type InitialCgroup struct {
// Path is an absolute path relative to the root of a cgroupfs filesystem
// that indicates where to place the init task. An empty string indicates
// the root of the filesystem.
Path string
// SetOwner indicates the UID and GID fields contain valid values. If true,
// Both UID and GID must be provided.
SetOwner bool
// UID of the initial cgroup path components, excluding the root cgroup.
UID auth.KUID
// GID of the initial cgroup path components, excluding the root cgroup.
GID auth.KGID
// SetMode indicates the Mode field contains a valid value.
SetMode bool
// Mode of the initial cgroup path components, excluding the root cgroup.
Mode linux.FileMode
}
// InternalData contains internal data passed in to the cgroupfs mount via
// vfs.GetFilesystemOptions.InternalData.
//
// +stateify savable
type InternalData struct {
DefaultControlValues map[string]int64
InitialCgroup InitialCgroup
}
// 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
// hierarchyName is the name for a named hierarchy. May be empty if the
// 'name=' mount option was not used when the hierarchy was created.
//
// Immutable after initialization.
hierarchyName string
// 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 atomicbitops.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 taskRWMutex `state:"nosave"`
}
// InitializeHierarchyID implements kernel.cgroupFS.InitializeHierarchyID.
func (fs *filesystem) InitializeHierarchyID(hid uint32) {
fs.hierarchyID = hid
}
// RootCgroup implements kernel.cgroupFS.RootCgroup.
func (fs *filesystem) RootCgroup() kernel.Cgroup {
return kernel.Cgroup{
Dentry: fs.root,
CgroupImpl: fs.root.Inode().(kernel.CgroupImpl),
}
}
// 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, kernel.CgroupControllerCPU)
}
if _, ok := mopts["cpuacct"]; ok {
delete(mopts, "cpuacct")
wantControllers = append(wantControllers, kernel.CgroupControllerCPUAcct)
}
if _, ok := mopts["cpuset"]; ok {
delete(mopts, "cpuset")
wantControllers = append(wantControllers, kernel.CgroupControllerCPUSet)
}
if _, ok := mopts["devices"]; ok {
delete(mopts, "devices")
wantControllers = append(wantControllers, kernel.CgroupControllerDevices)
}
if _, ok := mopts["job"]; ok {
delete(mopts, "job")
wantControllers = append(wantControllers, kernel.CgroupControllerJob)
}
if _, ok := mopts["memory"]; ok {
delete(mopts, "memory")
wantControllers = append(wantControllers, kernel.CgroupControllerMemory)
}
if _, ok := mopts["pids"]; ok {
delete(mopts, "pids")
wantControllers = append(wantControllers, kernel.CgroupControllerPIDs)
}
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
}
var name string
var ok bool
if name, ok = mopts["name"]; ok {
delete(mopts, "name")
}
var none bool
if _, ok = mopts["none"]; ok {
none = true
delete(mopts, "none")
}
if !none && len(wantControllers) == 0 {
// Specifying no controllers implies all controllers, unless "none" was
// explicitly requested.
wantControllers = allControllers
}
// Some combinations of "none", "all", "name=" and explicit controllers are
// not allowed. See Linux, kernel/cgroup.c:parse_cgroupfs_options().
// All empty hierarchies must have a name.
if len(wantControllers) == 0 && name == "" {
ctx.Debugf("cgroupfs.FilesystemType.GetFilesystem: empty hierarchy with no name")
return nil, nil, linuxerr.EINVAL
}
// Can't have "none" and some controllers.
if none && len(wantControllers) != 0 {
ctx.Debugf("cgroupfs.FilesystemType.GetFilesystem: 'none' specified with controllers: %v", wantControllers)
return nil, nil, linuxerr.EINVAL
}
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.
vfsfs, err := r.FindHierarchy(name, wantControllers)
if err != nil {
return nil, nil, err
}
if 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,
hierarchyName: name,
}
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 kernel.CgroupControllerCPU:
c = newCPUController(fs, defaults)
case kernel.CgroupControllerCPUAcct:
c = newCPUAcctController(fs)
case kernel.CgroupControllerCPUSet:
c = newCPUSetController(k, fs)
case kernel.CgroupControllerDevices:
c = newDevicesController(fs)
case kernel.CgroupControllerJob:
c = newJobController(fs)
case kernel.CgroupControllerMemory:
c = newMemoryController(fs, defaults)
case kernel.CgroupControllerPIDs:
c = newRootPIDsController(fs)
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, nil, defaultDirMode)
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(name, 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.effectiveRootCgroup())
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
}
idata := opts.InternalData.(*InternalData)
initPathStr := idata.InitialCgroup.Path
if initPathStr == "" {
return nil
}
ctx.Debugf("cgroupfs.FilesystemType.GetFilesystem: initial cgroup path: %v", initPathStr)
initPath := fspath.Parse(initPathStr)
if !initPath.Absolute {
ctx.Warningf("cgroupfs.FilesystemType.GetFilesystem: initial cgroup path invalid: %+v", initPath)
return linuxerr.EINVAL
}
if !initPath.HasComponents() {
// Explicit "/" as initial cgroup, nothing to do.
return nil
}
ownerCreds := auth.CredentialsFromContext(ctx).Fork()
if idata.InitialCgroup.SetOwner {
ownerCreds.EffectiveKUID = idata.InitialCgroup.UID
ownerCreds.EffectiveKGID = idata.InitialCgroup.GID
}
mode := defaultDirMode
if idata.InitialCgroup.SetMode {
mode = idata.InitialCgroup.Mode
}
// Have initial cgroup target, create the tree.
cgDir := fs.root.Inode().(*cgroupInode)
for pit := initPath.Begin; pit.Ok(); pit = pit.Next() {
cgDirI, err := cgDir.newDirWithOwner(ctx, ownerCreds, pit.String(), vfs.MkdirOptions{Mode: mode})
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) effectiveRootCgroup() 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.InodeAlwaysValid
kernfs.InodeAttrs
kernfs.InodeDirectoryNoNewChildren
kernfs.InodeNoopRefCount
kernfs.InodeNotAnonymous
kernfs.InodeNotSymlink
kernfs.InodeWatches
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.
func (d *dir) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {
return d.InodeAttrs.SetStat(ctx, fs, creds, opts)
}
// Open implements kernfs.Inode.Open.
func (d *dir) Open(ctx context.Context, rp *vfs.ResolvingPath, kd *kernfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {
opts.Flags &= linux.O_ACCMODE | linux.O_CREAT | linux.O_EXCL | linux.O_TRUNC |
linux.O_DIRECTORY | linux.O_NOFOLLOW | linux.O_NONBLOCK | linux.O_NOCTTY
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) {
return d.newDirWithOwner(ctx, auth.CredentialsFromContext(ctx), name, opts)
}
func (d *dir) newDirWithOwner(ctx context.Context, ownerCreds *auth.Credentials, 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
}
mode := opts.Mode.Permissions() | linux.ModeDirectory
return d.OrderedChildren.Inserter(name, func() kernfs.Inode {
d.IncLinks(1)
return d.fs.newCgroupInode(ctx, ownerCreds, d.cgi, mode)
})
}
// 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
}
func (d *dir) forEachChildDir(fn func(*dir)) {
d.OrderedChildren.ForEachChild(func(_ string, i kernfs.Inode) {
if childI, ok := i.(*cgroupInode); ok {
fn(&childI.dir)
}
})
}
// controllerFileImpl represents common cgroupfs-specific operations for control
// files.
type controllerFileImpl interface {
// Source extracts the underlying DynamicBytesFile for a control file.
Source() *kernfs.DynamicBytesFile
// AllowBackgroundAccess indicates whether a control file can be accessed
// from a background (i.e. non-task) context. Some control files cannot be
// meaningfully accessed from a non-task context because accessing them
// either have side effects on the calling context (ex: task migration
// across cgroups), or they refer to data which must be interpreted within
// the calling context (ex: when referring to a pid, in which pid
// namespace?).
//
// Currently, all writable control files that allow access from a background
// process can handle a nil FD, since a background write doesn't explicitly
// open the control file. This is enforced through the
// writableControllerFileImpl.
AllowBackgroundAccess() bool
}
// writableControllerFileImpl represents common cgroupfs-specific operations for
// a writable control file.
type writableControllerFileImpl interface {
controllerFileImpl
// WriteBackground writes data to a control file from a background
// context. This means the write isn't performed through and FD may be
// performed from a background context.
//
// Control files that support this should also return true for
// controllerFileImpl.AllowBackgroundAccess().
WriteBackground(ctx context.Context, src usermem.IOSequence) (int64, error)
}
// controllerFile represents a generic control file that appears within a cgroup
// directory.
//
// +stateify savable
type controllerFile struct {
kernfs.DynamicBytesFile
implStatFS
allowBackgroundAccess bool
}
var _ controllerFileImpl = (*controllerFile)(nil)
// Source implements controllerFileImpl.Source.
func (f *controllerFile) Source() *kernfs.DynamicBytesFile {
return &f.DynamicBytesFile
}
// AllowBackgroundAccess implements controllerFileImpl.AllowBackgroundAccess.
func (f *controllerFile) AllowBackgroundAccess() bool {
return f.allowBackgroundAccess
}
// SetStat implements kernfs.Inode.SetStat.
func (f *controllerFile) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {
return f.InodeAttrs.SetStat(ctx, fs, creds, opts)
}
func (fs *filesystem) newControllerFile(ctx context.Context, creds *auth.Credentials, data vfs.DynamicBytesSource, allowBackgroundAccess bool) kernfs.Inode {
f := &controllerFile{
allowBackgroundAccess: allowBackgroundAccess,
}
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, allowBackgroundAccess bool) kernfs.Inode {
f := &controllerFile{
allowBackgroundAccess: allowBackgroundAccess,
}
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
}
var _ controllerFileImpl = (*staticControllerFile)(nil)
// Source implements controllerFileImpl.Source.
func (f *staticControllerFile) Source() *kernfs.DynamicBytesFile {
return &f.DynamicBytesFile
}
// AllowBackgroundAccess implements controllerFileImpl.AllowBackgroundAccess.
func (f *staticControllerFile) AllowBackgroundAccess() bool {
return true
}
// SetStat implements kernfs.Inode.SetStat.
func (f *staticControllerFile) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Credentials, opts vfs.SetStatOptions) error {
return f.InodeAttrs.SetStat(ctx, fs, creds, opts)
}
// 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
}
// stubControllerFile is a writable control file that remembers the control
// value written to it.
//
// +stateify savable
type stubControllerFile struct {
controllerFile
// data is accessed through atomic ops.
data *atomicbitops.Int64
}
var _ controllerFileImpl = (*stubControllerFile)(nil)
// Generate implements vfs.DynamicBytesSource.Generate.
func (f *stubControllerFile) Generate(ctx context.Context, buf *bytes.Buffer) error {
fmt.Fprintf(buf, "%d\n", f.data.Load())
return nil
}
// Write implements vfs.WritableDynamicBytesSource.Write.
func (f *stubControllerFile) Write(ctx context.Context, _ *vfs.FileDescription, src usermem.IOSequence, offset int64) (int64, error) {
return f.WriteBackground(ctx, src)
}
// WriteBackground implements writableControllerFileImpl.WriteBackground.
func (f *stubControllerFile) WriteBackground(ctx context.Context, src usermem.IOSequence) (int64, error) {
val, n, err := parseInt64FromString(ctx, src)
if err != nil {
return 0, err
}
f.data.Store(val)
return n, nil
}
// newStubControllerFile creates a new stub controller file that loads and
// stores a control value from data.
func (fs *filesystem) newStubControllerFile(ctx context.Context, creds *auth.Credentials, data *atomicbitops.Int64, allowBackgroundAccess bool) kernfs.Inode {
f := &stubControllerFile{
controllerFile: controllerFile{
allowBackgroundAccess: allowBackgroundAccess,
},
data: data,
}
f.Init(ctx, creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), f, writableFileMode)
return f
}
|