github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/fsimpl/cgroupfs/memory.go (about) 1 // Copyright 2021 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package cgroupfs 16 17 import ( 18 "bytes" 19 "fmt" 20 "math" 21 22 "github.com/SagerNet/gvisor/pkg/abi/linux" 23 "github.com/SagerNet/gvisor/pkg/context" 24 "github.com/SagerNet/gvisor/pkg/sentry/fsimpl/kernfs" 25 "github.com/SagerNet/gvisor/pkg/sentry/kernel" 26 "github.com/SagerNet/gvisor/pkg/sentry/kernel/auth" 27 "github.com/SagerNet/gvisor/pkg/sentry/usage" 28 ) 29 30 // +stateify savable 31 type memoryController struct { 32 controllerCommon 33 34 limitBytes int64 35 } 36 37 var _ controller = (*memoryController)(nil) 38 39 func newMemoryController(fs *filesystem, defaults map[string]int64) *memoryController { 40 c := &memoryController{ 41 // Linux sets this to (PAGE_COUNTER_MAX * PAGE_SIZE) by default, which 42 // is ~ 2**63 on a 64-bit system. So essentially, inifinity. The exact 43 // value isn't very important. 44 limitBytes: math.MaxInt64, 45 } 46 if val, ok := defaults["memory.limit_in_bytes"]; ok { 47 c.limitBytes = val 48 delete(defaults, "memory.limit_in_bytes") 49 } 50 c.controllerCommon.init(controllerMemory, fs) 51 return c 52 } 53 54 // AddControlFiles implements controller.AddControlFiles. 55 func (c *memoryController) AddControlFiles(ctx context.Context, creds *auth.Credentials, _ *cgroupInode, contents map[string]kernfs.Inode) { 56 contents["memory.usage_in_bytes"] = c.fs.newControllerFile(ctx, creds, &memoryUsageInBytesData{}) 57 contents["memory.limit_in_bytes"] = c.fs.newStaticControllerFile(ctx, creds, linux.FileMode(0644), fmt.Sprintf("%d\n", c.limitBytes)) 58 } 59 60 // +stateify savable 61 type memoryUsageInBytesData struct{} 62 63 // Generate implements vfs.DynamicBytesSource.Generate. 64 func (d *memoryUsageInBytesData) Generate(ctx context.Context, buf *bytes.Buffer) error { 65 // TODO(b/183151557): This is a giant hack, we're using system-wide 66 // accounting since we know there is only one cgroup. 67 k := kernel.KernelFromContext(ctx) 68 mf := k.MemoryFile() 69 mf.UpdateUsage() 70 _, totalBytes := usage.MemoryAccounting.Copy() 71 72 fmt.Fprintf(buf, "%d\n", totalBytes) 73 return nil 74 }