// Copyright (c) 2026 Klaus Post, released under MIT License. See LICENSE file.

package cpuid

import (
	
	
	
	

	
)

// logicalCPU holds the topology-relevant CPUID data of a single logical
// processor. It is produced by parseLogicalCPU on whichever CPU the calling
// goroutine currently runs, so a full tree needs one per online CPU (see
// ScanTopology); a single one drives the extrapolated snapshot.
type logicalCPU struct {
	apicID   uint32            // (x2)APIC id
	vendor   Vendor            //
	smtShift uint8             // apicID>>smtShift == core id
	pkgShift uint8             // apicID>>pkgShift == package id
	l3Shift  uint8             // apicID>>l3Shift  == L3 (group) id; 0 if no L3
	nodeID   int               // AMD node id (leaf 0x8000001E ECX)
	coreType topology.CoreType //
	model    string            //
	caches   []cpuCache        //
}

// cpuCache pairs a decoded cache with the addressable number of logical
// processors that share it, which is what determines its sharing domain.
type cpuCache struct {
	c        topology.Cache
	numShare int
}

// topoSnapshot caches the extrapolated single-CPU topology; Detect resets it.
var topoSnapshot atomic.Pointer[topology.System]

// Topology returns the CPU topology as a fixed hierarchy of
// System → Package → Group → Core → Thread.
//
// It is extrapolated from the current core's CPUID and the detected core
// counts, so counts and cache totals are accurate for homogeneous CPUs but
// individual cores of a hybrid CPU cannot be classified. For an exact,
// per-core tree (real efficiency/performance mapping and CCD membership) use
// ScanTopology, which briefly pins the current goroutine to each CPU.
func ( CPUInfo) () *topology.System {
	if  := topoSnapshot.Load();  != nil {
		return 
	}
	 := snapshotTopology()
	topoSnapshot.Store()
	return 
}

// parseLogicalCPU reads the topology leaves of the current logical processor.
func parseLogicalCPU() logicalCPU {
	var  logicalCPU
	.vendor, _ = vendorID()
	 := maxFunctionID()
	 := maxExtendedFunction()

	// Extended topology enumeration: leaf 0x1F (V2) is preferred over 0x0B.
	// EAX[4:0] is the right-shift of the x2APIC id (EDX) that yields the id of
	// the next coarser level; ECX[15:8] is the level type (1=SMT, 2=Core, …).
	 := uint32(0)
	if  >= 0x1f {
		if , , ,  := cpuidex(0x1f, 0); &0xffff != 0 {
			 = 0x1f
		}
	}
	if  == 0 &&  >= 0xb {
		if , , ,  := cpuidex(0xb, 0); &0xffff != 0 {
			 = 0xb
		}
	}
	switch {
	case  != 0:
		var  uint8
		for  := range uint32(16) {
			, , ,  := cpuidex(, )
			if &0xffff == 0 {
				break
			}
			.apicID = 
			 := uint8( & 0x1f)
			if (>>8)&0xff == 1 { // SMT level
				.smtShift = 
			}
			if  >  {
				 = 
			}
		}
		.pkgShift = 
	case  >= 1:
		// Legacy 8-bit initial APIC id.
		, , ,  := cpuid(1)
		.apicID = ( >> 24) & 0xff
		.smtShift = ceilLog2(threadsPerCore())
		.pkgShift = 8
	}

	if .vendor == AMD || .vendor == Hygon {
		if  >= 0x8000001e {
			, , ,  := cpuid(0x8000001e)
			if  == 0 {
				.apicID =  // Extended APIC id, authoritative on AMD.
			}
			// EBX[15:8]+1 == threads per core, but only on Zen (fam>=0x17) and
			// Hygon (fam 0x18); pre-Zen "modules" (fam 0x15/0x16) are not SMT.
			if , ,  := familyModel(); .smtShift == 0 &&  >= 0x17 {
				.smtShift = ceilLog2(int((>>8)&0xff) + 1)
			}
			.nodeID = int( & 0xff)
		}
	}

	.caches = parseCaches(.vendor, , )
	for ,  := range .caches {
		if .c.Level == 3 {
			.l3Shift = ceilLog2(.numShare)
		}
	}
	.coreType, .model = parseCoreType(.vendor, )
	return 
}

// parseCaches decodes the deterministic cache leaves (Intel 0x04 / AMD
// 0x8000001D). AMD only populates 0x8000001D when TopologyExtensions is set.
func parseCaches( Vendor, ,  uint32) []cpuCache {
	var  []cpuCache
	switch  {
	case Intel:
		if  < 4 {
			return nil
		}
		for  := range uint32(16) {
			, , ,  := cpuidex(4, )
			if &0xf == 0 {
				break
			}
			 = append(, decodeCache(, , , ))
		}
	case AMD, Hygon:
		 := false
		if  >= 0x80000001 {
			, , ,  := cpuid(0x80000001)
			 = &(1<<22) != 0
		}
		if  >= 0x8000001d &&  {
			for  := range uint32(16) {
				, , ,  := cpuidex(0x8000001d, )
				if &0xf == 0 {
					break
				}
				 = append(, decodeCache(, , , ))
			}
		}
	}
	return 
}

// decodeCache reads one subleaf of leaf 0x04 / 0x8000001D, which share layout.
func decodeCache(, , ,  uint32) cpuCache {
	 := int(&0xfff) + 1
	 := int((>>12)&0x3ff) + 1
	 := int((>>22)&0x3ff) + 1
	 := int() + 1
	return cpuCache{
		c: topology.Cache{
			Level:     int(( >> 5) & 7),
			Type:      topology.CacheType( & 0xf), // 1=Data, 2=Instruction, 3=Unified
			Size:       *  *  * ,
			LineSize:  ,
			Ways:      ,
			Sets:      ,
			Inclusive: &2 != 0,
		},
		numShare: int((>>14)&0xfff) + 1,
	}
}

// parseCoreType classifies the current core from Intel's hybrid leaf 0x1A.
// The leaf reads 0 on non-hybrid Intel parts (so they fall through to
// performance), but all-efficiency parts populate it without the hybrid flag,
// so it is read whenever present rather than gated on that flag.
func parseCoreType( Vendor,  uint32) (topology.CoreType, string) {
	if  == Intel &&  >= 0x1a {
		switch , , ,  := cpuid(0x1a);  >> 24 {
		case 0x40:
			return topology.Performance, ""
		case 0x20:
			return topology.Efficiency, ""
		}
	}
	if  == Intel ||  == AMD ||  == Hygon {
		return topology.Performance, ""
	}
	return topology.Unknown, ""
}

// assembleTopology builds the exact tree from one record per logical CPU.
// Package/group/core membership is derived by masking the x2APIC id, and each
// cache instance is attached to the deepest node that contains every logical
// processor sharing it, so aggregate sizes never double-count.
func assembleTopology( []logicalCPU) *topology.System {
	 := &topology.System{Scanned: true, Online: len()}
	if len() == 0 {
		return 
	}
	.Vendor = [0].vendor.String()

	 := func( logicalCPU) uint8 {
		 := .l3Shift
		if  == 0 {
			 = .pkgShift // no L3: one group spans the package
		}
		if  < .smtShift {
			 = .smtShift
		}
		if  == 0 {
			 = 32
		}
		return 
	}

	type  struct {
		     topology.CoreType
		   string
		 []topology.Thread
	}
	 := map[uint32]*{}
	 := map[uint32]uint32{} // coreKey -> groupKey
	 := map[uint32]uint32{}   // groupKey -> pkgKey
	 := map[uint32]int{}     // groupKey -> NUMA node
	 := map[uint32]bool{}
	var , ,  []uint32

	for ,  := range  {
		 := .apicID >> .pkgShift
		 := .apicID >> ()
		 := .apicID >> .smtShift
		 := []
		if  == nil {
			 = &{: .coreType, : .model}
			[] = 
			 = append(, )
			[] = 
		}
		if ,  := []; ! {
			[] = 
			 = append(, )
		}
		[] = .nodeID
		if ![] {
			[] = true
			 = append(, )
		}
		. = append(., topology.Thread{APICID: .apicID, ID: })
	}

	, ,  := attachCaches(, )

	slices.Sort()
	slices.Sort()
	slices.Sort()

	,  := 0, 0
	for ,  := range  {
		 := topology.Package{ID: , Caches: sortCaches([])}
		for ,  := range  {
			if [] !=  {
				continue
			}
			 := topology.Group{ID: , NUMANode: [], Caches: sortCaches([])}
			++
			for ,  := range  {
				if [] !=  {
					continue
				}
				 := []
				slices.SortFunc(., func(,  topology.Thread) int { return cmp.Compare(.APICID, .APICID) })
				.Cores = append(.Cores, topology.Core{
					ID:      ,
					Type:    .,
					Model:   .,
					Threads: .,
					Caches:  sortCaches([]),
				})
				++
			}
			.Groups = append(.Groups, )
		}
		.Packages = append(.Packages, )
	}
	return 
}

// attachCaches groups every reported cache into instances by sharing domain
// and returns them keyed by the core/group/package they belong to.
func attachCaches( []logicalCPU,  func(logicalCPU) uint8) (, ,  map[uint32][]topology.Cache) {
	type  struct {
		 int
		   topology.CacheType
		   uint32
	}
	type  struct {
		      topology.Cache
		  map[uint32]bool
		 map[uint32]bool
		   map[uint32]bool
		 int
	}
	 := map[]*{}
	for ,  := range  {
		 := .apicID >> .pkgShift
		 := .apicID >> ()
		 := .apicID >> .smtShift
		for ,  := range .caches {
			 := {.c.Level, .c.Type, .apicID >> ceilLog2(.numShare)}
			 := []
			if  == nil {
				 = &{: .c, : map[uint32]bool{}, : map[uint32]bool{}, : map[uint32]bool{}}
				[] = 
			}
			.[], .[], .[] = true, true, true
			.++
		}
	}
	, ,  = map[uint32][]topology.Cache{}, map[uint32][]topology.Cache{}, map[uint32][]topology.Cache{}
	for ,  := range  {
		 := .
		.SharedThreads = .
		switch {
		case len(.) == 1:
			 := onlyKey(.)
			[] = append([], )
		case len(.) == 1:
			 := onlyKey(.)
			[] = append([], )
		default:
			 := onlyKey(.)
			[] = append([], )
		}
	}
	return , , 
}

// snapshotTopology extrapolates a homogeneous tree from the current core and
// the detected core counts, without pinning to other CPUs.
func snapshotTopology() *topology.System {
	if cpuid == nil {
		return countsTopology() // Non-x86: no CPUID, build from detected counts.
	}
	 := parseLogicalCPU()
	 := max(threadsPerCore(), 1)
	 := max(physicalCores(), 1)
	 := max(logicalCores(), *)

	var , , ,  *topology.Cache
	 := 0
	for  := range .caches {
		 := &.caches[]
		switch {
		case .c.Level == 1 && .c.Type == topology.Instruction:
			 = &.c
		case .c.Level == 1:
			 = &.c
		case .c.Level == 2:
			 = &.c
		case .c.Level == 3:
			 = &.c
			 = .numShare
		}
	}

	 := 
	if  > 0 && / > 0 {
		 =  / 
	}
	 = min(, )
	 := 1
	if  > 0 {
		 = ( +  - 1) / 
	}

	 := &topology.System{Vendor: .vendor.String(), Online: }
	 := topology.Package{}
	, ,  := 0, uint32(0), 
	for  := range  {
		 := topology.Group{ID: , NUMANode: .nodeID}
		 := min(, )
		for range  {
			 := topology.Core{ID: , Type: .coreType, Model: .model}
			for range  {
				.Threads = append(.Threads, topology.Thread{APICID: , ID: int()})
				++
			}
			addCache(&.Caches, , )
			addCache(&.Caches, , )
			addCache(&.Caches, , )
			.Cores = append(.Cores, )
			++
		}
		addCache(&.Caches, , *)
		 -= 
		.Groups = append(.Groups, )
	}
	.Packages = []topology.Package{}
	return 
}

func addCache( *[]topology.Cache,  *topology.Cache,  int) {
	if  == nil || .Size == 0 {
		return
	}
	 := *
	.SharedThreads = 
	* = append(*, )
}

// countsTopology builds a minimal tree from the already-detected counts and
// cache sizes, used where CPUID is not available (non-x86, or noasm builds).
func countsTopology() *topology.System {
	 := max(CPU.ThreadsPerCore, 1)
	 := CPU.PhysicalCores
	if  < 1 {
		 = max(1, CPU.LogicalCores/)
	}
	 := &topology.System{Vendor: CPU.VendorString, Online: CPU.LogicalCores}
	var  topology.Group
	 := 0
	for  := range  {
		 := topology.Core{ID: , Type: topology.Performance}
		for range  {
			.Threads = append(.Threads, topology.Thread{ID: })
			++
		}
		addCacheVal(&.Caches, 1, topology.Data, CPU.Cache.L1D, )
		addCacheVal(&.Caches, 1, topology.Instruction, CPU.Cache.L1I, )
		addCacheVal(&.Caches, 2, topology.Unified, CPU.Cache.L2, )
		.Cores = append(.Cores, )
	}
	addCacheVal(&.Caches, 3, topology.Unified, CPU.Cache.L3, *)
	.Packages = []topology.Package{{Groups: []topology.Group{}}}
	return 
}

func addCacheVal( *[]topology.Cache,  int,  topology.CacheType, ,  int) {
	if  <= 0 {
		return
	}
	* = append(*, topology.Cache{Level: , Type: , Size: , SharedThreads: })
}

func sortCaches( []topology.Cache) []topology.Cache {
	slices.SortFunc(, func(,  topology.Cache) int {
		if .Level != .Level {
			return cmp.Compare(.Level, .Level)
		}
		return cmp.Compare(.Type, .Type)
	})
	return 
}

func onlyKey( map[uint32]bool) uint32 {
	for  := range  {
		return 
	}
	return 0
}

// ceilLog2 returns the smallest s such that 1<<s >= n.
func ceilLog2( int) uint8 {
	if  <= 1 {
		return 0
	}
	return uint8(bits.Len(uint( - 1)))
}