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  // chunkOf returns the chunk at the given chunk index.
   330  func (s *pageAlloc) chunkOf(ci chunkIdx) *pallocData {
   331  	return &s.chunks[ci.l1()][ci.l2()]
   332  }
   333  
   334  // grow sets up the metadata for the address range [base, base+size).
   335  // It may allocate metadata, in which case *s.sysStat will be updated.
   336  //
   337  // s.mheapLock must be held.
   338  func (s *pageAlloc) grow(base, size uintptr) {
   339  	// Round up to chunks, since we can't deal with increments smaller
   340  	// than chunks. Also, sysGrow expects aligned values.
   341  	limit := alignUp(base+size, pallocChunkBytes)
   342  	base = alignDown(base, pallocChunkBytes)
   343  
   344  	// Grow the summary levels in a system-dependent manner.
   345  	// We just update a bunch of additional metadata here.
   346  	s.sysGrow(base, limit)
   347  
   348  	// Update s.start and s.end.
   349  	// If no growth happened yet, start == 0. This is generally
   350  	// safe since the zero page is unmapped.
   351  	firstGrowth := s.start == 0
   352  	start, end := chunkIndex(base), chunkIndex(limit)
   353  	if firstGrowth || start < s.start {
   354  		s.start = start
   355  	}
   356  	if end > s.end {
   357  		s.end = end
   358  	}
   359  	// Note that [base, limit) will never overlap with any existing
   360  	// range inUse because grow only ever adds never-used memory
   361  	// regions to the page allocator.
   362  	s.inUse.add(makeAddrRange(base, limit))
   363  
   364  	// A grow operation is a lot like a free operation, so if our
   365  	// chunk ends up below s.searchAddr, update s.searchAddr to the
   366  	// new address, just like in free.
   367  	if b := (offAddr{base}); b.lessThan(s.searchAddr) {
   368  		s.searchAddr = b
   369  	}
   370  
   371  	// Add entries into chunks, which is sparse, if needed. Then,
   372  	// initialize the bitmap.
   373  	//
   374  	// Newly-grown memory is always considered scavenged.
   375  	// Set all the bits in the scavenged bitmaps high.
   376  	for c := chunkIndex(base); c < chunkIndex(limit); c++ {
   377  		if s.chunks[c.l1()] == nil {
   378  			// Create the necessary l2 entry.
   379  			//
   380  			// Store it atomically to avoid races with readers which
   381  			// don't acquire the heap lock.
   382  			r := sysAlloc(unsafe.Sizeof(*s.chunks[0]), s.sysStat)
   383  			atomic.StorepNoWB(unsafe.Pointer(&s.chunks[c.l1()]), r)
   384  		}
   385  		s.chunkOf(c).scavenged.setRange(0, pallocChunkPages)
   386  	}
   387  
   388  	// Update summaries accordingly. The grow acts like a free, so
   389  	// we need to ensure this newly-free memory is visible in the
   390  	// summaries.
   391  	s.update(base, size/pageSize, true, false)
   392  }
   393  
   394  // update updates heap metadata. It must be called each time the bitmap
   395  // is updated.
   396  //
   397  // If contig is true, update does some optimizations assuming that there was
   398  // a contiguous allocation or free between addr and addr+npages. alloc indicates
   399  // whether the operation performed was an allocation or a free.
   400  //
   401  // s.mheapLock must be held.
   402  func (s *pageAlloc) update(base, npages uintptr, contig, alloc bool) {
   403  	// base, limit, start, and end are inclusive.
   404  	limit := base + npages*pageSize - 1
   405  	sc, ec := chunkIndex(base), chunkIndex(limit)
   406  
   407  	// Handle updating the lowest level first.
   408  	if sc == ec {
   409  		// Fast path: the allocation doesn't span more than one chunk,
   410  		// so update this one and if the summary didn't change, return.
   411  		x := s.summary[len(s.summary)-1][sc]
   412  		y := s.chunkOf(sc).summarize()
   413  		if x == y {
   414  			return
   415  		}
   416  		s.summary[len(s.summary)-1][sc] = y
   417  	} else if contig {
   418  		// Slow contiguous path: the allocation spans more than one chunk
   419  		// and at least one summary is guaranteed to change.
   420  		summary := s.summary[len(s.summary)-1]
   421  
   422  		// Update the summary for chunk sc.
   423  		summary[sc] = s.chunkOf(sc).summarize()
   424  
   425  		// Update the summaries for chunks in between, which are
   426  		// either totally allocated or freed.
   427  		whole := s.summary[len(s.summary)-1][sc+1 : ec]
   428  		if alloc {
   429  			// Should optimize into a memclr.
   430  			for i := range whole {
   431  				whole[i] = 0
   432  			}
   433  		} else {
   434  			for i := range whole {
   435  				whole[i] = freeChunkSum
   436  			}
   437  		}
   438  
   439  		// Update the summary for chunk ec.
   440  		summary[ec] = s.chunkOf(ec).summarize()
   441  	} else {
   442  		// Slow general path: the allocation spans more than one chunk
   443  		// and at least one summary is guaranteed to change.
   444  		//
   445  		// We can't assume a contiguous allocation happened, so walk over
   446  		// every chunk in the range and manually recompute the summary.
   447  		summary := s.summary[len(s.summary)-1]
   448  		for c := sc; c <= ec; c++ {
   449  			summary[c] = s.chunkOf(c).summarize()
   450  		}
   451  	}
   452  
   453  	// Walk up the radix tree and update the summaries appropriately.
   454  	changed := true
   455  	for l := len(s.summary) - 2; l >= 0 && changed; l-- {
   456  		// Update summaries at level l from summaries at level l+1.
   457  		changed = false
   458  
   459  		// "Constants" for the previous level which we
   460  		// need to compute the summary from that level.
   461  		logEntriesPerBlock := levelBits[l+1]
   462  		logMaxPages := levelLogPages[l+1]
   463  
   464  		// lo and hi describe all the parts of the level we need to look at.
   465  		lo, hi := addrsToSummaryRange(l, base, limit+1)
   466  
   467  		// Iterate over each block, updating the corresponding summary in the less-granular level.
   468  		for i := lo; i < hi; i++ {
   469  			children := s.summary[l+1][i<<logEntriesPerBlock : (i+1)<<logEntriesPerBlock]
   470  			sum := mergeSummaries(children, logMaxPages)
   471  			old := s.summary[l][i]
   472  			if old != sum {
   473  				changed = true
   474  				s.summary[l][i] = sum
   475  			}
   476  		}
   477  	}
   478  }
   479  
   480  // allocRange marks the range of memory [base, base+npages*pageSize) as
   481  // allocated. It also updates the summaries to reflect the newly-updated
   482  // bitmap.
   483  //
   484  // Returns the amount of scavenged memory in bytes present in the
   485  // allocated range.
   486  //
   487  // s.mheapLock must be held.
   488  func (s *pageAlloc) allocRange(base, npages uintptr) uintptr {
   489  	limit := base + npages*pageSize - 1
   490  	sc, ec := chunkIndex(base), chunkIndex(limit)
   491  	si, ei := chunkPageIndex(base), chunkPageIndex(limit)
   492  
   493  	scav := uint(0)
   494  	if sc == ec {
   495  		// The range doesn't cross any chunk boundaries.
   496  		chunk := s.chunkOf(sc)
   497  		scav += chunk.scavenged.popcntRange(si, ei+1-si)
   498  		chunk.allocRange(si, ei+1-si)
   499  	} else {
   500  		// The range crosses at least one chunk boundary.
   501  		chunk := s.chunkOf(sc)
   502  		scav += chunk.scavenged.popcntRange(si, pallocChunkPages-si)
   503  		chunk.allocRange(si, pallocChunkPages-si)
   504  		for c := sc + 1; c < ec; c++ {
   505  			chunk := s.chunkOf(c)
   506  			scav += chunk.scavenged.popcntRange(0, pallocChunkPages)
   507  			chunk.allocAll()
   508  		}
   509  		chunk = s.chunkOf(ec)
   510  		scav += chunk.scavenged.popcntRange(0, ei+1)
   511  		chunk.allocRange(0, ei+1)
   512  	}
   513  	s.update(base, npages, true, true)
   514  	return uintptr(scav) * pageSize
   515  }
   516  
   517  // findMappedAddr returns the smallest mapped offAddr that is
   518  // >= addr. That is, if addr refers to mapped memory, then it is
   519  // returned. If addr is higher than any mapped region, then
   520  // it returns maxOffAddr.
   521  //
   522  // s.mheapLock must be held.
   523  func (s *pageAlloc) findMappedAddr(addr offAddr) offAddr {
   524  	// If we're not in a test, validate first by checking mheap_.arenas.
   525  	// This is a fast path which is only safe to use outside of testing.
   526  	ai := arenaIndex(addr.addr())
   527  	if s.test || mheap_.arenas[ai.l1()] == nil || mheap_.arenas[ai.l1()][ai.l2()] == nil {
   528  		vAddr, ok := s.inUse.findAddrGreaterEqual(addr.addr())
   529  		if ok {
   530  			return offAddr{vAddr}
   531  		} else {
   532  			// The candidate search address is greater than any
   533  			// known address, which means we definitely have no
   534  			// free memory left.
   535  			return maxOffAddr
   536  		}
   537  	}
   538  	return addr
   539  }
   540  
   541  // find searches for the first (address-ordered) contiguous free region of
   542  // npages in size and returns a base address for that region.
   543  //
   544  // It uses s.searchAddr to prune its search and assumes that no palloc chunks
   545  // below chunkIndex(s.searchAddr) contain any free memory at all.
   546  //
   547  // find also computes and returns a candidate s.searchAddr, which may or
   548  // may not prune more of the address space than s.searchAddr already does.
   549  // This candidate is always a valid s.searchAddr.
   550  //
   551  // find represents the slow path and the full radix tree search.
   552  //
   553  // Returns a base address of 0 on failure, in which case the candidate
   554  // searchAddr returned is invalid and must be ignored.
   555  //
   556  // s.mheapLock must be held.
   557  func (s *pageAlloc) find(npages uintptr) (uintptr, offAddr) {
   558  	// Search algorithm.
   559  	//
   560  	// This algorithm walks each level l of the radix tree from the root level
   561  	// to the leaf level. It iterates over at most 1 << levelBits[l] of entries
   562  	// in a given level in the radix tree, and uses the summary information to
   563  	// find either:
   564  	//  1) That a given subtree contains a large enough contiguous region, at
   565  	//     which point it continues iterating on the next level, or
   566  	//  2) That there are enough contiguous boundary-crossing bits to satisfy
   567  	//     the allocation, at which point it knows exactly where to start
   568  	//     allocating from.
   569  	//
   570  	// i tracks the index into the current level l's structure for the
   571  	// contiguous 1 << levelBits[l] entries we're actually interested in.
   572  	//
   573  	// NOTE: Technically this search could allocate a region which crosses
   574  	// the arenaBaseOffset boundary, which when arenaBaseOffset != 0, is
   575  	// a discontinuity. However, the only way this could happen is if the
   576  	// page at the zero address is mapped, and this is impossible on
   577  	// every system we support where arenaBaseOffset != 0. So, the
   578  	// discontinuity is already encoded in the fact that the OS will never
   579  	// map the zero page for us, and this function doesn't try to handle
   580  	// this case in any way.
   581  
   582  	// i is the beginning of the block of entries we're searching at the
   583  	// current level.
   584  	i := 0
   585  
   586  	// firstFree is the region of address space that we are certain to
   587  	// find the first free page in the heap. base and bound are the inclusive
   588  	// bounds of this window, and both are addresses in the linearized, contiguous
   589  	// view of the address space (with arenaBaseOffset pre-added). At each level,
   590  	// this window is narrowed as we find the memory region containing the
   591  	// first free page of memory. To begin with, the range reflects the
   592  	// full process address space.
   593  	//
   594  	// firstFree is updated by calling foundFree each time free space in the
   595  	// heap is discovered.
   596  	//
   597  	// At the end of the search, base.addr() is the best new
   598  	// searchAddr we could deduce in this search.
   599  	firstFree := struct {
   600  		base, bound offAddr
   601  	}{
   602  		base:  minOffAddr,
   603  		bound: maxOffAddr,
   604  	}
   605  	// foundFree takes the given address range [addr, addr+size) and
   606  	// updates firstFree if it is a narrower range. The input range must
   607  	// either be fully contained within firstFree or not overlap with it
   608  	// at all.
   609  	//
   610  	// This way, we'll record the first summary we find with any free
   611  	// pages on the root level and narrow that down if we descend into
   612  	// that summary. But as soon as we need to iterate beyond that summary
   613  	// in a level to find a large enough range, we'll stop narrowing.
   614  	foundFree := func(addr offAddr, size uintptr) {
   615  		if firstFree.base.lessEqual(addr) && addr.add(size-1).lessEqual(firstFree.bound) {
   616  			// This range fits within the current firstFree window, so narrow
   617  			// down the firstFree window to the base and bound of this range.
   618  			firstFree.base = addr
   619  			firstFree.bound = addr.add(size - 1)
   620  		} else if !(addr.add(size-1).lessThan(firstFree.base) || firstFree.bound.lessThan(addr)) {
   621  			// This range only partially overlaps with the firstFree range,
   622  			// so throw.
   623  			print("runtime: addr = ", hex(addr.addr()), ", size = ", size, "\n")
   624  			print("runtime: base = ", hex(firstFree.base.addr()), ", bound = ", hex(firstFree.bound.addr()), "\n")
   625  			throw("range partially overlaps")
   626  		}
   627  	}
   628  
   629  	// lastSum is the summary which we saw on the previous level that made us
   630  	// move on to the next level. Used to print additional information in the
   631  	// case of a catastrophic failure.
   632  	// lastSumIdx is that summary's index in the previous level.
   633  	lastSum := packPallocSum(0, 0, 0)
   634  	lastSumIdx := -1
   635  
   636  nextLevel:
   637  	for l := 0; l < len(s.summary); l++ {
   638  		// For the root level, entriesPerBlock is the whole level.
   639  		entriesPerBlock := 1 << levelBits[l]
   640  		logMaxPages := levelLogPages[l]
   641  
   642  		// We've moved into a new level, so let's update i to our new
   643  		// starting index. This is a no-op for level 0.
   644  		i <<= levelBits[l]
   645  
   646  		// Slice out the block of entries we care about.
   647  		entries := s.summary[l][i : i+entriesPerBlock]
   648  
   649  		// Determine j0, the first index we should start iterating from.
   650  		// The searchAddr may help us eliminate iterations if we followed the
   651  		// searchAddr on the previous level or we're on the root leve, in which
   652  		// case the searchAddr should be the same as i after levelShift.
   653  		j0 := 0
   654  		if searchIdx := offAddrToLevelIndex(l, s.searchAddr); searchIdx&^(entriesPerBlock-1) == i {
   655  			j0 = searchIdx & (entriesPerBlock - 1)
   656  		}
   657  
   658  		// Run over the level entries looking for
   659  		// a contiguous run of at least npages either
   660  		// within an entry or across entries.
   661  		//
   662  		// base contains the page index (relative to
   663  		// the first entry's first page) of the currently
   664  		// considered run of consecutive pages.
   665  		//
   666  		// size contains the size of the currently considered
   667  		// run of consecutive pages.
   668  		var base, size uint
   669  		for j := j0; j < len(entries); j++ {
   670  			sum := entries[j]
   671  			if sum == 0 {
   672  				// A full entry means we broke any streak and
   673  				// that we should skip it altogether.
   674  				size = 0
   675  				continue
   676  			}
   677  
   678  			// We've encountered a non-zero summary which means
   679  			// free memory, so update firstFree.
   680  			foundFree(levelIndexToOffAddr(l, i+j), (uintptr(1)<<logMaxPages)*pageSize)
   681  
   682  			s := sum.start()
   683  			if size+s >= uint(npages) {
   684  				// If size == 0 we don't have a run yet,
   685  				// which means base isn't valid. So, set
   686  				// base to the first page in this block.
   687  				if size == 0 {
   688  					base = uint(j) << logMaxPages
   689  				}
   690  				// We hit npages; we're done!
   691  				size += s
   692  				break
   693  			}
   694  			if sum.max() >= uint(npages) {
   695  				// The entry itself contains npages contiguous
   696  				// free pages, so continue on the next level
   697  				// to find that run.
   698  				i += j
   699  				lastSumIdx = i
   700  				lastSum = sum
   701  				continue nextLevel
   702  			}
   703  			if size == 0 || s < 1<<logMaxPages {
   704  				// We either don't have a current run started, or this entry
   705  				// isn't totally free (meaning we can't continue the current
   706  				// one), so try to begin a new run by setting size and base
   707  				// based on sum.end.
   708  				size = sum.end()
   709  				base = uint(j+1)<<logMaxPages - size
   710  				continue
   711  			}
   712  			// The entry is completely free, so continue the run.
   713  			size += 1 << logMaxPages
   714  		}
   715  		if size >= uint(npages) {
   716  			// We found a sufficiently large run of free pages straddling
   717  			// some boundary, so compute the address and return it.
   718  			addr := levelIndexToOffAddr(l, i).add(uintptr(base) * pageSize).addr()
   719  			return addr, s.findMappedAddr(firstFree.base)
   720  		}
   721  		if l == 0 {
   722  			// We're at level zero, so that means we've exhausted our search.
   723  			return 0, maxSearchAddr
   724  		}
   725  
   726  		// We're not at level zero, and we exhausted the level we were looking in.
   727  		// This means that either our calculations were wrong or the level above
   728  		// lied to us. In either case, dump some useful state and throw.
   729  		print("runtime: summary[", l-1, "][", lastSumIdx, "] = ", lastSum.start(), ", ", lastSum.max(), ", ", lastSum.end(), "\n")
   730  		print("runtime: level = ", l, ", npages = ", npages, ", j0 = ", j0, "\n")
   731  		print("runtime: s.searchAddr = ", hex(s.searchAddr.addr()), ", i = ", i, "\n")
   732  		print("runtime: levelShift[level] = ", levelShift[l], ", levelBits[level] = ", levelBits[l], "\n")
   733  		for j := 0; j < len(entries); j++ {
   734  			sum := entries[j]
   735  			print("runtime: summary[", l, "][", i+j, "] = (", sum.start(), ", ", sum.max(), ", ", sum.end(), ")\n")
   736  		}
   737  		throw("bad summary data")
   738  	}
   739  
   740  	// Since we've gotten to this point, that means we haven't found a
   741  	// sufficiently-sized free region straddling some boundary (chunk or larger).
   742  	// This means the last summary we inspected must have had a large enough "max"
   743  	// value, so look inside the chunk to find a suitable run.
   744  	//
   745  	// After iterating over all levels, i must contain a chunk index which
   746  	// is what the final level represents.
   747  	ci := chunkIdx(i)
   748  	j, searchIdx := s.chunkOf(ci).find(npages, 0)
   749  	if j == ^uint(0) {
   750  		// We couldn't find any space in this chunk despite the summaries telling
   751  		// us it should be there. There's likely a bug, so dump some state and throw.
   752  		sum := s.summary[len(s.summary)-1][i]
   753  		print("runtime: summary[", len(s.summary)-1, "][", i, "] = (", sum.start(), ", ", sum.max(), ", ", sum.end(), ")\n")
   754  		print("runtime: npages = ", npages, "\n")
   755  		throw("bad summary data")
   756  	}
   757  
   758  	// Compute the address at which the free space starts.
   759  	addr := chunkBase(ci) + uintptr(j)*pageSize
   760  
   761  	// Since we actually searched the chunk, we may have
   762  	// found an even narrower free window.
   763  	searchAddr := chunkBase(ci) + uintptr(searchIdx)*pageSize
   764  	foundFree(offAddr{searchAddr}, chunkBase(ci+1)-searchAddr)
   765  	return addr, s.findMappedAddr(firstFree.base)
   766  }
   767  
   768  // alloc allocates npages worth of memory from the page heap, returning the base
   769  // address for the allocation and the amount of scavenged memory in bytes
   770  // contained in the region [base address, base address + npages*pageSize).
   771  //
   772  // Returns a 0 base address on failure, in which case other returned values
   773  // should be ignored.
   774  //
   775  // s.mheapLock must be held.
   776  func (s *pageAlloc) alloc(npages uintptr) (addr uintptr, scav uintptr) {
   777  	// If the searchAddr refers to a region which has a higher address than
   778  	// any known chunk, then we know we're out of memory.
   779  	if chunkIndex(s.searchAddr.addr()) >= s.end {
   780  		return 0, 0
   781  	}
   782  
   783  	// If npages has a chance of fitting in the chunk where the searchAddr is,
   784  	// search it directly.
   785  	searchAddr := minOffAddr
   786  	if pallocChunkPages-chunkPageIndex(s.searchAddr.addr()) >= uint(npages) {
   787  		// npages is guaranteed to be no greater than pallocChunkPages here.
   788  		i := chunkIndex(s.searchAddr.addr())
   789  		if max := s.summary[len(s.summary)-1][i].max(); max >= uint(npages) {
   790  			j, searchIdx := s.chunkOf(i).find(npages, chunkPageIndex(s.searchAddr.addr()))
   791  			if j == ^uint(0) {
   792  				print("runtime: max = ", max, ", npages = ", npages, "\n")
   793  				print("runtime: searchIdx = ", chunkPageIndex(s.searchAddr.addr()), ", s.searchAddr = ", hex(s.searchAddr.addr()), "\n")
   794  				throw("bad summary data")
   795  			}
   796  			addr = chunkBase(i) + uintptr(j)*pageSize
   797  			searchAddr = offAddr{chunkBase(i) + uintptr(searchIdx)*pageSize}
   798  			goto Found
   799  		}
   800  	}
   801  	// We failed to use a searchAddr for one reason or another, so try
   802  	// the slow path.
   803  	addr, searchAddr = s.find(npages)
   804  	if addr == 0 {
   805  		if npages == 1 {
   806  			// We failed to find a single free page, the smallest unit
   807  			// of allocation. This means we know the heap is completely
   808  			// exhausted. Otherwise, the heap still might have free
   809  			// space in it, just not enough contiguous space to
   810  			// accommodate npages.
   811  			s.searchAddr = maxSearchAddr
   812  		}
   813  		return 0, 0
   814  	}
   815  Found:
   816  	// Go ahead and actually mark the bits now that we have an address.
   817  	scav = s.allocRange(addr, npages)
   818  
   819  	// If we found a higher searchAddr, we know that all the
   820  	// heap memory before that searchAddr in an offset address space is
   821  	// allocated, so bump s.searchAddr up to the new one.
   822  	if s.searchAddr.lessThan(searchAddr) {
   823  		s.searchAddr = searchAddr
   824  	}
   825  	return addr, scav
   826  }
   827  
   828  // free returns npages worth of memory starting at base back to the page heap.
   829  //
   830  // s.mheapLock must be held.
   831  func (s *pageAlloc) free(base, npages uintptr) {
   832  	// If we're freeing pages below the s.searchAddr, update searchAddr.
   833  	if b := (offAddr{base}); b.lessThan(s.searchAddr) {
   834  		s.searchAddr = b
   835  	}
   836  	// Update the free high watermark for the scavenger.
   837  	limit := base + npages*pageSize - 1
   838  	if offLimit := (offAddr{limit}); s.scav.freeHWM.lessThan(offLimit) {
   839  		s.scav.freeHWM = offLimit
   840  	}
   841  	if npages == 1 {
   842  		// Fast path: we're clearing a single bit, and we know exactly
   843  		// where it is, so mark it directly.
   844  		i := chunkIndex(base)
   845  		s.chunkOf(i).free1(chunkPageIndex(base))
   846  	} else {
   847  		// Slow path: we're clearing more bits so we may need to iterate.
   848  		sc, ec := chunkIndex(base), chunkIndex(limit)
   849  		si, ei := chunkPageIndex(base), chunkPageIndex(limit)
   850  
   851  		if sc == ec {
   852  			// The range doesn't cross any chunk boundaries.
   853  			s.chunkOf(sc).free(si, ei+1-si)
   854  		} else {
   855  			// The range crosses at least one chunk boundary.
   856  			s.chunkOf(sc).free(si, pallocChunkPages-si)
   857  			for c := sc + 1; c < ec; c++ {
   858  				s.chunkOf(c).freeAll()
   859  			}
   860  			s.chunkOf(ec).free(0, ei+1)
   861  		}
   862  	}
   863  	s.update(base, npages, true, false)
   864  }
   865  
   866  const (
   867  	pallocSumBytes = unsafe.Sizeof(pallocSum(0))
   868  
   869  	// maxPackedValue is the maximum value that any of the three fields in
   870  	// the pallocSum may take on.
   871  	maxPackedValue    = 1 << logMaxPackedValue
   872  	logMaxPackedValue = logPallocChunkPages + (summaryLevels-1)*summaryLevelBits
   873  
   874  	freeChunkSum = pallocSum(uint64(pallocChunkPages) |
   875  		uint64(pallocChunkPages<<logMaxPackedValue) |
   876  		uint64(pallocChunkPages<<(2*logMaxPackedValue)))
   877  )
   878  
   879  // pallocSum is a packed summary type which packs three numbers: start, max,
   880  // and end into a single 8-byte value. Each of these values are a summary of
   881  // a bitmap and are thus counts, each of which may have a maximum value of
   882  // 2^21 - 1, or all three may be equal to 2^21. The latter case is represented
   883  // by just setting the 64th bit.
   884  type pallocSum uint64
   885  
   886  // packPallocSum takes a start, max, and end value and produces a pallocSum.
   887  func packPallocSum(start, max, end uint) pallocSum {
   888  	if max == maxPackedValue {
   889  		return pallocSum(uint64(1 << 63))
   890  	}
   891  	return pallocSum((uint64(start) & (maxPackedValue - 1)) |
   892  		((uint64(max) & (maxPackedValue - 1)) << logMaxPackedValue) |
   893  		((uint64(end) & (maxPackedValue - 1)) << (2 * logMaxPackedValue)))
   894  }
   895  
   896  // start extracts the start value from a packed sum.
   897  func (p pallocSum) start() uint {
   898  	if uint64(p)&uint64(1<<63) != 0 {
   899  		return maxPackedValue
   900  	}
   901  	return uint(uint64(p) & (maxPackedValue - 1))
   902  }
   903  
   904  // max extracts the max value from a packed sum.
   905  func (p pallocSum) max() uint {
   906  	if uint64(p)&uint64(1<<63) != 0 {
   907  		return maxPackedValue
   908  	}
   909  	return uint((uint64(p) >> logMaxPackedValue) & (maxPackedValue - 1))
   910  }
   911  
   912  // end extracts the end value from a packed sum.
   913  func (p pallocSum) end() uint {
   914  	if uint64(p)&uint64(1<<63) != 0 {
   915  		return maxPackedValue
   916  	}
   917  	return uint((uint64(p) >> (2 * logMaxPackedValue)) & (maxPackedValue - 1))
   918  }
   919  
   920  // unpack unpacks all three values from the summary.
   921  func (p pallocSum) unpack() (uint, uint, uint) {
   922  	if uint64(p)&uint64(1<<63) != 0 {
   923  		return maxPackedValue, maxPackedValue, maxPackedValue
   924  	}
   925  	return uint(uint64(p) & (maxPackedValue - 1)),
   926  		uint((uint64(p) >> logMaxPackedValue) & (maxPackedValue - 1)),
   927  		uint((uint64(p) >> (2 * logMaxPackedValue)) & (maxPackedValue - 1))
   928  }
   929  
   930  // mergeSummaries merges consecutive summaries which may each represent at
   931  // most 1 << logMaxPagesPerSum pages each together into one.
   932  func mergeSummaries(sums []pallocSum, logMaxPagesPerSum uint) pallocSum {
   933  	// Merge the summaries in sums into one.
   934  	//
   935  	// We do this by keeping a running summary representing the merged
   936  	// summaries of sums[:i] in start, max, and end.
   937  	start, max, end := sums[0].unpack()
   938  	for i := 1; i < len(sums); i++ {
   939  		// Merge in sums[i].
   940  		si, mi, ei := sums[i].unpack()
   941  
   942  		// Merge in sums[i].start only if the running summary is
   943  		// completely free, otherwise this summary's start
   944  		// plays no role in the combined sum.
   945  		if start == uint(i)<<logMaxPagesPerSum {
   946  			start += si
   947  		}
   948  
   949  		// Recompute the max value of the running sum by looking
   950  		// across the boundary between the running sum and sums[i]
   951  		// and at the max sums[i], taking the greatest of those two
   952  		// and the max of the running sum.
   953  		if end+si > max {
   954  			max = end + si
   955  		}
   956  		if mi > max {
   957  			max = mi
   958  		}
   959  
   960  		// Merge in end by checking if this new summary is totally
   961  		// free. If it is, then we want to extend the running sum's
   962  		// end by the new summary. If not, then we have some alloc'd
   963  		// pages in there and we just want to take the end value in
   964  		// sums[i].
   965  		if ei == 1<<logMaxPagesPerSum {
   966  			end += 1 << logMaxPagesPerSum
   967  		} else {
   968  			end = ei
   969  		}
   970  	}
   971  	return packPallocSum(start, max, end)
   972  }
   973  

View as plain text