// Copyright 2019 The Prometheus 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.

//go:build !windows
// +build !windows

package procfs

import (
	
	
	
	

	
)

// The VM interface is described at
//
//	https://www.kernel.org/doc/Documentation/sysctl/vm.txt
//
// Each setting is exposed as a single file.
// Each file contains one line with a single numerical value, except lowmem_reserve_ratio which holds an array
// and numa_zonelist_order (deprecated) which is a string.
type VM struct {
	AdminReserveKbytes        *int64   // /proc/sys/vm/admin_reserve_kbytes
	BlockDump                 *int64   // /proc/sys/vm/block_dump
	CompactUnevictableAllowed *int64   // /proc/sys/vm/compact_unevictable_allowed
	DirtyBackgroundBytes      *int64   // /proc/sys/vm/dirty_background_bytes
	DirtyBackgroundRatio      *int64   // /proc/sys/vm/dirty_background_ratio
	DirtyBytes                *int64   // /proc/sys/vm/dirty_bytes
	DirtyExpireCentisecs      *int64   // /proc/sys/vm/dirty_expire_centisecs
	DirtyRatio                *int64   // /proc/sys/vm/dirty_ratio
	DirtytimeExpireSeconds    *int64   // /proc/sys/vm/dirtytime_expire_seconds
	DirtyWritebackCentisecs   *int64   // /proc/sys/vm/dirty_writeback_centisecs
	DropCaches                *int64   // /proc/sys/vm/drop_caches
	ExtfragThreshold          *int64   // /proc/sys/vm/extfrag_threshold
	HugetlbShmGroup           *int64   // /proc/sys/vm/hugetlb_shm_group
	LaptopMode                *int64   // /proc/sys/vm/laptop_mode
	LegacyVaLayout            *int64   // /proc/sys/vm/legacy_va_layout
	LowmemReserveRatio        []*int64 // /proc/sys/vm/lowmem_reserve_ratio
	MaxMapCount               *int64   // /proc/sys/vm/max_map_count
	MemoryFailureEarlyKill    *int64   // /proc/sys/vm/memory_failure_early_kill
	MemoryFailureRecovery     *int64   // /proc/sys/vm/memory_failure_recovery
	MinFreeKbytes             *int64   // /proc/sys/vm/min_free_kbytes
	MinSlabRatio              *int64   // /proc/sys/vm/min_slab_ratio
	MinUnmappedRatio          *int64   // /proc/sys/vm/min_unmapped_ratio
	MmapMinAddr               *int64   // /proc/sys/vm/mmap_min_addr
	NrHugepages               *int64   // /proc/sys/vm/nr_hugepages
	NrHugepagesMempolicy      *int64   // /proc/sys/vm/nr_hugepages_mempolicy
	NrOvercommitHugepages     *int64   // /proc/sys/vm/nr_overcommit_hugepages
	NumaStat                  *int64   // /proc/sys/vm/numa_stat
	NumaZonelistOrder         string   // /proc/sys/vm/numa_zonelist_order
	OomDumpTasks              *int64   // /proc/sys/vm/oom_dump_tasks
	OomKillAllocatingTask     *int64   // /proc/sys/vm/oom_kill_allocating_task
	OvercommitKbytes          *int64   // /proc/sys/vm/overcommit_kbytes
	OvercommitMemory          *int64   // /proc/sys/vm/overcommit_memory
	OvercommitRatio           *int64   // /proc/sys/vm/overcommit_ratio
	PageCluster               *int64   // /proc/sys/vm/page-cluster
	PanicOnOom                *int64   // /proc/sys/vm/panic_on_oom
	PercpuPagelistFraction    *int64   // /proc/sys/vm/percpu_pagelist_fraction
	StatInterval              *int64   // /proc/sys/vm/stat_interval
	Swappiness                *int64   // /proc/sys/vm/swappiness
	UserReserveKbytes         *int64   // /proc/sys/vm/user_reserve_kbytes
	VfsCachePressure          *int64   // /proc/sys/vm/vfs_cache_pressure
	WatermarkBoostFactor      *int64   // /proc/sys/vm/watermark_boost_factor
	WatermarkScaleFactor      *int64   // /proc/sys/vm/watermark_scale_factor
	ZoneReclaimMode           *int64   // /proc/sys/vm/zone_reclaim_mode
}

// VM reads the VM statistics from the specified `proc` filesystem.
func ( FS) () (*VM, error) {
	 := .proc.Path("sys/vm")
	,  := os.Stat()
	if  != nil {
		return nil, 
	}
	if !.Mode().IsDir() {
		return nil, fmt.Errorf("%w: %s is not a directory", ErrFileRead, )
	}

	,  := os.ReadDir()
	if  != nil {
		return nil, 
	}

	var  VM
	for ,  := range  {
		if .IsDir() {
			continue
		}

		 := filepath.Join(, .Name())
		// ignore errors on read, as there are some write only
		// in /proc/sys/vm
		,  := util.SysReadFile()
		if  != nil {
			continue
		}
		 := util.NewValueParser()

		switch .Name() {
		case "admin_reserve_kbytes":
			.AdminReserveKbytes = .PInt64()
		case "block_dump":
			.BlockDump = .PInt64()
		case "compact_unevictable_allowed":
			.CompactUnevictableAllowed = .PInt64()
		case "dirty_background_bytes":
			.DirtyBackgroundBytes = .PInt64()
		case "dirty_background_ratio":
			.DirtyBackgroundRatio = .PInt64()
		case "dirty_bytes":
			.DirtyBytes = .PInt64()
		case "dirty_expire_centisecs":
			.DirtyExpireCentisecs = .PInt64()
		case "dirty_ratio":
			.DirtyRatio = .PInt64()
		case "dirtytime_expire_seconds":
			.DirtytimeExpireSeconds = .PInt64()
		case "dirty_writeback_centisecs":
			.DirtyWritebackCentisecs = .PInt64()
		case "drop_caches":
			.DropCaches = .PInt64()
		case "extfrag_threshold":
			.ExtfragThreshold = .PInt64()
		case "hugetlb_shm_group":
			.HugetlbShmGroup = .PInt64()
		case "laptop_mode":
			.LaptopMode = .PInt64()
		case "legacy_va_layout":
			.LegacyVaLayout = .PInt64()
		case "lowmem_reserve_ratio":
			 := strings.Fields()
			 := make([]*int64, 0, len())
			for ,  := range  {
				 := util.NewValueParser()
				 = append(, .PInt64())
			}
			.LowmemReserveRatio = 
		case "max_map_count":
			.MaxMapCount = .PInt64()
		case "memory_failure_early_kill":
			.MemoryFailureEarlyKill = .PInt64()
		case "memory_failure_recovery":
			.MemoryFailureRecovery = .PInt64()
		case "min_free_kbytes":
			.MinFreeKbytes = .PInt64()
		case "min_slab_ratio":
			.MinSlabRatio = .PInt64()
		case "min_unmapped_ratio":
			.MinUnmappedRatio = .PInt64()
		case "mmap_min_addr":
			.MmapMinAddr = .PInt64()
		case "nr_hugepages":
			.NrHugepages = .PInt64()
		case "nr_hugepages_mempolicy":
			.NrHugepagesMempolicy = .PInt64()
		case "nr_overcommit_hugepages":
			.NrOvercommitHugepages = .PInt64()
		case "numa_stat":
			.NumaStat = .PInt64()
		case "numa_zonelist_order":
			.NumaZonelistOrder = 
		case "oom_dump_tasks":
			.OomDumpTasks = .PInt64()
		case "oom_kill_allocating_task":
			.OomKillAllocatingTask = .PInt64()
		case "overcommit_kbytes":
			.OvercommitKbytes = .PInt64()
		case "overcommit_memory":
			.OvercommitMemory = .PInt64()
		case "overcommit_ratio":
			.OvercommitRatio = .PInt64()
		case "page-cluster":
			.PageCluster = .PInt64()
		case "panic_on_oom":
			.PanicOnOom = .PInt64()
		case "percpu_pagelist_fraction":
			.PercpuPagelistFraction = .PInt64()
		case "stat_interval":
			.StatInterval = .PInt64()
		case "swappiness":
			.Swappiness = .PInt64()
		case "user_reserve_kbytes":
			.UserReserveKbytes = .PInt64()
		case "vfs_cache_pressure":
			.VfsCachePressure = .PInt64()
		case "watermark_boost_factor":
			.WatermarkBoostFactor = .PInt64()
		case "watermark_scale_factor":
			.WatermarkScaleFactor = .PInt64()
		case "zone_reclaim_mode":
			.ZoneReclaimMode = .PInt64()
		}
		if  := .Err();  != nil {
			return nil, 
		}
	}

	return &, nil
}