Source file src/runtime/mem_sbrk.go

     1  // Copyright 2023 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build plan9 || wasm || wasm32
     6  
     7  package runtime
     8  
     9  import "unsafe"
    10  
    11  const isSbrkPlatform = true
    12  
    13  const memDebug = false
    14  
    15  // Memory management on sbrk systems (including the linear memory
    16  // on Wasm).
    17  
    18  // bloc is the runtime's sense of the break, which can go up or
    19  // down. blocMax is the system's break, also the high water mark
    20  // of bloc. The runtime uses memory up to bloc. The memory
    21  // between bloc and blocMax is allocated by the OS but not used
    22  // by the runtime.
    23  //
    24  // When the runtime needs to grow the heap address range, it
    25  // increases bloc. When it needs to grow beyond blocMax, it calls
    26  // the system sbrk to allocate more memory (and therefore
    27  // increase blocMax).
    28  //
    29  // When the runtime frees memory at the end of the address space,
    30  // it decreases bloc, but does not reduces the system break (as
    31  // the OS doesn't support it). When the runtime frees memory in
    32  // the middle of the address space, the memory goes to a free
    33  // list.
    34  
    35  var bloc uintptr    // The runtime's sense of break. Can go up or down.
    36  var blocMax uintptr // The break of the OS. Only increase.
    37  var memlock mutex
    38  
    39  type memHdr struct {
    40  	next memHdrPtr
    41  	size uintptr
    42  }
    43  
    44  var memFreelist memHdrPtr // sorted in ascending order
    45  
    46  type memHdrPtr uintptr
    47  
    48  func (p memHdrPtr) ptr() *memHdr   { return (*memHdr)(unsafe.Pointer(p)) }
    49  func (p *memHdrPtr) set(x *memHdr) { *p = memHdrPtr(unsafe.Pointer(x)) }
    50  
    51  // memAlloc allocates n bytes from the brk reservation, or if it's full,
    52  // the system.
    53  //
    54  // memlock must be held.
    55  //
    56  // memAlloc must be called on the system stack, otherwise a stack growth
    57  // could cause us to call back into it. Since memlock is held, that could
    58  // lead to a self-deadlock.
    59  //
    60  //go:systemstack
    61  func memAlloc(n uintptr) unsafe.Pointer {
    62  	if p := memAllocNoGrow(n); p != nil {
    63  		return p
    64  	}
    65  	return sbrk(n)
    66  }
    67  
    68  // memAllocNoGrow attempts to allocate n bytes from the existing brk.
    69  //
    70  // memlock must be held.
    71  //
    72  // memAlloc must be called on the system stack, otherwise a stack growth
    73  // could cause us to call back into it. Since memlock is held, that could
    74  // lead to a self-deadlock.
    75  //
    76  //go:systemstack
    77  func memAllocNoGrow(n uintptr) unsafe.Pointer {
    78  	if n > ^uintptr(0)-(physPageSize-1) {
    79  		return nil
    80  	}
    81  	n = memRound(n)
    82  	var prevp *memHdr
    83  	for p := memFreelist.ptr(); p != nil; p = p.next.ptr() {
    84  		if p.size >= n {
    85  			if p.size == n {
    86  				if prevp != nil {
    87  					prevp.next = p.next
    88  				} else {
    89  					memFreelist = p.next
    90  				}
    91  			} else {
    92  				p.size -= n
    93  				p = (*memHdr)(add(unsafe.Pointer(p), p.size))
    94  			}
    95  			*p = memHdr{}
    96  			return unsafe.Pointer(p)
    97  		}
    98  		prevp = p
    99  	}
   100  	return nil
   101  }
   102  
   103  // memFree makes [ap, ap+n) available for reallocation by memAlloc.
   104  //
   105  // memlock must be held.
   106  //
   107  // memAlloc must be called on the system stack, otherwise a stack growth
   108  // could cause us to call back into it. Since memlock is held, that could
   109  // lead to a self-deadlock.
   110  //
   111  //go:systemstack
   112  func memFree(ap unsafe.Pointer, n uintptr) {
   113  	n = memRound(n)
   114  	memclrNoHeapPointers(ap, n)
   115  	bp := (*memHdr)(ap)
   116  	bp.size = n
   117  	bpn := uintptr(ap)
   118  	if memFreelist == 0 {
   119  		bp.next = 0
   120  		memFreelist.set(bp)
   121  		return
   122  	}
   123  	p := memFreelist.ptr()
   124  	if bpn < uintptr(unsafe.Pointer(p)) {
   125  		memFreelist.set(bp)
   126  		if bpn+bp.size == uintptr(unsafe.Pointer(p)) {
   127  			bp.size += p.size
   128  			bp.next = p.next
   129  			*p = memHdr{}
   130  		} else {
   131  			bp.next.set(p)
   132  		}
   133  		return
   134  	}
   135  	for ; p.next != 0; p = p.next.ptr() {
   136  		if bpn > uintptr(unsafe.Pointer(p)) && bpn < uintptr(unsafe.Pointer(p.next)) {
   137  			break
   138  		}
   139  	}
   140  	if bpn+bp.size == uintptr(unsafe.Pointer(p.next)) {
   141  		bp.size += p.next.ptr().size
   142  		bp.next = p.next.ptr().next
   143  		*p.next.ptr() = memHdr{}
   144  	} else {
   145  		bp.next = p.next
   146  	}
   147  	if uintptr(unsafe.Pointer(p))+p.size == bpn {
   148  		p.size += bp.size
   149  		p.next = bp.next
   150  		*bp = memHdr{}
   151  	} else {
   152  		p.next.set(bp)
   153  	}
   154  }
   155  
   156  // memCheck checks invariants around free list management.
   157  //
   158  // memlock must be held.
   159  //
   160  // memAlloc must be called on the system stack, otherwise a stack growth
   161  // could cause us to call back into it. Since memlock is held, that could
   162  // lead to a self-deadlock.
   163  //
   164  //go:systemstack
   165  func memCheck() {
   166  	if !memDebug {
   167  		return
   168  	}
   169  	for p := memFreelist.ptr(); p != nil && p.next != 0; p = p.next.ptr() {
   170  		if uintptr(unsafe.Pointer(p)) == uintptr(unsafe.Pointer(p.next)) {
   171  			print("runtime: ", unsafe.Pointer(p), " == ", unsafe.Pointer(p.next), "\n")
   172  			throw("mem: infinite loop")
   173  		}
   174  		if uintptr(unsafe.Pointer(p)) > uintptr(unsafe.Pointer(p.next)) {
   175  			print("runtime: ", unsafe.Pointer(p), " > ", unsafe.Pointer(p.next), "\n")
   176  			throw("mem: unordered list")
   177  		}
   178  		if uintptr(unsafe.Pointer(p))+p.size > uintptr(unsafe.Pointer(p.next)) {
   179  			print("runtime: ", unsafe.Pointer(p), "+", p.size, " > ", unsafe.Pointer(p.next), "\n")
   180  			throw("mem: overlapping blocks")
   181  		}
   182  		for b := add(unsafe.Pointer(p), unsafe.Sizeof(memHdr{})); uintptr(b) < uintptr(unsafe.Pointer(p))+p.size; b = add(b, 1) {
   183  			if *(*byte)(b) != 0 {
   184  				print("runtime: value at addr ", b, " with offset ", uintptr(b)-uintptr(unsafe.Pointer(p)), " in block ", p, " of size ", p.size, " is not zero\n")
   185  				throw("mem: uninitialised memory")
   186  			}
   187  		}
   188  	}
   189  }
   190  
   191  func memRound(p uintptr) uintptr {
   192  	return alignUp(p, physPageSize)
   193  }
   194  
   195  func initBloc() {
   196  	bloc = memRound(firstmoduledata.end)
   197  	blocMax = bloc
   198  }
   199  
   200  func sysAllocOS(n uintptr, _ string) unsafe.Pointer {
   201  	var p uintptr
   202  	systemstack(func() {
   203  		lock(&memlock)
   204  		p = uintptr(memAlloc(n))
   205  		memCheck()
   206  		unlock(&memlock)
   207  	})
   208  	return unsafe.Pointer(p)
   209  }
   210  
   211  func sysFreeOS(v unsafe.Pointer, n uintptr) {
   212  	if v == nil {
   213  		// A failed sysReserveOS returns nil, so freeing it is a no-op.
   214  		return
   215  	}
   216  	systemstack(func() {
   217  		lock(&memlock)
   218  		if uintptr(v)+n == bloc {
   219  			// Address range being freed is at the end of memory,
   220  			// so record a new lower value for end of memory.
   221  			// Can't actually shrink address space because segment is shared.
   222  			memclrNoHeapPointers(v, n)
   223  			bloc -= n
   224  		} else {
   225  			memFree(v, n)
   226  			memCheck()
   227  		}
   228  		unlock(&memlock)
   229  	})
   230  }
   231  
   232  func sysUnusedOS(v unsafe.Pointer, n uintptr) {
   233  }
   234  
   235  func sysUsedOS(v unsafe.Pointer, n uintptr) {
   236  }
   237  
   238  func sysHugePageOS(v unsafe.Pointer, n uintptr) {
   239  }
   240  
   241  func sysNoHugePageOS(v unsafe.Pointer, n uintptr) {
   242  }
   243  
   244  func sysHugePageCollapseOS(v unsafe.Pointer, n uintptr) {
   245  }
   246  
   247  func sysMapOS(v unsafe.Pointer, n uintptr, _ string) {
   248  }
   249  
   250  func sysFaultOS(v unsafe.Pointer, n uintptr) {
   251  }
   252  
   253  func sysReserveOS(v unsafe.Pointer, n uintptr, _ string) unsafe.Pointer {
   254  	var p uintptr
   255  	systemstack(func() {
   256  		lock(&memlock)
   257  		if uintptr(v) == bloc {
   258  			// Address hint is the current end of memory,
   259  			// so try to extend the address space.
   260  			p = uintptr(sbrk(n))
   261  		}
   262  		if p == 0 && v == nil {
   263  			p = uintptr(memAlloc(n))
   264  			memCheck()
   265  		}
   266  		unlock(&memlock)
   267  	})
   268  	return unsafe.Pointer(p)
   269  }
   270  
   271  func sysReserveAlignedSbrk(size, align uintptr) (unsafe.Pointer, uintptr) {
   272  	if size > ^uintptr(0)-align || size+align > ^uintptr(0)-(physPageSize-1) {
   273  		return nil, 0
   274  	}
   275  	var p uintptr
   276  	systemstack(func() {
   277  		lock(&memlock)
   278  		if base := memAllocNoGrow(size + align); base != nil {
   279  			// We can satisfy the reservation from the free list.
   280  			// Trim off the unaligned parts.
   281  			start := alignUp(uintptr(base), align)
   282  			if startLen := start - uintptr(base); startLen > 0 {
   283  				memFree(base, startLen)
   284  			}
   285  			end := start + size
   286  			if endLen := (uintptr(base) + size + align) - end; endLen > 0 {
   287  				memFree(unsafe.Pointer(end), endLen)
   288  			}
   289  			memCheck()
   290  			unlock(&memlock)
   291  			p = start
   292  			return
   293  		}
   294  
   295  		// Round up bloc to align, then allocate size.
   296  		p = alignUp(bloc, align)
   297  		if p < bloc || size > ^uintptr(0)-p {
   298  			p, size = 0, 0
   299  			unlock(&memlock)
   300  			return
   301  		}
   302  		r := sbrk(p + size - bloc)
   303  		if r == nil {
   304  			p, size = 0, 0
   305  		} else if l := p - uintptr(r); l > 0 {
   306  			// Free the area we skipped over for alignment.
   307  			memFree(r, l)
   308  			memCheck()
   309  		}
   310  		unlock(&memlock)
   311  	})
   312  	return unsafe.Pointer(p), size
   313  }
   314  
   315  func needZeroAfterSysUnusedOS() bool {
   316  	return true
   317  }
   318  

View as plain text