//go:build linux

package mmap

import (
	"math"
	"os"
	"sync"

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

// Mode selects sharing behavior. Modes are exclusive, not a bitmask.
type Mode uint8

// Private creates a copy-on-write mapping (MAP_PRIVATE). Writes do not change
// the source file. Later file changes have unspecified visibility in the view.
const Private Mode = 0

// Shared shares changes with other mappings and the source file (MAP_SHARED).
// Visibility does not imply synchronization between readers and writers or
// durable storage. Anonymous Shared mappings have no source file.
const Shared Mode = 1

// Protection is a bitmask of requested page permissions. Combine Read and Write
// with |. Actual permissions may be broader on some architectures or process
// personalities; protection is not a security boundary.
type Protection uint8

// NoAccess prohibits memory access (PROT_NONE), and is the zero protection.
const NoAccess Protection = unix.PROT_NONE

// Read requests readable pages (PROT_READ).
const Read Protection = unix.PROT_READ

// Write requests writable pages (PROT_WRITE).
const Write Protection = unix.PROT_WRITE

// Options controls a new mapping. The zero value selects Private and NoAccess.
// Executable mappings and additional Linux mapping flags are not supported.
type Options struct {
	// Mode selects private copy-on-write or shared backing; zero is Private.
	Mode Mode

	// Protection requests page permissions; zero is NoAccess. Set Read and/or
	// Write explicitly before accessing Bytes.
	Protection Protection
}

// SyncMode selects the writeback behavior for Sync. Zero selects SyncWait.
// The modes are mutually exclusive.
type SyncMode uint8

// SyncWait completes synchronous data writeback (MS_SYNC) for the file
// range covered by a shared file mapping, at page granularity.
const SyncWait SyncMode = unix.MS_SYNC

// SyncAsync requests MS_ASYNC. Linux already tracks dirty pages and this
// mode neither starts nor waits for writeback.
const SyncAsync SyncMode = unix.MS_ASYNC

// SyncFlags selects additional synchronization behavior. Zero requests only
// the selected writeback mode.
type SyncFlags uint8

// SyncInvalidate requests MS_INVALIDATE. Linux may return EBUSY for locked
// pages. Success gives no guarantee of eviction or reload.
const SyncInvalidate SyncFlags = unix.MS_INVALIDATE

// SyncOptions controls whole-region synchronization. The zero value waits
// for writeback from a shared file mapping.
type SyncOptions struct {
	// Mode selects SyncWait (also the zero default) or SyncAsync.
	Mode SyncMode

	// Flags optionally requests SyncInvalidate with either mode.
	Flags SyncFlags
}

// Map creates a file-backed region using [mmap(2)]. It borrows file only during
// the call, protecting descriptor lifetime against concurrent file.Close. The
// caller owns the returned region and must close it independently of the file.
// Closing file after success does not invalidate the mapping.
//
// The length must be positive and offset nonnegative and page-aligned, using
// os.Getpagesize. Invalid arguments or unknown options match os.ErrInvalid;
// offset+length beyond int64 matches EOVERFLOW. Validation precedes file access.
// A nil file matches os.ErrInvalid; a closed file matches os.ErrClosed.
// Errors wrap an os.PathError and preserve underlying errno identity.
//
// The file must permit reading; Shared with Write also requires write access.
// Mapping does not extend the file or freeze its size: accessing whole pages
// beyond EOF, including after truncation, can cause a fatal SIGBUS. File size
// checks cannot prevent concurrent truncation; callers own that coordination.
// Close does not synchronize dirty pages to durable storage.
//
// [mmap(2)]: https://man7.org/linux/man-pages/man2/mmap.2.html
func Map(file *os.File, offset int64, length int, options Options) (*Region, error) {
	flags, err := mappingFlags(offset, length, options)
	if err != nil {
		return nil, &os.PathError{Op: "mmap", Path: "mmap", Err: err}
	}

	conn, err := file.SyscallConn()
	if err != nil {
		return nil, &os.PathError{Op: "mmap", Path: "mmap", Err: err}
	}

	var data []byte
	var callErr error
	err = conn.Control(func(fd uintptr) {
		data, callErr = unix.Mmap(int(fd), offset, length, int(options.Protection), flags)
	})
	if err != nil {
		// os.File's raw Control reports its private closing error when Close
		// prevents the callback; normalize it to the public owner error.
		err = os.ErrClosed
	} else {
		err = callErr
	}
	if err != nil {
		return nil, &os.PathError{Op: "mmap", Path: file.Name(), Err: err}
	}

	return &Region{data: data}, nil
}

// Anonymous creates a zero-initialized region using [mmap(2)] with
// MAP_ANONYMOUS. The caller owns it and must close it. Options and positive
// length are validated as in Map. Shared selects a shared anonymous backing
// object; separate Anonymous calls always create independent objects.
//
// [mmap(2)]: https://man7.org/linux/man-pages/man2/mmap.2.html
func Anonymous(length int, options Options) (*Region, error) {
	flags, err := mappingFlags(0, length, options)
	if err != nil {
		return nil, &os.PathError{Op: "mmap", Path: "anonymous", Err: err}
	}

	data, err := unix.Mmap(-1, 0, length, int(options.Protection), flags|unix.MAP_ANONYMOUS)
	if err != nil {
		return nil, &os.PathError{Op: "mmap", Path: "anonymous", Err: err}
	}

	region := &Region{data: data}
	if options.Mode == Shared {
		region.sharedAnonymousPages = 1 + (length-1)/os.Getpagesize()
	}
	return region, nil
}

// Region owns one complete mapping. Do not copy a Region after first use.
// Nil receivers are unsupported. The zero value owns nothing: Bytes returns
// nil and error-returning methods match os.ErrInvalid. After successful Close,
// Bytes returns nil and all other methods, including Close, match os.ErrClosed.
//
// Methods serialize their operations, but returned slices escape that lock.
// Callers must coordinate ALL slice use with Resize, Close, Protect, and Advise,
// and synchronize conflicting memory accesses. Coordinate writes with Sync to
// control which changes are included. A concurrent Bytes call does not keep
// its result mapped. There is no finalizer: unmapping is explicit.
type Region struct {
	data                 []byte
	sharedAnonymousPages int // Original backing size in pages, zero for other mappings.
	mu                   sync.Mutex
	closed               bool
}

// Bytes returns a borrowed view with length and capacity equal to the requested
// mapping length. It does not copy or check page permissions. Normal Go bounds
// checks apply; page rounding does not permit extending the slice.
//
// Every view, subslice, or pointer becomes invalid after successful Resize or
// Close. Access then can fault or silently corrupt an unrelated mapping at a
// reused address. Keeping a slice or Region reachable cannot pin the mapping.
func (r *Region) Bytes() []byte {
	r.mu.Lock()
	defer r.mu.Unlock()

	return r.data
}

// Resize sets the region's byte length through [mremap(2)]. Linux may
// relocate the mapping. The retained prefix keeps its contents and protection.
// Linux rounds both lengths up to pages. Shrinking releases only whole pages,
// and growing within the last mapped page may expose existing contents.
//
// Stop using every borrowed slice and pointer before Resize. On success, even
// if the address or length did not change, discard those views and call Bytes
// for the new view. Resize can block. It leaves the size of any backing file
// unchanged. Before accessing a grown file mapping, arrange sufficient backing
// storage so access to whole pages beyond EOF cannot fault.
//
// Owner-state errors take precedence. A nonpositive length or a shared
// anonymous length beyond the original page-rounded backing size matches
// os.ErrInvalid. On failure, the original mapping and its views remain valid
// with their existing protections, and kernel errors preserve their errno.
// Growing a locked region is subject to RLIMIT_MEMLOCK.
//
// [mremap(2)]: https://man7.org/linux/man-pages/man2/mremap.2.html
func (r *Region) Resize(length int) error {
	r.mu.Lock()
	defer r.mu.Unlock()

	if err := r.stateError(); err != nil {
		return &os.PathError{Op: "mremap", Path: "mmap", Err: err}
	}
	if length <= 0 {
		return &os.PathError{Op: "mremap", Path: "mmap", Err: os.ErrInvalid}
	}
	requestedPages := 1 + (length-1)/os.Getpagesize()
	if r.sharedAnonymousPages > 0 && requestedPages > r.sharedAnonymousPages {
		return &os.PathError{Op: "mremap", Path: "mmap", Err: os.ErrInvalid}
	}
	data, err := unix.Mremap(r.data, length, unix.MREMAP_MAYMOVE)
	if err != nil {
		return &os.PathError{Op: "mremap", Path: "mmap", Err: err}
	}

	r.data = data
	return nil
}

// Protect changes permissions on all pages intersecting the region through
// [mprotect(2)]. Only NoAccess, Read, Write, or Read|Write are accepted; unknown
// bits match os.ErrInvalid without changing permissions. Owner-state errors
// take precedence. Kernel errors retain their errno; do not assume a failed
// kernel call changed no pages. NoAccess views still have their original length
// but cannot be accessed until protection is changed again.
//
// [mprotect(2)]: https://man7.org/linux/man-pages/man2/mprotect.2.html
func (r *Region) Protect(protection Protection) error {
	r.mu.Lock()
	defer r.mu.Unlock()

	if err := r.stateError(); err != nil {
		return &os.PathError{Op: "mprotect", Path: "mmap", Err: err}
	}
	if protection & ^(Read|Write) != 0 {
		return &os.PathError{Op: "mprotect", Path: "mmap", Err: os.ErrInvalid}
	}
	if err := unix.Mprotect(r.data, int(protection)); err != nil {
		return &os.PathError{Op: "mprotect", Path: "mmap", Err: err}
	}

	return nil
}

// Sync synchronizes all pages intersecting the region through [msync(2)].
// SyncWait returns after the filesystem completes data synchronization for a
// shared file mapping. Private changes stay private, and anonymous mappings
// have no persistent backing. Sync can block. For a defined set of writes,
// coordinate writers through its return. Views retain their lifetime and
// permissions. File or directory changes outside the mapped data and crash
// consistency of a series of updates require separate coordination.
//
// Owner-state errors take precedence over options validation. Unknown or
// combined modes and unknown flags match os.ErrInvalid. Kernel errors preserve
// errno and may follow partial writeback. The mapping remains owned after an error.
//
// [msync(2)]: https://man7.org/linux/man-pages/man2/msync.2.html
func (r *Region) Sync(options SyncOptions) error {
	r.mu.Lock()
	defer r.mu.Unlock()

	if err := r.stateError(); err != nil {
		return &os.PathError{Op: "msync", Path: "mmap", Err: err}
	}

	var flags int
	switch options.Mode {
	case 0, SyncWait:
		flags = unix.MS_SYNC
	case SyncAsync:
		flags = unix.MS_ASYNC
	default:
		return &os.PathError{Op: "msync", Path: "mmap", Err: os.ErrInvalid}
	}
	if options.Flags & ^SyncInvalidate != 0 {
		return &os.PathError{Op: "msync", Path: "mmap", Err: os.ErrInvalid}
	}
	if err := unix.Msync(r.data, flags|int(options.Flags)); err != nil {
		return &os.PathError{Op: "msync", Path: "mmap", Err: err}
	}

	return nil
}

// Close unmaps the complete current region using [munmap(2)], invalidating all
// escaped views. Callers must stop all view access before calling it. On error
// the owner retains its mapping so the error can be addressed and Close retried.
// Unmapping releases the region's memory locks. The source file has an
// independent lifetime. Call Sync before Close to wait for shared file writeback.
//
// [munmap(2)]: https://man7.org/linux/man-pages/man2/mmap.2.html
func (r *Region) Close() error {
	r.mu.Lock()
	defer r.mu.Unlock()

	if err := r.stateError(); err != nil {
		return &os.PathError{Op: "munmap", Path: "mmap", Err: err}
	}
	if err := unix.Munmap(r.data); err != nil {
		return &os.PathError{Op: "munmap", Path: "mmap", Err: err}
	}

	r.data = nil
	r.closed = true
	return nil
}

// stateError requires r.mu to be held; nil data alone cannot distinguish a
// never-initialized owner from a successfully closed one.
func (r *Region) stateError() error {
	if r.closed {
		return os.ErrClosed
	}
	if r.data == nil {
		return os.ErrInvalid
	}

	return nil
}

func mappingFlags(offset int64, length int, options Options) (int, error) {
	invalidLength := length <= 0
	invalidOffset := offset < 0 || offset%int64(os.Getpagesize()) != 0
	unknownProtection := options.Protection & ^(Read|Write) != 0
	if invalidLength || invalidOffset || unknownProtection {
		return 0, os.ErrInvalid
	}
	if offset > math.MaxInt64-int64(length) {
		return 0, unix.EOVERFLOW
	}

	switch options.Mode {
	case Private:
		return unix.MAP_PRIVATE, nil
	case Shared:
		return unix.MAP_SHARED, nil
	default:
		return 0, os.ErrInvalid
	}
}
