Skip to main content

torsh_backend/cpu/
memory.rs

1//! CPU Memory Management with NUMA awareness
2
3// Framework infrastructure - components designed for future use
4#![allow(dead_code)]
5use crate::buffer::{generate_buffer_id, BufferHandle};
6use crate::memory::{MemoryManager, MemoryPool, MemoryStats, PoolStats};
7use crate::{Buffer, BufferDescriptor, Device};
8use torsh_core::device::DeviceType;
9use torsh_core::error::{Result, TorshError};
10use torsh_core::sync::MutexExt;
11
12#[cfg(feature = "std")]
13use std::collections::HashMap;
14#[cfg(feature = "std")]
15use std::sync::{Arc, Mutex};
16
17#[cfg(not(feature = "std"))]
18use alloc::{collections::BTreeMap as HashMap, sync::Arc};
19#[cfg(not(feature = "std"))]
20use spin::Mutex;
21
22#[cfg(not(feature = "std"))]
23use alloc::{boxed::Box, vec::Vec};
24
25use std::sync::atomic::{AtomicU64, Ordering};
26use std::time::Instant;
27
28/// NUMA node information
29#[derive(Debug, Clone)]
30pub struct NumaNode {
31    /// Node ID
32    pub id: u32,
33    /// Available memory in bytes
34    pub available_memory: u64,
35    /// Memory bandwidth in GB/s
36    pub memory_bandwidth: f64,
37    /// CPU cores associated with this node
38    pub cpu_cores: Vec<u32>,
39    /// Distance to other NUMA nodes
40    pub distances: HashMap<u32, u32>,
41}
42
43/// NUMA topology information
44#[derive(Debug, Clone)]
45pub struct NumaTopology {
46    /// Available NUMA nodes
47    pub nodes: HashMap<u32, NumaNode>,
48    /// Current thread's preferred NUMA node
49    pub current_node: u32,
50    /// Whether NUMA is available on this system
51    pub numa_available: bool,
52}
53
54/// Memory access pattern tracking
55#[derive(Debug)]
56pub struct MemoryAccessPattern {
57    /// Access frequency counter
58    pub access_count: AtomicU64,
59    /// Last access time
60    pub last_access: Instant,
61    /// Access pattern (sequential, random, etc.)
62    pub pattern_type: AccessPatternType,
63    /// Preferred NUMA node for this allocation
64    pub preferred_node: u32,
65}
66
67impl Clone for MemoryAccessPattern {
68    fn clone(&self) -> Self {
69        Self {
70            access_count: AtomicU64::new(self.access_count.load(Ordering::Relaxed)),
71            last_access: self.last_access,
72            pattern_type: self.pattern_type,
73            preferred_node: self.preferred_node,
74        }
75    }
76}
77
78/// Types of memory access patterns
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum AccessPatternType {
81    Sequential,
82    Random,
83    Strided,
84    Temporal,
85    Unknown,
86}
87
88/// Memory allocation strategy
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum NumaAllocationStrategy {
91    /// Allocate on local NUMA node
92    Local,
93    /// Allocate on preferred node
94    Preferred(u32),
95    /// Interleave across all nodes
96    Interleaved,
97    /// Best fit based on available memory
98    BestFit,
99    /// Round-robin across nodes
100    RoundRobin,
101}
102
103/// CPU memory manager implementation
104#[derive(Debug, Clone)]
105pub struct CpuMemoryManager {
106    pools: Arc<Mutex<HashMap<usize, CpuMemoryPool>>>,
107    stats: Arc<Mutex<MemoryStats>>,
108    numa_topology: Arc<Mutex<NumaTopology>>,
109    #[allow(dead_code)]
110    numa_pools: Arc<Mutex<HashMap<(usize, u32), CpuMemoryPool>>>, // (size_class, numa_node) -> pool
111    allocation_strategy: Arc<Mutex<NumaAllocationStrategy>>,
112    access_patterns: Arc<Mutex<HashMap<usize, MemoryAccessPattern>>>,
113    round_robin_counter: Arc<Mutex<u32>>,
114}
115
116impl CpuMemoryManager {
117    /// Create a new CPU memory manager
118    pub fn new() -> Self {
119        let numa_topology = Self::detect_numa_topology();
120        Self {
121            pools: Arc::new(Mutex::new(HashMap::new())),
122            stats: Arc::new(Mutex::new(MemoryStats::default())),
123            numa_topology: Arc::new(Mutex::new(numa_topology)),
124            numa_pools: Arc::new(Mutex::new(HashMap::new())),
125            allocation_strategy: Arc::new(Mutex::new(NumaAllocationStrategy::Local)),
126            access_patterns: Arc::new(Mutex::new(HashMap::new())),
127            round_robin_counter: Arc::new(Mutex::new(0)),
128        }
129    }
130
131    /// Detect NUMA topology of the system
132    fn detect_numa_topology() -> NumaTopology {
133        let mut numa_topology = NumaTopology {
134            nodes: HashMap::new(),
135            current_node: 0,
136            numa_available: false,
137        };
138
139        // Try to detect NUMA nodes
140        #[cfg(target_os = "linux")]
141        {
142            numa_topology.numa_available = Self::detect_linux_numa(&mut numa_topology);
143        }
144
145        #[cfg(not(target_os = "linux"))]
146        {
147            // Fallback: create a single node
148            numa_topology.nodes.insert(
149                0,
150                NumaNode {
151                    id: 0,
152                    available_memory: 8 * 1024 * 1024 * 1024, // 8GB
153                    memory_bandwidth: 50.0,
154                    cpu_cores: (0..num_cpus::get() as u32).collect(),
155                    distances: HashMap::new(),
156                },
157            );
158        }
159
160        numa_topology
161    }
162
163    /// Detect NUMA topology on Linux systems
164    #[cfg(target_os = "linux")]
165    fn detect_linux_numa(numa_topology: &mut NumaTopology) -> bool {
166        use std::fs;
167        use std::path::Path;
168
169        let numa_path = Path::new("/sys/devices/system/node");
170        if !numa_path.exists() {
171            return false;
172        }
173
174        let mut numa_available = false;
175
176        // Read NUMA nodes
177        if let Ok(entries) = fs::read_dir(numa_path) {
178            for entry in entries.flatten() {
179                let name = entry.file_name();
180                let name_str = name.to_string_lossy();
181
182                if let Some(stripped) = name_str.strip_prefix("node") {
183                    if let Ok(node_id) = stripped.parse::<u32>() {
184                        numa_available = true;
185
186                        // Get memory information
187                        let meminfo_path = entry.path().join("meminfo");
188                        let available_memory =
189                            if let Ok(content) = fs::read_to_string(&meminfo_path) {
190                                Self::parse_numa_meminfo(&content)
191                            } else {
192                                1024 * 1024 * 1024 // 1GB default
193                            };
194
195                        // Get CPU list
196                        let cpulist_path = entry.path().join("cpulist");
197                        let cpu_cores = if let Ok(content) = fs::read_to_string(&cpulist_path) {
198                            Self::parse_cpu_list(&content)
199                        } else {
200                            Vec::new()
201                        };
202
203                        // Get distances
204                        let distance_path = entry.path().join("distance");
205                        let distances = if let Ok(content) = fs::read_to_string(&distance_path) {
206                            Self::parse_numa_distances(&content)
207                        } else {
208                            HashMap::new()
209                        };
210
211                        numa_topology.nodes.insert(
212                            node_id,
213                            NumaNode {
214                                id: node_id,
215                                available_memory,
216                                memory_bandwidth: 50.0, // Default bandwidth
217                                cpu_cores,
218                                distances,
219                            },
220                        );
221                    }
222                }
223            }
224        }
225
226        // Set current node
227        numa_topology.current_node = Self::get_current_numa_node();
228
229        numa_available
230    }
231
232    /// Parse NUMA memory information
233    #[cfg(target_os = "linux")]
234    fn parse_numa_meminfo(content: &str) -> u64 {
235        for line in content.lines() {
236            if line.starts_with("Node") && line.contains("MemTotal:") {
237                let parts: Vec<&str> = line.split_whitespace().collect();
238                if parts.len() >= 3 {
239                    if let Ok(kb) = parts[2].parse::<u64>() {
240                        return kb * 1024; // Convert KB to bytes
241                    }
242                }
243            }
244        }
245        1024 * 1024 * 1024 // 1GB default
246    }
247
248    /// Parse CPU list from NUMA node
249    #[cfg(target_os = "linux")]
250    fn parse_cpu_list(content: &str) -> Vec<u32> {
251        let mut cpu_cores = Vec::new();
252        let content = content.trim();
253
254        for range in content.split(',') {
255            if let Some(dash_pos) = range.find('-') {
256                // Range format: "0-3"
257                let start = range[..dash_pos].parse::<u32>().unwrap_or(0);
258                let end = range[dash_pos + 1..].parse::<u32>().unwrap_or(0);
259                for cpu in start..=end {
260                    cpu_cores.push(cpu);
261                }
262            } else {
263                // Single CPU
264                if let Ok(cpu) = range.parse::<u32>() {
265                    cpu_cores.push(cpu);
266                }
267            }
268        }
269
270        cpu_cores
271    }
272
273    /// Parse NUMA distance information
274    #[cfg(target_os = "linux")]
275    fn parse_numa_distances(content: &str) -> HashMap<u32, u32> {
276        let mut distances = HashMap::new();
277        let content = content.trim();
278
279        for (node_id, distance_str) in content.split_whitespace().enumerate() {
280            if let Ok(distance) = distance_str.parse::<u32>() {
281                distances.insert(node_id as u32, distance);
282            }
283        }
284
285        distances
286    }
287
288    /// Get current thread's NUMA node
289    fn get_current_numa_node() -> u32 {
290        #[cfg(target_os = "linux")]
291        {
292            // Try to get current CPU and map it to NUMA node
293            if let Ok(cpu) = std::fs::read_to_string("/proc/self/stat") {
294                // Parse the CPU field from /proc/self/stat
295                let fields: Vec<&str> = cpu.split_whitespace().collect();
296                if fields.len() > 38 {
297                    if let Ok(cpu_id) = fields[38].parse::<u32>() {
298                        return Self::cpu_to_numa_node(cpu_id);
299                    }
300                }
301            }
302        }
303
304        0 // Default to node 0
305    }
306
307    /// Map CPU ID to NUMA node
308    #[cfg(target_os = "linux")]
309    fn cpu_to_numa_node(cpu_id: u32) -> u32 {
310        use std::fs;
311        use std::path::Path;
312
313        let cpu_path_str = format!("/sys/devices/system/cpu/cpu{}/node", cpu_id);
314        let cpu_path = Path::new(&cpu_path_str);
315        if let Ok(content) = fs::read_to_string(cpu_path) {
316            content.trim().parse::<u32>().unwrap_or(0)
317        } else {
318            0
319        }
320    }
321
322    /// Set NUMA allocation strategy
323    pub fn set_allocation_strategy(&self, strategy: NumaAllocationStrategy) -> Result<()> {
324        let mut allocation_strategy = self.allocation_strategy.lock().map_err(|_| {
325            TorshError::AllocationError("Failed to acquire allocation strategy lock".to_string())
326        })?;
327        *allocation_strategy = strategy;
328        Ok(())
329    }
330
331    /// Get current allocation strategy
332    pub fn get_allocation_strategy(&self) -> Result<NumaAllocationStrategy> {
333        let allocation_strategy = self.allocation_strategy.lock().map_err(|_| {
334            TorshError::AllocationError("Failed to acquire allocation strategy lock".to_string())
335        })?;
336        Ok(*allocation_strategy)
337    }
338
339    /// Select NUMA node for allocation based on strategy
340    fn select_numa_node(&self, size: usize) -> Result<u32> {
341        let strategy = self.get_allocation_strategy()?;
342        let numa_topology = self.numa_topology.lock().map_err(|_| {
343            TorshError::AllocationError("Failed to acquire NUMA topology lock".to_string())
344        })?;
345
346        if !numa_topology.numa_available {
347            return Ok(0); // Default to node 0 if NUMA is not available
348        }
349
350        match strategy {
351            NumaAllocationStrategy::Local => Ok(numa_topology.current_node),
352            NumaAllocationStrategy::Preferred(node_id) => {
353                if numa_topology.nodes.contains_key(&node_id) {
354                    Ok(node_id)
355                } else {
356                    Ok(numa_topology.current_node)
357                }
358            }
359            NumaAllocationStrategy::Interleaved => {
360                // Select node based on address interleaving
361                let node_count = numa_topology.nodes.len() as u32;
362                Ok((size / 4096) as u32 % node_count) // Page-based interleaving
363            }
364            NumaAllocationStrategy::BestFit => {
365                // Find node with most available memory
366                let mut best_node = numa_topology.current_node;
367                let mut best_memory = 0;
368
369                for (node_id, node) in &numa_topology.nodes {
370                    if node.available_memory > best_memory {
371                        best_memory = node.available_memory;
372                        best_node = *node_id;
373                    }
374                }
375
376                Ok(best_node)
377            }
378            NumaAllocationStrategy::RoundRobin => {
379                let mut counter = self.round_robin_counter.lock().map_err(|_| {
380                    TorshError::AllocationError(
381                        "Failed to acquire round-robin counter lock".to_string(),
382                    )
383                })?;
384
385                let node_count = numa_topology.nodes.len() as u32;
386                let selected_node = *counter % node_count;
387                *counter = (*counter + 1) % node_count;
388
389                Ok(selected_node)
390            }
391        }
392    }
393
394    /// Allocate memory on specific NUMA node
395    fn allocate_on_numa_node(
396        &self,
397        size: usize,
398        alignment: usize,
399        numa_node: u32,
400    ) -> Result<*mut u8> {
401        #[cfg(target_os = "linux")]
402        {
403            // NUMA allocation is disabled to avoid linking dependencies
404            // In a production version, this would check for libnuma availability
405            // and use numa_alloc_onnode if available
406            let _ = numa_node; // Acknowledge the parameter
407        }
408
409        // Fallback to regular allocation
410        let layout = std::alloc::Layout::from_size_align(size, alignment)
411            .map_err(|e| TorshError::AllocationError(format!("Invalid layout: {}", e)))?;
412
413        let ptr = unsafe { std::alloc::alloc(layout) };
414        if ptr.is_null() {
415            return Err(TorshError::AllocationError(format!(
416                "Failed to allocate {} bytes on NUMA node {}",
417                size, numa_node
418            )));
419        }
420
421        Ok(ptr)
422    }
423
424    /// Prefetch memory to improve access patterns
425    pub fn prefetch_memory(
426        &self,
427        ptr: *mut u8,
428        size: usize,
429        pattern: AccessPatternType,
430    ) -> Result<()> {
431        match pattern {
432            AccessPatternType::Sequential => {
433                // Prefetch sequential pages
434                self.prefetch_sequential(ptr, size)
435            }
436            AccessPatternType::Random => {
437                // Prefetch random access patterns
438                self.prefetch_random(ptr, size)
439            }
440            AccessPatternType::Strided => {
441                // Prefetch strided access patterns
442                self.prefetch_strided(ptr, size)
443            }
444            AccessPatternType::Temporal => {
445                // Prefetch for temporal locality
446                self.prefetch_temporal(ptr, size)
447            }
448            AccessPatternType::Unknown => {
449                // Use default prefetching strategy
450                self.prefetch_default(ptr, size)
451            }
452        }
453    }
454
455    /// Prefetch sequential memory pattern
456    fn prefetch_sequential(&self, ptr: *mut u8, size: usize) -> Result<()> {
457        let page_size = 4096;
458        let pages = (size + page_size - 1) / page_size;
459
460        for i in 0..pages {
461            let page_ptr = unsafe { ptr.add(i * page_size) };
462            self.prefetch_page(page_ptr);
463        }
464
465        Ok(())
466    }
467
468    /// Prefetch random memory pattern
469    fn prefetch_random(&self, ptr: *mut u8, size: usize) -> Result<()> {
470        // For random access, prefetch a few strategic pages
471        let page_size = 4096;
472        let pages = (size + page_size - 1) / page_size;
473
474        // Prefetch first, middle, and last pages
475        self.prefetch_page(ptr);
476        if pages > 1 {
477            let mid_ptr = unsafe { ptr.add((pages / 2) * page_size) };
478            self.prefetch_page(mid_ptr);
479        }
480        if pages > 2 {
481            let last_ptr = unsafe { ptr.add((pages - 1) * page_size) };
482            self.prefetch_page(last_ptr);
483        }
484
485        Ok(())
486    }
487
488    /// Prefetch strided memory pattern
489    fn prefetch_strided(&self, ptr: *mut u8, size: usize) -> Result<()> {
490        let page_size = 4096;
491        let stride = page_size * 2; // Every other page
492        let mut offset = 0;
493
494        while offset < size {
495            let page_ptr = unsafe { ptr.add(offset) };
496            self.prefetch_page(page_ptr);
497            offset += stride;
498        }
499
500        Ok(())
501    }
502
503    /// Prefetch temporal memory pattern
504    fn prefetch_temporal(&self, ptr: *mut u8, size: usize) -> Result<()> {
505        // For temporal locality, prefetch the entire region
506        self.prefetch_sequential(ptr, size)
507    }
508
509    /// Default prefetch strategy
510    fn prefetch_default(&self, ptr: *mut u8, size: usize) -> Result<()> {
511        // Use sequential prefetching as default
512        self.prefetch_sequential(ptr, size)
513    }
514
515    /// Prefetch a single page
516    fn prefetch_page(&self, _ptr: *mut u8) {
517        #[cfg(target_arch = "x86_64")]
518        {
519            unsafe {
520                // Use Intel prefetch instructions
521                std::arch::x86_64::_mm_prefetch(_ptr as *const i8, std::arch::x86_64::_MM_HINT_T0);
522            }
523        }
524
525        #[cfg(target_arch = "aarch64")]
526        {
527            // Prefetch instructions are currently unstable in Rust
528            // TODO: Re-enable when stabilized (see issue #117217)
529            // unsafe {
530            //     std::arch::aarch64::_prefetch(
531            //         ptr as *const i8,
532            //         std::arch::aarch64::_PREFETCH_READ,
533            //         std::arch::aarch64::_PREFETCH_LOCALITY3,
534            //     );
535            // }
536        }
537
538        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
539        {
540            // No prefetch instruction available
541            let _ = ptr;
542        }
543    }
544
545    /// Track memory access pattern
546    pub fn track_access(&self, ptr: *mut u8, access_type: AccessPatternType) -> Result<()> {
547        let mut patterns = self.access_patterns.lock().map_err(|_| {
548            TorshError::AllocationError("Failed to acquire access patterns lock".to_string())
549        })?;
550
551        if let Some(pattern) = patterns.get_mut(&(ptr as usize)) {
552            pattern.access_count.fetch_add(1, Ordering::Relaxed);
553            pattern.last_access = Instant::now();
554            pattern.pattern_type = access_type;
555        }
556
557        Ok(())
558    }
559
560    /// Get memory access statistics
561    pub fn get_access_stats(&self, ptr: *mut u8) -> Result<Option<MemoryAccessPattern>> {
562        let patterns = self.access_patterns.lock().map_err(|_| {
563            TorshError::AllocationError("Failed to acquire access patterns lock".to_string())
564        })?;
565
566        Ok(patterns.get(&(ptr as usize)).cloned())
567    }
568
569    /// Optimize memory layout based on access patterns
570    pub fn optimize_layout(&self) -> Result<()> {
571        let patterns = self.access_patterns.lock().map_err(|_| {
572            TorshError::AllocationError("Failed to acquire access patterns lock".to_string())
573        })?;
574
575        // Analyze access patterns and suggest NUMA node migrations
576        for (_ptr_val, pattern) in patterns.iter() {
577            let access_count = pattern.access_count.load(Ordering::Relaxed);
578            let current_node = Self::get_current_numa_node();
579
580            // If access count is high and preferred node is different, consider migration
581            if access_count > 1000 && pattern.preferred_node != current_node {
582                // Log suggestion for migration (implementation would depend on specific needs)
583                #[cfg(feature = "tracing")]
584                tracing::info!(
585                    "High access count {} for allocation {:?}, consider migrating to node {}",
586                    access_count,
587                    _ptr_val,
588                    pattern.preferred_node
589                );
590            }
591        }
592
593        Ok(())
594    }
595
596    /// Create a new CPU memory manager with config
597    pub fn with_config(config: crate::MemoryPoolConfig) -> Self {
598        let numa_topology = Self::detect_numa_topology();
599        let manager = Self {
600            pools: Arc::new(Mutex::new(HashMap::new())),
601            stats: Arc::new(Mutex::new(MemoryStats::default())),
602            numa_topology: Arc::new(Mutex::new(numa_topology)),
603            numa_pools: Arc::new(Mutex::new(HashMap::new())),
604            allocation_strategy: Arc::new(Mutex::new(NumaAllocationStrategy::Local)),
605            access_patterns: Arc::new(Mutex::new(HashMap::new())),
606            round_robin_counter: Arc::new(Mutex::new(0)),
607        };
608
609        // Configure NUMA strategy based on config
610        if let Some(strategy) = config.numa_strategy {
611            let _ = manager.set_allocation_strategy(strategy);
612        }
613
614        manager
615    }
616
617    /// Calculate size class for a given size (power of 2 rounding)
618    fn calculate_size_class(size: usize) -> usize {
619        if size <= 64 {
620            64
621        } else {
622            size.next_power_of_two()
623        }
624    }
625}
626
627impl MemoryManager for CpuMemoryManager {
628    fn allocate(&mut self, descriptor: &BufferDescriptor) -> Result<Buffer> {
629        let size = descriptor.size;
630        let alignment = descriptor.alignment.unwrap_or(std::mem::align_of::<u8>());
631        let size_class = Self::calculate_size_class(size);
632
633        // Select NUMA node for allocation
634        let numa_node = self.select_numa_node(size)?;
635
636        // Try NUMA-aware allocation first
637        let ptr = if let Ok(numa_ptr) = self.allocate_on_numa_node(size, alignment, numa_node) {
638            // Track access pattern for NUMA-allocated memory
639            let mut patterns = self.access_patterns.lock().map_err(|_| {
640                TorshError::AllocationError("Failed to acquire access patterns lock".to_string())
641            })?;
642
643            let pattern = MemoryAccessPattern {
644                access_count: AtomicU64::new(0),
645                last_access: Instant::now(),
646                pattern_type: AccessPatternType::Unknown,
647                preferred_node: numa_node,
648            };
649
650            patterns.insert(numa_ptr as usize, pattern);
651            numa_ptr
652        } else {
653            // Fallback to regular pool allocation
654            {
655                let mut pools = self.pools.lock().map_err(|_| {
656                    TorshError::AllocationError("Failed to acquire pools lock".to_string())
657                })?;
658
659                pools
660                    .entry(size_class)
661                    .or_insert_with(|| CpuMemoryPool::new(size_class));
662            }
663
664            let mut pools = self.pools.lock().map_err(|_| {
665                TorshError::AllocationError("Failed to acquire pools lock".to_string())
666            })?;
667
668            let pool = pools
669                .get_mut(&size_class)
670                .expect("size_class should exist in pools");
671            pool.allocate(size, alignment)
672                .map_err(|e| TorshError::AllocationError(e.to_string()))?
673        };
674
675        // Update statistics
676        let mut stats = self
677            .stats
678            .lock()
679            .map_err(|_| TorshError::AllocationError("Failed to acquire stats lock".to_string()))?;
680        stats.allocated_memory += size;
681        stats.peak_memory = stats.peak_memory.max(stats.allocated_memory);
682        stats.total_allocations += 1;
683        stats.active_allocations += 1;
684
685        Ok(Buffer::new(
686            generate_buffer_id(),
687            self.device().clone(),
688            size,
689            descriptor.usage,
690            descriptor.clone(),
691            BufferHandle::Cpu { ptr, size },
692        ))
693    }
694
695    fn deallocate(&mut self, buffer: &Buffer) -> Result<()> {
696        let size_class = Self::calculate_size_class(buffer.size);
697
698        // Extract pointer from buffer handle
699        let ptr = match &buffer.handle {
700            BufferHandle::Cpu { ptr, .. } => *ptr,
701            _ => {
702                return Err(TorshError::AllocationError(
703                    "Invalid buffer handle type for CPU backend".to_string(),
704                ))
705            }
706        };
707
708        // Deallocate from the pool
709        {
710            let mut pools = self.pools.lock().map_err(|_| {
711                TorshError::AllocationError("Failed to acquire pools lock".to_string())
712            })?;
713
714            if let Some(pool) = pools.get_mut(&size_class) {
715                pool.deallocate(ptr, buffer.size)
716                    .map_err(|e| TorshError::AllocationError(e.to_string()))?;
717            } else {
718                return Err(TorshError::InvalidArgument(
719                    "No pool found for deallocating buffer".to_string(),
720                ));
721            }
722        }
723
724        // Update statistics
725        let mut stats = self
726            .stats
727            .lock()
728            .map_err(|_| TorshError::AllocationError("Failed to acquire stats lock".to_string()))?;
729        stats.allocated_memory = stats.allocated_memory.saturating_sub(buffer.size);
730        stats.total_deallocations += 1;
731        stats.active_allocations = stats.active_allocations.saturating_sub(1);
732
733        Ok(())
734    }
735
736    fn stats(&self) -> MemoryStats {
737        self.stats.lock_or_recover().clone()
738    }
739
740    fn garbage_collect(&mut self) -> Result<usize> {
741        // For CPU memory, we don't need explicit garbage collection
742        Ok(0)
743    }
744
745    fn set_pool(&mut self, _pool: Box<dyn MemoryPool>) -> Result<()> {
746        // Simple implementation - we manage our own pools
747        Ok(())
748    }
749
750    fn device(&self) -> &Device {
751        use crate::device::DeviceInfo;
752        use std::sync::OnceLock;
753        static CPU_DEVICE: OnceLock<Device> = OnceLock::new();
754        CPU_DEVICE.get_or_init(|| Device {
755            id: 0,
756            device_type: DeviceType::Cpu,
757            name: "CPU".to_string(),
758            info: DeviceInfo {
759                vendor: "CPU".to_string(),
760                driver_version: "CPU Backend 1.0".to_string(),
761                total_memory: 8 * 1024 * 1024 * 1024, // 8GB typical
762                available_memory: 8 * 1024 * 1024 * 1024,
763                compute_units: 1,
764                max_work_group_size: u32::MAX as usize,
765                max_work_group_dimensions: vec![u32::MAX as usize, 1, 1],
766                clock_frequency_mhz: 3000, // 3GHz typical
767                memory_bandwidth_gbps: 50.0,
768                peak_gflops: 100.0,
769                features: Vec::new(),
770                properties: Vec::new(),
771            },
772        })
773    }
774
775    fn allocate_raw(&mut self, size: usize, alignment: usize) -> Result<*mut u8> {
776        let size_class = Self::calculate_size_class(size);
777
778        // Select NUMA node for allocation
779        let numa_node = self.select_numa_node(size)?;
780
781        // Try NUMA-aware allocation first
782        if let Ok(numa_ptr) = self.allocate_on_numa_node(size, alignment, numa_node) {
783            // Track access pattern for NUMA-allocated memory
784            let mut patterns = self.access_patterns.lock().map_err(|_| {
785                TorshError::AllocationError("Failed to acquire access patterns lock".to_string())
786            })?;
787
788            let pattern = MemoryAccessPattern {
789                access_count: AtomicU64::new(0),
790                last_access: Instant::now(),
791                pattern_type: AccessPatternType::Unknown,
792                preferred_node: numa_node,
793            };
794
795            patterns.insert(numa_ptr as usize, pattern);
796            return Ok(numa_ptr);
797        }
798
799        // Fallback to regular pool allocation
800        {
801            let mut pools = self.pools.lock().map_err(|_| {
802                TorshError::AllocationError("Failed to acquire pools lock".to_string())
803            })?;
804
805            pools
806                .entry(size_class)
807                .or_insert_with(|| CpuMemoryPool::new(size_class));
808        }
809
810        let mut pools = self
811            .pools
812            .lock()
813            .map_err(|_| TorshError::AllocationError("Failed to acquire pools lock".to_string()))?;
814
815        let pool = pools
816            .get_mut(&size_class)
817            .expect("size_class should exist in pools");
818        pool.allocate(size, alignment)
819            .map_err(|e| TorshError::AllocationError(e.to_string()))
820    }
821
822    fn deallocate_raw(&mut self, ptr: *mut u8, size: usize) -> Result<()> {
823        let size_class = Self::calculate_size_class(size);
824
825        // Clean up access pattern tracking
826        {
827            let mut patterns = self.access_patterns.lock().map_err(|_| {
828                TorshError::AllocationError("Failed to acquire access patterns lock".to_string())
829            })?;
830            patterns.remove(&(ptr as usize));
831        }
832
833        let mut pools = self
834            .pools
835            .lock()
836            .map_err(|_| TorshError::AllocationError("Failed to acquire pools lock".to_string()))?;
837
838        if let Some(pool) = pools.get_mut(&size_class) {
839            pool.deallocate(ptr, size)
840                .map_err(|e| TorshError::AllocationError(e.to_string()))
841        } else {
842            // If no pool found, this might be NUMA-allocated memory
843            // Use std::alloc::dealloc as fallback (same as allocate_on_numa_node)
844            let alignment = if size <= 8 { 8 } else { 16 }; // Default alignment
845            if let Ok(layout) = std::alloc::Layout::from_size_align(size, alignment) {
846                unsafe {
847                    std::alloc::dealloc(ptr, layout);
848                }
849                Ok(())
850            } else {
851                Err(TorshError::InvalidArgument(
852                    "Invalid layout for deallocating memory".to_string(),
853                ))
854            }
855        }
856    }
857
858    fn supports_unified_memory(&self) -> bool {
859        // CPU memory is essentially "unified" since it's all system memory
860        true
861    }
862
863    fn allocate_unified(&mut self, size: usize) -> Result<*mut u8> {
864        // For CPU, unified memory is just regular allocation
865        self.allocate_raw(size, std::mem::align_of::<u8>())
866    }
867
868    fn deallocate_unified(&mut self, ptr: *mut u8, size: usize) -> Result<()> {
869        // For CPU, unified memory deallocation is just regular deallocation
870        self.deallocate_raw(ptr, size)
871    }
872
873    fn prefetch_to_device(&self, _ptr: *mut u8, _size: usize) -> Result<()> {
874        // No-op for CPU since all memory is already on the "device"
875        Ok(())
876    }
877
878    fn prefetch_to_host(&self, _ptr: *mut u8, _size: usize) -> Result<()> {
879        // No-op for CPU since all memory is already on the host
880        Ok(())
881    }
882
883    fn set_memory_advice(
884        &self,
885        _ptr: *mut u8,
886        _size: usize,
887        _advice: crate::memory::MemoryAdvice,
888    ) -> Result<()> {
889        // No-op for CPU since memory advice doesn't apply
890        Ok(())
891    }
892
893    fn available_memory(&self) -> Result<usize> {
894        // Get system memory info
895        #[cfg(target_os = "linux")]
896        {
897            use std::fs;
898            if let Ok(meminfo) = fs::read_to_string("/proc/meminfo") {
899                for line in meminfo.lines() {
900                    if line.starts_with("MemAvailable:") {
901                        if let Some(kb_str) = line.split_whitespace().nth(1) {
902                            if let Ok(kb) = kb_str.parse::<usize>() {
903                                return Ok(kb * 1024); // Convert KB to bytes
904                            }
905                        }
906                    }
907                }
908            }
909        }
910
911        // Fallback estimate
912        Ok(4 * 1024 * 1024 * 1024) // 4GB
913    }
914
915    fn total_memory(&self) -> Result<usize> {
916        // Get total system memory
917        #[cfg(target_os = "linux")]
918        {
919            use std::fs;
920            if let Ok(meminfo) = fs::read_to_string("/proc/meminfo") {
921                for line in meminfo.lines() {
922                    if line.starts_with("MemTotal:") {
923                        if let Some(kb_str) = line.split_whitespace().nth(1) {
924                            if let Ok(kb) = kb_str.parse::<usize>() {
925                                return Ok(kb * 1024); // Convert KB to bytes
926                            }
927                        }
928                    }
929                }
930            }
931        }
932
933        // Fallback estimate
934        Ok(8 * 1024 * 1024 * 1024) // 8GB
935    }
936
937    fn synchronize(&self) -> Result<()> {
938        // CPU operations are synchronous, so nothing to do
939        Ok(())
940    }
941
942    fn defragment(&mut self) -> Result<crate::memory::DefragmentationResult> {
943        // Simple stub implementation for CPU
944        Ok(crate::memory::DefragmentationResult {
945            blocks_moved: 0,
946            memory_compacted: 0,
947            duration_ms: 0.0,
948            fragmentation_before: 0.0,
949            fragmentation_after: 0.0,
950            efficiency_improvement: 0.0,
951            success: true,
952        })
953    }
954
955    fn needs_defragmentation(&self) -> bool {
956        // CPU memory pools typically don't need defragmentation
957        false
958    }
959
960    fn fragmentation_info(&self) -> crate::memory::FragmentationInfo {
961        // Simple implementation returning basic fragmentation info
962        crate::memory::FragmentationInfo {
963            overall_fragmentation: 0.1,
964            external_fragmentation: 0.05,
965            internal_fragmentation: 0.05,
966            free_blocks: 1,
967            allocated_blocks: 0,
968            largest_free_block: 1024 * 1024,
969            smallest_free_block: 1024,
970            average_free_block: 512 * 1024,
971            total_free_memory: 1024 * 1024,
972            total_allocated_memory: 0,
973            utilization_efficiency: 0.9,
974            allocation_efficiency: 0.9,
975        }
976    }
977
978    fn compact_memory(&mut self) -> Result<crate::memory::CompactionResult> {
979        // Simple stub implementation for CPU
980        Ok(crate::memory::CompactionResult {
981            allocations_moved: 0,
982            bytes_moved: 0,
983            duration_ms: 0.0,
984            largest_free_before: 1024 * 1024,
985            largest_free_after: 1024 * 1024,
986            free_blocks_before: 1,
987            free_blocks_after: 1,
988            success: true,
989        })
990    }
991
992    fn set_defragmentation_policy(&mut self, _policy: crate::memory::DefragmentationPolicy) {
993        // No-op for CPU since it doesn't need complex defragmentation
994    }
995}
996
997impl Default for CpuMemoryManager {
998    fn default() -> Self {
999        Self::new()
1000    }
1001}
1002
1003/// CPU memory manager factory
1004pub struct CpuMemoryManagerFactory;
1005
1006impl crate::memory::MemoryManagerFactory for CpuMemoryManagerFactory {
1007    fn create_manager(&self, _device: &Device) -> Result<Box<dyn crate::memory::MemoryManager>> {
1008        Ok(Box::new(CpuMemoryManager::new()))
1009    }
1010
1011    fn backend_type(&self) -> crate::BackendType {
1012        crate::BackendType::Cpu
1013    }
1014
1015    fn supports_device(&self, device: &Device) -> bool {
1016        device.device_type == DeviceType::Cpu
1017    }
1018}
1019
1020/// CPU memory pool implementation
1021#[derive(Debug)]
1022pub struct CpuMemoryPool {
1023    size_class: usize,
1024    #[allow(clippy::arc_with_non_send_sync)]
1025    free_blocks: Arc<Mutex<Vec<*mut u8>>>,
1026    #[allow(clippy::arc_with_non_send_sync)]
1027    allocated_blocks: Arc<Mutex<HashMap<*mut u8, (usize, usize)>>>, // (size, alignment)
1028}
1029
1030// SAFETY: We ensure thread safety by using Mutex and proper synchronization
1031unsafe impl Send for CpuMemoryPool {}
1032unsafe impl Sync for CpuMemoryPool {}
1033
1034impl Clone for CpuMemoryPool {
1035    fn clone(&self) -> Self {
1036        Self {
1037            size_class: self.size_class,
1038            free_blocks: Arc::clone(&self.free_blocks),
1039            allocated_blocks: Arc::clone(&self.allocated_blocks),
1040        }
1041    }
1042}
1043
1044impl CpuMemoryPool {
1045    /// Create a new CPU memory pool
1046    pub fn new(size_class: usize) -> Self {
1047        #[allow(clippy::arc_with_non_send_sync)]
1048        let free_blocks = Arc::new(Mutex::new(Vec::new()));
1049        #[allow(clippy::arc_with_non_send_sync)]
1050        let allocated_blocks = Arc::new(Mutex::new(HashMap::new()));
1051
1052        Self {
1053            size_class,
1054            free_blocks,
1055            allocated_blocks,
1056        }
1057    }
1058}
1059
1060impl MemoryPool for CpuMemoryPool {
1061    fn allocate(&mut self, size: usize, alignment: usize) -> Result<*mut u8> {
1062        let mut free_blocks = self.free_blocks.lock().map_err(|_| {
1063            TorshError::AllocationError("Failed to acquire free_blocks lock".to_string())
1064        })?;
1065
1066        // Try to reuse a free block
1067        if let Some(ptr) = free_blocks.pop() {
1068            let mut allocated_blocks = self.allocated_blocks.lock().map_err(|_| {
1069                TorshError::AllocationError("Failed to acquire allocated_blocks lock".to_string())
1070            })?;
1071            allocated_blocks.insert(ptr, (size, alignment));
1072            return Ok(ptr);
1073        }
1074
1075        // Allocate new block
1076        let layout = std::alloc::Layout::from_size_align(self.size_class, alignment)
1077            .map_err(|e| TorshError::AllocationError(format!("Invalid layout: {}", e)))?;
1078
1079        let ptr = unsafe { std::alloc::alloc(layout) };
1080
1081        if ptr.is_null() {
1082            return Err(TorshError::AllocationError(format!(
1083                "Failed to allocate {} bytes",
1084                size
1085            )));
1086        }
1087
1088        let mut allocated_blocks = self.allocated_blocks.lock().map_err(|_| {
1089            TorshError::AllocationError("Failed to acquire allocated_blocks lock".to_string())
1090        })?;
1091        allocated_blocks.insert(ptr, (size, alignment));
1092
1093        Ok(ptr)
1094    }
1095
1096    fn deallocate(&mut self, ptr: *mut u8, _size: usize) -> Result<()> {
1097        let mut allocated_blocks = self.allocated_blocks.lock().map_err(|_| {
1098            TorshError::AllocationError("Failed to acquire allocated_blocks lock".to_string())
1099        })?;
1100
1101        if allocated_blocks.remove(&ptr).is_some() {
1102            let mut free_blocks = self.free_blocks.lock().map_err(|_| {
1103                TorshError::AllocationError("Failed to acquire free_blocks lock".to_string())
1104            })?;
1105
1106            // Add to free list for reuse
1107            free_blocks.push(ptr);
1108            Ok(())
1109        } else {
1110            Err(TorshError::InvalidArgument(
1111                "Attempted to deallocate unknown pointer".to_string(),
1112            ))
1113        }
1114    }
1115
1116    fn stats(&self) -> PoolStats {
1117        let allocated_blocks = self
1118            .allocated_blocks
1119            .lock()
1120            .unwrap_or_else(|_| panic!("Lock poisoned"));
1121        let free_blocks = self
1122            .free_blocks
1123            .lock()
1124            .unwrap_or_else(|_| panic!("Lock poisoned"));
1125
1126        let allocated_bytes: usize = allocated_blocks.values().map(|(size, _)| *size).sum();
1127        let total_capacity = (allocated_blocks.len() + free_blocks.len()) * self.size_class;
1128
1129        PoolStats {
1130            capacity: total_capacity,
1131            allocated: allocated_bytes,
1132            available: total_capacity - allocated_bytes,
1133            free_blocks: free_blocks.len(),
1134            allocated_blocks: allocated_blocks.len(),
1135            largest_free_block: if free_blocks.is_empty() {
1136                0
1137            } else {
1138                self.size_class
1139            },
1140            smallest_free_block: if free_blocks.is_empty() {
1141                0
1142            } else {
1143                self.size_class
1144            },
1145            average_free_block: if free_blocks.is_empty() {
1146                0
1147            } else {
1148                self.size_class
1149            },
1150        }
1151    }
1152
1153    fn reset(&mut self) -> Result<()> {
1154        let mut allocated_blocks = self.allocated_blocks.lock().map_err(|_| {
1155            TorshError::AllocationError("Failed to acquire allocated_blocks lock".to_string())
1156        })?;
1157        let mut free_blocks = self.free_blocks.lock().map_err(|_| {
1158            TorshError::AllocationError("Failed to acquire free_blocks lock".to_string())
1159        })?;
1160
1161        // Deallocate all blocks
1162        for (&ptr, &(size, alignment)) in allocated_blocks.iter() {
1163            let layout = std::alloc::Layout::from_size_align(size, alignment)
1164                .expect("layout should be valid for previously allocated block");
1165            unsafe {
1166                std::alloc::dealloc(ptr, layout);
1167            }
1168        }
1169
1170        for &ptr in free_blocks.iter() {
1171            let layout = std::alloc::Layout::from_size_align(self.size_class, 1)
1172                .expect("layout should be valid for size_class");
1173            unsafe {
1174                std::alloc::dealloc(ptr, layout);
1175            }
1176        }
1177
1178        allocated_blocks.clear();
1179        free_blocks.clear();
1180
1181        Ok(())
1182    }
1183
1184    fn capacity(&self) -> usize {
1185        let allocated_blocks = self
1186            .allocated_blocks
1187            .lock()
1188            .unwrap_or_else(|_| panic!("Lock poisoned"));
1189        let free_blocks = self
1190            .free_blocks
1191            .lock()
1192            .unwrap_or_else(|_| panic!("Lock poisoned"));
1193        (allocated_blocks.len() + free_blocks.len()) * self.size_class
1194    }
1195
1196    fn available(&self) -> usize {
1197        let free_blocks = self
1198            .free_blocks
1199            .lock()
1200            .unwrap_or_else(|_| panic!("Lock poisoned"));
1201        free_blocks.len() * self.size_class
1202    }
1203
1204    fn defragment(&mut self) -> Result<crate::memory::DefragmentationResult> {
1205        // Simple stub implementation for CPU memory pool
1206        Ok(crate::memory::DefragmentationResult {
1207            blocks_moved: 0,
1208            memory_compacted: 0,
1209            duration_ms: 0.0,
1210            fragmentation_before: 0.0,
1211            fragmentation_after: 0.0,
1212            efficiency_improvement: 0.0,
1213            success: true,
1214        })
1215    }
1216
1217    fn needs_defragmentation(&self) -> bool {
1218        // CPU memory pools typically don't need defragmentation
1219        false
1220    }
1221
1222    fn fragmentation_info(&self) -> crate::memory::FragmentationInfo {
1223        let allocated_count = self.allocated_blocks.lock_or_recover().len();
1224        let free_count = self.free_blocks.lock_or_recover().len();
1225
1226        crate::memory::FragmentationInfo {
1227            overall_fragmentation: 0.1,
1228            external_fragmentation: 0.05,
1229            internal_fragmentation: 0.05,
1230            free_blocks: free_count,
1231            allocated_blocks: allocated_count,
1232            largest_free_block: self.size_class,
1233            smallest_free_block: if free_count > 0 { self.size_class } else { 0 },
1234            average_free_block: self.size_class,
1235            total_free_memory: free_count * self.size_class,
1236            total_allocated_memory: allocated_count * self.size_class,
1237            utilization_efficiency: 0.9,
1238            allocation_efficiency: 0.9,
1239        }
1240    }
1241
1242    fn compact(&mut self) -> Result<crate::memory::CompactionResult> {
1243        // Simple stub implementation for CPU memory pool
1244        Ok(crate::memory::CompactionResult {
1245            allocations_moved: 0,
1246            bytes_moved: 0,
1247            duration_ms: 0.0,
1248            largest_free_before: self.size_class,
1249            largest_free_after: self.size_class,
1250            free_blocks_before: self.free_blocks.lock_or_recover().len(),
1251            free_blocks_after: self.free_blocks.lock_or_recover().len(),
1252            success: true,
1253        })
1254    }
1255}
1256
1257// Implement Drop for CpuMemoryPool to clean up allocated memory
1258impl Drop for CpuMemoryPool {
1259    fn drop(&mut self) {
1260        // Clean up any remaining allocated blocks (still in use)
1261        if let Ok(allocated_blocks) = self.allocated_blocks.lock() {
1262            for (&ptr, &(size, alignment)) in allocated_blocks.iter() {
1263                let layout = std::alloc::Layout::from_size_align(size, alignment)
1264                    .expect("layout should be valid for previously allocated block");
1265                unsafe {
1266                    std::alloc::dealloc(ptr, layout);
1267                }
1268            }
1269        }
1270
1271        // Clean up free blocks (available for reuse)
1272        if let Ok(free_blocks) = self.free_blocks.lock() {
1273            for &ptr in free_blocks.iter() {
1274                // Use consistent alignment for size_class allocations
1275                let layout = std::alloc::Layout::from_size_align(self.size_class, 8)
1276                    .expect("layout should be valid for size_class");
1277                unsafe {
1278                    std::alloc::dealloc(ptr, layout);
1279                }
1280            }
1281        }
1282    }
1283}
1284
1285#[cfg(test)]
1286mod tests {
1287    use super::*;
1288    // Removed unused import
1289
1290    #[test]
1291    fn test_size_class_calculation() {
1292        assert_eq!(CpuMemoryManager::calculate_size_class(32), 64);
1293        assert_eq!(CpuMemoryManager::calculate_size_class(64), 64);
1294        assert_eq!(CpuMemoryManager::calculate_size_class(65), 128);
1295        assert_eq!(CpuMemoryManager::calculate_size_class(1000), 1024);
1296        assert_eq!(CpuMemoryManager::calculate_size_class(2048), 2048);
1297    }
1298
1299    #[test]
1300    fn test_memory_manager_creation() {
1301        let manager = CpuMemoryManager::new();
1302        let stats = manager.stats();
1303        assert_eq!(stats.allocated_memory, 0);
1304    }
1305
1306    #[test]
1307    fn test_unified_memory_allocation() {
1308        let mut manager = CpuMemoryManager::new();
1309
1310        // Test unified memory support
1311        assert!(manager.supports_unified_memory());
1312
1313        // Test unified memory allocation
1314        let ptr = manager
1315            .allocate_unified(1024)
1316            .expect("unified memory allocation should succeed");
1317        assert!(!ptr.is_null());
1318
1319        // Test deallocation
1320        let result = manager.deallocate_unified(ptr, 1024);
1321        assert!(result.is_ok());
1322    }
1323
1324    #[test]
1325    fn test_raw_memory_allocation() {
1326        let mut manager = CpuMemoryManager::new();
1327
1328        // Test raw memory allocation with alignment
1329        let ptr = manager
1330            .allocate_raw(256, 16)
1331            .expect("raw memory allocation should succeed");
1332        assert!(!ptr.is_null());
1333
1334        // Check alignment
1335        assert_eq!(ptr as usize % 16, 0);
1336
1337        // Test deallocation
1338        let result = manager.deallocate_raw(ptr, 256);
1339        assert!(result.is_ok());
1340    }
1341
1342    #[test]
1343    fn test_memory_info_queries() {
1344        let manager = CpuMemoryManager::new();
1345
1346        // Test memory queries
1347        let total = manager
1348            .total_memory()
1349            .expect("total memory query should succeed");
1350        let available = manager
1351            .available_memory()
1352            .expect("available memory query should succeed");
1353
1354        assert!(total > 0);
1355        assert!(available > 0);
1356        assert!(available <= total);
1357    }
1358
1359    #[test]
1360    fn test_memory_operations() {
1361        let mut manager = CpuMemoryManager::new();
1362
1363        // Test prefetch operations (should be no-ops for CPU)
1364        let ptr = manager
1365            .allocate_raw(64, 8)
1366            .expect("raw memory allocation should succeed");
1367
1368        assert!(manager.prefetch_to_device(ptr, 64).is_ok());
1369        assert!(manager.prefetch_to_host(ptr, 64).is_ok());
1370
1371        // Test memory advice (should be no-op for CPU)
1372        assert!(manager
1373            .set_memory_advice(ptr, 64, crate::memory::MemoryAdvice::SetReadMostly)
1374            .is_ok());
1375
1376        // Test synchronization (should be no-op for CPU)
1377        assert!(manager.synchronize().is_ok());
1378
1379        // Cleanup
1380        manager
1381            .deallocate_raw(ptr, 64)
1382            .expect("raw memory deallocation should succeed");
1383    }
1384
1385    #[test]
1386    fn test_memory_manager_factory() {
1387        use crate::device::{Device, DeviceInfo};
1388        use crate::memory::MemoryManagerFactory;
1389
1390        let factory = CpuMemoryManagerFactory;
1391        let device = Device::new(
1392            0,
1393            DeviceType::Cpu,
1394            "Test CPU".to_string(),
1395            DeviceInfo::default(),
1396        );
1397
1398        // Test device support
1399        assert!(factory.supports_device(&device));
1400        assert_eq!(factory.backend_type(), crate::BackendType::Cpu);
1401
1402        // Test manager creation
1403        let manager = factory.create_manager(&device);
1404        assert!(manager.is_ok());
1405
1406        let manager = manager.expect("operation should succeed");
1407        assert!(manager.supports_unified_memory());
1408    }
1409}