// Set max memory used by minio as a process, this value is usually
// set to 'unlimited' but we need to validate additionally to verify
// if any hard limit is set by the user, in such a scenario would need
// to reset the global max cache size to be 80% of the hardlimit set
// by the user. This is done to honor the system limits and not crash.
func setMaxMemory() error {
	var rLimit syscall.Rlimit
	err := syscall.Getrlimit(syscall.RLIMIT_AS, &rLimit)
	if err != nil {
		return err
	}
	// Set the current limit to Max, it is default 'unlimited'.
	// TO decrease this limit further user has to manually edit
	// `/etc/security/limits.conf`
	rLimit.Cur = rLimit.Max
	err = syscall.Setrlimit(syscall.RLIMIT_AS, &rLimit)
	if err != nil {
		return err
	}
	err = syscall.Getrlimit(syscall.RLIMIT_AS, &rLimit)
	if err != nil {
		return err
	}
	// Validate if rlimit memory is set to lower
	// than max cache size. Then we should use such value.
	if uint64(rLimit.Cur) < globalMaxCacheSize {
		globalMaxCacheSize = (80 / 100) * uint64(rLimit.Cur)
	}

	// Make sure globalMaxCacheSize is less than RAM size.
	stats, err := sys.GetStats()
	if err != nil && err != sys.ErrNotImplemented {
		// sys.GetStats() is implemented only on linux. Ignore errors
		// from other OSes.
		return err
	}
	if err == nil && stats.TotalRAM < globalMaxCacheSize {
		globalMaxCacheSize = (80 / 100) * stats.TotalRAM
	}
	return nil
}
// Set max memory used by minio as a process, this value is usually
// set to 'unlimited' but we need to validate additionally to verify
// if any hard limit is set by the user, in such a scenario would need
// to reset the global max cache size to be 80% of the hardlimit set
// by the user. This is done to honor the system limits and not crash.
func setMaxMemory() error {
	var rLimit syscall.Rlimit
	err := syscall.Getrlimit(syscall.RLIMIT_AS, &rLimit)
	if err != nil {
		return err
	}
	// Set the current limit to Max, it is default 'unlimited'.
	// TO decrease this limit further user has to manually edit
	// `/etc/security/limits.conf`
	rLimit.Cur = rLimit.Max
	err = syscall.Setrlimit(syscall.RLIMIT_AS, &rLimit)
	if err != nil {
		return err
	}
	err = syscall.Getrlimit(syscall.RLIMIT_AS, &rLimit)
	if err != nil {
		return err
	}
	// Validate if rlimit memory is set to lower
	// than max cache size. Then we should use such value.
	if uint64(rLimit.Cur) < globalMaxCacheSize {
		globalMaxCacheSize = uint64(float64(50*rLimit.Cur) / 100)
	}

	// Make sure globalMaxCacheSize is less than RAM size.
	stats, err := sys.GetStats()
	if err != nil && err != sys.ErrNotImplemented {
		return err
	}
	// If TotalRAM is >= minRAMSize we proceed to enable cache.
	// cache is always 50% of the totalRAM.
	if err == nil && stats.TotalRAM >= minRAMSize {
		globalMaxCacheSize = uint64(float64(50*stats.TotalRAM) / 100)
	}
	return nil
}