rat_congestion 0.1.0

High-performance congestion control algorithms for network protocols
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
//! Platform-specific optimizations for congestion control.
//!
//! This module provides platform-specific constants, optimizations, and
//! system call wrappers to maximize performance on different operating systems.

use std::time::Duration;

/// Platform detection and optimization constants.
pub mod detection {
    /// Detect the current platform at compile time.
    #[cfg(target_os = "linux")]
    pub const PLATFORM: &str = "linux";
    
    #[cfg(target_os = "macos")]
    pub const PLATFORM: &str = "macos";
    
    #[cfg(target_os = "freebsd")]
    pub const PLATFORM: &str = "freebsd";
    
    #[cfg(target_os = "windows")]
    pub const PLATFORM: &str = "windows";
    
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "windows")))]
    pub const PLATFORM: &str = "unknown";
    
    /// Check if the current platform supports advanced networking features.
    pub fn has_advanced_networking() -> bool {
        matches!(PLATFORM, "linux" | "freebsd")
    }
    
    /// Check if the platform supports high-resolution timers.
    pub fn has_high_resolution_timers() -> bool {
        !matches!(PLATFORM, "windows")
    }
    
    /// Check if the platform supports SO_REUSEPORT.
    pub fn supports_reuseport() -> bool {
        matches!(PLATFORM, "linux" | "freebsd" | "macos")
    }
}

/// Platform-specific constants for optimal performance.
pub mod constants {
    use super::detection::PLATFORM;
    use std::time::Duration;
    
    /// Get platform-optimized initial congestion window.
    pub fn initial_cwnd() -> u64 {
        match PLATFORM {
            "linux" => 10,      // Linux supports RFC 6928
            "freebsd" => 10,    // FreeBSD also supports larger initial cwnd
            "macos" => 4,       // macOS is more conservative
            "windows" => 4,     // Windows is conservative
            _ => 4,             // Default conservative value
        }
    }
    
    /// Get platform-optimized maximum congestion window.
    pub fn max_cwnd() -> u64 {
        match PLATFORM {
            "linux" => 0x7fff_ffff,    // Linux can handle very large windows
            "freebsd" => 0x7fff_ffff,  // FreeBSD similar to Linux
            "macos" => 0x3fff_ffff,    // macOS slightly more conservative
            "windows" => 0x1fff_ffff,  // Windows more conservative
            _ => 0x0fff_ffff,          // Default safe value
        }
    }
    
    /// Get platform-optimized minimum RTT for calculations.
    pub fn min_rtt_threshold() -> Duration {
        match PLATFORM {
            "linux" => Duration::from_micros(100),    // Linux has good timer resolution
            "freebsd" => Duration::from_micros(100),  // FreeBSD similar
            "macos" => Duration::from_micros(200),    // macOS slightly higher
            "windows" => Duration::from_micros(500),  // Windows higher due to timer resolution
            _ => Duration::from_micros(1000),         // Conservative default
        }
    }
    
    /// Get platform-optimized pacing granularity.
    pub fn pacing_granularity() -> Duration {
        match PLATFORM {
            "linux" => Duration::from_micros(50),     // Linux supports fine-grained pacing
            "freebsd" => Duration::from_micros(100),  // FreeBSD good but not as fine
            "macos" => Duration::from_micros(200),    // macOS more coarse
            "windows" => Duration::from_micros(1000), // Windows much more coarse
            _ => Duration::from_micros(1000),         // Safe default
        }
    }
    
    /// Get platform-optimized buffer sizes.
    pub fn socket_buffer_size() -> usize {
        match PLATFORM {
            "linux" => 16 * 1024 * 1024,    // 16MB for Linux
            "freebsd" => 8 * 1024 * 1024,   // 8MB for FreeBSD
            "macos" => 4 * 1024 * 1024,     // 4MB for macOS
            "windows" => 2 * 1024 * 1024,   // 2MB for Windows
            _ => 1024 * 1024,               // 1MB default
        }
    }
    
    /// Get platform-optimized batch size for packet processing.
    pub fn batch_size() -> usize {
        match PLATFORM {
            "linux" => 64,      // Linux can handle large batches efficiently
            "freebsd" => 32,    // FreeBSD good batch support
            "macos" => 16,      // macOS moderate batching
            "windows" => 8,     // Windows smaller batches
            _ => 4,             // Conservative default
        }
    }
}

/// Platform-specific optimizations and system calls.
pub mod optimizations {
    use super::detection::PLATFORM;
    use std::time::{Duration, Instant};
    
    /// High-resolution timestamp function optimized per platform.
    #[inline(always)]
    pub fn high_resolution_timestamp() -> Instant {
        // All modern platforms support high-resolution timestamps through std::time::Instant
        // The implementation is already optimized per platform by the standard library
        Instant::now()
    }
    
    /// Platform-optimized sleep function for pacing.
    #[inline]
    pub fn precise_sleep(duration: Duration) {
        match PLATFORM {
            "linux" => {
                // Linux: Use nanosleep for better precision
                std::thread::sleep(duration);
            },
            "freebsd" => {
                // FreeBSD: Similar to Linux
                std::thread::sleep(duration);
            },
            "macos" => {
                // macOS: Standard sleep is usually sufficient
                std::thread::sleep(duration);
            },
            "windows" => {
                // Windows: May need to adjust for timer resolution
                if duration < Duration::from_millis(1) {
                    // For very short durations, busy wait might be more accurate
                    let start = Instant::now();
                    while start.elapsed() < duration {
                        std::hint::spin_loop();
                    }
                } else {
                    std::thread::sleep(duration);
                }
            },
            _ => {
                std::thread::sleep(duration);
            }
        }
    }
    
    /// Platform-optimized memory prefetch hint.
    #[inline(always)]
    pub fn prefetch_hint<T>(ptr: *const T) {
        #[cfg(target_arch = "x86_64")]
        {
            // Use prefetch instructions on x86_64
            unsafe {
                std::arch::x86_64::_mm_prefetch(
                    ptr as *const i8,
                    std::arch::x86_64::_MM_HINT_T0
                );
            }
        }
        
        #[cfg(target_arch = "aarch64")]
        {
            // ARM64 prefetch
            unsafe {
                std::arch::asm!("prfm pldl1keep, [{}]", in(reg) ptr);
            }
        }
        
        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
        {
            // No-op for other architectures
            let _ = ptr;
        }
    }
    
    /// Platform-optimized CPU cache line size.
    pub const fn cache_line_size() -> usize {
        #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
        {
            64 // Most modern CPUs use 64-byte cache lines
        }
        
        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
        {
            32 // Conservative default
        }
    }
    
    /// Align a value to cache line boundary.
    #[inline(always)]
    pub const fn align_to_cache_line(size: usize) -> usize {
        let cache_line = cache_line_size();
        (size + cache_line - 1) & !(cache_line - 1)
    }
}

/// Platform-specific network stack integration.
pub mod network {
    use super::detection::PLATFORM;
    
    /// Get the recommended TCP congestion control algorithm for the platform.
    pub fn recommended_tcp_algorithm() -> &'static str {
        match PLATFORM {
            "linux" => "bbr",      // Linux has excellent BBR support
            "freebsd" => "cubic",   // FreeBSD traditionally uses CUBIC
            "macos" => "cubic",     // macOS uses CUBIC by default
            "windows" => "cubic",   // Windows uses CUBIC-like algorithm
            _ => "cubic",           // Safe default
        }
    }
    
    /// Check if the platform supports ECN (Explicit Congestion Notification).
    pub fn supports_ecn() -> bool {
        match PLATFORM {
            "linux" => true,     // Linux has good ECN support
            "freebsd" => true,   // FreeBSD supports ECN
            "macos" => false,    // macOS ECN support is limited
            "windows" => false,  // Windows ECN support varies
            _ => false,          // Conservative default
        }
    }
    
    /// Get platform-specific socket options for optimal performance.
    pub fn get_socket_options() -> Vec<(&'static str, i32)> {
        let mut options = Vec::new();
        
        match PLATFORM {
            "linux" => {
                options.push(("TCP_NODELAY", 1));
                options.push(("SO_REUSEADDR", 1));
                options.push(("SO_REUSEPORT", 1));
                options.push(("TCP_QUICKACK", 1));
            },
            "freebsd" => {
                options.push(("TCP_NODELAY", 1));
                options.push(("SO_REUSEADDR", 1));
                options.push(("SO_REUSEPORT", 1));
            },
            "macos" => {
                options.push(("TCP_NODELAY", 1));
                options.push(("SO_REUSEADDR", 1));
                options.push(("SO_REUSEPORT", 1));
            },
            "windows" => {
                options.push(("TCP_NODELAY", 1));
                options.push(("SO_REUSEADDR", 1));
            },
            _ => {
                options.push(("TCP_NODELAY", 1));
                options.push(("SO_REUSEADDR", 1));
            }
        }
        
        options
    }
}

/// SIMD optimizations when available.
#[cfg(feature = "simd")]
pub mod simd {
    /// Check if AVX2 is available (x86_64 only).
    #[cfg(target_arch = "x86_64")]
    pub fn has_avx2() -> bool {
        is_x86_feature_detected!("avx2")
    }
    
    /// Check if NEON is available (ARM64 only).
    #[cfg(target_arch = "aarch64")]
    pub fn has_neon() -> bool {
        // NEON is standard on ARM64
        true
    }
    
    /// Vectorized operations for batch processing.
    #[cfg(target_arch = "x86_64")]
    pub mod x86_64 {
        use std::arch::x86_64::*;
        
        /// SIMD-optimized batch RTT calculation.
        #[target_feature(enable = "avx2")]
        pub unsafe fn batch_rtt_calculation(rtts: &[u64]) -> (u64, u64) {
            if rtts.len() < 4 {
                // Fall back to scalar for small arrays
                let sum: u64 = rtts.iter().sum();
                let avg = sum / rtts.len() as u64;
                let min = *rtts.iter().min().unwrap_or(&0);
                return (avg, min);
            }
            
            let mut sum_vec = _mm256_setzero_si256();
            let mut min_vec = _mm256_set1_epi64x(i64::MAX);
            
            let chunks = rtts.chunks_exact(4);
            let remainder = chunks.remainder();
            
            for chunk in chunks {
                let data = _mm256_loadu_si256(chunk.as_ptr() as *const __m256i);
                sum_vec = _mm256_add_epi64(sum_vec, data);
                min_vec = _mm256_min_epi64(min_vec, data);
            }
            
            // Extract results from vectors
            let sum_array: [i64; 4] = std::mem::transmute(sum_vec);
            let min_array: [i64; 4] = std::mem::transmute(min_vec);
            
            let mut total_sum = sum_array.iter().sum::<i64>() as u64;
            let mut global_min = min_array.iter().min().copied().unwrap_or(i64::MAX) as u64;
            
            // Handle remainder
            for &rtt in remainder {
                total_sum += rtt;
                global_min = global_min.min(rtt);
            }
            
            let avg = total_sum / rtts.len() as u64;
            (avg, global_min)
        }
    }
    
    #[cfg(target_arch = "aarch64")]
    pub mod aarch64 {
        use std::arch::aarch64::*;
        
        /// NEON-optimized batch RTT calculation.
        pub unsafe fn batch_rtt_calculation(rtts: &[u64]) -> (u64, u64) {
            if rtts.len() < 2 {
                let sum: u64 = rtts.iter().sum();
                let avg = sum / rtts.len() as u64;
                let min = *rtts.iter().min().unwrap_or(&0);
                return (avg, min);
            }
            
            let mut sum_vec = vdupq_n_u64(0);
            let mut min_vec = vdupq_n_u64(u64::MAX);
            
            let chunks = rtts.chunks_exact(2);
            let remainder = chunks.remainder();
            
            for chunk in chunks {
                let data = vld1q_u64(chunk.as_ptr());
                sum_vec = vaddq_u64(sum_vec, data);
                min_vec = vminq_u64(min_vec, data);
            }
            
            // Extract results
            let sum_array = [vgetq_lane_u64(sum_vec, 0), vgetq_lane_u64(sum_vec, 1)];
            let min_array = [vgetq_lane_u64(min_vec, 0), vgetq_lane_u64(min_vec, 1)];
            
            let mut total_sum = sum_array.iter().sum::<u64>();
            let mut global_min = min_array.iter().min().copied().unwrap_or(u64::MAX);
            
            // Handle remainder
            for &rtt in remainder {
                total_sum += rtt;
                global_min = global_min.min(rtt);
            }
            
            let avg = total_sum / rtts.len() as u64;
            (avg, global_min)
        }
    }
}

/// Platform-specific performance tuning recommendations.
pub mod tuning {
    use super::detection::PLATFORM;
    
    /// Get platform-specific tuning recommendations.
    pub fn get_tuning_recommendations() -> Vec<(&'static str, &'static str)> {
        let mut recommendations = Vec::new();
        
        match PLATFORM {
            "linux" => {
                recommendations.push(("net.core.rmem_max", "134217728"));
                recommendations.push(("net.core.wmem_max", "134217728"));
                recommendations.push(("net.ipv4.tcp_rmem", "4096 87380 134217728"));
                recommendations.push(("net.ipv4.tcp_wmem", "4096 65536 134217728"));
                recommendations.push(("net.ipv4.tcp_congestion_control", "bbr"));
                recommendations.push(("net.core.default_qdisc", "fq"));
            },
            "freebsd" => {
                recommendations.push(("net.inet.tcp.sendbuf_max", "134217728"));
                recommendations.push(("net.inet.tcp.recvbuf_max", "134217728"));
                recommendations.push(("net.inet.tcp.cc.algorithm", "cubic"));
            },
            "macos" => {
                recommendations.push(("net.inet.tcp.sendspace", "1048576"));
                recommendations.push(("net.inet.tcp.recvspace", "1048576"));
            },
            "windows" => {
                recommendations.push(("TcpWindowSize", "1048576"));
                recommendations.push(("TcpAckFrequency", "1"));
                recommendations.push(("TCPNoDelay", "1"));
            },
            _ => {
                // Generic recommendations
                recommendations.push(("socket_buffer_size", "1048576"));
            }
        }
        
        recommendations
    }
    
    /// Print platform-specific tuning guide.
    pub fn print_tuning_guide() {
        println!("Platform-specific tuning recommendations for {}:", PLATFORM);
        
        for (param, value) in get_tuning_recommendations() {
            match PLATFORM {
                "linux" => {
                    println!("  echo '{}' > /proc/sys/{}", value, param.replace('.', "/"));
                },
                "freebsd" => {
                    println!("  sysctl {}={}", param, value);
                },
                "macos" => {
                    println!("  sudo sysctl -w {}={}", param, value);
                },
                "windows" => {
                    println!("  Set registry key: {} = {}", param, value);
                },
                _ => {
                    println!("  Configure: {} = {}", param, value);
                }
            }
        }
    }
}