go: runtime: excessive memory use between 1.21.0 -> 1.21.1 due to hugepages and the linux/amd64 `max_ptes_none` default of 512

What version of Go are you using (go version)?

$ go version
go version go1.21.4 linux/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GO111MODULE=''
GOARCH='amd64'
GOBIN=''
GOCACHE='/home/builder/.cache/go-build'
GOENV='/home/builder/.config/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='amd64'
GOHOSTOS='linux'
GOINSECURE=''
GOMODCACHE='/home/builder/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='linux'
GOPATH='/home/builder/go'
GOPRIVATE=''
GOPROXY='https://proxy.golang.org,direct'
GOROOT='/usr/local/go'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/usr/local/go/pkg/tool/linux_amd64'
GOVCS=''
GOVERSION='go1.21.4'
GCCGO='gccgo'
GOAMD64='v1'
AR='ar'
CC='gcc'
CXX='g++'
CGO_ENABLED='0'
GOMOD='/dev/null'
GOWORK=''
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
PKG_CONFIG='pkg-config'
GOGCCFLAGS='-fPIC -m64 -Wl,--no-gc-sections -fmessage-length=0 -ffile-prefix-map=/tmp/go-build3335037910=/tmp/go-build -gno-record-gcc-switches'

What did you do?

Our production service was recently shut down by the OOM, which led us to inspect its memory usage in details.

We discovered that, when running, our process had a memory consumption (RSS) that grew over time and never shrank.

sample runtime.MemStats report :

	"Alloc": 830731560,
	"TotalAlloc": 341870177656,
	"Sys": 8023999048,
	"Lookups": 0,
	"Mallocs": 3129044622,
	"Frees": 3124956536,
	"HeapAlloc": 830731560,
	"HeapSys": 7836532736,
	"HeapIdle": 6916292608,
	"HeapInuse": 920240128,
	"HeapReleased": 6703923200,
	"HeapObjects": 4088086,
	"StackInuse": 15204352,
	"StackSys": 15204352,
	"MSpanInuse": 8563968,
	"MSpanSys": 17338944,
	"MCacheInuse": 4800,
	"MCacheSys": 15600,
	"BuckHashSys": 5794138,
	"GCSys": 146092920,
	"OtherSys": 3020358,
	"NextGC": 1046754240,
	"LastGC": 1700579048506142728,
	"PauseTotalNs": 108783964,

at that time, the reported RSS for our process was 3,19Gb.

We looked at our history in more details, and observed that we had a big change in production behavior when we upgraded our go version from 1.19.5 to 1.20.0 - we unfortunately didn’t notice the issue at that time, because we upgrade (and restart) our service on a regular basis.

To confirm this theory, we have downgraded our go version back to 1.19.13, and our memory consumption is now small and stable again.

Here is a graph of the RSS of our service over the last 48h, the drop corresponds to our new deployment with go 1.19.13 :

image

It should be noted that our production kernel is a hardened kernel based on grsecurity 5.15.28, which may be related to this issue (randomized heap addresses ?)

What did you expect to see?

A constant and stable memory usage.

What did you see instead?

The go runtime seems to not release memory back to the system.


Unfortunately, we have only been able to observe this issue on our production system, in production conditions.

We were not yet able to reproduce the issue on other systems, or by running isolated features in test programs deployed on our production infrastructure.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 3
  • Comments: 70 (41 by maintainers)

Commits related to this issue

Most upvoted comments

We can confirm that the disablethp flag and the actions linked with it (see commit e48984499a) are enough to fix the issue in our case.

[edit] for completeness: we tested this patch on top of version 1.21.5, which is the the version referenced by this branch in our fork: test-fix-64332

@sakib-malik-7417 Thanks for reporting.

I understand go runtime do not want to handle this “OS stuff” and leave it to the devs to handle (as suggested by the linux doc according to you), but it becomes difficult for application devs when suddenly after one release they see a diff runtime behaviour (OOM, etc) and they have to take an OS decision which they were not taking otherwise

I was fully prepared for the Go runtime to handle this “OS stuff,” but it’s just not really reasonable to handle on our end with the current Linux APIs, and I had to learn the hard way. We may return to this in the future; I don’t know.

A debug.DisableTHP() would be great 😃

To be clear, I think that all we’re going to do is GODEBUG=<something>, not a new API. If you want to set this at run-time, there’s already a way:

import "golang.org/x/sys/unix"

...
unix.Prctl(unix.PR_SET_THP_DISABLE, 1, 0, 0, 0)
...

EDIT: I’ll make sure to mention this in the THP docs at https://go.dev/doc/gc-guide#Linux_transparent_huge_pages.

@LeGEC @vanackere Just also wanted to say thanks for the thorough investigation and for bearing with me on this.

@ihtkas If you’re disabling huge pages and still seeing a memory increase, then that is something else, then that is independent of this issue. Please file a new issue. I have updated the issue title to be more precise.

On a side, Is this fixed in Go 1.22 by any chance?

I’m not sure what you mean. As of Go 1.21, the runtime is no longer going to try and work around the max_ptes_none default in the Linux kernel. That is not going to change. There already are quite a few workarounds to this particular issue, and it looks like you’ve applied them.

what is the expected gain from backing these pages with hugepages (or not) ?

It’s less about backing with huge pages and more about disabling huge pages for small heaps. These mappings tend to be quite large in comparison to small heaps which might lead to the kernel backing them with a huge page, leading to large proportional overheads.

The main reason to keep the mitigation in this case is that the runtime doesn’t ever return any of this memory to the OS, so even if the Linux configuration doesn’t have a high max_ptes_none we might still end up with an unnecessary huge page on this metadata with nothing else we can do about it. With the general heap we regularly return memory to the OS, so if max_ptes_none is zero as per the GC guide’s recommendation, the broken huge pages will stay broken.

If it were up to me we wouldn’t call MADV_HUGEPAGE at all, but these mappings grow very slowly compared to the heap and we have no other way to undo MADV_NOHUGEPAGE. Although the initial mapping size is big compared to the heap size, because these mappings grow slowly, there won’t actually be very many calls to and/or initial accesses to newly MADV_HUGEPAGE’d memory, mitigating most of the stall issues that make MADV_HUGEPAGE problematic. Also, the math works out that the worst-case additional overhead for asking the OS to provide a huge page is proportionally very small, mitigating that issue as well.

Overall, I think the cost/benefit just works out in favor of keeping this particular mitigation. It helps small programs stay small without really hurting anyone else in practice.

we can confidently say that, on our production setup, the above patch is enough to fix our issue

One good-ish news with the experiments we ran today, we narrowed the scope for our issue to go1.21.0..go.1.21.1

It turns out the memory issue does not show up with go1.21.0, but does appear with go1.21.1.

We will test this patch and update your with the result.

If your application makes a lot of large irregularly-sized memory allocations (on the order of MiB) and not many small-sized allocations, then that increases the chance that there are persistent holes in the heap. There exists a background system goroutine that finds these holes and returns them to the OS, but the OS can sometimes make a poor decision and undo that work. The default Linux configuration is such that it can always make this poor decision; that’s the default value of /sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_none I mentioned earlier. However, note that if you find yourself in such a situation, pooling those large allocations is likely a good idea anyway and may mitigate some of the issue.

Our application indeed keeps, for performance reasons, several in-memory caches of database views (where entries are invalidated by triggers/notifications). This means that in practice objects are usually allocated “in batch” and some of those may stay alive for a very long time while others are unallocated / invalidated and replaced by new values regularly, perhaps this pattern could explain the poor behavior we were seeing ?

Anyway we now have at least a stable workaround, so thanks again for helping us on this 😄

Memory usage is so much better and predictable that I even think hugepage allocations by the go runtime should be made opt-in instead of opt-out so that only people interested in trading (much) higher memory usage for better throughput actually enable this.

To be absolutely clear, huge pages are no longer controlled by the Go runtime at all. There’s no distinction of “opt-in” vs. “opt-out” to be made here. Except for two very specific niche cases, the Go runtime, as of Go 1.21.4, does not touch any memory’s huge page state.

Changing the transparent huge pages opt-in vs. opt-out is a request that should go to Linux or the Linux distro you’re using. We filed such a bug to discuss changing a default a long time ago, and there has been no movement over the years. Some Linux distros took it into their own hands and disabled huge pages by default unless the program explicitly requests it. (I believe some popular Debian images disable it.) Go no longer requests it.

At a higher level, I do not feel comfortable making this decision for application owners. I also do not feel particularly good about a Go runtime option about disabling huge pages at all; after all, there are already Linux configuration options for that, and ways to disable it per-process.

However, the Go runtime used to touch huge page state, so I recognize the need for compatibility across Go versions and that is why I’m on-board with the GODEBUG setting. For better or for worse, I took Go out of this entire space. Huge pages are already complicated enough; having the Go runtime have its own settings in addition to the OS just makes things more confusing. As of Go 1.21.4, the choice lies entirely with Linux. The runtime now just tries its best to be friendly to huge pages in its policies (while avoiding detriment to the non-huge-page cases), but that’s the extent of it.

(By the way since the go GC is not a moving one, how are huge pages behaving in case of memory fragmentation ? In other terms: can a set of huge pages stay pinned indefinitely because of a small set of live object ?)

Yes, fragmentation can definitely lead to poor utilization of huge pages. That being said, this is not usually a problem for most Go programs. The GC frees memory in batches, so most Go heaps tend to get very dense by the end of the GC cycle and all page-level fragmentation gets filled.

If your application makes a lot of large irregularly-sized memory allocations (on the order of MiB) and not many small-sized allocations, then that increases the chance that there are persistent holes in the heap. There exists a background system goroutine that finds these holes and returns them to the OS, but the OS can sometimes make a poor decision and undo that work. The default Linux configuration is such that it can always make this poor decision; that’s the default value of /sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_none I mentioned earlier. However, note that if you find yourself in such a situation, pooling those large allocations is likely a good idea anyway and may mitigate some of the issue.

Another suggestion / idea : perhaps we could make minHeapForMetadataHugePages settable by an environment variable (instead of the GODEBUG env var to disable hugepages), and perhaps also with an initial value meaning that the feature is disabled ?

To be clear, that variable only gets used in some very niche circumstances. It does not apply to heap memory. I don’t expect changing that to meaningfully affect anybody’s memory usage in practice.

a quick update:

using 1.21.4, and turning off huge pages on a per process basis using the instruction:

unix.Prctl(unix.PR_SET_THP_DISABLE, 1, 0, 0, 0)

suggested by @mknyszek works for us, our processes RSS remains stable.


We would rather be sure the hugepages instructions are never activated (right now, we rely on the fact that no package’s init() function allocates too much memory and force the heap over the 1Gb threshold before our main() function has a chance to kick in), but we can keep up with the latest go version and have a stable production.

Thank you very much for your insights and the time you took to look over our issue @mknyszek

@LeGEC @vanackere Just also wanted to say thanks for the thorough investigation and for bearing with me on this.

@mknyszek: thank you for the patient support 😄

Oof.

So, that partial revert is going to, in the fullness of time, mark quite a lot of memory as MADV_NOHUGEPAGE and never unmark. This is akin to partially disabling huge pages. Removing the call to sysNoHugePage is very intentional. I don’t think the Go runtime should be in the business of trying to mark memory as MADV_HUGEPAGE or MADV_NOHUGEPAGE. Part of the problem is the Linux API. There’s no way to unmark MADV_NOHUGEPAGE, only to mark as MADV_HUGEPAGE. That is, there are 3 states memory could be in. “None”, “NOHUGEPAGE”, and “HUGEPAGE”. System calls exist to go from “None” to “NOHUGEPAGE” and “HUGEPAGE”, and between “NOHUGEPAGE” and “HUGEPAGE”. But not back to “None”. And unfortunately MADV_HUGEPAGE is problematic. See #61718.

Versions of Go prior to Go 1.21.0 would somewhat unpredictably mark memory as NOHUGEPAGE and then back to HUGEPAGE, which is why there’s a difference specifically with this CL, even though this code didn’t exist earlier. I would also rather not return to this state.

My recommendation is to try and adjust your system’s configuration according to https://go.dev/doc/gc-guide#Linux_transparent_huge_pages, or to just disable huge pages altogether. Specifically, I would suggest trying to set /sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_none to 0. The fact that MADV_NOHUGEPAGE matters so much for your application suggests to me that khugepaged is being really overzealous with backing memory with huge pages. Versions of Go before Go 1.21.1 tried to work around this, but I do not think this is worth doing (again, because of the issues with MADV_HUGEPAGE and the inability to properly undo MADV_NOHUGEPAGE).

I understand this does not sound ideal, but I’m reluctant to do anything else. I went down a long and painful road to try and figure this out and make it all work, but it just doesn’t. The whole design of huge pages on Linux is focused around application owners controlling their environment, not around language runtimes making decisions for them. There are some claims that MADV_COLLAPSE for instance is meant for memory allocators, which is why I tried that in the culprit you found, but I’ve found in practice it does not work well for that use-case in its current iteration. See #63334.

we are still missing a targeted reproducer, though

Given what I think I’m seeing here (an overzealous khugepaged), it’s going to be really hard to generate a reproducer. I’ve tried in the past to do so and failed many times, even though the behavior was reproducible in real applications. There’s clearly something I was missing, and I would commend you for trying again, but I wouldn’t sink too much time into it.

we are currently testing a program compiled with the partial revert : https://github.com/trustelem/go/commit/840fc3c97ac3b7d086d941f1a59e95dedc92949d

we will keep you posted with our observations

@mknyszek : yes you are right, the lines I mentioned do not explain the difference in behavior.

looking at the differences introduced in 06df329a8 which are still present in go1.21.4 or master, there are modifications in mgcscavenge.go L774-L784 :

@@ -771,7 +771,7 @@ func (p *pageAlloc) scavengeOne(ci chunkIdx, searchIdx uint, max uintptr) uintpt
-			shouldNoHugePage := p.scav.index.setNoHugePage(ci)
+			p.scav.index.setNoHugePage(ci)

			// With that done, it's safe to unlock.
			unlock(p.mheapLock)
			if !p.test {
				pageTraceScav(getg().m.p.ptr(), 0, addr, uintptr(npages))

				// Only perform sys* operations if we're not in a test.
				// It's dangerous to do so otherwise.
-				if shouldNoHugePage {
-					sysNoHugePage(unsafe.Pointer(chunkBase(ci)), pallocChunkBytes)
-				}

on master, the call to p.scav.index.setNoHugePage(ci) got removed altogether.

If I understand correctly: in go1.21.0 and before, there was an opportunity for a memory range that was flagged as “hugePage” when allocated to be unmarked(*) when freed, and this opportunity is not present anymore in go1.21.1 and later. Did I get that part right ?

This may be combined with an issue in the way our customized version of the kernel reclaims (or not) memory from a process.


(*) and when allocated, I guess (*mheap).sysAlloc() (in file malloc.go) gets called, and may call sysHugePage() when an internal threshold of 1Gb is reached

What I’m confused by in all of this is that nearly all calls to sysHugePage and sysNoHugePage have been removed in Go 1.21.4 (and on tip-of-tree). All calls to madvise(v, n, _MADV_COLLAPSE), which was added in 06df3292a8, were also removed in Go 1.21.4. Is this all still reproducible in Go 1.21.4?

couldn’t this set of lines : … trigger weird things when address randomization is enabled ?

Possibly, but those lines are also there in Go 1.21.0. So that doesn’t explain the difference. That’s also another one of those cases where the worst case can’t possibly account for GiB of memory use. That map is worst-case 2^48 B / 64 MiB * 8 bytes = 32 MiB on linux/amd64.

I suppose it’s possible these lines are involved as well but this is another case where I fail to see how that could account for all the memory use. (Also this memory is also all attributed to GCSys. In the worst case huge pages are doubling this memory overhead, but in practice I doubt that’s true. And even then I still don’t think it’s enough to account for everything?)

is there a way to entirely disable the hugepage specificities in the runtime on linux ?

Yeah, if you want to rule out (or confirm) anything hugepage related, you can do a few things. On the machine you can run echo never >/sys/kernel/mm/transparent_hugepage/enabled.

Another option is disabling hugepages at the process level with something like prctl(PR_SET_THP_DISABLE, ...). (You can use the golang.org/x/sys/unix package for this. There’s a Prctl function and PR_SET_THP_DISABLE is also available as a constant.)

One good-ish news with the experiments we ran today, we narrowed the scope for our issue to go1.21.0…go.1.21.1

Huh. That does seem to run counter to my theory in https://github.com/golang/go/issues/64332#issuecomment-1830174854.

Also, in a 48-bit address space on linux/amd64 the worst case size of that metadata is only 128 MiB. That can’t ever really explain several GiB of memory use, unless you’re using some of the fancy 52-bit addressable hardware and have it enabled in your kernel. EDIT: Go will actually never use that extra address space and might break horribly if it tries. I’m pretty sure in the mmap call you have to specifically request an address in the extended range. So the 52-bit extension can’t possibly be it either.

I see you’re editing your previous comment, so I’ll hold additional commentary until you’re done. 😃

@LeGEC Yes; part of the huge page work was making the runtime a little less eager to return memory to the OS, but it hasn’t meaningfully affected actual memory use so far. This is by design; the same memory that would get released is only released one GC cycle later than it otherwise would. (Even more details: the heap is divided into hugepage-ish-sized chunks and the runtime avoids releasing small amounts of memory in these chunks if they’re going to get dense in the next GC cycle anyway. Otherwise it’s a total waste of a syscall.)

I think it’s unlikely that this is the source of your issues, but perhaps one detail is relevant. The metadata the runtime uses for managing these hugepage-ish-sized chunks has increased 64x. This is up from 1 bit per 4 MiB of heap to 8 bytes per 4 MiB of heap, or 1 MiB for a 2 TiB heap. But this calculation is assuming the heap is contiguous. The metadata is sized proportionally to [max heap address - min heap address]. With ASLR turned on, that range can clearly get much wider.

This sounds pretty damning, but I didn’t mention it before because that’s just mapped memory. In theory, even if your heap is 2 TiB in size, the OS will only actually back the parts of this data structure that are accessed.

… Unfortunately I am only now realizing that the runtime does iterate over this whole data structure in the background (yielding its time if it takes a while, so it won’t noticeably impact throughput or latency). 🤦 That will effectively force the OS to back the entire memory region.

Would it be difficult to graph runtime.MemStats.GCSys before and after? If that’s the source of the difference, I think that fully explains the problem. I did have a hunch this could be a problem earlier, but your MemStats dumps didn’t implicate GCSys at all, not on the order of GiB anyway. But maybe that was just taken at an inopportune time?

@Nasfame I appreciate that you’re trying to help create a reproducer, but I don’t think replicating the high-level details of the application is going to result in a reproducible case. There are plenty of high-load services (microservices, monoliths, etc.) on common platforms that are running with Go 1.21, and to our knowledge they haven’t experienced the same issue.

Therefore, the issue has to lie in something very specific to @LeGEC’s application, either in how their application uses Go or in how Go is interacting with their environment (even if the issue is ultimately in the Go runtime). The relevant details appear to be that (1) it reproduces in Go 1.21 and not Go 1.20, and (2) the system is running with a bunch of security features enabled that to my knowledge aren’t super common (like ASLR).

As a side-note, the number of lines of code in an application’s source isn’t really going to be indicative of much in general.

https://go.dev/cl/545275 mentions the fix for the darwin kernel. But the bug occurs in linux.

It was a mistake. I marked the comment off-topic.

Unfortunately neither of us can bisect because we can’t run the reproducer.

@mknyszek : yes, we’re trying to run the parts of our services in isolation, unfortunately none of the would be culprits seem to be guilty alone (or, more probably, we haven’t identified the right culprit).

Today we rebuilt our server with gotip (golang master version 0c7e5d3) and deployed, and the same buggy memory behavior clearly shows up.

update: we tried go 1.20.11 today, and still have a reasonable (for us …) RSS value

behavior change happens between 1.20.11 and 1.21.4. updating the title accordingly

@mknyszek RSS was mesured by simple output of ps aux. The value mentionned in the inital post may have been slightly wrong indeed, but not by much : the RSS of our process right before restarting the service with our version compiled with go 1.19 was 4397688 (with a VSZ of 9107484)

The same production process with go 1.19.13 gives currently the following values, much more coherent with the actual allocations reported by profiling :

image

The huge page related changes can’t be the culprit, because huge pages were only forced by the runtime between Go 1.21.0 and Go 1.21.3 (inclusive). Go 1.21.4 no longer adjusts huge page settings at all. I don’t see any of those versions in the conversation above.