package bbolt

import (
	
	
	
	
	
	
	
	

	berrors 
	
	fl 
)

// The time elapsed between consecutive file locking attempts.
const flockRetryTimeout = 50 * time.Millisecond

// FreelistType is the type of the freelist backend
type FreelistType string

// TODO(ahrtr): eventually we should (step by step)
//  1. default to `FreelistMapType`;
//  2. remove the `FreelistArrayType`, do not export `FreelistMapType`
//     and remove field `FreelistType' from both `DB` and `Options`;
const (
	// FreelistArrayType indicates backend freelist type is array
	FreelistArrayType = FreelistType("array")
	// FreelistMapType indicates backend freelist type is hashmap
	FreelistMapType = FreelistType("hashmap")
)

// DB represents a collection of buckets persisted to a file on disk.
// All data access is performed through transactions which can be obtained through the DB.
// All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called.
type DB struct {
	// When enabled, the database will perform a Check() after every commit.
	// A panic is issued if the database is in an inconsistent state. This
	// flag has a large performance impact so it should only be used for
	// debugging purposes.
	StrictMode bool

	// Setting the NoSync flag will cause the database to skip fsync()
	// calls after each commit. This can be useful when bulk loading data
	// into a database and you can restart the bulk load in the event of
	// a system failure or database corruption. Do not set this flag for
	// normal use.
	//
	// If the package global IgnoreNoSync constant is true, this value is
	// ignored.  See the comment on that constant for more details.
	//
	// THIS IS UNSAFE. PLEASE USE WITH CAUTION.
	NoSync bool

	// When true, skips syncing freelist to disk. This improves the database
	// write performance under normal operation, but requires a full database
	// re-sync during recovery.
	NoFreelistSync bool

	// FreelistType sets the backend freelist type. There are two options. Array which is simple but endures
	// dramatic performance degradation if database is large and fragmentation in freelist is common.
	// The alternative one is using hashmap, it is faster in almost all circumstances
	// but it doesn't guarantee that it offers the smallest page id available. In normal case it is safe.
	// The default type is array
	FreelistType FreelistType

	// When true, skips the truncate call when growing the database.
	// Setting this to true is only safe on non-ext3/ext4 systems.
	// Skipping truncation avoids preallocation of hard drive space and
	// bypasses a truncate() and fsync() syscall on remapping.
	//
	// https://github.com/boltdb/bolt/issues/284
	NoGrowSync bool

	// When `true`, bbolt will always load the free pages when opening the DB.
	// When opening db in write mode, this flag will always automatically
	// set to `true`.
	PreLoadFreelist bool

	// If you want to read the entire database fast, you can set MmapFlag to
	// syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead.
	MmapFlags int

	// MaxBatchSize is the maximum size of a batch. Default value is
	// copied from DefaultMaxBatchSize in Open.
	//
	// If <=0, disables batching.
	//
	// Do not change concurrently with calls to Batch.
	MaxBatchSize int

	// MaxBatchDelay is the maximum delay before a batch starts.
	// Default value is copied from DefaultMaxBatchDelay in Open.
	//
	// If <=0, effectively disables batching.
	//
	// Do not change concurrently with calls to Batch.
	MaxBatchDelay time.Duration

	// AllocSize is the amount of space allocated when the database
	// needs to create new pages. This is done to amortize the cost
	// of truncate() and fsync() when growing the data file.
	AllocSize int

	// MaxSize is the maximum size (in bytes) allowed for the data file.
	// If a caller's attempt to add data results in the need to grow
	// the data file, an error will be returned and the data file will not grow.
	// <=0 means no limit.
	MaxSize int

	// Mlock locks database file in memory when set to true.
	// It prevents major page faults, however used memory can't be reclaimed.
	//
	// Supported only on Unix via mlock/munlock syscalls.
	Mlock bool

	logger Logger

	path     string
	openFile func(string, int, os.FileMode) (*os.File, error)
	file     *os.File
	// `dataref` isn't used at all on Windows, and the golangci-lint
	// always fails on Windows platform.
	//nolint
	dataref  []byte // mmap'ed readonly, write throws SEGV
	data     *[common.MaxMapSize]byte
	datasz   int
	meta0    *common.Meta
	meta1    *common.Meta
	pageSize int
	opened   bool
	rwtx     *Tx
	stats    *Stats

	freelist     fl.Interface
	freelistLoad sync.Once

	pagePool sync.Pool

	batchMu sync.Mutex
	batch   *batch

	rwlock   sync.Mutex   // Allows only one writer at a time.
	metalock sync.Mutex   // Protects meta page access.
	mmaplock sync.RWMutex // Protects mmap access during remapping.
	statlock sync.RWMutex // Protects stats access.

	ops struct {
		writeAt func(b []byte, off int64) (n int, err error)
	}

	// Read only mode.
	// When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately.
	readOnly bool
}

// Path returns the path to currently open database file.
func ( *DB) () string {
	return .path
}

// GoString returns the Go string representation of the database.
func ( *DB) () string {
	return fmt.Sprintf("bolt.DB{path:%q}", .path)
}

// String returns the string representation of the database.
func ( *DB) () string {
	return fmt.Sprintf("DB<%q>", .path)
}

// Open creates and opens a database at the given path with a given file mode.
// If the file does not exist then it will be created automatically with a given file mode.
// Passing in nil options will cause Bolt to open the database with the default options.
// Note: For read/write transactions, ensure the owner has write permission on the created/opened database file, e.g. 0600
func ( string,  os.FileMode,  *Options) ( *DB,  error) {
	 = &DB{
		opened: true,
	}

	// Set default options if no options are provided.
	if  == nil {
		 = DefaultOptions
	}
	.NoSync = .NoSync
	.NoGrowSync = .NoGrowSync
	.MmapFlags = .MmapFlags
	.NoFreelistSync = .NoFreelistSync
	.PreLoadFreelist = .PreLoadFreelist
	.FreelistType = .FreelistType
	.Mlock = .Mlock
	.MaxSize = .MaxSize

	// Set default values for later DB operations.
	.MaxBatchSize = common.DefaultMaxBatchSize
	.MaxBatchDelay = common.DefaultMaxBatchDelay
	.AllocSize = common.DefaultAllocSize

	if !.NoStatistics {
		.stats = new(Stats)
	}

	if .Logger == nil {
		.logger = getDiscardLogger()
	} else {
		.logger = .Logger
	}

	 := .Logger()
	if  != discardLogger {
		.Infof("Opening db file (%s) with mode %s and with options: %s", , , )
		defer func() {
			if  != nil {
				.Errorf("Opening bbolt db (%s) failed: %v", , )
			} else {
				.Infof("Opening bbolt db (%s) successfully", )
			}
		}()
	}

	 := os.O_RDWR
	if .ReadOnly {
		 = os.O_RDONLY
		.readOnly = true
	} else {
		// always load free pages in write mode
		.PreLoadFreelist = true
		 |= os.O_CREATE
	}

	.openFile = .OpenFile
	if .openFile == nil {
		.openFile = os.OpenFile
	}

	// Open data file and separate sync handler for metadata writes.
	if .file,  = .openFile(, , );  != nil {
		_ = .close()
		.Errorf("failed to open db file (%s): %v", , )
		return nil, 
	}
	.path = .file.Name()

	// Lock file so that other processes using Bolt in read-write mode cannot
	// use the database  at the same time. This would cause corruption since
	// the two processes would write meta pages and free pages separately.
	// The database file is locked exclusively (only one process can grab the lock)
	// if !options.ReadOnly.
	// The database file is locked using the shared lock (more than one process may
	// hold a lock at the same time) otherwise (options.ReadOnly is set).
	if  = flock(, !.readOnly, .Timeout);  != nil {
		_ = .close()
		.Errorf("failed to lock db file (%s), readonly: %t, error: %v", , .readOnly, )
		return nil, 
	}

	// Default values for test hooks
	.ops.writeAt = .file.WriteAt

	if .pageSize = .PageSize; .pageSize == 0 {
		// Set the default page size to the OS page size.
		.pageSize = common.DefaultPageSize
	}

	// Initialize the database if it doesn't exist.
	if ,  := .file.Stat();  != nil {
		_ = .close()
		.Errorf("failed to get db file's stats (%s): %v", , )
		return nil, 
	} else if .Size() == 0 {
		// Initialize new files with meta pages.
		if  = .init();  != nil {
			// clean up file descriptor on initialization fail
			_ = .close()
			.Errorf("failed to initialize db file (%s): %v", , )
			return nil, 
		}
	} else {
		// try to get the page size from the metadata pages
		if .pageSize,  = .getPageSize();  != nil {
			_ = .close()
			.Errorf("failed to get page size from db file (%s): %v", , )
			return nil, 
		}
	}

	// Initialize page pool.
	.pagePool = sync.Pool{
		New: func() interface{} {
			return make([]byte, .pageSize)
		},
	}

	// Memory map the data file.
	if  = .mmap(.InitialMmapSize);  != nil {
		_ = .close()
		.Errorf("failed to map db file (%s): %v", , )
		return nil, 
	}

	if .PreLoadFreelist {
		.loadFreelist()
	}

	if .readOnly {
		return , nil
	}

	// Flush freelist when transitioning from no sync to sync so
	// NoFreelistSync unaware boltdb can open the db later.
	if !.NoFreelistSync && !.hasSyncedFreelist() {
		,  := .Begin(true)
		if  != nil {
			 = .Commit()
		}
		if  != nil {
			.Errorf("starting readwrite transaction failed: %v", )
			_ = .close()
			return nil, 
		}
	}

	// Mark the database as opened and return.
	return , nil
}

// getPageSize reads the pageSize from the meta pages. It tries
// to read the first meta page firstly. If the first page is invalid,
// then it tries to read the second page using the default page size.
func ( *DB) () (int, error) {
	var (
		,  bool
	)

	// Read the first meta page to determine the page size.
	if , ,  := .getPageSizeFromFirstMeta();  != nil {
		// We cannot read the page size from page 0, but can read page 0.
		 = 
	} else {
		return , nil
	}

	// Read the second meta page to determine the page size.
	if , ,  := .getPageSizeFromSecondMeta();  != nil {
		// We cannot read the page size from page 1, but can read page 1.
		 = 
	} else {
		return , nil
	}

	// If we can't read the page size from both pages, but can read
	// either page, then we assume it's the same as the OS or the one
	// given, since that's how the page size was chosen in the first place.
	//
	// If both pages are invalid, and (this OS uses a different page size
	// from what the database was created with or the given page size is
	// different from what the database was created with), then we are out
	// of luck and cannot access the database.
	if  ||  {
		return .pageSize, nil
	}

	return 0, berrors.ErrInvalid
}

// getPageSizeFromFirstMeta reads the pageSize from the first meta page
func ( *DB) () (int, bool, error) {
	var  [0x1000]byte
	var  bool
	if ,  := .file.ReadAt([:], 0);  == nil &&  == len() {
		 = true
		if  := .pageInBuffer([:], 0).Meta(); .Validate() == nil {
			return int(.PageSize()), , nil
		}
	}
	return 0, , berrors.ErrInvalid
}

// getPageSizeFromSecondMeta reads the pageSize from the second meta page
func ( *DB) () (int, bool, error) {
	var (
		    int64
		 bool
	)

	// get the db file size
	if ,  := .file.Stat();  != nil {
		return 0, , 
	} else {
		 = .Size()
	}

	// We need to read the second meta page, so we should skip the first page;
	// but we don't know the exact page size yet, it's chicken & egg problem.
	// The solution is to try all the possible page sizes, which starts from 1KB
	// and until 16MB (1024<<14) or the end of the db file
	//
	// TODO: should we support larger page size?
	for  := 0;  <= 14; ++ {
		var  [0x1000]byte
		var  int64 = 1024 << uint()
		if  >= -1024 {
			break
		}
		,  := .file.ReadAt([:], )
		if ( == nil &&  == len()) || ( == io.EOF && int64() == (-)) {
			 = true
			if  := .pageInBuffer([:], 0).Meta(); .Validate() == nil {
				return int(.PageSize()), , nil
			}
		}
	}

	return 0, , berrors.ErrInvalid
}

// loadFreelist reads the freelist if it is synced, or reconstructs it
// by scanning the DB if it is not synced. It assumes there are no
// concurrent accesses being made to the freelist.
func ( *DB) () {
	.freelistLoad.Do(func() {
		.freelist = newFreelist(.FreelistType)
		if !.hasSyncedFreelist() {
			// Reconstruct free list by scanning the DB.
			.freelist.Init(.freepages())
		} else {
			// Read free list from freelist page.
			.freelist.Read(.page(.meta().Freelist()))
		}
		if .stats != nil {
			.stats.FreePageN = .freelist.FreeCount()
		}
	})
}

func ( *DB) () bool {
	return .meta().Freelist() != common.PgidNoFreelist
}

func ( *DB) () (int, error) {
	,  := .file.Stat()
	if  != nil {
		return 0, fmt.Errorf("file stat error: %w", )
	}
	 := int(.Size())
	if  < .pageSize*2 {
		return 0, fmt.Errorf("file size too small %d", )
	}
	return , nil
}

// mmap opens the underlying memory-mapped file and initializes the meta references.
// minsz is the minimum size that the new mmap can be.
func ( *DB) ( int) ( error) {
	.mmaplock.Lock()
	defer .mmaplock.Unlock()

	 := .Logger()

	// Ensure the size is at least the minimum size.
	var  int
	,  = .fileSize()
	if  != nil {
		.Errorf("getting file size failed: %w", )
		return 
	}
	var  = 
	if  <  {
		 = 
	}
	,  = .mmapSize()
	if  != nil {
		.Errorf("getting map size failed: %w", )
		return 
	}

	if .MaxSize > 0 &&  > .MaxSize {
		// On Windows, the data file is expanded to the full mapped size during mmap,
		// so we must reject any mmap size larger than the configured max size.
		//
		// On other platforms, mmap itself does not grow the file immediately, so the
		// mapped size may exceed the max size temporarily. The file size limit is
		// enforced later when the file actually grows.
		//
		// In practice, this check mainly applies when opening a database with a large
		// InitialMmapSize. In all other cases, file growth is already guarded during
		// page allocation.
		if  >  && runtime.GOOS == "windows" {
			.Logger().Errorf("[GOOS: %s, GOARCH: %s] maximum db size reached, size: %d, db.MaxSize: %d", runtime.GOOS, runtime.GOARCH, , .MaxSize)
			return berrors.ErrMaxSizeReached
		}
	}

	if .Mlock {
		// Unlock db memory
		if  := .munlock();  != nil {
			return 
		}
	}

	// Dereference all mmap references before unmapping.
	if .rwtx != nil {
		.rwtx.root.dereference()
	}

	// Unmap existing data before continuing.
	if  = .munmap();  != nil {
		return 
	}

	// Memory-map the data file as a byte slice.
	// gofail: var mapError string
	// return errors.New(mapError)
	if  = mmap(, );  != nil {
		.Errorf("[GOOS: %s, GOARCH: %s] mmap failed, size: %d, error: %v", runtime.GOOS, runtime.GOARCH, , )
		return 
	}

	// Perform unmmap on any error to reset all data fields:
	// dataref, data, datasz, meta0 and meta1.
	defer func() {
		if  != nil {
			if  := .munmap();  != nil {
				 = fmt.Errorf("%w; rollback unmap also failed: %v", , )
			}
		}
	}()

	if .Mlock {
		// Don't allow swapping of data file
		if  := .mlock();  != nil {
			return 
		}
	}

	// Save references to the meta pages.
	.meta0 = .page(0).Meta()
	.meta1 = .page(1).Meta()

	// Validate the meta pages. We only return an error if both meta pages fail
	// validation, since meta0 failing validation means that it wasn't saved
	// properly -- but we can recover using meta1. And vice-versa.
	 := .meta0.Validate()
	 := .meta1.Validate()
	if  != nil &&  != nil {
		.Errorf("both meta pages are invalid, meta0: %v, meta1: %v", , )
		return 
	}

	return nil
}

func ( *DB) () {
	.dataref = nil
	.data = nil
	.datasz = 0

	.meta0 = nil
	.meta1 = nil
}

// munmap unmaps the data file from memory.
func ( *DB) () error {
	defer .invalidate()

	// gofail: var unmapError string
	// return errors.New(unmapError)
	if  := munmap();  != nil {
		.Logger().Errorf("[GOOS: %s, GOARCH: %s] munmap failed, db.datasz: %d, error: %v", runtime.GOOS, runtime.GOARCH, .datasz, )
		return fmt.Errorf("unmap error: %w", )
	}

	return nil
}

// mmapSize determines the appropriate size for the mmap given the current size
// of the database. The minimum size is 32KB and doubles until it reaches 1GB.
// Returns an error if the new mmap size is greater than the max allowed.
func ( *DB) ( int) (int, error) {
	// Double the size from 32KB until 1GB.
	for  := uint(15);  <= 30; ++ {
		if  <= 1<< {
			return 1 << , nil
		}
	}

	// Verify the requested size is not above the maximum allowed.
	if  > common.MaxMapSize {
		return 0, errors.New("mmap too large")
	}

	// If larger than 1GB then grow by 1GB at a time.
	 := int64()
	if  :=  % int64(common.MaxMmapStep);  > 0 {
		 += int64(common.MaxMmapStep) - 
	}

	// Ensure that the mmap size is a multiple of the page size.
	// This should always be true since we're incrementing in MBs.
	 := int64(.pageSize)
	if ( % ) != 0 {
		 = (( / ) + 1) * 
	}

	// If we've exceeded the max size then only grow up to the max size.
	if  > common.MaxMapSize {
		 = common.MaxMapSize
	}

	return int(), nil
}

func ( *DB) ( int) error {
	// gofail: var munlockError string
	// return errors.New(munlockError)
	if  := munlock(, );  != nil {
		.Logger().Errorf("[GOOS: %s, GOARCH: %s] munlock failed, fileSize: %d, db.datasz: %d, error: %v", runtime.GOOS, runtime.GOARCH, , .datasz, )
		return fmt.Errorf("munlock error: %w", )
	}
	return nil
}

func ( *DB) ( int) error {
	// gofail: var mlockError string
	// return errors.New(mlockError)
	if  := mlock(, );  != nil {
		.Logger().Errorf("[GOOS: %s, GOARCH: %s] mlock failed, fileSize: %d, db.datasz: %d, error: %v", runtime.GOOS, runtime.GOARCH, , .datasz, )
		return fmt.Errorf("mlock error: %w", )
	}
	return nil
}

func ( *DB) (,  int) error {
	if  := .munlock();  != nil {
		return 
	}
	if  := .mlock();  != nil {
		return 
	}
	return nil
}

// init creates a new database file and initializes its meta pages.
func ( *DB) () error {
	// Create two meta pages on a buffer.
	 := make([]byte, .pageSize*4)
	for  := 0;  < 2; ++ {
		 := .pageInBuffer(, common.Pgid())
		.SetId(common.Pgid())
		.SetFlags(common.MetaPageFlag)

		// Initialize the meta page.
		 := .Meta()
		.SetMagic(common.Magic)
		.SetVersion(common.Version)
		.SetPageSize(uint32(.pageSize))
		.SetFreelist(2)
		.SetRootBucket(common.NewInBucket(3, 0))
		.SetPgid(4)
		.SetTxid(common.Txid())
		.SetChecksum(.Sum64())
	}

	// Write an empty freelist at page 3.
	 := .pageInBuffer(, common.Pgid(2))
	.SetId(2)
	.SetFlags(common.FreelistPageFlag)
	.SetCount(0)

	// Write an empty leaf page at page 4.
	 = .pageInBuffer(, common.Pgid(3))
	.SetId(3)
	.SetFlags(common.LeafPageFlag)
	.SetCount(0)

	// Write the buffer to our data file.
	if ,  := .ops.writeAt(, 0);  != nil {
		.Logger().Errorf("writeAt failed: %w", )
		return 
	}
	if  := fdatasync();  != nil {
		.Logger().Errorf("[GOOS: %s, GOARCH: %s] fdatasync failed: %w", runtime.GOOS, runtime.GOARCH, )
		return 
	}

	return nil
}

// Close releases all database resources.
// It will block waiting for any open transactions to finish
// before closing the database and returning.
func ( *DB) () error {
	.rwlock.Lock()
	defer .rwlock.Unlock()

	.metalock.Lock()
	defer .metalock.Unlock()

	.mmaplock.Lock()
	defer .mmaplock.Unlock()

	return .close()
}

func ( *DB) () error {
	if !.opened {
		return nil
	}

	.opened = false

	.freelist = nil

	// Clear ops.
	.ops.writeAt = nil

	var  []error
	// Close the mmap.
	if  := .munmap();  != nil {
		 = append(, )
	}

	// Close file handles.
	if .file != nil {
		// No need to unlock read-only file.
		if !.readOnly {
			// Unlock the file.
			if  := funlock();  != nil {
				 = append(, fmt.Errorf("bolt.Close(): funlock error: %w", ))
			}
		}

		// Close the file descriptor.
		if  := .file.Close();  != nil {
			 = append(, fmt.Errorf("db file close: %w", ))
		}
		.file = nil
	}

	.path = ""

	if len() > 0 {
		return [0]
	}
	return nil
}

// Begin starts a new transaction.
// Multiple read-only transactions can be used concurrently but only one
// write transaction can be used at a time. Starting multiple write transactions
// will cause the calls to block and be serialized until the current write
// transaction finishes.
//
// Transactions should not be dependent on one another. Opening a read
// transaction and a write transaction in the same goroutine can cause the
// writer to deadlock because the database periodically needs to re-mmap itself
// as it grows and it cannot do that while a read transaction is open.
//
// If a long running read transaction (for example, a snapshot transaction) is
// needed, you might want to set DB.InitialMmapSize to a large enough value
// to avoid potential blocking of write transaction.
//
// IMPORTANT: You must close read-only transactions after you are finished or
// else the database will not reclaim old pages.
func ( *DB) ( bool) ( *Tx,  error) {
	if  := .Logger();  != discardLogger {
		.Debugf("Starting a new transaction [writable: %t]", )
		defer func() {
			if  != nil {
				.Errorf("Starting a new transaction [writable: %t] failed: %v", , )
			} else {
				.Debugf("Starting a new transaction [writable: %t] successfully", )
			}
		}()
	}

	if  {
		return .beginRWTx()
	}
	return .beginTx()
}

func ( *DB) () Logger {
	if  == nil || .logger == nil {
		return getDiscardLogger()
	}
	return .logger
}

func ( *DB) () (*Tx, error) {
	// Lock the meta pages while we initialize the transaction. We obtain
	// the meta lock before the mmap lock because that's the order that the
	// write transaction will obtain them.
	.metalock.Lock()

	// Obtain a read-only lock on the mmap. When the mmap is remapped it will
	// obtain a write lock so all transactions must finish before it can be
	// remapped.
	.mmaplock.RLock()

	// Exit if the database is not open yet.
	if !.opened {
		.mmaplock.RUnlock()
		.metalock.Unlock()
		return nil, berrors.ErrDatabaseNotOpen
	}

	// Exit if the database is not correctly mapped.
	if .data == nil {
		.mmaplock.RUnlock()
		.metalock.Unlock()
		return nil, berrors.ErrInvalidMapping
	}

	// Create a transaction associated with the database.
	 := &Tx{}
	.init()

	if .freelist != nil {
		.freelist.AddReadonlyTXID(.meta.Txid())
	}

	// Unlock the meta pages.
	.metalock.Unlock()

	// Update the transaction stats.
	if .stats != nil {
		.statlock.Lock()
		.stats.TxN++
		.stats.OpenTxN++
		.statlock.Unlock()
	}

	return , nil
}

func ( *DB) () (*Tx, error) {
	// If the database was opened with Options.ReadOnly, return an error.
	if .readOnly {
		return nil, berrors.ErrDatabaseReadOnly
	}

	// Obtain writer lock. This is released by the transaction when it closes.
	// This enforces only one writer transaction at a time.
	.rwlock.Lock()

	// Once we have the writer lock then we can lock the meta pages so that
	// we can set up the transaction.
	.metalock.Lock()
	defer .metalock.Unlock()

	// Exit if the database is not open yet.
	if !.opened {
		.rwlock.Unlock()
		return nil, berrors.ErrDatabaseNotOpen
	}

	// Exit if the database is not correctly mapped.
	if .data == nil {
		.rwlock.Unlock()
		return nil, berrors.ErrInvalidMapping
	}

	// Create a transaction associated with the database.
	 := &Tx{writable: true}
	.init()
	.rwtx = 
	.freelist.ReleasePendingPages()
	return , nil
}

// removeTx removes a transaction from the database.
func ( *DB) ( *Tx) {
	// Release the read lock on the mmap.
	.mmaplock.RUnlock()

	// Use the meta lock to restrict access to the DB object.
	.metalock.Lock()

	if .freelist != nil {
		.freelist.RemoveReadonlyTXID(.meta.Txid())
	}

	// Unlock the meta pages.
	.metalock.Unlock()

	// Merge statistics.
	if .stats != nil {
		.statlock.Lock()
		.stats.OpenTxN--
		.stats.TxStats.add(&.stats)
		.statlock.Unlock()
	}
}

// Update executes a function within the context of a read-write managed transaction.
// If no error is returned from the function then the transaction is committed.
// If an error is returned then the entire transaction is rolled back.
// Any error that is returned from the function or returned from the commit is
// returned from the Update() method.
//
// Attempting to manually commit or rollback within the function will cause a panic.
func ( *DB) ( func(*Tx) error) error {
	,  := .Begin(true)
	if  != nil {
		return 
	}

	// Make sure the transaction rolls back in the event of a panic.
	defer func() {
		if .db != nil {
			.rollback()
		}
	}()

	// Mark as a managed tx so that the inner function cannot manually commit.
	.managed = true

	// If an error is returned from the function then rollback and return error.
	 = ()
	.managed = false
	if  != nil {
		_ = .Rollback()
		return 
	}

	return .Commit()
}

// View executes a function within the context of a managed read-only transaction.
// Any error that is returned from the function is returned from the View() method.
//
// Attempting to manually rollback within the function will cause a panic.
func ( *DB) ( func(*Tx) error) error {
	,  := .Begin(false)
	if  != nil {
		return 
	}

	// Make sure the transaction rolls back in the event of a panic.
	defer func() {
		if .db != nil {
			.rollback()
		}
	}()

	// Mark as a managed tx so that the inner function cannot manually rollback.
	.managed = true

	// If an error is returned from the function then pass it through.
	 = ()
	.managed = false
	if  != nil {
		_ = .Rollback()
		return 
	}

	return .Rollback()
}

// Batch calls fn as part of a batch. It behaves similar to Update,
// except:
//
// 1. concurrent Batch calls can be combined into a single Bolt
// transaction.
//
// 2. the function passed to Batch may be called multiple times,
// regardless of whether it returns error or not.
//
// This means that Batch function side effects must be idempotent and
// take permanent effect only after a successful return is seen in
// caller.
//
// The maximum batch size and delay can be adjusted with DB.MaxBatchSize
// and DB.MaxBatchDelay, respectively.
//
// Batch is only useful when there are multiple goroutines calling it.
func ( *DB) ( func(*Tx) error) error {
	 := make(chan error, 1)

	.batchMu.Lock()
	if (.batch == nil) || (.batch != nil && len(.batch.calls) >= .MaxBatchSize) {
		// There is no existing batch, or the existing batch is full; start a new one.
		.batch = &batch{
			db: ,
		}
		.batch.timer = time.AfterFunc(.MaxBatchDelay, .batch.trigger)
	}
	.batch.calls = append(.batch.calls, call{fn: , err: })
	if len(.batch.calls) >= .MaxBatchSize {
		// wake up batch, it's ready to run
		go .batch.trigger()
	}
	.batchMu.Unlock()

	 := <-
	if  == trySolo {
		 = .Update()
	}
	return 
}

type call struct {
	fn  func(*Tx) error
	err chan<- error
}

type batch struct {
	db    *DB
	timer *time.Timer
	start sync.Once
	calls []call
}

// trigger runs the batch if it hasn't already been run.
func ( *batch) () {
	.start.Do(.run)
}

// run performs the transactions in the batch and communicates results
// back to DB.Batch.
func ( *batch) () {
	.db.batchMu.Lock()
	.timer.Stop()
	// Make sure no new work is added to this batch, but don't break
	// other batches.
	if .db.batch ==  {
		.db.batch = nil
	}
	.db.batchMu.Unlock()

:
	for len(.calls) > 0 {
		var  = -1
		 := .db.Update(func( *Tx) error {
			for ,  := range .calls {
				if  := safelyCall(.fn, );  != nil {
					 = 
					return 
				}
			}
			return nil
		})

		if  >= 0 {
			// take the failing transaction out of the batch. it's
			// safe to shorten b.calls here because db.batch no longer
			// points to us, and we hold the mutex anyway.
			 := .calls[]
			.calls[], .calls = .calls[len(.calls)-1], .calls[:len(.calls)-1]
			// tell the submitter re-run it solo, continue with the rest of the batch
			.err <- trySolo
			continue 
		}

		// pass success, or bolt internal errors, to all callers
		for ,  := range .calls {
			.err <- 
		}
		break 
	}
}

// trySolo is a special sentinel error value used for signaling that a
// transaction function should be re-run. It should never be seen by
// callers.
var trySolo = errors.New("batch function returned an error and should be re-run solo")

type panicked struct {
	reason interface{}
}

func ( panicked) () string {
	if ,  := .reason.(error);  {
		return .Error()
	}
	return fmt.Sprintf("panic: %v", .reason)
}

func safelyCall( func(*Tx) error,  *Tx) ( error) {
	defer func() {
		if  := recover();  != nil {
			 = panicked{}
		}
	}()
	return ()
}

// Sync executes fdatasync() against the database file handle.
//
// This is not necessary under normal operation, however, if you use NoSync
// then it allows you to force the database file to sync against the disk.
func ( *DB) () ( error) {
	if  := .Logger();  != discardLogger {
		.Debugf("Syncing bbolt db (%s)", .path)
		defer func() {
			if  != nil {
				.Errorf("[GOOS: %s, GOARCH: %s] syncing bbolt db (%s) failed: %v", runtime.GOOS, runtime.GOARCH, .path, )
			} else {
				.Debugf("Syncing bbolt db (%s) successfully", .path)
			}
		}()
	}

	return fdatasync()
}

// Stats retrieves ongoing performance stats for the database.
// This is only updated when a transaction closes.
func ( *DB) () Stats {
	var  Stats
	if .stats != nil {
		.statlock.RLock()
		 = *.stats
		.statlock.RUnlock()
	}
	return 
}

// This is for internal access to the raw data bytes from the C cursor, use
// carefully, or not at all.
func ( *DB) () *Info {
	common.Assert(.data != nil, "database file isn't correctly mapped")
	return &Info{uintptr(unsafe.Pointer(&.data[0])), .pageSize}
}

// page retrieves a page reference from the mmap based on the current page size.
func ( *DB) ( common.Pgid) *common.Page {
	 :=  * common.Pgid(.pageSize)
	return (*common.Page)(unsafe.Pointer(&.data[]))
}

// pageInBuffer retrieves a page reference from a given byte array based on the current page size.
func ( *DB) ( []byte,  common.Pgid) *common.Page {
	return (*common.Page)(unsafe.Pointer(&[*common.Pgid(.pageSize)]))
}

// meta retrieves the current meta page reference.
func ( *DB) () *common.Meta {
	// We have to return the meta with the highest txid which doesn't fail
	// validation. Otherwise, we can cause errors when in fact the database is
	// in a consistent state. metaA is the one with the higher txid.
	 := .meta0
	 := .meta1
	if .meta1.Txid() > .meta0.Txid() {
		 = .meta1
		 = .meta0
	}

	// Use higher meta page if valid. Otherwise, fallback to previous, if valid.
	if  := .Validate();  == nil {
		return 
	} else if  := .Validate();  == nil {
		return 
	}

	// This should never be reached, because both meta1 and meta0 were validated
	// on mmap() and we do fsync() on every write.
	panic("bolt.DB.meta(): invalid meta pages")
}

// allocate returns a contiguous block of memory starting at a given page.
func ( *DB) ( common.Txid,  int) (*common.Page, error) {
	// Allocate a temporary buffer for the page.
	var  []byte
	if  == 1 {
		 = .pagePool.Get().([]byte)
	} else {
		 = make([]byte, *.pageSize)
	}
	 := (*common.Page)(unsafe.Pointer(&[0]))
	.SetOverflow(uint32( - 1))

	// Use pages from the freelist if they are available.
	.SetId(.freelist.Allocate(, ))
	if .Id() != 0 {
		return , nil
	}

	// Resize mmap() if we're at the end.
	.SetId(.rwtx.meta.Pgid())
	var  = int((.Id()+common.Pgid())+1) * .pageSize
	if .MaxSize > 0 {
		 := 
		,  := .mmapSize()
		if  != nil {
			return nil, fmt.Errorf("mmap size calculation error: %w", )
		}
		if runtime.GOOS == "windows" {
			// nextAllocSize may not exactly match nextMmapSize.
			// On Windows, this mismatch may cause the file size to slightly exceed maxSize,
			// while it is harmless on other platforms.
			 = 
		} else {
			// On non-Windows platforms, the database file is only grown explicitly in grow calls.
			 = .growSize(, )
		}
		if  > .MaxSize {
			.Logger().Errorf("[GOOS: %s, GOARCH: %s] maximum db size reached, minSize: %d (allocSize: %d), db.MaxSize: %d", runtime.GOOS, runtime.GOARCH, , , .MaxSize)
			return nil, berrors.ErrMaxSizeReached
		}
	}
	if  >= .datasz {
		if  := .mmap();  != nil {
			if  == berrors.ErrMaxSizeReached {
				return nil, 
			} else {
				return nil, fmt.Errorf("mmap allocate error: %s", )
			}
		}
	}

	// Move the page id high water mark.
	 := .rwtx.meta.Pgid()
	.rwtx.meta.SetPgid( + common.Pgid())

	return , nil
}

// grow grows the size of the database to the given sz.
func ( *DB) ( int) error {
	// Ignore if the new size is less than available file size.
	 := .Logger()
	,  := .fileSize()
	if  != nil {
		.Errorf("getting file size failed: %w", )
		return 
	}
	if  <=  {
		return nil
	}

	 = .growSize(.datasz, )

	// Truncate and fsync to ensure file size metadata is flushed.
	// https://github.com/boltdb/bolt/issues/284
	if !.NoGrowSync && !.readOnly {
		if runtime.GOOS != "windows" {
			// gofail: var resizeFileError string
			// return errors.New(resizeFileError)
			if  := .file.Truncate(int64());  != nil {
				.Errorf("[GOOS: %s, GOARCH: %s] truncating file failed, size: %d, db.datasz: %d, error: %v", runtime.GOOS, runtime.GOARCH, , .datasz, )
				return fmt.Errorf("file resize error: %s", )
			}
		}
		if  := .file.Sync();  != nil {
			.Errorf("[GOOS: %s, GOARCH: %s] syncing file failed, db.datasz: %d, error: %v", runtime.GOOS, runtime.GOARCH, .datasz, )
			return fmt.Errorf("file sync error: %s", )
		}
		if .Mlock {
			// unlock old file and lock new one
			if  := .mrelock(, );  != nil {
				return fmt.Errorf("mlock/munlock error: %s", )
			}
		}
	}

	return nil
}

func ( *DB) (,  int) int {
	// If the data is smaller than the alloc size then only allocate what's needed.
	// Once it goes over the allocation size then allocate in chunks.
	if  <= .AllocSize {
		return 
	} else {
		return  + .AllocSize
	}
}

func ( *DB) () bool {
	return .readOnly
}

func ( *DB) () []common.Pgid {
	,  := .beginTx()
	defer func() {
		 = .Rollback()
		if  != nil {
			panic("freepages: failed to rollback tx")
		}
	}()
	if  != nil {
		panic("freepages: failed to open read only tx")
	}

	 := make(map[common.Pgid]*common.Page)
	 := make(map[common.Pgid]bool)
	 := make(chan error)

	go func() {
		defer close()
		.recursivelyCheckBucket(&.root, , , HexKVStringer(), )
	}()
	// following for loop will exit once channel is closed in the above goroutine.
	// we don't need to wait explictly with a waitgroup
	for  := range  {
		panic(fmt.Sprintf("freepages: failed to get all reachable pages (%v)", ))
	}

	// TODO: If check bucket reported any corruptions (ech) we shouldn't proceed to freeing the pages.

	var  []common.Pgid
	for  := common.Pgid(2);  < .meta().Pgid(); ++ {
		if ,  := []; ! {
			 = append(, )
		}
	}
	return 
}

func newFreelist( FreelistType) fl.Interface {
	if  == FreelistMapType {
		return fl.NewHashMapFreelist()
	}
	return fl.NewArrayFreelist()
}

// Options represents the options that can be set when opening a database.
type Options struct {
	// Timeout is the amount of time to wait to obtain a file lock.
	// When set to zero it will wait indefinitely.
	Timeout time.Duration

	// Sets the DB.NoGrowSync flag before memory mapping the file.
	NoGrowSync bool

	// Do not sync freelist to disk. This improves the database write performance
	// under normal operation, but requires a full database re-sync during recovery.
	NoFreelistSync bool

	// PreLoadFreelist sets whether to load the free pages when opening
	// the db file. Note when opening db in write mode, bbolt will always
	// load the free pages.
	PreLoadFreelist bool

	// FreelistType sets the backend freelist type. There are two options. Array which is simple but endures
	// dramatic performance degradation if database is large and fragmentation in freelist is common.
	// The alternative one is using hashmap, it is faster in almost all circumstances
	// but it doesn't guarantee that it offers the smallest page id available. In normal case it is safe.
	// The default type is array
	FreelistType FreelistType

	// Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to
	// grab a shared lock (UNIX).
	ReadOnly bool

	// Sets the DB.MmapFlags flag before memory mapping the file.
	MmapFlags int

	// InitialMmapSize is the initial mmap size of the database
	// in bytes. Read transactions won't block write transaction
	// if the InitialMmapSize is large enough to hold database mmap
	// size. (See DB.Begin for more information)
	//
	// If <=0, the initial map size is 0.
	// If initialMmapSize is smaller than the previous database size,
	// it takes no effect.
	//
	// Note: On Windows, due to platform limitations, the database file size
	// will be immediately resized to match `InitialMmapSize` (aligned to page size)
	// when the DB is opened. On non-Windows platforms, the file size will grow
	// dynamically based on the actual amount of written data, regardless of `InitialMmapSize`.
	// Refer to https://github.com/etcd-io/bbolt/issues/378#issuecomment-1378121966.
	InitialMmapSize int

	// PageSize overrides the default OS page size.
	PageSize int

	// MaxSize sets the maximum size of the data file. A value <= 0 means no limit.
	MaxSize int

	// NoSync sets the initial value of DB.NoSync. Normally this can just be
	// set directly on the DB itself when returned from Open(), but this option
	// is useful in APIs which expose Options but not the underlying DB.
	NoSync bool

	// OpenFile is used to open files. It defaults to os.OpenFile. This option
	// is useful for writing hermetic tests.
	OpenFile func(string, int, os.FileMode) (*os.File, error)

	// Mlock locks database file in memory when set to true.
	// It prevents potential page faults, however
	// used memory can't be reclaimed. (UNIX only)
	Mlock bool

	// Logger is the logger used for bbolt.
	Logger Logger

	// NoStatistics turns off statistics collection, Stats method will
	// return empty structure in this case. This can be beneficial for
	// performance under high-concurrency read-only transactions.
	NoStatistics bool
}

func ( *Options) () string {
	if  == nil {
		return "{}"
	}

	return fmt.Sprintf("{Timeout: %s, NoGrowSync: %t, NoFreelistSync: %t, PreLoadFreelist: %t, FreelistType: %s, ReadOnly: %t, MmapFlags: %x, InitialMmapSize: %d, PageSize: %d, MaxSize: %d, NoSync: %t, OpenFile: %p, Mlock: %t, Logger: %p, NoStatistics: %t}",
		.Timeout, .NoGrowSync, .NoFreelistSync, .PreLoadFreelist, .FreelistType, .ReadOnly, .MmapFlags, .InitialMmapSize, .PageSize, .MaxSize, .NoSync, .OpenFile, .Mlock, .Logger, .NoStatistics)

}

// DefaultOptions represent the options used if nil options are passed into Open().
// No timeout is used which will cause Bolt to wait indefinitely for a lock.
var DefaultOptions = &Options{
	Timeout:      0,
	NoGrowSync:   false,
	FreelistType: FreelistArrayType,
}

// Stats represents statistics about the database.
type Stats struct {
	// Put `TxStats` at the first field to ensure it's 64-bit aligned. Note
	// that the first word in an allocated struct can be relied upon to be
	// 64-bit aligned. Refer to https://pkg.go.dev/sync/atomic#pkg-note-BUG.
	// Also refer to discussion in https://github.com/etcd-io/bbolt/issues/577.
	TxStats TxStats // global, ongoing stats.

	// Freelist stats
	FreePageN     int // total number of free pages on the freelist
	PendingPageN  int // total number of pending pages on the freelist
	FreeAlloc     int // total bytes allocated in free pages
	FreelistInuse int // total bytes used by the freelist

	// Transaction stats
	TxN     int // total number of started read transactions
	OpenTxN int // number of currently open read transactions
}

// Sub calculates and returns the difference between two sets of database stats.
// This is useful when obtaining stats at two different points and time and
// you need the performance counters that occurred within that time span.
func ( *Stats) ( *Stats) Stats {
	if  == nil {
		return *
	}
	var  Stats
	.FreePageN = .FreePageN
	.PendingPageN = .PendingPageN
	.FreeAlloc = .FreeAlloc
	.FreelistInuse = .FreelistInuse
	.TxN = .TxN - .TxN
	.TxStats = .TxStats.Sub(&.TxStats)
	return 
}

type Info struct {
	Data     uintptr
	PageSize int
}