1#![allow(dead_code)]
9use std::alloc::{self, Layout};
10use std::ptr::NonNull;
11
12use crate::cpu::error::CpuResult;
13
14pub const CACHE_LINE_SIZE: usize = 64;
16
17#[derive(Debug, Clone, Copy)]
19pub enum AccessPattern {
20 Sequential, Strided(usize), Random, Blocked(usize), }
25
26#[derive(Debug, Clone, Copy)]
28pub enum LayoutStrategy {
29 RowMajor, ColumnMajor, Blocked(usize), ZMorton, Hilbert, CacheOblivious, }
36
37#[derive(Debug, Clone, Copy)]
39pub enum NumaPolicy {
40 Local, Interleave, Preferred(usize), Bind(usize), }
45
46#[derive(Debug, Clone, Copy)]
48pub enum PrefetchStrategy {
49 None,
50 Software(usize), Hardware, Adaptive, }
54
55pub struct CacheAlignedAllocator {
57 alignment: usize,
58 numa_policy: NumaPolicy,
59}
60
61impl Default for CacheAlignedAllocator {
62 fn default() -> Self {
63 Self::new()
64 }
65}
66
67impl CacheAlignedAllocator {
68 pub fn new() -> Self {
69 Self {
70 alignment: CACHE_LINE_SIZE,
71 numa_policy: NumaPolicy::Local,
72 }
73 }
74
75 pub fn with_alignment(alignment: usize) -> Self {
76 Self {
77 alignment,
78 numa_policy: NumaPolicy::Local,
79 }
80 }
81
82 pub fn with_numa_policy(numa_policy: NumaPolicy) -> Self {
83 Self {
84 alignment: CACHE_LINE_SIZE,
85 numa_policy,
86 }
87 }
88
89 pub fn allocate<T>(&self, count: usize) -> CpuResult<CacheAlignedBuffer<T>> {
91 let layout = Layout::from_size_align(
92 count * std::mem::size_of::<T>(),
93 self.alignment.max(std::mem::align_of::<T>()),
94 )
95 .map_err(|_| crate::cpu::error::cpu_errors::memory_allocation_error("Invalid layout"))?;
96
97 let ptr = unsafe { alloc::alloc(layout) };
98 if ptr.is_null() {
99 return Err(crate::cpu::error::cpu_errors::memory_allocation_error(
100 "Allocation failed",
101 ));
102 }
103
104 Ok(CacheAlignedBuffer {
105 ptr: NonNull::new(ptr as *mut T).expect("ptr should not be null after null check"),
106 len: count,
107 layout,
108 numa_policy: self.numa_policy,
109 })
110 }
111
112 pub fn allocate_zeroed<T>(&self, count: usize) -> CpuResult<CacheAlignedBuffer<T>> {
114 let layout = Layout::from_size_align(
115 count * std::mem::size_of::<T>(),
116 self.alignment.max(std::mem::align_of::<T>()),
117 )
118 .map_err(|_| crate::cpu::error::cpu_errors::memory_allocation_error("Invalid layout"))?;
119
120 let ptr = unsafe { alloc::alloc_zeroed(layout) };
121 if ptr.is_null() {
122 return Err(crate::cpu::error::cpu_errors::memory_allocation_error(
123 "Allocation failed",
124 ));
125 }
126
127 Ok(CacheAlignedBuffer {
128 ptr: NonNull::new(ptr as *mut T).expect("ptr should not be null after null check"),
129 len: count,
130 layout,
131 numa_policy: self.numa_policy,
132 })
133 }
134}
135
136pub struct CacheAlignedBuffer<T> {
138 ptr: NonNull<T>,
139 len: usize,
140 layout: Layout,
141 #[allow(dead_code)]
142 numa_policy: NumaPolicy,
143}
144
145impl<T> CacheAlignedBuffer<T> {
146 pub fn as_ptr(&self) -> *const T {
148 self.ptr.as_ptr()
149 }
150
151 pub fn as_mut_ptr(&mut self) -> *mut T {
153 self.ptr.as_ptr()
154 }
155
156 pub fn len(&self) -> usize {
158 self.len
159 }
160
161 pub fn is_empty(&self) -> bool {
163 self.len == 0
164 }
165
166 pub unsafe fn as_slice(&self) -> &[T] {
175 std::slice::from_raw_parts(self.ptr.as_ptr(), self.len)
176 }
177
178 pub unsafe fn as_mut_slice(&mut self) -> &mut [T] {
188 std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len)
189 }
190
191 pub fn is_cache_aligned(&self) -> bool {
193 (self.ptr.as_ptr() as usize).is_multiple_of(CACHE_LINE_SIZE)
194 }
195}
196
197impl<T> Drop for CacheAlignedBuffer<T> {
198 fn drop(&mut self) {
199 unsafe {
200 alloc::dealloc(self.ptr.as_ptr() as *mut u8, self.layout);
201 }
202 }
203}
204
205unsafe impl<T: Send> Send for CacheAlignedBuffer<T> {}
206unsafe impl<T: Sync> Sync for CacheAlignedBuffer<T> {}
207
208pub struct AccessPatternOptimizer {
210 prefetch_strategy: PrefetchStrategy,
211 layout_strategy: LayoutStrategy,
212 cache_line_size: usize,
213 l1_cache_size: usize,
214 l2_cache_size: usize,
215 l3_cache_size: usize,
216}
217
218impl Default for AccessPatternOptimizer {
219 fn default() -> Self {
220 Self::new()
221 }
222}
223
224impl AccessPatternOptimizer {
225 pub fn new() -> Self {
226 Self {
227 prefetch_strategy: PrefetchStrategy::Adaptive,
228 layout_strategy: LayoutStrategy::RowMajor,
229 cache_line_size: CACHE_LINE_SIZE,
230 l1_cache_size: 32 * 1024, l2_cache_size: 256 * 1024, l3_cache_size: 8 * 1024 * 1024, }
234 }
235
236 pub fn with_cache_sizes(l1: usize, l2: usize, l3: usize) -> Self {
237 Self {
238 prefetch_strategy: PrefetchStrategy::Adaptive,
239 layout_strategy: LayoutStrategy::RowMajor,
240 cache_line_size: CACHE_LINE_SIZE,
241 l1_cache_size: l1,
242 l2_cache_size: l2,
243 l3_cache_size: l3,
244 }
245 }
246
247 pub fn set_prefetch_strategy(&mut self, strategy: PrefetchStrategy) {
249 self.prefetch_strategy = strategy;
250 }
251
252 pub fn set_layout_strategy(&mut self, strategy: LayoutStrategy) {
254 self.layout_strategy = strategy;
255 }
256
257 pub fn optimal_block_size(&self, element_size: usize, cache_level: CacheLevel) -> usize {
259 let cache_size = match cache_level {
260 CacheLevel::L1 => self.l1_cache_size,
261 CacheLevel::L2 => self.l2_cache_size,
262 CacheLevel::L3 => self.l3_cache_size,
263 };
264
265 let usable_cache = cache_size / 2;
267 let _elements_in_cache = usable_cache / element_size;
268
269 let mut block_size = 1;
271 while block_size * block_size * element_size <= usable_cache {
272 block_size *= 2;
273 }
274 block_size / 2
275 }
276
277 pub fn optimize_matrix_access<T: Copy>(
279 &self,
280 matrix: &[T],
281 rows: usize,
282 cols: usize,
283 access_pattern: AccessPattern,
284 ) -> Vec<usize> {
285 match access_pattern {
286 AccessPattern::Sequential => (0..matrix.len()).collect(),
287 AccessPattern::Strided(stride) => (0..matrix.len()).step_by(stride).collect(),
288 AccessPattern::Random => {
289 let mut indices: Vec<usize> = (0..matrix.len()).collect();
291 indices.sort_by_key(|&i| i / (self.cache_line_size / std::mem::size_of::<T>()));
293 indices
294 }
295 AccessPattern::Blocked(block_size) => {
296 self.generate_blocked_access_pattern(rows, cols, block_size)
297 }
298 }
299 }
300
301 fn generate_blocked_access_pattern(
303 &self,
304 rows: usize,
305 cols: usize,
306 block_size: usize,
307 ) -> Vec<usize> {
308 let mut indices = Vec::new();
309
310 let row_blocks = (rows + block_size - 1) / block_size;
311 let col_blocks = (cols + block_size - 1) / block_size;
312
313 for block_row in 0..row_blocks {
314 for block_col in 0..col_blocks {
315 let start_row = block_row * block_size;
316 let end_row = ((block_row + 1) * block_size).min(rows);
317 let start_col = block_col * block_size;
318 let end_col = ((block_col + 1) * block_size).min(cols);
319
320 for i in start_row..end_row {
321 for j in start_col..end_col {
322 indices.push(i * cols + j);
323 }
324 }
325 }
326 }
327
328 indices
329 }
330
331 pub fn prefetch_memory<T>(&self, ptr: *const T, len: usize, access_pattern: AccessPattern) {
333 match self.prefetch_strategy {
334 PrefetchStrategy::None => {}
335 PrefetchStrategy::Software(distance) => {
336 self.software_prefetch(ptr, len, distance, access_pattern);
337 }
338 PrefetchStrategy::Hardware => {
339 #[cfg(target_arch = "x86_64")]
341 unsafe {
342 std::arch::x86_64::_mm_prefetch(
344 ptr as *const i8,
345 std::arch::x86_64::_MM_HINT_T0,
346 );
347 }
348 }
349 PrefetchStrategy::Adaptive => {
350 match access_pattern {
352 AccessPattern::Sequential => {
353 self.software_prefetch(ptr, len, 4, access_pattern);
354 }
355 AccessPattern::Strided(stride) if stride <= 16 => {
356 self.software_prefetch(ptr, len, 2, access_pattern);
357 }
358 _ => {
359 #[cfg(target_arch = "x86_64")]
361 unsafe {
362 std::arch::x86_64::_mm_prefetch(
363 ptr as *const i8,
364 std::arch::x86_64::_MM_HINT_T1,
365 );
366 }
367 }
368 }
369 }
370 }
371 }
372
373 fn software_prefetch<T>(
375 &self,
376 _ptr: *const T,
377 len: usize,
378 distance: usize,
379 pattern: AccessPattern,
380 ) {
381 match pattern {
382 AccessPattern::Sequential => {
383 for _i in (0..len).step_by(self.cache_line_size / std::mem::size_of::<T>()) {
384 if _i + distance < len {
385 #[cfg(target_arch = "x86_64")]
386 unsafe {
387 let prefetch_ptr = _ptr.add(_i + distance);
388 std::arch::x86_64::_mm_prefetch(
389 prefetch_ptr as *const i8,
390 std::arch::x86_64::_MM_HINT_T0,
391 );
392 }
393 }
394 }
395 }
396 AccessPattern::Strided(stride) => {
397 for _i in (0..len).step_by(stride) {
398 if _i + distance * stride < len {
399 #[cfg(target_arch = "x86_64")]
400 unsafe {
401 let prefetch_ptr = _ptr.add(_i + distance * stride);
402 std::arch::x86_64::_mm_prefetch(
403 prefetch_ptr as *const i8,
404 std::arch::x86_64::_MM_HINT_T0,
405 );
406 }
407 }
408 }
409 }
410 _ => {
411 for _i in (0..len).step_by(self.cache_line_size / std::mem::size_of::<T>()) {
413 #[cfg(target_arch = "x86_64")]
414 unsafe {
415 let prefetch_ptr = _ptr.add(_i);
416 std::arch::x86_64::_mm_prefetch(
417 prefetch_ptr as *const i8,
418 std::arch::x86_64::_MM_HINT_T1,
419 );
420 }
421 }
422 }
423 }
424 }
425
426 pub fn calculate_bandwidth_utilization(
428 &self,
429 bytes_transferred: usize,
430 time_elapsed: std::time::Duration,
431 ) -> f64 {
432 if time_elapsed.as_secs_f64() > 0.0 {
433 bytes_transferred as f64 / time_elapsed.as_secs_f64() / (1024.0 * 1024.0 * 1024.0)
434 } else {
436 0.0
437 }
438 }
439
440 pub fn optimal_streaming_chunk_size(&self, element_size: usize) -> usize {
442 let target_bytes = (self.l2_cache_size * 3) / 4;
444 let chunk_elements = target_bytes / element_size;
445
446 let elements_per_line = self.cache_line_size / element_size;
448 (chunk_elements / elements_per_line) * elements_per_line
449 }
450}
451
452#[derive(Debug, Clone, Copy)]
454pub enum CacheLevel {
455 L1,
456 L2,
457 L3,
458}
459
460pub struct LayoutTransformer {
462 optimizer: AccessPatternOptimizer,
463}
464
465impl Default for LayoutTransformer {
466 fn default() -> Self {
467 Self::new()
468 }
469}
470
471impl LayoutTransformer {
472 pub fn new() -> Self {
473 Self {
474 optimizer: AccessPatternOptimizer::new(),
475 }
476 }
477
478 pub fn to_blocked_layout<T: Copy>(
480 &self,
481 input: &[T],
482 rows: usize,
483 cols: usize,
484 block_size: usize,
485 ) -> Vec<T> {
486 let mut output = vec![input[0]; input.len()]; let row_blocks = (rows + block_size - 1) / block_size;
489 let col_blocks = (cols + block_size - 1) / block_size;
490
491 let mut out_idx = 0;
492
493 for block_row in 0..row_blocks {
494 for block_col in 0..col_blocks {
495 let start_row = block_row * block_size;
496 let end_row = ((block_row + 1) * block_size).min(rows);
497 let start_col = block_col * block_size;
498 let end_col = ((block_col + 1) * block_size).min(cols);
499
500 for i in start_row..end_row {
501 for j in start_col..end_col {
502 if out_idx < output.len() {
503 output[out_idx] = input[i * cols + j];
504 out_idx += 1;
505 }
506 }
507 }
508 }
509 }
510
511 output
512 }
513
514 pub fn from_blocked_layout<T: Copy>(
516 &self,
517 input: &[T],
518 rows: usize,
519 cols: usize,
520 block_size: usize,
521 ) -> Vec<T> {
522 let mut output = vec![input[0]; input.len()];
523
524 let row_blocks = (rows + block_size - 1) / block_size;
525 let col_blocks = (cols + block_size - 1) / block_size;
526
527 let mut in_idx = 0;
528
529 for block_row in 0..row_blocks {
530 for block_col in 0..col_blocks {
531 let start_row = block_row * block_size;
532 let end_row = ((block_row + 1) * block_size).min(rows);
533 let start_col = block_col * block_size;
534 let end_col = ((block_col + 1) * block_size).min(cols);
535
536 for i in start_row..end_row {
537 for j in start_col..end_col {
538 if in_idx < input.len() {
539 output[i * cols + j] = input[in_idx];
540 in_idx += 1;
541 }
542 }
543 }
544 }
545 }
546
547 output
548 }
549
550 pub fn estimate_cache_miss_rate(
552 &self,
553 data_size: usize,
554 access_pattern: AccessPattern,
555 cache_level: CacheLevel,
556 ) -> f64 {
557 let cache_size = match cache_level {
558 CacheLevel::L1 => self.optimizer.l1_cache_size,
559 CacheLevel::L2 => self.optimizer.l2_cache_size,
560 CacheLevel::L3 => self.optimizer.l3_cache_size,
561 };
562
563 match access_pattern {
564 AccessPattern::Sequential => {
565 if data_size <= cache_size {
566 0.01 } else {
568 1.0 - (cache_size as f64 / data_size as f64)
569 }
570 }
571 AccessPattern::Strided(stride) => {
572 let effective_size = data_size * stride;
573 if effective_size <= cache_size {
574 0.05
575 } else {
576 0.8
577 }
578 }
579 AccessPattern::Random => {
580 if data_size <= cache_size {
581 0.1
582 } else {
583 0.95 }
585 }
586 AccessPattern::Blocked(block_size) => {
587 let block_data_size = block_size * block_size * 4; if block_data_size <= cache_size {
589 0.02
590 } else {
591 0.3
592 }
593 }
594 }
595 }
596}
597
598#[cfg(test)]
599mod tests {
600 use super::*;
601
602 #[test]
603 fn test_cache_aligned_allocator() {
604 let allocator = CacheAlignedAllocator::new();
605 let buffer = allocator
606 .allocate::<f32>(1000)
607 .expect("operation should succeed");
608
609 assert_eq!(buffer.len(), 1000);
610 assert!(buffer.is_cache_aligned());
611 }
612
613 #[test]
614 fn test_access_pattern_optimizer() {
615 let optimizer = AccessPatternOptimizer::new();
616
617 let block_size = optimizer.optimal_block_size(4, CacheLevel::L1);
618 assert!(block_size > 0);
619 assert!(block_size.is_power_of_two());
620
621 let streaming_chunk = optimizer.optimal_streaming_chunk_size(4);
622 assert!(streaming_chunk > 0);
623 assert!(streaming_chunk % (CACHE_LINE_SIZE / 4) == 0);
624 }
625
626 #[test]
627 fn test_matrix_access_optimization() {
628 let optimizer = AccessPatternOptimizer::new();
629 let matrix = vec![1.0f32; 100];
630
631 let indices = optimizer.optimize_matrix_access(&matrix, 10, 10, AccessPattern::Sequential);
632
633 assert_eq!(indices.len(), matrix.len());
634 assert_eq!(indices, (0..100).collect::<Vec<_>>());
635
636 let blocked_indices =
637 optimizer.optimize_matrix_access(&matrix, 10, 10, AccessPattern::Blocked(4));
638
639 assert_eq!(blocked_indices.len(), matrix.len());
640 }
641
642 #[test]
643 fn test_layout_transformer() {
644 let transformer = LayoutTransformer::new();
645 let input: Vec<f32> = (0..16).map(|i| i as f32).collect();
646
647 let blocked = transformer.to_blocked_layout(&input, 4, 4, 2);
648 assert_eq!(blocked.len(), input.len());
649
650 let restored = transformer.from_blocked_layout(&blocked, 4, 4, 2);
651 assert_eq!(restored, input);
652 }
653
654 #[test]
655 fn test_cache_miss_estimation() {
656 let transformer = LayoutTransformer::new();
657
658 let miss_rate_seq =
659 transformer.estimate_cache_miss_rate(1000, AccessPattern::Sequential, CacheLevel::L1);
660
661 let miss_rate_random =
662 transformer.estimate_cache_miss_rate(1000, AccessPattern::Random, CacheLevel::L1);
663
664 assert!(miss_rate_seq < miss_rate_random);
665 }
666
667 #[test]
668 fn test_bandwidth_calculation() {
669 let optimizer = AccessPatternOptimizer::new();
670 let bandwidth = optimizer.calculate_bandwidth_utilization(
671 1024 * 1024 * 1024, std::time::Duration::from_secs(1),
673 );
674
675 assert!((bandwidth - 1.0).abs() < 0.01); }
677}
678
679pub fn calculate_memory_bandwidth(bytes: usize, elapsed: std::time::Duration) -> f64 {
683 if elapsed.as_secs_f64() > 0.0 {
684 bytes as f64 / elapsed.as_secs_f64() / (1024.0 * 1024.0 * 1024.0) } else {
686 0.0
687 }
688}