torsh-backend 0.1.2

Backend abstraction layer for ToRSh
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
//! Zero-copy memory transfer implementations for ToRSh backends
//!
//! This module provides efficient zero-copy host-device and device-device transfers
//! where supported by the underlying hardware and drivers.

// Framework infrastructure - components designed for future use
#![allow(dead_code)]
use crate::error::{BackendError, BackendResult};
use crate::{Device, MemoryManager};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use torsh_core::device::DeviceType;

#[cfg(feature = "cuda")]
use crate::cuda::CudaDevice as SciRs2CudaDevice;

// Temporary mock for scirs2_cuda (actual crate not yet available)
// This mock provides stub implementations until scirs2_cuda is implemented
#[cfg(feature = "cuda")]
mod scirs2_cuda {
    // Mock CUDA device type for fallback scenarios
    #[derive(Debug)]
    pub struct MockCudaDevice {
        id: usize,
    }

    pub mod memory {
        pub enum MemoryAdvice {
            SetPreferredLocation(u32),
            SetAccessedBy(u32),
            SetReadMostly,
            UnsetReadMostly,
        }

        pub async fn prefetch_async(
            _device: &crate::cuda::CudaDevice,
            _ptr: *const u8,
            _size: usize,
        ) -> Result<(), String> {
            Err("CUDA not available".to_string())
        }

        pub async fn set_advice(
            _ptr: *const u8,
            _size: usize,
            _advice: MemoryAdvice,
        ) -> Result<(), String> {
            Err("CUDA not available".to_string())
        }

        pub async fn copy_peer_to_peer(
            _src: *const u8,
            _dst: *mut u8,
            _size: usize,
        ) -> Result<(), String> {
            Err("CUDA not available".to_string())
        }

        pub async fn copy_host_to_device_async(
            _src: *const u8,
            _dst: *mut u8,
            _size: usize,
        ) -> Result<(), String> {
            Err("CUDA not available".to_string())
        }

        pub async fn copy_device_to_host_async(
            _src: *const u8,
            _dst: *mut u8,
            _size: usize,
        ) -> Result<(), String> {
            Err("CUDA not available".to_string())
        }

        pub fn copy_host_to_device(
            _src: *const u8,
            _dst: *mut u8,
            _size: usize,
        ) -> Result<(), String> {
            Err("CUDA not available".to_string())
        }

        pub fn copy_device_to_host(
            _src: *const u8,
            _dst: *mut u8,
            _size: usize,
        ) -> Result<(), String> {
            Err("CUDA not available".to_string())
        }
    }

    // Add missing synchronize function for CUDA - this is at the scirs2_cuda module level
    pub fn synchronize(_device: &crate::cuda::CudaDevice) -> Result<(), String> {
        Err("CUDA not available".to_string())
    }
}

#[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
use crate::metal::MetalDevice as SciRs2MetalDevice;

// Temporary mock for scirs2_metal since scirs2_core doesn't have a metal module yet
#[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
mod scirs2_metal {
    pub mod memory {
        use crate::metal::device::MetalDevice;

        pub enum CpuCacheMode {
            WriteCombined,
        }

        pub fn set_cpu_cache_mode(
            _device: &MetalDevice,
            _ptr: *mut u8,
            _mode: CpuCacheMode,
        ) -> Result<(), String> {
            // Mock implementation - in real implementation would set Metal cache mode
            Ok(())
        }

        pub async fn copy_host_to_device_async(
            _device: &MetalDevice,
            _src_ptr: *const u8,
            _dst_ptr: *mut u8,
            _size: usize,
        ) -> Result<(), String> {
            // Mock implementation - in real implementation would use Metal async copy
            Ok(())
        }

        pub async fn copy_device_to_host_async(
            _device: &MetalDevice,
            _src_ptr: *const u8,
            _dst_ptr: *mut u8,
            _size: usize,
        ) -> Result<(), String> {
            // Mock implementation - in real implementation would use Metal async copy
            Ok(())
        }

        pub fn copy_host_to_device(
            _device: &MetalDevice,
            _src_ptr: *const u8,
            _dst_ptr: *mut u8,
            _size: usize,
        ) -> Result<(), String> {
            // Mock implementation - in real implementation would use Metal sync copy
            Ok(())
        }

        pub fn copy_device_to_host(
            _device: &MetalDevice,
            _src_ptr: *const u8,
            _dst_ptr: *mut u8,
            _size: usize,
        ) -> Result<(), String> {
            // Mock implementation - in real implementation would use Metal sync copy
            Ok(())
        }
    }

    pub fn synchronize(_device: &crate::metal::device::MetalDevice) -> Result<(), String> {
        // Mock implementation - in real implementation would synchronize Metal commands
        Ok(())
    }
}

/// Transfer mode for zero-copy operations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransferMode {
    /// Synchronous transfer (blocking)
    Synchronous,
    /// Asynchronous transfer (non-blocking)
    Asynchronous,
    /// Streaming transfer (for large data)
    Streaming,
    /// Peer-to-peer direct transfer
    PeerToPeer,
}

/// Transfer direction
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransferDirection {
    /// Host to device transfer
    HostToDevice,
    /// Device to host transfer
    DeviceToHost,
    /// Device to device transfer (same device)
    DeviceToDevice,
    /// Cross-device transfer (different devices)
    CrossDevice,
}

/// Zero-copy capability flags
#[derive(Debug, Clone, Copy)]
pub struct ZeroCopyCapabilities {
    /// Supports unified memory (host-device accessible)
    pub unified_memory: bool,
    /// Supports peer-to-peer access
    pub peer_to_peer: bool,
    /// Supports memory mapping
    pub memory_mapping: bool,
    /// Supports direct GPU access
    pub direct_gpu_access: bool,
    /// Supports pinned host memory
    pub pinned_memory: bool,
    /// Supports memory advice hints
    pub memory_advice: bool,
    /// Supports asynchronous transfers
    pub async_transfers: bool,
    /// Supports streaming transfers
    pub streaming_transfers: bool,
}

impl Default for ZeroCopyCapabilities {
    fn default() -> Self {
        Self {
            unified_memory: false,
            peer_to_peer: false,
            memory_mapping: false,
            direct_gpu_access: false,
            pinned_memory: false,
            memory_advice: false,
            async_transfers: false,
            streaming_transfers: false,
        }
    }
}

impl ZeroCopyCapabilities {
    /// Check if any zero-copy features are supported
    pub fn has_any_capabilities(&self) -> bool {
        self.unified_memory
            || self.peer_to_peer
            || self.memory_mapping
            || self.direct_gpu_access
            || self.pinned_memory
            || self.async_transfers
    }

    /// Get capabilities score (0.0 to 1.0)
    pub fn capability_score(&self) -> f32 {
        let mut score = 0.0;
        let total_features = 8.0;

        if self.unified_memory {
            score += 1.0;
        }
        if self.peer_to_peer {
            score += 1.0;
        }
        if self.memory_mapping {
            score += 1.0;
        }
        if self.direct_gpu_access {
            score += 1.0;
        }
        if self.pinned_memory {
            score += 1.0;
        }
        if self.memory_advice {
            score += 1.0;
        }
        if self.async_transfers {
            score += 1.0;
        }
        if self.streaming_transfers {
            score += 1.0;
        }

        score / total_features
    }

    /// Get recommended transfer mode for given capabilities
    pub fn recommended_transfer_mode(&self) -> TransferMode {
        if self.streaming_transfers {
            TransferMode::Streaming
        } else if self.async_transfers {
            TransferMode::Asynchronous
        } else if self.peer_to_peer {
            TransferMode::PeerToPeer
        } else {
            TransferMode::Synchronous
        }
    }
}

/// Zero-copy transfer descriptor
#[derive(Debug, Clone)]
pub struct ZeroCopyTransfer {
    /// Source device
    pub source_device: Device,
    /// Destination device
    pub destination_device: Device,
    /// Transfer direction
    pub direction: TransferDirection,
    /// Transfer mode
    pub mode: TransferMode,
    /// Source memory pointer
    pub source_ptr: *mut u8,
    /// Destination memory pointer
    pub destination_ptr: *mut u8,
    /// Size in bytes
    pub size: usize,
    /// Memory alignment requirement
    pub alignment: usize,
    /// Priority level (0 = highest, higher numbers = lower priority)
    pub priority: u32,
    /// Optional stream/queue for asynchronous operations
    pub stream_id: Option<u64>,
}

unsafe impl Send for ZeroCopyTransfer {}
unsafe impl Sync for ZeroCopyTransfer {}

impl ZeroCopyTransfer {
    /// Create a new zero-copy transfer descriptor
    pub fn new(
        source_device: Device,
        destination_device: Device,
        source_ptr: *mut u8,
        destination_ptr: *mut u8,
        size: usize,
    ) -> Self {
        let direction = if source_device.device_type() == DeviceType::Cpu
            && destination_device.device_type() != DeviceType::Cpu
        {
            TransferDirection::HostToDevice
        } else if source_device.device_type() != DeviceType::Cpu
            && destination_device.device_type() == DeviceType::Cpu
        {
            TransferDirection::DeviceToHost
        } else if source_device.id() == destination_device.id() {
            TransferDirection::DeviceToDevice
        } else {
            TransferDirection::CrossDevice
        };

        Self {
            source_device,
            destination_device,
            direction,
            mode: TransferMode::Synchronous,
            source_ptr,
            destination_ptr,
            size,
            alignment: 1,
            priority: 1,
            stream_id: None,
        }
    }

    /// Set transfer mode
    pub fn with_mode(mut self, mode: TransferMode) -> Self {
        self.mode = mode;
        self
    }

    /// Set alignment requirement
    pub fn with_alignment(mut self, alignment: usize) -> Self {
        self.alignment = alignment;
        self
    }

    /// Set priority
    pub fn with_priority(mut self, priority: u32) -> Self {
        self.priority = priority;
        self
    }

    /// Set stream ID for asynchronous operations
    pub fn with_stream(mut self, stream_id: u64) -> Self {
        self.stream_id = Some(stream_id);
        self
    }

    /// Check if transfer can be zero-copy
    pub fn is_zero_copy_possible(&self, capabilities: &ZeroCopyCapabilities) -> bool {
        match self.direction {
            TransferDirection::HostToDevice | TransferDirection::DeviceToHost => {
                capabilities.unified_memory || capabilities.pinned_memory
            }
            TransferDirection::DeviceToDevice => capabilities.memory_mapping,
            TransferDirection::CrossDevice => capabilities.peer_to_peer,
        }
    }

    /// Estimate transfer bandwidth (bytes per second)
    pub fn estimate_bandwidth(&self, device_type: DeviceType) -> u64 {
        match (device_type, self.direction) {
            (DeviceType::Cuda(_), TransferDirection::HostToDevice) => {
                if self.alignment >= 256 {
                    25_000_000_000 // 25 GB/s for well-aligned transfers
                } else {
                    12_000_000_000 // 12 GB/s for unaligned
                }
            }
            (DeviceType::Cuda(_), TransferDirection::DeviceToHost) => {
                if self.alignment >= 256 {
                    20_000_000_000 // 20 GB/s
                } else {
                    10_000_000_000 // 10 GB/s
                }
            }
            (DeviceType::Cuda(_), TransferDirection::CrossDevice) => 50_000_000_000, // 50 GB/s NVLink
            (DeviceType::Metal(_), TransferDirection::HostToDevice) => 40_000_000_000, // 40 GB/s unified memory
            (DeviceType::Metal(_), TransferDirection::DeviceToHost) => 40_000_000_000,
            (DeviceType::Wgpu(_), TransferDirection::HostToDevice) => 8_000_000_000, // 8 GB/s
            (DeviceType::Wgpu(_), TransferDirection::DeviceToHost) => 6_000_000_000, // 6 GB/s
            (DeviceType::Cpu, _) => 50_000_000_000, // 50 GB/s DDR4/5
            _ => 1_000_000_000,                     // 1 GB/s fallback
        }
    }

    /// Estimate transfer time in microseconds
    pub fn estimate_transfer_time_us(&self, device_type: DeviceType) -> u64 {
        let bandwidth = self.estimate_bandwidth(device_type);
        if bandwidth == 0 {
            u64::MAX
        } else {
            (self.size as u64 * 1_000_000) / bandwidth
        }
    }
}

/// Zero-copy transfer statistics
#[derive(Debug, Default, Clone)]
pub struct ZeroCopyStats {
    /// Total number of transfers attempted
    pub total_transfers: u64,
    /// Number of successful zero-copy transfers
    pub zero_copy_transfers: u64,
    /// Number of fallback copies
    pub fallback_transfers: u64,
    /// Total bytes transferred via zero-copy
    pub zero_copy_bytes: u64,
    /// Total bytes transferred via fallback
    pub fallback_bytes: u64,
    /// Total transfer time in microseconds
    pub total_transfer_time_us: u64,
    /// Average transfer bandwidth in bytes per second
    pub average_bandwidth: f64,
    /// Number of transfer errors
    pub error_count: u64,
}

impl ZeroCopyStats {
    /// Calculate zero-copy success rate
    pub fn zero_copy_success_rate(&self) -> f64 {
        if self.total_transfers == 0 {
            0.0
        } else {
            (self.zero_copy_transfers as f64) / (self.total_transfers as f64)
        }
    }

    /// Calculate bandwidth efficiency (actual vs theoretical)
    pub fn bandwidth_efficiency(&self, theoretical_bandwidth: u64) -> f64 {
        if theoretical_bandwidth == 0 {
            0.0
        } else {
            self.average_bandwidth / (theoretical_bandwidth as f64)
        }
    }

    /// Calculate error rate
    pub fn error_rate(&self) -> f64 {
        if self.total_transfers == 0 {
            0.0
        } else {
            (self.error_count as f64) / (self.total_transfers as f64)
        }
    }

    /// Update statistics with a new transfer
    pub fn update_transfer(
        &mut self,
        bytes: u64,
        time_us: u64,
        was_zero_copy: bool,
        was_error: bool,
    ) {
        self.total_transfers += 1;

        if was_error {
            self.error_count += 1;
            return;
        }

        if was_zero_copy {
            self.zero_copy_transfers += 1;
            self.zero_copy_bytes += bytes;
        } else {
            self.fallback_transfers += 1;
            self.fallback_bytes += bytes;
        }

        self.total_transfer_time_us += time_us;

        // Update average bandwidth
        let total_bytes = self.zero_copy_bytes + self.fallback_bytes;
        if self.total_transfer_time_us > 0 {
            self.average_bandwidth =
                (total_bytes as f64) / (self.total_transfer_time_us as f64 / 1_000_000.0);
        }
    }
}

/// Zero-copy transfer manager
pub struct ZeroCopyManager {
    /// Device capabilities cache
    capabilities: Arc<RwLock<HashMap<String, ZeroCopyCapabilities>>>,
    /// Transfer statistics
    stats: Arc<RwLock<ZeroCopyStats>>,
    /// Memory managers for each device
    memory_managers: HashMap<String, Arc<dyn MemoryManager>>,
    /// SciRS2 CUDA devices for actual zero-copy operations
    #[cfg(feature = "cuda")]
    cuda_devices: HashMap<String, Arc<SciRs2CudaDevice>>,
    /// SciRS2 Metal devices for actual zero-copy operations
    #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
    metal_devices: HashMap<String, Arc<SciRs2MetalDevice>>,
}

impl ZeroCopyManager {
    /// Create a new zero-copy transfer manager
    pub fn new() -> Self {
        Self {
            capabilities: Arc::new(RwLock::new(HashMap::new())),
            stats: Arc::new(RwLock::new(ZeroCopyStats::default())),
            memory_managers: HashMap::new(),
            #[cfg(feature = "cuda")]
            cuda_devices: HashMap::new(),
            #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
            metal_devices: HashMap::new(),
        }
    }

    /// Register a device with its capabilities
    pub fn register_device(
        &mut self,
        device: &Device,
        capabilities: ZeroCopyCapabilities,
        memory_manager: Arc<dyn MemoryManager>,
    ) -> BackendResult<()> {
        let device_key = format!("{}:{}", device.device_type(), device.id());

        {
            let mut caps = self
                .capabilities
                .write()
                .expect("lock should not be poisoned");
            caps.insert(device_key.clone(), capabilities);
        }

        self.memory_managers.insert(device_key, memory_manager);
        Ok(())
    }

    /// Register a CUDA device for zero-copy operations
    #[cfg(feature = "cuda")]
    pub fn register_cuda_device(
        &mut self,
        device: &Device,
        scirs2_device: Arc<SciRs2CudaDevice>,
        capabilities: ZeroCopyCapabilities,
        memory_manager: Arc<dyn MemoryManager>,
    ) -> BackendResult<()> {
        let device_key = format!("{}:{}", device.device_type(), device.id());

        // Register device capabilities and memory manager
        self.register_device(device, capabilities, memory_manager)?;

        // Register SciRS2 device for actual operations
        self.cuda_devices.insert(device_key, scirs2_device);
        Ok(())
    }

    /// Register a Metal device for zero-copy operations
    #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
    pub fn register_metal_device(
        &mut self,
        device: &Device,
        scirs2_device: Arc<SciRs2MetalDevice>,
        capabilities: ZeroCopyCapabilities,
        memory_manager: Arc<dyn MemoryManager>,
    ) -> BackendResult<()> {
        let device_key = format!("{}:{}", device.device_type(), device.id());

        // Register device capabilities and memory manager
        self.register_device(device, capabilities, memory_manager)?;

        // Register SciRS2 device for actual operations
        self.metal_devices.insert(device_key, scirs2_device);
        Ok(())
    }

    /// Get device capabilities
    pub fn get_capabilities(&self, device: &Device) -> Option<ZeroCopyCapabilities> {
        let device_key = format!("{}:{}", device.device_type(), device.id());
        let caps = self
            .capabilities
            .read()
            .expect("lock should not be poisoned");
        caps.get(&device_key).copied()
    }

    /// Check if zero-copy transfer is possible between devices
    pub fn can_zero_copy(&self, source: &Device, destination: &Device) -> bool {
        let source_caps = self.get_capabilities(source);
        let dest_caps = self.get_capabilities(destination);

        match (source_caps, dest_caps) {
            (Some(src), Some(dst)) => {
                // Check specific transfer compatibility
                if source.id() == destination.id() {
                    // Same device - check memory mapping
                    src.memory_mapping && dst.memory_mapping
                } else if source.device_type() == DeviceType::Cpu {
                    // Host to device - check unified memory or pinned memory
                    dst.unified_memory || dst.pinned_memory
                } else if destination.device_type() == DeviceType::Cpu {
                    // Device to host - check unified memory or pinned memory
                    src.unified_memory || src.pinned_memory
                } else {
                    // Device to device - check peer-to-peer
                    src.peer_to_peer && dst.peer_to_peer
                }
            }
            _ => false,
        }
    }

    /// Perform zero-copy transfer
    pub async fn transfer(&mut self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        let start_time = std::time::Instant::now();

        // Check if zero-copy is possible
        if !self.can_zero_copy(&transfer.source_device, &transfer.destination_device) {
            return self.fallback_transfer(transfer, start_time).await;
        }

        // Attempt zero-copy transfer based on direction and capabilities
        let result = match transfer.direction {
            TransferDirection::HostToDevice => self.host_to_device_transfer(transfer).await,
            TransferDirection::DeviceToHost => self.device_to_host_transfer(transfer).await,
            TransferDirection::DeviceToDevice => self.device_to_device_transfer(transfer).await,
            TransferDirection::CrossDevice => self.cross_device_transfer(transfer).await,
        };

        let elapsed_us = start_time.elapsed().as_micros() as u64;
        let was_zero_copy = result.is_ok() && result.as_ref().unwrap_or(&false) == &true;
        let was_error = result.is_err();

        // Update statistics
        {
            let mut stats = self.stats.write().expect("lock should not be poisoned");
            stats.update_transfer(transfer.size as u64, elapsed_us, was_zero_copy, was_error);
        }

        result
    }

    /// Host to device zero-copy transfer
    async fn host_to_device_transfer(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        let dest_caps = self
            .get_capabilities(&transfer.destination_device)
            .ok_or_else(|| {
                BackendError::BackendError("Destination device not registered".to_string())
            })?;

        if dest_caps.unified_memory {
            // Use unified memory - data is already accessible by device
            self.unified_memory_transfer(transfer).await
        } else if dest_caps.pinned_memory {
            // Use pinned host memory with DMA transfer
            self.pinned_memory_transfer(transfer).await
        } else {
            Err(BackendError::BackendError(
                "No zero-copy method available for host to device transfer".to_string(),
            ))
        }
    }

    /// Device to host zero-copy transfer
    async fn device_to_host_transfer(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        let source_caps = self
            .get_capabilities(&transfer.source_device)
            .ok_or_else(|| {
                BackendError::BackendError("Source device not registered".to_string())
            })?;

        if source_caps.unified_memory {
            // Use unified memory - data is already accessible by host
            self.unified_memory_transfer(transfer).await
        } else if source_caps.pinned_memory {
            // Use pinned host memory with DMA transfer
            self.pinned_memory_transfer(transfer).await
        } else {
            Err(BackendError::BackendError(
                "No zero-copy method available for device to host transfer".to_string(),
            ))
        }
    }

    /// Device to device zero-copy transfer (same device)
    async fn device_to_device_transfer(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        let device_caps = self
            .get_capabilities(&transfer.source_device)
            .ok_or_else(|| BackendError::BackendError("Device not registered".to_string()))?;

        if device_caps.memory_mapping {
            // Use memory mapping for device-local transfer
            self.memory_mapped_transfer(transfer).await
        } else {
            Err(BackendError::BackendError(
                "No zero-copy method available for device to device transfer".to_string(),
            ))
        }
    }

    /// Cross-device zero-copy transfer
    #[allow(unused_unsafe)]
    async fn cross_device_transfer(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        let source_caps = self
            .get_capabilities(&transfer.source_device)
            .ok_or_else(|| {
                BackendError::BackendError("Source device not registered".to_string())
            })?;
        let dest_caps = self
            .get_capabilities(&transfer.destination_device)
            .ok_or_else(|| {
                BackendError::BackendError("Destination device not registered".to_string())
            })?;

        if source_caps.peer_to_peer && dest_caps.peer_to_peer {
            // Use peer-to-peer transfer (e.g., NVLink, PCIe P2P)
            self.peer_to_peer_transfer(transfer).await
        } else {
            Err(BackendError::BackendError(
                "No zero-copy method available for cross-device transfer".to_string(),
            ))
        }
    }

    /// Unified memory transfer implementation
    async fn unified_memory_transfer(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        let device_key = format!(
            "{}:{}",
            transfer.destination_device.device_type(),
            transfer.destination_device.id()
        );

        match transfer.destination_device.device_type() {
            #[cfg(feature = "cuda")]
            DeviceType::Cuda(_) => {
                if self.cuda_devices.get(&device_key).is_some() {
                    // TODO: Implement when scirs2_cuda memory operations are available
                    // For now, return an error indicating the feature is not yet implemented
                    Err(BackendError::BackendError(
                        "CUDA unified memory prefetch not yet implemented - requires scirs2_cuda"
                            .to_string(),
                    ))
                } else {
                    Err(BackendError::BackendError(
                        "CUDA device not registered for unified memory".to_string(),
                    ))
                }
            }

            #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
            DeviceType::Metal(_) => {
                if let Some(metal_device) = self.metal_devices.get(&device_key) {
                    // Use SciRS2 Metal unified memory
                    #[allow(unused_unsafe)]
                    unsafe {
                        scirs2_metal::memory::set_cpu_cache_mode(
                            metal_device,
                            transfer.source_ptr,
                            scirs2_metal::memory::CpuCacheMode::WriteCombined,
                        )
                        .map_err(|e| {
                            BackendError::BackendError(format!("Metal cache mode failed: {}", e))
                        })?;

                        // For Metal, unified memory is automatically managed by the system
                        // No explicit prefetch needed
                    }
                    Ok(true)
                } else {
                    Err(BackendError::BackendError(
                        "Metal device not registered for unified memory".to_string(),
                    ))
                }
            }

            _ => {
                // Fallback to memory manager for other device types
                if let Some(memory_manager) = self.memory_managers.get(&device_key) {
                    let _ = memory_manager.set_memory_advice(
                        transfer.source_ptr,
                        transfer.size,
                        crate::memory::MemoryAdvice::SetPreferredLocation,
                    );
                    let _ = memory_manager.prefetch_to_device(transfer.source_ptr, transfer.size);
                    Ok(true)
                } else {
                    Err(BackendError::BackendError(
                        "Memory manager not found for device".to_string(),
                    ))
                }
            }
        }
    }

    /// Pinned memory transfer implementation
    async fn pinned_memory_transfer(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        #[allow(unused_variables)]
        let device_key = format!(
            "{}:{}",
            transfer.destination_device.device_type(),
            transfer.destination_device.id()
        );

        match transfer.destination_device.device_type() {
            #[cfg(feature = "cuda")]
            DeviceType::Cuda(_) => {
                if let Some(cuda_device) = self.cuda_devices.get(&device_key) {
                    match transfer.mode {
                        TransferMode::Asynchronous => {
                            self.launch_cuda_async_transfer(cuda_device, transfer).await
                        }
                        TransferMode::Streaming => {
                            self.launch_cuda_streaming_transfer(cuda_device, transfer)
                                .await
                        }
                        _ => self.launch_cuda_sync_transfer(cuda_device, transfer).await,
                    }
                } else {
                    Err(BackendError::BackendError(
                        "CUDA device not registered for pinned memory".to_string(),
                    ))
                }
            }

            #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
            DeviceType::Metal(_) => {
                if let Some(metal_device) = self.metal_devices.get(&device_key) {
                    match transfer.mode {
                        TransferMode::Asynchronous => {
                            self.launch_metal_async_transfer(metal_device, transfer)
                                .await
                        }
                        TransferMode::Streaming => {
                            self.launch_metal_streaming_transfer(metal_device, transfer)
                                .await
                        }
                        _ => {
                            self.launch_metal_sync_transfer(metal_device, transfer)
                                .await
                        }
                    }
                } else {
                    Err(BackendError::BackendError(
                        "Metal device not registered for pinned memory".to_string(),
                    ))
                }
            }

            _ => {
                // Fallback to generic implementation
                match transfer.mode {
                    TransferMode::Asynchronous => self.launch_async_dma(transfer).await,
                    TransferMode::Streaming => self.launch_streaming_transfer(transfer).await,
                    _ => self.launch_sync_dma(transfer).await,
                }
            }
        }
    }

    /// Memory mapped transfer implementation
    async fn memory_mapped_transfer(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        // For memory mapped transfers, we can use device-local copy operations
        // This avoids host involvement

        if transfer.source_ptr.is_null() || transfer.destination_ptr.is_null() {
            return Err(BackendError::InvalidArgument(
                "Null pointer in memory mapped transfer".to_string(),
            ));
        }

        // Use device-optimized memory copy (e.g., GPU kernels)
        self.launch_device_copy(transfer).await
    }

    /// Peer-to-peer transfer implementation
    async fn peer_to_peer_transfer(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        // For peer-to-peer transfers, devices can directly access each other's memory
        // This is particularly efficient with technologies like NVLink

        let source_caps = self
            .get_capabilities(&transfer.source_device)
            .expect("source device capabilities should exist");
        let dest_caps = self
            .get_capabilities(&transfer.destination_device)
            .expect("destination device capabilities should exist");

        if !source_caps.peer_to_peer || !dest_caps.peer_to_peer {
            return Err(BackendError::BackendError(
                "Peer-to-peer not supported on one or both devices".to_string(),
            ));
        }

        // Launch peer-to-peer DMA transfer
        self.launch_p2p_transfer(transfer).await
    }

    /// Fallback transfer using conventional copying
    async fn fallback_transfer(
        &mut self,
        transfer: &ZeroCopyTransfer,
        start_time: std::time::Instant,
    ) -> BackendResult<bool> {
        // Perform conventional memory copy
        if transfer.source_ptr.is_null() || transfer.destination_ptr.is_null() {
            return Err(BackendError::InvalidArgument(
                "Null pointer in fallback transfer".to_string(),
            ));
        }

        // Safety: This is unsafe as it involves raw pointer operations
        // In a real implementation, this would use proper device APIs
        unsafe {
            std::ptr::copy_nonoverlapping(
                transfer.source_ptr,
                transfer.destination_ptr,
                transfer.size,
            );
        }

        let elapsed_us = start_time.elapsed().as_micros() as u64;

        // Update statistics for fallback transfer
        {
            let mut stats = self.stats.write().expect("lock should not be poisoned");
            stats.update_transfer(transfer.size as u64, elapsed_us, false, false);
        }

        Ok(false) // Not zero-copy
    }

    /// Launch asynchronous DMA transfer
    async fn launch_async_dma(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        // Implementation would use device-specific async DMA APIs
        // For now, simulate async operation
        #[cfg(feature = "async")]
        tokio::task::yield_now().await;

        // Simulate DMA copy
        if !transfer.source_ptr.is_null() && !transfer.destination_ptr.is_null() {
            unsafe {
                std::ptr::copy_nonoverlapping(
                    transfer.source_ptr,
                    transfer.destination_ptr,
                    transfer.size,
                );
            }
        }

        Ok(true)
    }

    /// Launch streaming transfer
    async fn launch_streaming_transfer(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        // For streaming transfers, break large transfers into smaller chunks
        const CHUNK_SIZE: usize = 64 * 1024 * 1024; // 64MB chunks

        let num_chunks = (transfer.size + CHUNK_SIZE - 1) / CHUNK_SIZE;

        for chunk in 0..num_chunks {
            let chunk_offset = chunk * CHUNK_SIZE;
            let chunk_size = std::cmp::min(CHUNK_SIZE, transfer.size - chunk_offset);

            if chunk_size == 0 {
                break;
            }

            // Create chunk transfer
            let chunk_transfer = ZeroCopyTransfer {
                source_ptr: unsafe { transfer.source_ptr.add(chunk_offset) },
                destination_ptr: unsafe { transfer.destination_ptr.add(chunk_offset) },
                size: chunk_size,
                mode: TransferMode::Asynchronous,
                ..transfer.clone()
            };

            // Launch chunk transfer
            self.launch_async_dma(&chunk_transfer).await?;

            // Yield between chunks
            #[cfg(feature = "async")]
            tokio::task::yield_now().await;
        }

        Ok(true)
    }

    /// Launch synchronous DMA transfer
    async fn launch_sync_dma(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        // Implementation would use device-specific sync DMA APIs
        if !transfer.source_ptr.is_null() && !transfer.destination_ptr.is_null() {
            unsafe {
                std::ptr::copy_nonoverlapping(
                    transfer.source_ptr,
                    transfer.destination_ptr,
                    transfer.size,
                );
            }
            Ok(true)
        } else {
            Err(BackendError::InvalidArgument(
                "Null pointer in sync DMA transfer".to_string(),
            ))
        }
    }

    /// Launch device-local copy operation
    async fn launch_device_copy(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        // Implementation would use device-specific copy kernels
        if !transfer.source_ptr.is_null() && !transfer.destination_ptr.is_null() {
            unsafe {
                std::ptr::copy_nonoverlapping(
                    transfer.source_ptr,
                    transfer.destination_ptr,
                    transfer.size,
                );
            }
            Ok(true)
        } else {
            Err(BackendError::InvalidArgument(
                "Null pointer in device copy".to_string(),
            ))
        }
    }

    /// Launch peer-to-peer transfer
    #[allow(unused_unsafe)]
    async fn launch_p2p_transfer(&self, transfer: &ZeroCopyTransfer) -> BackendResult<bool> {
        #[allow(unused_variables)]
        let source_key = format!(
            "{}:{}",
            transfer.source_device.device_type(),
            transfer.source_device.id()
        );
        #[allow(unused_variables)]
        let dest_key = format!(
            "{}:{}",
            transfer.destination_device.device_type(),
            transfer.destination_device.id()
        );

        match (
            transfer.source_device.device_type(),
            transfer.destination_device.device_type(),
        ) {
            #[cfg(feature = "cuda")]
            (DeviceType::Cuda(_), DeviceType::Cuda(_)) => {
                if self.cuda_devices.get(&source_key).is_some()
                    && self.cuda_devices.get(&dest_key).is_some()
                {
                    // TODO: Implement when scirs2_cuda memory operations are available
                    Err(BackendError::BackendError(
                        "CUDA P2P transfer not yet implemented - requires scirs2_cuda".to_string(),
                    ))
                } else {
                    Err(BackendError::BackendError(
                        "CUDA devices not registered for P2P transfer".to_string(),
                    ))
                }
            }

            _ => {
                // Fallback to conventional copy for non-CUDA P2P
                if !transfer.source_ptr.is_null() && !transfer.destination_ptr.is_null() {
                    unsafe {
                        std::ptr::copy_nonoverlapping(
                            transfer.source_ptr,
                            transfer.destination_ptr,
                            transfer.size,
                        );
                    }
                    Ok(true)
                } else {
                    Err(BackendError::InvalidArgument(
                        "Null pointer in P2P transfer".to_string(),
                    ))
                }
            }
        }
    }

    /// Launch CUDA asynchronous transfer
    #[cfg(feature = "cuda")]
    #[allow(unused_unsafe)]
    async fn launch_cuda_async_transfer(
        &self,
        _cuda_device: &SciRs2CudaDevice,
        _transfer: &ZeroCopyTransfer,
    ) -> BackendResult<bool> {
        // TODO: Implement when scirs2_cuda memory operations are available
        Err(BackendError::BackendError(
            "CUDA async transfer not yet implemented - requires scirs2_cuda".to_string(),
        ))
    }

    /// Launch CUDA synchronous transfer
    #[cfg(feature = "cuda")]
    async fn launch_cuda_sync_transfer(
        &self,
        _cuda_device: &SciRs2CudaDevice,
        _transfer: &ZeroCopyTransfer,
    ) -> BackendResult<bool> {
        // TODO: Implement when scirs2_cuda memory operations are available
        Err(BackendError::BackendError(
            "CUDA sync transfer not yet implemented - requires scirs2_cuda".to_string(),
        ))
    }

    /// Launch CUDA streaming transfer
    #[cfg(feature = "cuda")]
    async fn launch_cuda_streaming_transfer(
        &self,
        cuda_device: &SciRs2CudaDevice,
        transfer: &ZeroCopyTransfer,
    ) -> BackendResult<bool> {
        const CHUNK_SIZE: usize = 64 * 1024 * 1024; // 64MB chunks for CUDA
        let num_chunks = (transfer.size + CHUNK_SIZE - 1) / CHUNK_SIZE;

        for chunk in 0..num_chunks {
            let chunk_offset = chunk * CHUNK_SIZE;
            let chunk_size = std::cmp::min(CHUNK_SIZE, transfer.size - chunk_offset);

            if chunk_size == 0 {
                break;
            }

            // Create chunk transfer
            let chunk_transfer = ZeroCopyTransfer {
                source_ptr: unsafe { transfer.source_ptr.add(chunk_offset) },
                destination_ptr: unsafe { transfer.destination_ptr.add(chunk_offset) },
                size: chunk_size,
                ..transfer.clone()
            };

            // Launch chunk transfer asynchronously
            self.launch_cuda_async_transfer(cuda_device, &chunk_transfer)
                .await?;

            // Yield between chunks for better scheduling
            #[cfg(feature = "async")]
            tokio::task::yield_now().await;
        }

        // Synchronize all transfers
        scirs2_cuda::synchronize(cuda_device).map_err(|e| {
            BackendError::BackendError(format!("CUDA streaming sync failed: {}", e))
        })?;

        Ok(true)
    }

    /// Launch Metal asynchronous transfer
    #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
    async fn launch_metal_async_transfer(
        &self,
        metal_device: &SciRs2MetalDevice,
        transfer: &ZeroCopyTransfer,
    ) -> BackendResult<bool> {
        #[allow(unused_unsafe)]
        unsafe {
            match transfer.direction {
                TransferDirection::HostToDevice => {
                    scirs2_metal::memory::copy_host_to_device_async(
                        metal_device,
                        transfer.source_ptr,
                        transfer.destination_ptr,
                        transfer.size,
                    )
                    .await
                    .map_err(|e| {
                        BackendError::BackendError(format!(
                            "Metal H2D async transfer failed: {}",
                            e
                        ))
                    })?;
                }
                TransferDirection::DeviceToHost => {
                    scirs2_metal::memory::copy_device_to_host_async(
                        metal_device,
                        transfer.source_ptr,
                        transfer.destination_ptr,
                        transfer.size,
                    )
                    .await
                    .map_err(|e| {
                        BackendError::BackendError(format!(
                            "Metal D2H async transfer failed: {}",
                            e
                        ))
                    })?;
                }
                _ => {
                    return Err(BackendError::InvalidArgument(
                        "Invalid transfer direction for Metal async transfer".to_string(),
                    ));
                }
            }
        }
        Ok(true)
    }

    /// Launch Metal synchronous transfer
    #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
    async fn launch_metal_sync_transfer(
        &self,
        metal_device: &SciRs2MetalDevice,
        transfer: &ZeroCopyTransfer,
    ) -> BackendResult<bool> {
        #[allow(unused_unsafe)]
        unsafe {
            match transfer.direction {
                TransferDirection::HostToDevice => {
                    scirs2_metal::memory::copy_host_to_device(
                        metal_device,
                        transfer.source_ptr,
                        transfer.destination_ptr,
                        transfer.size,
                    )
                    .map_err(|e| {
                        BackendError::BackendError(format!("Metal H2D sync transfer failed: {}", e))
                    })?;
                }
                TransferDirection::DeviceToHost => {
                    scirs2_metal::memory::copy_device_to_host(
                        metal_device,
                        transfer.source_ptr,
                        transfer.destination_ptr,
                        transfer.size,
                    )
                    .map_err(|e| {
                        BackendError::BackendError(format!("Metal D2H sync transfer failed: {}", e))
                    })?;
                }
                _ => {
                    return Err(BackendError::InvalidArgument(
                        "Invalid transfer direction for Metal sync transfer".to_string(),
                    ));
                }
            }
        }
        Ok(true)
    }

    /// Launch Metal streaming transfer
    #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
    async fn launch_metal_streaming_transfer(
        &self,
        metal_device: &SciRs2MetalDevice,
        transfer: &ZeroCopyTransfer,
    ) -> BackendResult<bool> {
        const CHUNK_SIZE: usize = 32 * 1024 * 1024; // 32MB chunks for Metal
        let num_chunks = (transfer.size + CHUNK_SIZE - 1) / CHUNK_SIZE;

        for chunk in 0..num_chunks {
            let chunk_offset = chunk * CHUNK_SIZE;
            let chunk_size = std::cmp::min(CHUNK_SIZE, transfer.size - chunk_offset);

            if chunk_size == 0 {
                break;
            }

            // Create chunk transfer
            let chunk_transfer = ZeroCopyTransfer {
                source_ptr: unsafe { transfer.source_ptr.add(chunk_offset) },
                destination_ptr: unsafe { transfer.destination_ptr.add(chunk_offset) },
                size: chunk_size,
                ..transfer.clone()
            };

            // Launch chunk transfer asynchronously
            self.launch_metal_async_transfer(metal_device, &chunk_transfer)
                .await?;

            // Yield between chunks
            #[cfg(feature = "async")]
            tokio::task::yield_now().await;
        }

        // Synchronize all transfers
        scirs2_metal::synchronize(metal_device).map_err(|e| {
            BackendError::BackendError(format!("Metal streaming sync failed: {}", e))
        })?;

        Ok(true)
    }

    /// Get transfer statistics
    pub fn get_stats(&self) -> ZeroCopyStats {
        self.stats
            .read()
            .expect("lock should not be poisoned")
            .clone()
    }

    /// Reset transfer statistics
    pub fn reset_stats(&self) {
        let mut stats = self.stats.write().expect("lock should not be poisoned");
        *stats = ZeroCopyStats::default();
    }

    /// Get optimal transfer mode for given transfer
    pub fn get_optimal_transfer_mode(&self, transfer: &ZeroCopyTransfer) -> TransferMode {
        let source_caps = self.get_capabilities(&transfer.source_device);
        let dest_caps = self.get_capabilities(&transfer.destination_device);

        match (source_caps, dest_caps) {
            (Some(src), Some(dst)) => {
                // Choose based on capabilities and transfer size
                if transfer.size > 100 * 1024 * 1024
                    && src.streaming_transfers
                    && dst.streaming_transfers
                {
                    TransferMode::Streaming
                } else if src.async_transfers && dst.async_transfers {
                    TransferMode::Asynchronous
                } else if transfer.direction == TransferDirection::CrossDevice
                    && src.peer_to_peer
                    && dst.peer_to_peer
                {
                    TransferMode::PeerToPeer
                } else {
                    TransferMode::Synchronous
                }
            }
            _ => TransferMode::Synchronous,
        }
    }

    /// Optimize transfer parameters
    pub fn optimize_transfer(&self, mut transfer: ZeroCopyTransfer) -> ZeroCopyTransfer {
        // Set optimal transfer mode
        transfer.mode = self.get_optimal_transfer_mode(&transfer);

        // Optimize alignment for better performance
        if transfer.alignment < 256 && transfer.size > 1024 * 1024 {
            transfer.alignment = 256; // Optimize for large transfers
        }

        // Set appropriate priority based on size
        transfer.priority = if transfer.size > 100 * 1024 * 1024 {
            0 // High priority for large transfers
        } else {
            1 // Normal priority
        };

        transfer
    }
}

impl Default for ZeroCopyManager {
    fn default() -> Self {
        Self::new()
    }
}

/// Utility functions for zero-copy operations
pub mod utils {
    use super::*;

    /// Detect zero-copy capabilities for different device types
    pub fn detect_capabilities(device_type: DeviceType) -> ZeroCopyCapabilities {
        match device_type {
            DeviceType::Cuda(_) => ZeroCopyCapabilities {
                unified_memory: true,
                peer_to_peer: true,
                memory_mapping: true,
                direct_gpu_access: true,
                pinned_memory: true,
                memory_advice: true,
                async_transfers: true,
                streaming_transfers: true,
            },
            DeviceType::Metal(_) => ZeroCopyCapabilities {
                unified_memory: true,
                peer_to_peer: false, // Limited P2P support
                memory_mapping: true,
                direct_gpu_access: true,
                pinned_memory: true,
                memory_advice: true,
                async_transfers: true,
                streaming_transfers: true,
            },
            DeviceType::Wgpu(_) => ZeroCopyCapabilities {
                unified_memory: false,
                peer_to_peer: false,
                memory_mapping: true,
                direct_gpu_access: false,
                pinned_memory: false,
                memory_advice: false,
                async_transfers: true,
                streaming_transfers: false,
            },
            DeviceType::Cpu => ZeroCopyCapabilities {
                unified_memory: true,
                peer_to_peer: false,
                memory_mapping: true,
                direct_gpu_access: false,
                pinned_memory: true,
                memory_advice: false,
                async_transfers: false,
                streaming_transfers: false,
            },
        }
    }

    /// Check if pointers are properly aligned for zero-copy
    pub fn check_alignment(ptr: *const u8, alignment: usize) -> bool {
        if alignment == 0 || (alignment & (alignment - 1)) != 0 {
            return false; // Invalid alignment (must be power of 2)
        }
        (ptr as usize).is_multiple_of(alignment)
    }

    /// Calculate optimal chunk size for streaming transfers
    pub fn optimal_chunk_size(total_size: usize, device_type: DeviceType) -> usize {
        let base_chunk_size = match device_type {
            DeviceType::Cuda(_) => 64 * 1024 * 1024,  // 64MB
            DeviceType::Metal(_) => 32 * 1024 * 1024, // 32MB
            DeviceType::Wgpu(_) => 16 * 1024 * 1024,  // 16MB
            DeviceType::Cpu => 128 * 1024 * 1024,     // 128MB
        };

        // Adjust chunk size based on total size
        if total_size < base_chunk_size {
            total_size
        } else {
            std::cmp::min(base_chunk_size, total_size / 8) // At least 8 chunks
        }
    }

    /// Estimate transfer efficiency
    pub fn estimate_efficiency(
        transfer: &ZeroCopyTransfer,
        capabilities: &ZeroCopyCapabilities,
    ) -> f32 {
        if !transfer.is_zero_copy_possible(capabilities) {
            return 0.0; // No zero-copy possible
        }

        let mut efficiency: f32 = 1.0;

        // Reduce efficiency for suboptimal alignment
        if transfer.alignment < 256 {
            efficiency *= 0.8;
        }

        // Reduce efficiency for small transfers
        if transfer.size < 4096 {
            efficiency *= 0.5;
        }

        // Boost efficiency for optimal transfer modes
        match transfer.mode {
            TransferMode::Streaming if transfer.size > 100 * 1024 * 1024 => efficiency *= 1.2,
            TransferMode::PeerToPeer if transfer.direction == TransferDirection::CrossDevice => {
                efficiency *= 1.3
            }
            TransferMode::Asynchronous => efficiency *= 1.1,
            _ => {}
        }

        efficiency.min(1.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::device::{Device, DeviceInfo};
    use std::ptr::null_mut;

    fn create_test_device(device_type: DeviceType, id: usize) -> Device {
        let info = DeviceInfo::default();
        Device::new(
            id,
            device_type,
            format!("Test {:?} {}", device_type, id),
            info,
        )
    }

    #[test]
    fn test_zero_copy_capabilities_default() {
        let caps = ZeroCopyCapabilities::default();
        assert!(!caps.has_any_capabilities());
        assert_eq!(caps.capability_score(), 0.0);
        assert_eq!(caps.recommended_transfer_mode(), TransferMode::Synchronous);
    }

    #[test]
    fn test_zero_copy_capabilities_scoring() {
        let mut caps = ZeroCopyCapabilities::default();
        caps.unified_memory = true;
        caps.async_transfers = true;

        assert!(caps.has_any_capabilities());
        assert_eq!(caps.capability_score(), 0.25); // 2/8 features
        assert_eq!(caps.recommended_transfer_mode(), TransferMode::Asynchronous);
    }

    #[test]
    fn test_zero_copy_transfer_creation() {
        let cpu_device = create_test_device(DeviceType::Cpu, 0);
        let gpu_device = create_test_device(DeviceType::Cuda(1), 1);

        let transfer = ZeroCopyTransfer::new(cpu_device, gpu_device, null_mut(), null_mut(), 1024);

        assert_eq!(transfer.direction, TransferDirection::HostToDevice);
        assert_eq!(transfer.mode, TransferMode::Synchronous);
        assert_eq!(transfer.size, 1024);
        assert_eq!(transfer.alignment, 1);
        assert_eq!(transfer.priority, 1);
        assert!(transfer.stream_id.is_none());
    }

    #[test]
    fn test_zero_copy_transfer_direction_detection() {
        let cpu_device = create_test_device(DeviceType::Cpu, 0);
        let gpu_device1 = create_test_device(DeviceType::Cuda(1), 1);
        let gpu_device2 = create_test_device(DeviceType::Cuda(2), 2);

        // Host to device
        let transfer = ZeroCopyTransfer::new(
            cpu_device.clone(),
            gpu_device1.clone(),
            null_mut(),
            null_mut(),
            1024,
        );
        assert_eq!(transfer.direction, TransferDirection::HostToDevice);

        // Device to host
        let transfer = ZeroCopyTransfer::new(
            gpu_device1.clone(),
            cpu_device,
            null_mut(),
            null_mut(),
            1024,
        );
        assert_eq!(transfer.direction, TransferDirection::DeviceToHost);

        // Device to device (same)
        let transfer = ZeroCopyTransfer::new(
            gpu_device1.clone(),
            gpu_device1.clone(),
            null_mut(),
            null_mut(),
            1024,
        );
        assert_eq!(transfer.direction, TransferDirection::DeviceToDevice);

        // Cross device
        let transfer = ZeroCopyTransfer::new(
            gpu_device1.clone(),
            gpu_device2,
            null_mut(),
            null_mut(),
            1024,
        );
        assert_eq!(transfer.direction, TransferDirection::CrossDevice);
    }

    #[test]
    fn test_zero_copy_transfer_builder() {
        let cpu_device = create_test_device(DeviceType::Cpu, 0);
        let gpu_device = create_test_device(DeviceType::Cuda(1), 1);

        let transfer = ZeroCopyTransfer::new(cpu_device, gpu_device, null_mut(), null_mut(), 1024)
            .with_mode(TransferMode::Asynchronous)
            .with_alignment(256)
            .with_priority(0)
            .with_stream(42);

        assert_eq!(transfer.mode, TransferMode::Asynchronous);
        assert_eq!(transfer.alignment, 256);
        assert_eq!(transfer.priority, 0);
        assert_eq!(transfer.stream_id, Some(42));
    }

    #[test]
    fn test_zero_copy_transfer_zero_copy_possible() {
        let cpu_device = create_test_device(DeviceType::Cpu, 0);
        let gpu_device = create_test_device(DeviceType::Cuda(1), 1);

        let transfer = ZeroCopyTransfer::new(cpu_device, gpu_device, null_mut(), null_mut(), 1024);

        let caps_unified = ZeroCopyCapabilities {
            unified_memory: true,
            ..Default::default()
        };

        let caps_pinned = ZeroCopyCapabilities {
            pinned_memory: true,
            ..Default::default()
        };

        let caps_none = ZeroCopyCapabilities::default();

        assert!(transfer.is_zero_copy_possible(&caps_unified));
        assert!(transfer.is_zero_copy_possible(&caps_pinned));
        assert!(!transfer.is_zero_copy_possible(&caps_none));
    }

    #[test]
    fn test_zero_copy_transfer_bandwidth_estimation() {
        let cpu_device = create_test_device(DeviceType::Cpu, 0);
        let gpu_device = create_test_device(DeviceType::Cuda(1), 1);

        let transfer = ZeroCopyTransfer::new(cpu_device, gpu_device, null_mut(), null_mut(), 1024)
            .with_alignment(256);

        let bandwidth = transfer.estimate_bandwidth(DeviceType::Cuda(1));
        assert_eq!(bandwidth, 25_000_000_000); // Well-aligned CUDA transfer

        let transfer_unaligned = ZeroCopyTransfer::new(
            create_test_device(DeviceType::Cpu, 0),
            create_test_device(DeviceType::Cuda(1), 1),
            null_mut(),
            null_mut(),
            1024,
        )
        .with_alignment(1);

        let bandwidth_unaligned = transfer_unaligned.estimate_bandwidth(DeviceType::Cuda(1));
        assert_eq!(bandwidth_unaligned, 12_000_000_000); // Unaligned CUDA transfer
    }

    #[test]
    fn test_zero_copy_stats() {
        let mut stats = ZeroCopyStats::default();

        // Test initial state
        assert_eq!(stats.zero_copy_success_rate(), 0.0);
        assert_eq!(stats.error_rate(), 0.0);

        // Update with successful zero-copy transfer
        stats.update_transfer(1024, 100, true, false);
        assert_eq!(stats.total_transfers, 1);
        assert_eq!(stats.zero_copy_transfers, 1);
        assert_eq!(stats.zero_copy_success_rate(), 1.0);

        // Update with fallback transfer
        stats.update_transfer(512, 200, false, false);
        assert_eq!(stats.total_transfers, 2);
        assert_eq!(stats.fallback_transfers, 1);
        assert_eq!(stats.zero_copy_success_rate(), 0.5);

        // Update with error
        stats.update_transfer(256, 50, false, true);
        assert_eq!(stats.total_transfers, 3);
        assert_eq!(stats.error_count, 1);
        assert!((stats.error_rate() - (1.0 / 3.0)).abs() < 0.001);
    }

    #[test]
    fn test_zero_copy_manager_creation() {
        let manager = ZeroCopyManager::new();
        assert!(manager
            .capabilities
            .read()
            .expect("lock should not be poisoned")
            .is_empty());

        let stats = manager.get_stats();
        assert_eq!(stats.total_transfers, 0);
    }

    #[test]
    fn test_utils_detect_capabilities() {
        let cuda_caps = utils::detect_capabilities(DeviceType::Cuda(0));
        assert!(cuda_caps.unified_memory);
        assert!(cuda_caps.peer_to_peer);
        assert!(cuda_caps.streaming_transfers);

        let webgpu_caps = utils::detect_capabilities(DeviceType::Wgpu(0));
        assert!(!webgpu_caps.unified_memory);
        assert!(!webgpu_caps.peer_to_peer);
        assert!(!webgpu_caps.streaming_transfers);
    }

    #[test]
    fn test_utils_check_alignment() {
        let ptr = 0x1000 as *const u8; // 4KB aligned

        assert!(utils::check_alignment(ptr, 16));
        assert!(utils::check_alignment(ptr, 256));
        assert!(utils::check_alignment(ptr, 4096));
        assert!(!utils::check_alignment(ptr, 8192));

        // Test invalid alignments
        assert!(!utils::check_alignment(ptr, 0));
        assert!(!utils::check_alignment(ptr, 3)); // Not power of 2
    }

    #[test]
    fn test_utils_optimal_chunk_size() {
        let cuda_chunk = utils::optimal_chunk_size(1024 * 1024 * 1024, DeviceType::Cuda(0));
        assert_eq!(cuda_chunk, 64 * 1024 * 1024); // 64MB for large transfers

        let small_chunk = utils::optimal_chunk_size(1024, DeviceType::Cuda(0));
        assert_eq!(small_chunk, 1024); // Use full size for small transfers
    }

    #[test]
    fn test_utils_estimate_efficiency() {
        let cpu_device = create_test_device(DeviceType::Cpu, 0);
        let gpu_device = create_test_device(DeviceType::Cuda(1), 1);

        let transfer =
            ZeroCopyTransfer::new(cpu_device, gpu_device, null_mut(), null_mut(), 1024 * 1024)
                .with_alignment(256)
                .with_mode(TransferMode::Asynchronous);

        let caps = ZeroCopyCapabilities {
            unified_memory: true,
            async_transfers: true,
            ..Default::default()
        };

        let efficiency = utils::estimate_efficiency(&transfer, &caps);
        assert!(efficiency > 0.0); // Should be positive for valid zero-copy transfers
        assert!(efficiency <= 1.0); // Efficiency is capped at 1.0
    }
}