Black Lives Matter. Support the Equal Justice Initiative.

Source file src/runtime/mpagealloc.go

Documentation: runtime

     1  // Copyright 2019 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  // Page allocator.
     6  //
     7  // The page allocator manages mapped pages (defined by pageSize, NOT
     8  // physPageSize) for allocation and re-use. It is embedded into mheap.
     9  //
    10  // Pages are managed using a bitmap that is sharded into chunks.
    11  // In the bitmap, 1 means in-use, and 0 means free. The bitmap spans the
    12  // process's address space. Chunks are managed in a sparse-array-style structure
    13  // similar to mheap.arenas, since the bitmap may be large on some systems.
    14  //
    15  // The bitmap is efficiently searched by using a radix tree in combination
    16  // with fast bit-wise intrinsics. Allocation is performed using an address-ordered
    17  // first-fit approach.
    18  //
    19  // Each entry in the radix tree is a summary that describes three properties of
    20  // a particular region of the address space: the number of contiguous free pages
    21  // at the start and end of the region it represents, and the maximum number of
    22  // contiguous free pages found anywhere in that region.
    23  //
    24  // Each level of the radix tree is stored as one contiguous array, which represents
    25  // a different granularity of subdivision of the processes' address space. Thus, this
    26  // radix tree is actually implicit in these large arrays, as opposed to having explicit
    27  // dynamically-allocated pointer-based node structures. Naturally, these arrays may be
    28  // quite large for system with large address spaces, so in these cases they are mapped
    29  // into memory as needed. The leaf summaries of the tree correspond to a bitmap chunk.
    30  //
    31  // The root level (referred to as L0 and index 0 in pageAlloc.summary) has each
    32  // summary represent the largest section of address space (16 GiB on 64-bit systems),
    33  // with each subsequent level representing successively smaller subsections until we
    34  // reach the finest granularity at the leaves, a chunk.
    35  //
    36  // More specifically, each summary in each level (except for leaf summaries)
    37  // represents some number of entries in the following level. For example, each
    38  // summary in the root level may represent a 16 GiB region of address space,
    39  // and in the next level there could be 8 corresponding entries which represent 2
    40  // GiB subsections of that 16 GiB region, each of which could correspond to 8
    41  // entries in the next level which each represent 256 MiB regions, and so on.
    42  //
    43  // Thus, this design only scales to heaps so large, but can always be extended to
    44  // larger heaps by simply adding levels to the radix tree, which mostly costs
    45  // additional virtual address space. The choice of managing large arrays also means
    46  // that a large amount of virtual address space may be reserved by the runtime.
    47  
    48  package runtime
    49  
    50  import (
    51  	"runtime/internal/atomic"
    52  	"unsafe"
    53  )
    54  
    55  const (
    56  	// The size of a bitmap chunk, i.e. the amount of bits (that is, pages) to consider
    57  	// in the bitmap at once.
    58  	pallocChunkPages    = 1 << logPallocChunkPages
    59  	pallocChunkBytes    = pallocChunkPages * pageSize
    60  	logPallocChunkPages = 9
    61  	logPallocChunkBytes = logPallocChunkPages + pageShift
    62  
    63  	// The number of radix bits for each level.
    64  	//
    65  	// The value of 3 is chosen such that the block of summaries we need to scan at
    66  	// each level fits in 64 bytes (2^3 summaries * 8 bytes per summary), which is
    67  	// close to the L1 cache line width on many systems. Also, a value of 3 fits 4 tree
    68  	// levels perfectly into the 21-bit pallocBits summary field at the root level.
    69  	//
    70  	// The following equation explains how each of the constants relate:
    71  	// summaryL0Bits + (summaryLevels-1)*summaryLevelBits + logPallocChunkBytes = heapAddrBits
    72  	//
    73  	// summaryLevels is an architecture-dependent value defined in mpagealloc_*.go.
    74  	summaryLevelBits = 3
    75  	summaryL0Bits    = heapAddrBits - logPallocChunkBytes - (summaryLevels-1)*summaryLevelBits
    76  
    77  	// pallocChunksL2Bits is the number of bits of the chunk index number
    78  	// covered by the second level of the chunks map.
    79  	//
    80  	// See (*pageAlloc).chunks for more details. Update the documentation
    81  	// there should this change.
    82  	pallocChunksL2Bits  = heapAddrBits - logPallocChunkBytes - pallocChunksL1Bits
    83  	pallocChunksL1Shift = pallocChunksL2Bits
    84  )
    85  
    86  // Maximum searchAddr value, which indicates that the heap has no free space.
    87  //
    88  // We alias maxOffAddr just to make it clear that this is the maximum address
    89  // for the page allocator's search space. See maxOffAddr for details.
    90  var maxSearchAddr = maxOffAddr
    91  
    92  // Global chunk index.
    93  //
    94  // Represents an index into the leaf level of the radix tree.
    95  // Similar to arenaIndex, except instead of arenas, it divides the address
    96  // space into chunks.
    97  type chunkIdx uint
    98  
    99  // chunkIndex returns the global index of the palloc chunk containing the
   100  // pointer p.
   101  func chunkIndex(p uintptr) chunkIdx {
   102  	return chunkIdx((p - arenaBaseOffset) / pallocChunkBytes)
   103  }
   104  
   105  // chunkIndex returns the base address of the palloc chunk at index ci.
   106  func chunkBase(ci chunkIdx) uintptr {
   107  	return uintptr(ci)*pallocChunkBytes + arenaBaseOffset
   108  }
   109  
   110  // chunkPageIndex computes the index of the page that contains p,
   111  // relative to the chunk which contains p.
   112  func chunkPageIndex(p uintptr) uint {
   113  	return uint(p % pallocChunkBytes / pageSize)
   114  }
   115  
   116  // l1 returns the index into the first level of (*pageAlloc).chunks.
   117  func (i chunkIdx) l1() uint {
   118  	if pallocChunksL1Bits == 0 {
   119  		// Let the compiler optimize this away if there's no
   120  		// L1 map.
   121  		return 0
   122  	} else {
   123  		return uint(i) >> pallocChunksL1Shift
   124  	}
   125  }
   126  
   127  // l2 returns the index into the second level of (*pageAlloc).chunks.
   128  func (i chunkIdx) l2() uint {
   129  	if pallocChunksL1Bits == 0 {
   130  		return uint(i)
   131  	} else {
   132  		return uint(i) & (1<<pallocChunksL2Bits - 1)
   133  	}
   134  }
   135  
   136  // offAddrToLevelIndex converts an address in the offset address space
   137  // to the index into summary[level] containing addr.
   138  func offAddrToLevelIndex(level int, addr offAddr) int {
   139  	return int((addr.a - arenaBaseOffset) >> levelShift[level])
   140  }
   141  
   142  // levelIndexToOffAddr converts an index into summary[level] into
   143  // the corresponding address in the offset address space.
   144  func levelIndexToOffAddr(level, idx int) offAddr {
   145  	return offAddr{(uintptr(idx) << levelShift[level]) + arenaBaseOffset}
   146  }
   147  
   148  // addrsToSummaryRange converts base and limit pointers into a range
   149  // of entries for the given summary level.
   150  //
   151  // The returned range is inclusive on the lower bound and exclusive on
   152  // the upper bound.
   153  func addrsToSummaryRange(level int, base, limit uintptr) (lo int, hi int) {
   154  	// This is slightly more nuanced than just a shift for the exclusive
   155  	// upper-bound. Note that the exclusive upper bound may be within a
   156  	// summary at this level, meaning if we just do the obvious computation
   157  	// hi will end up being an inclusive upper bound. Unfortunately, just
   158  	// adding 1 to that is too broad since we might be on the very edge of
   159  	// of a summary's max page count boundary for this level
   160  	// (1 << levelLogPages[level]). So, make limit an inclusive upper bound
   161  	// then shift, then add 1, so we get an exclusive upper bound at the end.
   162  	lo = int((base - arenaBaseOffset) >> levelShift[level])
   163  	hi = int(((limit-1)-arenaBaseOffset)>>levelShift[level]) + 1
   164  	return
   165  }
   166  
   167  // blockAlignSummaryRange aligns indices into the given level to that
   168  // level's block width (1 << levelBits[level]). It assumes lo is inclusive
   169  // and hi is exclusive, and so aligns them down and up respectively.
   170  func blockAlignSummaryRange(level int, lo, hi int) (int, int) {
   171  	e := uintptr(1) << levelBits[level]
   172  	return int(alignDown(uintptr(lo), e)), int(alignUp(uintptr(hi), e))
   173  }
   174  
   175  type pageAlloc struct {
   176  	// Radix tree of summaries.
   177  	//
   178  	// Each slice's cap represents the whole memory reservation.
   179  	// Each slice's len reflects the allocator's maximum known
   180  	// mapped heap address for that level.
   181  	//
   182  	// The backing store of each summary level is reserved in init
   183  	// and may or may not be committed in grow (small address spaces
   184  	// may commit all the memory in init).
   185  	//
   186  	// The purpose of keeping len <= cap is to enforce bounds checks
   187  	// on the top end of the slice so that instead of an unknown
   188  	// runtime segmentation fault, we get a much friendlier out-of-bounds
   189  	// error.
   190  	//
   191  	// To iterate over a summary level, use inUse to determine which ranges
   192  	// are currently available. Otherwise one might try to access
   193  	// memory which is only Reserved which may result in a hard fault.
   194  	//
   195  	// We may still get segmentation faults < len since some of that
   196  	// memory may not be committed yet.
   197  	summary [summaryLevels][]pallocSum
   198  
   199  	// chunks is a slice of bitmap chunks.
   200  	//
   201  	// The total size of chunks is quite large on most 64-bit platforms
   202  	// (O(GiB) or more) if flattened, so rather than making one large mapping
   203  	// (which has problems on some platforms, even when PROT_NONE) we use a
   204  	// two-level sparse array approach similar to the arena index in mheap.
   205  	//
   206  	// To find the chunk containing a memory address `a`, do:
   207  	//   chunkOf(chunkIndex(a))
   208  	//
   209  	// Below is a table describing the configuration for chunks for various
   210  	// heapAddrBits supported by the runtime.
   211  	//
   212  	// heapAddrBits | L1 Bits | L2 Bits | L2 Entry Size
   213  	// ------------------------------------------------
   214  	// 32           | 0       | 10      | 128 KiB
   215  	// 33 (iOS)     | 0       | 11      | 256 KiB
   216  	// 48           | 13      | 13      | 1 MiB
   217  	//
   218  	// There's no reason to use the L1 part of chunks on 32-bit, the
   219  	// address space is small so the L2 is small. For platforms with a
   220  	// 48-bit address space, we pick the L1 such that the L2 is 1 MiB
   221  	// in size, which is a good balance between low granularity without
   222  	// making the impact on BSS too high (note the L1 is stored directly
   223  	// in pageAlloc).
   224  	//
   225  	// To iterate over the bitmap, use inUse to determine which ranges
   226  	// are currently available. Otherwise one might iterate over unused
   227  	// ranges.
   228  	//
   229  	// TODO(mknyszek): Consider changing the definition of the bitmap
   230  	// such that 1 means free and 0 means in-use so that summaries and
   231  	// the bitmaps align better on zero-values.
   232  	chunks [1 << pallocChunksL1Bits]*[1 << pallocChunksL2Bits]pallocData
   233  
   234  	// The address to start an allocation search with. It must never
   235  	// point to any memory that is not contained in inUse, i.e.
   236  	// inUse.contains(searchAddr.addr()) must always be true. The one
   237  	// exception to this rule is that it may take on the value of
   238  	// maxOffAddr to indicate that the heap is exhausted.
   239  	//
   240  	// We guarantee that all valid heap addresses below this value
   241  	// are allocated and not worth searching.
   242  	searchAddr offAddr
   243  
   244  	// start and end represent the chunk indices
   245  	// which pageAlloc knows about. It assumes
   246  	// chunks in the range [start, end) are
   247  	// currently ready to use.
   248  	start, end chunkIdx
   249  
   250  	// inUse is a slice of ranges of address space which are
   251  	// known by the page allocator to be currently in-use (passed
   252  	// to grow).
   253  	//
   254  	// This field is currently unused on 32-bit architectures but
   255  	// is harmless to track. We care much more about having a
   256  	// contiguous heap in these cases and take additional measures
   257  	// to ensure that, so in nearly all cases this should have just
   258  	// 1 element.
   259  	//
   260  	// All access is protected by the mheapLock.
   261  	inUse addrRanges
   262  
   263  	// scav stores the scavenger state.
   264  	//
   265  	// All fields are protected by mheapLock.
   266  	scav struct {
   267  		// inUse is a slice of ranges of address space which have not
   268  		// yet been looked at by the scavenger.
   269  		inUse addrRanges
   270  
   271  		// gen is the scavenge generation number.
   272  		gen uint32
   273  
   274  		// reservationBytes is how large of a reservation should be made
   275  		// in bytes of address space for each scavenge iteration.
   276  		reservationBytes uintptr
   277  
   278  		// released is the amount of memory released this generation.
   279  		released uintptr
   280  
   281  		// scavLWM is the lowest (offset) address that the scavenger reached this
   282  		// scavenge generation.
   283  		scavLWM offAddr
   284  
   285  		// freeHWM is the highest (offset) address of a page that was freed to
   286  		// the page allocator this scavenge generation.
   287  		freeHWM offAddr
   288  	}
   289  
   290  	// mheap_.lock. This level of indirection makes it possible
   291  	// to test pageAlloc indepedently of the runtime allocator.
   292  	mheapLock *mutex
   293  
   294  	// sysStat is the runtime memstat to update when new system
   295  	// memory is committed by the pageAlloc for allocation metadata.
   296  	sysStat *uint64
   297  
   298  	// Whether or not this struct is being used in tests.
   299  	test bool
   300  }
   301  
   302  func (s *pageAlloc) init(mheapLock *mutex, sysStat *uint64) {
   303  	if levelLogPages[0] > logMaxPackedValue {
   304  		// We can't represent 1<<levelLogPages[0] pages, the maximum number
   305  		// of pages we need to represent at the root level, in a summary, which
   306  		// is a big problem. Throw.
   307  		print("runtime: root level max pages = ", 1<<levelLogPages[0], "\n")
   308  		print("runtime: summary max pages = ", maxPackedValue, "\n")
   309  		throw("root level max pages doesn't fit in summary")
   310  	}
   311  	s.sysStat = sysStat
   312  
   313  	// Initialize s.inUse.
   314  	s.inUse.init(sysStat)
   315  
   316  	// System-dependent initialization.
   317  	s.sysInit()
   318  
   319  	// Start with the searchAddr in a state indicating there's no free memory.
   320  	s.searchAddr = maxSearchAddr
   321  
   322  	// Set the mheapLock.
   323  	s.mheapLock = mheapLock
   324  
   325  	// Initialize scavenge tracking state.
   326  	s.scav.scavLWM = maxSearchAddr
   327  }
   328  
   329  // tryChunkOf returns the bitmap data for the given chunk.
   330  //
   331  // Returns nil if the chunk data has not been mapped.
   332  func (s *pageAlloc) tryChunkOf(ci chunkIdx) *pallocData {
   333  	l2 := s.chunks[ci.l1()]
   334  	if l2 == nil {
   335  		return nil
   336  	}
   337  	return &l2[ci.l2()]
   338  }
   339  
   340  // chunkOf returns the chunk at the given chunk index.
   341  //
   342  // The chunk index must be valid or this method may throw.
   343  func (s *pageAlloc) chunkOf(ci chunkIdx) *pallocData {
   344  	return &s.chunks[ci.l1()][ci.l2()]
   345  }
   346  
   347  // grow sets up the metadata for the address range [base, base+size).
   348  // It may allocate metadata, in which case *s.sysStat will be updated.
   349  //
   350  // s.mheapLock must be held.
   351  func (s *pageAlloc) grow(base, size uintptr) {
   352  	// Round up to chunks, since we can't deal with increments smaller
   353  	// than chunks. Also, sysGrow expects aligned values.
   354  	limit := alignUp(base+size, pallocChunkBytes)
   355  	base = alignDown(base, pallocChunkBytes)
   356  
   357  	// Grow the summary levels in a system-dependent manner.
   358  	// We just update a bunch of additional metadata here.
   359  	s.sysGrow(base, limit)
   360  
   361  	// Update s.start and s.end.
   362  	// If no growth happened yet, start == 0. This is generally
   363  	// safe since the zero page is unmapped.
   364  	firstGrowth := s.start == 0
   365  	start, end := chunkIndex(base), chunkIndex(limit)
   366  	if firstGrowth || start < s.start {
   367  		s.start = start
   368  	}
   369  	if end > s.end {
   370  		s.end = end
   371  	}
   372  	// Note that [base, limit) will never overlap with any existing
   373  	// range inUse because grow only ever adds never-used memory
   374  	// regions to the page allocator.
   375  	s.inUse.add(makeAddrRange(base, limit))
   376  
   377  	// A grow operation is a lot like a free operation, so if our
   378  	// chunk ends up below s.searchAddr, update s.searchAddr to the
   379  	// new address, just like in free.
   380  	if b := (offAddr{base}); b.lessThan(s.searchAddr) {
   381  		s.searchAddr = b
   382  	}
   383  
   384  	// Add entries into chunks, which is sparse, if needed. Then,
   385  	// initialize the bitmap.
   386  	//
   387  	// Newly-grown memory is always considered scavenged.
   388  	// Set all the bits in the scavenged bitmaps high.
   389  	for c := chunkIndex(base); c < chunkIndex(limit); c++ {
   390  		if s.chunks[c.l1()] == nil {
   391  			// Create the necessary l2 entry.
   392  			//
   393  			// Store it atomically to avoid races with readers which
   394  			// don't acquire the heap lock.
   395  			r := sysAlloc(unsafe.Sizeof(*s.chunks[0]), s.sysStat)
   396  			atomic.StorepNoWB(unsafe.Pointer(&s.chunks[c.l1()]), r)
   397  		}
   398  		s.chunkOf(c).scavenged.setRange(0, pallocChunkPages)
   399  	}
   400  
   401  	// Update summaries accordingly. The grow acts like a free, so
   402  	// we need to ensure this newly-free memory is visible in the
   403  	// summaries.
   404  	s.update(base, size/pageSize, true, false)
   405  }
   406  
   407  // update updates heap metadata. It must be called each time the bitmap
   408  // is updated.
   409  //
   410  // If contig is true, update does some optimizations assuming that there was
   411  // a contiguous allocation or free between addr and addr+npages. alloc indicates
   412  // whether the operation performed was an allocation or a free.
   413  //
   414  // s.mheapLock must be held.
   415  func (s *pageAlloc) update(base, npages uintptr, contig, alloc bool) {
   416  	// base, limit, start, and end are inclusive.
   417  	limit := base + npages*pageSize - 1
   418  	sc, ec := chunkIndex(base), chunkIndex(limit)
   419  
   420  	// Handle updating the lowest level first.
   421  	if sc == ec {
   422  		// Fast path: the allocation doesn't span more than one chunk,
   423  		// so update this one and if the summary didn't change, return.
   424  		x := s.summary[len(s.summary)-1][sc]
   425  		y := s.chunkOf(sc).summarize()
   426  		if x == y {
   427  			return
   428  		}
   429  		s.summary[len(s.summary)-1][sc] = y
   430  	} else if contig {
   431  		// Slow contiguous path: the allocation spans more than one chunk
   432  		// and at least one summary is guaranteed to change.
   433  		summary := s.summary[len(s.summary)-1]
   434  
   435  		// Update the summary for chunk sc.
   436  		summary[sc] = s.chunkOf(sc).summarize()
   437  
   438  		// Update the summaries for chunks in between, which are
   439  		// either totally allocated or freed.
   440  		whole := s.summary[len(s.summary)-1][sc+1 : ec]
   441  		if alloc {
   442  			// Should optimize into a memclr.
   443  			for i := range whole {
   444  				whole[i] = 0
   445  			}
   446  		} else {
   447  			for i := range whole {
   448  				whole[i] = freeChunkSum
   449  			}
   450  		}
   451  
   452  		// Update the summary for chunk ec.
   453  		summary[ec] = s.chunkOf(ec).summarize()
   454  	} else {
   455  		// Slow general path: the allocation spans more than one chunk
   456  		// and at least one summary is guaranteed to change.
   457  		//
   458  		// We can't assume a contiguous allocation happened, so walk over
   459  		// every chunk in the range and manually recompute the summary.
   460  		summary := s.summary[len(s.summary)-1]
   461  		for c := sc; c <= ec; c++ {
   462  			summary[c] = s.chunkOf(c).summarize()
   463  		}
   464  	}
   465  
   466  	// Walk up the radix tree and update the summaries appropriately.
   467  	changed := true
   468  	for l := len(s.summary) - 2; l >= 0 && changed; l-- {
   469  		// Update summaries at level l from summaries at level l+1.
   470  		changed = false
   471  
   472  		// "Constants" for the previous level which we
   473  		// need to compute the summary from that level.
   474  		logEntriesPerBlock := levelBits[l+1]
   475  		logMaxPages := levelLogPages[l+1]
   476  
   477  		// lo and hi describe all the parts of the level we need to look at.
   478  		lo, hi := addrsToSummaryRange(l, base, limit+1)
   479  
   480  		// Iterate over each block, updating the corresponding summary in the less-granular level.
   481  		for i := lo; i < hi; i++ {
   482  			children := s.summary[l+1][i<<logEntriesPerBlock : (i+1)<<logEntriesPerBlock]
   483  			sum := mergeSummaries(children, logMaxPages)
   484  			old := s.summary[l][i]
   485  			if old != sum {
   486  				changed = true
   487  				s.summary[l][i] = sum
   488  			}
   489  		}
   490  	}
   491  }
   492  
   493  // allocRange marks the range of memory [base, base+npages*pageSize) as
   494  // allocated. It also updates the summaries to reflect the newly-updated
   495  // bitmap.
   496  //
   497  // Returns the amount of scavenged memory in bytes present in the
   498  // allocated range.
   499  //
   500  // s.mheapLock must be held.
   501  func (s *pageAlloc) allocRange(base, npages uintptr) uintptr {
   502  	limit := base + npages*pageSize - 1
   503  	sc, ec := chunkIndex(base), chunkIndex(limit)
   504  	si, ei := chunkPageIndex(base), chunkPageIndex(limit)
   505  
   506  	scav := uint(0)
   507  	if sc == ec {
   508  		// The range doesn't cross any chunk boundaries.
   509  		chunk := s.chunkOf(sc)
   510  		scav += chunk.scavenged.popcntRange(si, ei+1-si)
   511  		chunk.allocRange(si, ei+1-si)
   512  	} else {
   513  		// The range crosses at least one chunk boundary.
   514  		chunk := s.chunkOf(sc)
   515  		scav += chunk.scavenged.popcntRange(si, pallocChunkPages-si)
   516  		chunk.allocRange(si, pallocChunkPages-si)
   517  		for c := sc + 1; c < ec; c++ {
   518  			chunk := s.chunkOf(c)
   519  			scav += chunk.scavenged.popcntRange(0, pallocChunkPages)
   520  			chunk.allocAll()
   521  		}
   522  		chunk = s.chunkOf(ec)
   523  		scav += chunk.scavenged.popcntRange(0, ei+1)
   524  		chunk.allocRange(0, ei+1)
   525  	}
   526  	s.update(base, npages, true, true)
   527  	return uintptr(scav) * pageSize
   528  }
   529  
   530  // findMappedAddr returns the smallest mapped offAddr that is
   531  // >= addr. That is, if addr refers to mapped memory, then it is
   532  // returned. If addr is higher than any mapped region, then
   533  // it returns maxOffAddr.
   534  //
   535  // s.mheapLock must be held.
   536  func (s *pageAlloc) findMappedAddr(addr offAddr) offAddr {
   537  	// If we're not in a test, validate first by checking mheap_.arenas.
   538  	// This is a fast path which is only safe to use outside of testing.
   539  	ai := arenaIndex(addr.addr())
   540  	if s.test || mheap_.arenas[ai.l1()] == nil || mheap_.arenas[ai.l1()][ai.l2()] == nil {
   541  		vAddr, ok := s.inUse.findAddrGreaterEqual(addr.addr())
   542  		if ok {
   543  			return offAddr{vAddr}
   544  		} else {
   545  			// The candidate search address is greater than any
   546  			// known address, which means we definitely have no
   547  			// free memory left.
   548  			return maxOffAddr
   549  		}
   550  	}
   551  	return addr
   552  }
   553  
   554  // find searches for the first (address-ordered) contiguous free region of
   555  // npages in size and returns a base address for that region.
   556  //
   557  // It uses s.searchAddr to prune its search and assumes that no palloc chunks
   558  // below chunkIndex(s.searchAddr) contain any free memory at all.
   559  //
   560  // find also computes and returns a candidate s.searchAddr, which may or
   561  // may not prune more of the address space than s.searchAddr already does.
   562  // This candidate is always a valid s.searchAddr.
   563  //
   564  // find represents the slow path and the full radix tree search.
   565  //
   566  // Returns a base address of 0 on failure, in which case the candidate
   567  // searchAddr returned is invalid and must be ignored.
   568  //
   569  // s.mheapLock must be held.
   570  func (s *pageAlloc) find(npages uintptr) (uintptr, offAddr) {
   571  	// Search algorithm.
   572  	//
   573  	// This algorithm walks each level l of the radix tree from the root level
   574  	// to the leaf level. It iterates over at most 1 << levelBits[l] of entries
   575  	// in a given level in the radix tree, and uses the summary information to
   576  	// find either:
   577  	//  1) That a given subtree contains a large enough contiguous region, at
   578  	//     which point it continues iterating on the next level, or
   579  	//  2) That there are enough contiguous boundary-crossing bits to satisfy
   580  	//     the allocation, at which point it knows exactly where to start
   581  	//     allocating from.
   582  	//
   583  	// i tracks the index into the current level l's structure for the
   584  	// contiguous 1 << levelBits[l] entries we're actually interested in.
   585  	//
   586  	// NOTE: Technically this search could allocate a region which crosses
   587  	// the arenaBaseOffset boundary, which when arenaBaseOffset != 0, is
   588  	// a discontinuity. However, the only way this could happen is if the
   589  	// page at the zero address is mapped, and this is impossible on
   590  	// every system we support where arenaBaseOffset != 0. So, the
   591  	// discontinuity is already encoded in the fact that the OS will never
   592  	// map the zero page for us, and this function doesn't try to handle
   593  	// this case in any way.
   594  
   595  	// i is the beginning of the block of entries we're searching at the
   596  	// current level.
   597  	i := 0
   598  
   599  	// firstFree is the region of address space that we are certain to
   600  	// find the first free page in the heap. base and bound are the inclusive
   601  	// bounds of this window, and both are addresses in the linearized, contiguous
   602  	// view of the address space (with arenaBaseOffset pre-added). At each level,
   603  	// this window is narrowed as we find the memory region containing the
   604  	// first free page of memory. To begin with, the range reflects the
   605  	// full process address space.
   606  	//
   607  	// firstFree is updated by calling foundFree each time free space in the
   608  	// heap is discovered.
   609  	//
   610  	// At the end of the search, base.addr() is the best new
   611  	// searchAddr we could deduce in this search.
   612  	firstFree := struct {
   613  		base, bound offAddr
   614  	}{
   615  		base:  minOffAddr,
   616  		bound: maxOffAddr,
   617  	}
   618  	// foundFree takes the given address range [addr, addr+size) and
   619  	// updates firstFree if it is a narrower range. The input range must
   620  	// either be fully contained within firstFree or not overlap with it
   621  	// at all.
   622  	//
   623  	// This way, we'll record the first summary we find with any free
   624  	// pages on the root level and narrow that down if we descend into
   625  	// that summary. But as soon as we need to iterate beyond that summary
   626  	// in a level to find a large enough range, we'll stop narrowing.
   627  	foundFree := func(addr offAddr, size uintptr) {
   628  		if firstFree.base.lessEqual(addr) && addr.add(size-1).lessEqual(firstFree.bound) {
   629  			// This range fits within the current firstFree window, so narrow
   630  			// down the firstFree window to the base and bound of this range.
   631  			firstFree.base = addr
   632  			firstFree.bound = addr.add(size - 1)
   633  		} else if !(addr.add(size-1).lessThan(firstFree.base) || firstFree.bound.lessThan(addr)) {
   634  			// This range only partially overlaps with the firstFree range,
   635  			// so throw.
   636  			print("runtime: addr = ", hex(addr.addr()), ", size = ", size, "\n")
   637  			print("runtime: base = ", hex(firstFree.base.addr()), ", bound = ", hex(firstFree.bound.addr()), "\n")
   638  			throw("range partially overlaps")
   639  		}
   640  	}
   641  
   642  	// lastSum is the summary which we saw on the previous level that made us
   643  	// move on to the next level. Used to print additional information in the
   644  	// case of a catastrophic failure.
   645  	// lastSumIdx is that summary's index in the previous level.
   646  	lastSum := packPallocSum(0, 0, 0)
   647  	lastSumIdx := -1
   648  
   649  nextLevel:
   650  	for l := 0; l < len(s.summary); l++ {
   651  		// For the root level, entriesPerBlock is the whole level.
   652  		entriesPerBlock := 1 << levelBits[l]
   653  		logMaxPages := levelLogPages[l]
   654  
   655  		// We've moved into a new level, so let's update i to our new
   656  		// starting index. This is a no-op for level 0.
   657  		i <<= levelBits[l]
   658  
   659  		// Slice out the block of entries we care about.
   660  		entries := s.summary[l][i : i+entriesPerBlock]
   661  
   662  		// Determine j0, the first index we should start iterating from.
   663  		// The searchAddr may help us eliminate iterations if we followed the
   664  		// searchAddr on the previous level or we're on the root leve, in which
   665  		// case the searchAddr should be the same as i after levelShift.
   666  		j0 := 0
   667  		if searchIdx := offAddrToLevelIndex(l, s.searchAddr); searchIdx&^(entriesPerBlock-1) == i {
   668  			j0 = searchIdx & (entriesPerBlock - 1)
   669  		}
   670  
   671  		// Run over the level entries looking for
   672  		// a contiguous run of at least npages either
   673  		// within an entry or across entries.
   674  		//
   675  		// base contains the page index (relative to
   676  		// the first entry's first page) of the currently
   677  		// considered run of consecutive pages.
   678  		//
   679  		// size contains the size of the currently considered
   680  		// run of consecutive pages.
   681  		var base, size uint
   682  		for j := j0; j < len(entries); j++ {
   683  			sum := entries[j]
   684  			if sum == 0 {
   685  				// A full entry means we broke any streak and
   686  				// that we should skip it altogether.
   687  				size = 0
   688  				continue
   689  			}
   690  
   691  			// We've encountered a non-zero summary which means
   692  			// free memory, so update firstFree.
   693  			foundFree(levelIndexToOffAddr(l, i+j), (uintptr(1)<<logMaxPages)*pageSize)
   694  
   695  			s := sum.start()
   696  			if size+s >= uint(npages) {
   697  				// If size == 0 we don't have a run yet,
   698  				// which means base isn't valid. So, set
   699  				// base to the first page in this block.
   700  				if size == 0 {
   701  					base = uint(j) << logMaxPages
   702  				}
   703  				// We hit npages; we're done!
   704  				size += s
   705  				break
   706  			}
   707  			if sum.max() >= uint(npages) {
   708  				// The entry itself contains npages contiguous
   709  				// free pages, so continue on the next level
   710  				// to find that run.
   711  				i += j
   712  				lastSumIdx = i
   713  				lastSum = sum
   714  				continue nextLevel
   715  			}
   716  			if size == 0 || s < 1<<logMaxPages {
   717  				// We either don't have a current run started, or this entry
   718  				// isn't totally free (meaning we can't continue the current
   719  				// one), so try to begin a new run by setting size and base
   720  				// based on sum.end.
   721  				size = sum.end()
   722  				base = uint(j+1)<<logMaxPages - size
   723  				continue
   724  			}
   725  			// The entry is completely free, so continue the run.
   726  			size += 1 << logMaxPages
   727  		}
   728  		if size >= uint(npages) {
   729  			// We found a sufficiently large run of free pages straddling
   730  			// some boundary, so compute the address and return it.
   731  			addr := levelIndexToOffAddr(l, i).add(uintptr(base) * pageSize).addr()
   732  			return addr, s.findMappedAddr(firstFree.base)
   733  		}
   734  		if l == 0 {
   735  			// We're at level zero, so that means we've exhausted our search.
   736  			return 0, maxSearchAddr
   737  		}
   738  
   739  		// We're not at level zero, and we exhausted the level we were looking in.
   740  		// This means that either our calculations were wrong or the level above
   741  		// lied to us. In either case, dump some useful state and throw.
   742  		print("runtime: summary[", l-1, "][", lastSumIdx, "] = ", lastSum.start(), ", ", lastSum.max(), ", ", lastSum.end(), "\n")
   743  		print("runtime: level = ", l, ", npages = ", npages, ", j0 = ", j0, "\n")
   744  		print("runtime: s.searchAddr = ", hex(s.searchAddr.addr()), ", i = ", i, "\n")
   745  		print("runtime: levelShift[level] = ", levelShift[l], ", levelBits[level] = ", levelBits[l], "\n")
   746  		for j := 0; j < len(entries); j++ {
   747  			sum := entries[j]
   748  			print("runtime: summary[", l, "][", i+j, "] = (", sum.start(), ", ", sum.max(), ", ", sum.end(), ")\n")
   749  		}
   750  		throw("bad summary data")
   751  	}
   752  
   753  	// Since we've gotten to this point, that means we haven't found a
   754  	// sufficiently-sized free region straddling some boundary (chunk or larger).
   755  	// This means the last summary we inspected must have had a large enough "max"
   756  	// value, so look inside the chunk to find a suitable run.
   757  	//
   758  	// After iterating over all levels, i must contain a chunk index which
   759  	// is what the final level represents.
   760  	ci := chunkIdx(i)
   761  	j, searchIdx := s.chunkOf(ci).find(npages, 0)
   762  	if j == ^uint(0) {
   763  		// We couldn't find any space in this chunk despite the summaries telling
   764  		// us it should be there. There's likely a bug, so dump some state and throw.
   765  		sum := s.summary[len(s.summary)-1][i]
   766  		print("runtime: summary[", len(s.summary)-1, "][", i, "] = (", sum.start(), ", ", sum.max(), ", ", sum.end(), ")\n")
   767  		print("runtime: npages = ", npages, "\n")
   768  		throw("bad summary data")
   769  	}
   770  
   771  	// Compute the address at which the free space starts.
   772  	addr := chunkBase(ci) + uintptr(j)*pageSize
   773  
   774  	// Since we actually searched the chunk, we may have
   775  	// found an even narrower free window.
   776  	searchAddr := chunkBase(ci) + uintptr(searchIdx)*pageSize
   777  	foundFree(offAddr{searchAddr}, chunkBase(ci+1)-searchAddr)
   778  	return addr, s.findMappedAddr(firstFree.base)
   779  }
   780  
   781  // alloc allocates npages worth of memory from the page heap, returning the base
   782  // address for the allocation and the amount of scavenged memory in bytes
   783  // contained in the region [base address, base address + npages*pageSize).
   784  //
   785  // Returns a 0 base address on failure, in which case other returned values
   786  // should be ignored.
   787  //
   788  // s.mheapLock must be held.
   789  func (s *pageAlloc) alloc(npages uintptr) (addr uintptr, scav uintptr) {
   790  	// If the searchAddr refers to a region which has a higher address than
   791  	// any known chunk, then we know we're out of memory.
   792  	if chunkIndex(s.searchAddr.addr()) >= s.end {
   793  		return 0, 0
   794  	}
   795  
   796  	// If npages has a chance of fitting in the chunk where the searchAddr is,
   797  	// search it directly.
   798  	searchAddr := minOffAddr
   799  	if pallocChunkPages-chunkPageIndex(s.searchAddr.addr()) >= uint(npages) {
   800  		// npages is guaranteed to be no greater than pallocChunkPages here.
   801  		i := chunkIndex(s.searchAddr.addr())
   802  		if max := s.summary[len(s.summary)-1][i].max(); max >= uint(npages) {
   803  			j, searchIdx := s.chunkOf(i).find(npages, chunkPageIndex(s.searchAddr.addr()))
   804  			if j == ^uint(0) {
   805  				print("runtime: max = ", max, ", npages = ", npages, "\n")
   806  				print("runtime: searchIdx = ", chunkPageIndex(s.searchAddr.addr()), ", s.searchAddr = ", hex(s.searchAddr.addr()), "\n")
   807  				throw("bad summary data")
   808  			}
   809  			addr = chunkBase(i) + uintptr(j)*pageSize
   810  			searchAddr = offAddr{chunkBase(i) + uintptr(searchIdx)*pageSize}
   811  			goto Found
   812  		}
   813  	}
   814  	// We failed to use a searchAddr for one reason or another, so try
   815  	// the slow path.
   816  	addr, searchAddr = s.find(npages)
   817  	if addr == 0 {
   818  		if npages == 1 {
   819  			// We failed to find a single free page, the smallest unit
   820  			// of allocation. This means we know the heap is completely
   821  			// exhausted. Otherwise, the heap still might have free
   822  			// space in it, just not enough contiguous space to
   823  			// accommodate npages.
   824  			s.searchAddr = maxSearchAddr
   825  		}
   826  		return 0, 0
   827  	}
   828  Found:
   829  	// Go ahead and actually mark the bits now that we have an address.
   830  	scav = s.allocRange(addr, npages)
   831  
   832  	// If we found a higher searchAddr, we know that all the
   833  	// heap memory before that searchAddr in an offset address space is
   834  	// allocated, so bump s.searchAddr up to the new one.
   835  	if s.searchAddr.lessThan(searchAddr) {
   836  		s.searchAddr = searchAddr
   837  	}
   838  	return addr, scav
   839  }
   840  
   841  // free returns npages worth of memory starting at base back to the page heap.
   842  //
   843  // s.mheapLock must be held.
   844  func (s *pageAlloc) free(base, npages uintptr) {
   845  	// If we're freeing pages below the s.searchAddr, update searchAddr.
   846  	if b := (offAddr{base}); b.lessThan(s.searchAddr) {
   847  		s.searchAddr = b
   848  	}
   849  	// Update the free high watermark for the scavenger.
   850  	limit := base + npages*pageSize - 1
   851  	if offLimit := (offAddr{limit}); s.scav.freeHWM.lessThan(offLimit) {
   852  		s.scav.freeHWM = offLimit
   853  	}
   854  	if npages == 1 {
   855  		// Fast path: we're clearing a single bit, and we know exactly
   856  		// where it is, so mark it directly.
   857  		i := chunkIndex(base)
   858  		s.chunkOf(i).free1(chunkPageIndex(base))
   859  	} else {
   860  		// Slow path: we're clearing more bits so we may need to iterate.
   861  		sc, ec := chunkIndex(base), chunkIndex(limit)
   862  		si, ei := chunkPageIndex(base), chunkPageIndex(limit)
   863  
   864  		if sc == ec {
   865  			// The range doesn't cross any chunk boundaries.
   866  			s.chunkOf(sc).free(si, ei+1-si)
   867  		} else {
   868  			// The range crosses at least one chunk boundary.
   869  			s.chunkOf(sc).free(si, pallocChunkPages-si)
   870  			for c := sc + 1; c < ec; c++ {
   871  				s.chunkOf(c).freeAll()
   872  			}
   873  			s.chunkOf(ec).free(0, ei+1)
   874  		}
   875  	}
   876  	s.update(base, npages, true, false)
   877  }
   878  
   879  const (
   880  	pallocSumBytes = unsafe.Sizeof(pallocSum(0))
   881  
   882  	// maxPackedValue is the maximum value that any of the three fields in
   883  	// the pallocSum may take on.
   884  	maxPackedValue    = 1 << logMaxPackedValue
   885  	logMaxPackedValue = logPallocChunkPages + (summaryLevels-1)*summaryLevelBits
   886  
   887  	freeChunkSum = pallocSum(uint64(pallocChunkPages) |
   888  		uint64(pallocChunkPages<<logMaxPackedValue) |
   889  		uint64(pallocChunkPages<<(2*logMaxPackedValue)))
   890  )
   891  
   892  // pallocSum is a packed summary type which packs three numbers: start, max,
   893  // and end into a single 8-byte value. Each of these values are a summary of
   894  // a bitmap and are thus counts, each of which may have a maximum value of
   895  // 2^21 - 1, or all three may be equal to 2^21. The latter case is represented
   896  // by just setting the 64th bit.
   897  type pallocSum uint64
   898  
   899  // packPallocSum takes a start, max, and end value and produces a pallocSum.
   900  func packPallocSum(start, max, end uint) pallocSum {
   901  	if max == maxPackedValue {
   902  		return pallocSum(uint64(1 << 63))
   903  	}
   904  	return pallocSum((uint64(start) & (maxPackedValue - 1)) |
   905  		((uint64(max) & (maxPackedValue - 1)) << logMaxPackedValue) |
   906  		((uint64(end) & (maxPackedValue - 1)) << (2 * logMaxPackedValue)))
   907  }
   908  
   909  // start extracts the start value from a packed sum.
   910  func (p pallocSum) start() uint {
   911  	if uint64(p)&uint64(1<<63) != 0 {
   912  		return maxPackedValue
   913  	}
   914  	return uint(uint64(p) & (maxPackedValue - 1))
   915  }
   916  
   917  // max extracts the max value from a packed sum.
   918  func (p pallocSum) max() uint {
   919  	if uint64(p)&uint64(1<<63) != 0 {
   920  		return maxPackedValue
   921  	}
   922  	return uint((uint64(p) >> logMaxPackedValue) & (maxPackedValue - 1))
   923  }
   924  
   925  // end extracts the end value from a packed sum.
   926  func (p pallocSum) end() uint {
   927  	if uint64(p)&uint64(1<<63) != 0 {
   928  		return maxPackedValue
   929  	}
   930  	return uint((uint64(p) >> (2 * logMaxPackedValue)) & (maxPackedValue - 1))
   931  }
   932  
   933  // unpack unpacks all three values from the summary.
   934  func (p pallocSum) unpack() (uint, uint, uint) {
   935  	if uint64(p)&uint64(1<<63) != 0 {
   936  		return maxPackedValue, maxPackedValue, maxPackedValue
   937  	}
   938  	return uint(uint64(p) & (maxPackedValue - 1)),
   939  		uint((uint64(p) >> logMaxPackedValue) & (maxPackedValue - 1)),
   940  		uint((uint64(p) >> (2 * logMaxPackedValue)) & (maxPackedValue - 1))
   941  }
   942  
   943  // mergeSummaries merges consecutive summaries which may each represent at
   944  // most 1 << logMaxPagesPerSum pages each together into one.
   945  func mergeSummaries(sums []pallocSum, logMaxPagesPerSum uint) pallocSum {
   946  	// Merge the summaries in sums into one.
   947  	//
   948  	// We do this by keeping a running summary representing the merged
   949  	// summaries of sums[:i] in start, max, and end.
   950  	start, max, end := sums[0].unpack()
   951  	for i := 1; i < len(sums); i++ {
   952  		// Merge in sums[i].
   953  		si, mi, ei := sums[i].unpack()
   954  
   955  		// Merge in sums[i].start only if the running summary is
   956  		// completely free, otherwise this summary's start
   957  		// plays no role in the combined sum.
   958  		if start == uint(i)<<logMaxPagesPerSum {
   959  			start += si
   960  		}
   961  
   962  		// Recompute the max value of the running sum by looking
   963  		// across the boundary between the running sum and sums[i]
   964  		// and at the max sums[i], taking the greatest of those two
   965  		// and the max of the running sum.
   966  		if end+si > max {
   967  			max = end + si
   968  		}
   969  		if mi > max {
   970  			max = mi
   971  		}
   972  
   973  		// Merge in end by checking if this new summary is totally
   974  		// free. If it is, then we want to extend the running sum's
   975  		// end by the new summary. If not, then we have some alloc'd
   976  		// pages in there and we just want to take the end value in
   977  		// sums[i].
   978  		if ei == 1<<logMaxPagesPerSum {
   979  			end += 1 << logMaxPagesPerSum
   980  		} else {
   981  			end = ei
   982  		}
   983  	}
   984  	return packPallocSum(start, max, end)
   985  }
   986  

View as plain text