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
#![no_std]

//! This crate provides the operating system with hints about memory access
//! patterns. For example, if the user calls memadvise::advise() with
//! Advice::Sequential, the kernel may start bringing memory pages into
//! RAM (if they were on disk) starting at the beginning of the block of
//! memory passed.
//!
//! # Example
//!
//! This example shows the basic usage of the crate.
//!
//! ```rust,ignore
//! extern crate memadvise;
//! extern crate page_size;
//! 
//! // Allocate block of memory in a system specific manner.
//! 
//! // Get portion of memory block (must be aligned to system page size).
//! let address: *mut () = ... 
//! let length = 320000;
//! 
//! // Tell the OS to start loading this portion into RAM starting at the beginning.
//! memadvise::advise(address, length, Advice::Sequential).unwrap();
//! 
//! // Do something with this portion of memory.
//! 
//! // Tell the OS we do not need this portion right now.
//! // That way, the OS can safely swap it out to disk.
//! memadvise::advise(address, length, Advice::DontNeed).unwrap();
//!
//! // Do some other stuff.
//!
//! // Be sure to free block of memory (system specific) at the end.
//! ```

// `const_fn` is needed for `spin::Once`.
#![cfg_attr(feature = "no_std", feature(const_fn))]
#![cfg_attr(all(feature = "no_std", not(windows)), allow(unused_extern_crates))]

extern crate page_size;

#[cfg(not(feature = "no_std"))]
extern crate std;

#[cfg(unix)]
extern crate libc;

#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
extern crate kernel32;
#[cfg(feature = "no_std")]
extern crate spin;

pub enum Advice {
    /// No special usage
    Normal,
    /// Will access memory block in order from low address to high address; OS should aggressively read ahead 
    Sequential,
    /// Will access random chunks from memory block; OS may not have to read ahead
    Random,
    /// Will need to access this memory block soon; OS should read ahead
    WillNeed,
    /// Will NOT need to access this memory block soon
    DontNeed,
}

/// This function gives the system advice about a certain block of memory.
///
/// # Arguments
///
/// * address - a raw pointer to a memory address that must be a multiple of the system's page size
///
/// * length - size of memory block in bytes (must be nonzero)
///
/// * advice - hint to pass to the operating system
pub fn advise(address: *mut (), length: usize, advice: Advice)
                     -> Result<(), MemAdviseError> {
    advise_helper(address, length, advice)
}

/// The possible errors returned by `advise()`
pub enum MemAdviseError {
    /// Passed null pointer in `address` field
    NullAddress,
    /// Invalid value for `length`
    InvalidLength,
    /// `address` is not properly aligned
    UnalignedAddress,
    /// Memory block is invalid for some other reason
    InvalidRange,
}

// Unix Section

#[cfg(unix)]
#[inline]
fn advise_helper(address: *mut (), length: usize, advice: Advice)
                            -> Result<(), MemAdviseError> {
    unix::advise(address, length, advice)
}

#[cfg(unix)]
mod unix {
    #[cfg(feature = "no_std")]
    use core::ptr;
    #[cfg(not(feature = "no_std"))]
    use std::ptr;

    #[cfg(target_os = "android")]
    use libc::{c_void, madvise, MADV_DONTNEED, MADV_NORMAL, MADV_RANDOM, MADV_SEQUENTIAL, MADV_WILLNEED};
    #[cfg(not(target_os = "android"))]
    use libc::{c_void, posix_madvise as madvise, POSIX_MADV_DONTNEED as MADV_DONTNEED, POSIX_MADV_NORMAL as MADV_NORMAL, POSIX_MADV_RANDOM as MADV_RANDOM, POSIX_MADV_SEQUENTIAL as MADV_SEQUENTIAL, POSIX_MADV_WILLNEED as MADV_WILLNEED};

    use page_size;
    
    use super::{Advice, MemAdviseError};
    
    #[inline]
    pub fn advise(address: *mut (),
                  length: usize,
                  advice: Advice)
                  -> Result<(), MemAdviseError>
    {
        // Check for null pointer.
        if address == ptr::null_mut() {
            return Err(MemAdviseError::NullAddress);
        }

        // Check for invalid length.
        if length == 0 {
            return Err(MemAdviseError::InvalidLength);
        }

        // Ensure `address` is a multiple of the system page size.
        // Assume the page size is a power of 2.
        let page_size = page_size::get();
        let ptr_usize = address as usize;

        if ptr_usize & !(page_size - 1) != ptr_usize {
            return Err(MemAdviseError::UnalignedAddress);
        }

        // Get Advice value
        let advice_internal = match advice {
            Advice::DontNeed => MADV_DONTNEED,
            Advice::Normal => MADV_NORMAL,
            Advice::Random => MADV_RANDOM,
            Advice::Sequential => MADV_SEQUENTIAL,
            Advice::WillNeed => MADV_WILLNEED,
        };

        let res = unsafe {
            madvise(address as *mut c_void,
                    length,
                    advice_internal)
        };

        if res == 0 {
            Ok(())
        }
        // Assume that the system call failed because of an invalid address range.
        // We *SHOULD* have handled any other invalid inputs.
        else {
            Err(MemAdviseError::InvalidRange)
        }
    }

    #[cfg(test)]
    mod tests {
        use libc::{MAP_ANON, MAP_PRIVATE, PROT_READ, mmap, munmap};
        
        use super::*;

        // Anonymous maps are not part of the POSIX standard, but they are widely available.
        // We use `libc::MAP_ANON` since NetBSD does not support `libc::MAP_ANONYMOUS`.
        #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd", target_os = "netbsd", target_os = "android"))]
        #[test]
        fn test_unix_memadvise() {
            let length = 2 * page_size::get();

            let address = unsafe {
                mmap(ptr::null_mut(),
                     length,
                     PROT_READ,
                     MAP_PRIVATE | MAP_ANON,
                     -1,
                     0)
            };
            
            assert_ne!(address, ptr::null_mut());
            
            match advise(address as *mut (),
                         length as usize,
                         Advice::WillNeed) {
                Ok(_) => {},
                _ => { assert!(false); },
            }
            
            match advise(address as *mut (),
                         length as usize,
                         Advice::DontNeed) {
                Ok(_) => {},
                _ => { assert!(false); },
            }

            let res = unsafe {
                munmap(address, length)
            };
            
            assert_eq!(res, 0);
        }

        #[test]
        fn test_unix_memadvise_null_address() {
            match advise(ptr::null_mut(), 0, Advice::Normal) {
                Err(MemAdviseError::NullAddress) => {},
                _ => { assert!(false); },
            }
        }

        #[test]
        fn test_unix_memadvise_zero_length() {
            let mut test: usize = 3;
            let address = &mut test as *mut usize as *mut ();

            match advise(address, 0, Advice::Normal) {
                Err(MemAdviseError::InvalidLength) => {},
                _ => { assert!(false); },
            }
        }

        #[test]
        fn test_unix_memadvise_unaligned_address() {
            let mut test = page_size::get() + 1;
            let address = &mut test as *mut usize as *mut ();

            match advise(address, 64, Advice::Normal) {
                Err(MemAdviseError::UnalignedAddress) => {},
                _ => { assert!(false); },
            }
        }

        #[test]
        fn test_unix_memadvise_invalid_range() {
            // We cannot use a value of 0 for the address, since that would
            // be caught by the null pointer check. The second page of memory
            // in the address space is almost certainly invalid.
            let address = page_size::get() as *mut usize as *mut ();

            match advise(address, 64, Advice::Normal) {
                Err(MemAdviseError::InvalidRange) => {},
                _ => { assert!(false); },
            }
        }
    }
}

// Windows Section

#[cfg(windows)]
#[inline]
fn advise_helper(address: *mut (), length: usize, advice: Advice)
                     -> Result<(), MemAdviseError> {
    windows::advise(address, length, advice)
}

#[cfg(windows)]
mod windows {
    #[cfg(feature = "no_std")]
    use core::ptr;
    #[cfg(not(feature = "no_std"))]
    use std::ptr;

    #[cfg(feature = "no_std")]
    use core::mem;
    #[cfg(not(feature = "no_std"))]
    use std::mem;

    use kernel32::{GetCurrentProcess, PrefetchVirtualMemory, VerifyVersionInfoA, VerSetConditionMask};

    use winapi::basetsd::{SIZE_T, ULONG_PTR};
    use winapi::memoryapi::{PWIN32_MEMORY_RANGE_ENTRY, WIN32_MEMORY_RANGE_ENTRY};
    use winapi::minwindef::{BYTE, DWORD, ULONG};
    use winapi::winnt::{LPOSVERSIONINFOEXA, OSVERSIONINFOEXA, PVOID, ULONGLONG};

    #[cfg(feature = "no_std")]
    use spin::Once;
    #[cfg(not(feature = "no_std"))]
    use std::sync::{Once, ONCE_INIT};

    use page_size;
    
    use super::{Advice, MemAdviseError};

    const VER_MAJORVERSION: DWORD = 0x2;
    const VER_MINORVERSION: DWORD = 0x1;
    const VER_GREATER_EQUAL: BYTE = 0x3;

    #[inline]
    pub fn advise(address: *mut (),
                  length: usize,
                  advice: Advice)
                  -> Result<(), MemAdviseError>
    {
        // Check for null pointer.
        if address == ptr::null_mut() {
            return Err(MemAdviseError::NullAddress);
        }

        // Check for invalid length.
        if length == 0 {
            return Err(MemAdviseError::InvalidLength);
        }

        // Ensure `address` is a multiple of the system page size.
        // Assume the page size is a power of 2.
        let page_size = page_size::get();
        let ptr_usize = address as usize;

        if ptr_usize & !(page_size - 1) != ptr_usize {
            return Err(MemAdviseError::UnalignedAddress);
        }

        // Windows only really supports `Advice::WillNeed`.
        // `Advice::{Random, Sequential, WillNeed}` all tell the system to
        // prefetch memory. `Advice::{DontNeed, Normal}` do not do anything.
        match advice {
            Advice::Normal | Advice::DontNeed => {
                return Ok(());
            },
            _ => {},
        }

        let mut memrange = WIN32_MEMORY_RANGE_ENTRY {
            VirtualAddress: address as PVOID,
            NumberOfBytes: length as SIZE_T,
        };

        // Do nothing if we are running on Windows 7.
        if !is_prefetch_supported() {
            return Ok(())
        }

        let res = unsafe {
            PrefetchVirtualMemory(
                GetCurrentProcess(),
                1 as ULONG_PTR,
                &mut memrange as PWIN32_MEMORY_RANGE_ENTRY,
                0 as ULONG
            )
        };

        // Check that function completed successfully.
        if res == 0 {
            Err(MemAdviseError::InvalidRange)
        }
        else {
            Ok(())
        }
    }

    // Only Windows8+ supports `kernel32::PrefetchVirtualMemory()`.
    #[cfg(all(windows, feature = "no_std"))]
    #[inline]
    fn is_prefetch_supported() -> bool {
        static INIT: Once<bool> = Once::new();
        
        *INIT.call_once(supported_helper)
    }

    #[cfg(all(windows, not(feature = "no_std")))]
    #[inline]
    fn is_prefetch_supported() -> bool {
        static INIT: Once = ONCE_INIT;
        static mut SUPPORTED: bool = false;

        unsafe {
            INIT.call_once(|| SUPPORTED = supported_helper());
            SUPPORTED
        }
    }

    #[inline]
    fn supported_helper() -> bool {
        // Build type mask.
        let type_mask = VER_MAJORVERSION | VER_MINORVERSION;
        
        // Build condition mask.
        let cond_mask = unsafe {
            VerSetConditionMask(
                0 as ULONGLONG,
                type_mask,
                VER_GREATER_EQUAL
            )
        };
        
        // Initialize version info.
        let mut info: OSVERSIONINFOEXA = unsafe { mem::zeroed() };
        info.dwMajorVersion = 6 as DWORD;
        info.dwMinorVersion = 2 as DWORD;

        // Test version
        let res = unsafe {
            VerifyVersionInfoA(
                &mut info as LPOSVERSIONINFOEXA,
                type_mask,
                cond_mask
            )
        };

        res != 0
    }

    #[cfg(test)]
    mod tests {
        use kernel32::{VirtualAlloc, VirtualFree};

        use winapi::basetsd::SIZE_T;
        use winapi::minwindef::{BOOL, DWORD, LPVOID};
        use winapi::winnt::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE};

        use super::*;

        // Assume Windows8+.
        #[test]
        fn test_is_prefetch_supported() {
            assert_eq!(is_prefetch_supported(), true);
            assert_eq!(is_prefetch_supported(), true);
        }

        #[test]
        fn test_windows_memadvise() {
            let length = page_size::get() as SIZE_T;

            let address = unsafe {
                VirtualAlloc(
                    ptr::null_mut() as LPVOID,
                    length,
                    MEM_COMMIT | MEM_RESERVE,
                    PAGE_READWRITE
                )
            };

            assert_ne!(address, ptr::null_mut() as LPVOID);

            let addr = address as *mut ();
            let len = length as usize;
            
            match advise(addr, len, Advice::WillNeed) {
                Ok(_) => {},
                _ => { assert!(false); },
            }
                        
            match advise(addr, len, Advice::DontNeed) {
                Ok(_) => {},
                _ => { assert!(false); },
            }

            let res = unsafe { VirtualFree(address, 0, MEM_RELEASE) };

            assert_ne!(res, 0 as BOOL);
        }

        #[test]
        fn test_windows_memadvise_null_address() {
            match advise(ptr::null_mut(), 0, Advice::Normal) {
                Err(MemAdviseError::NullAddress) => {},
                _ => { assert!(false); },
            }
        }

        #[test]
        fn test_windows_memadvise_zero_length() {
            let mut test: usize = 3;
            let address = &mut test as *mut usize as *mut ();

            match advise(address, 0, Advice::Normal) {
                Err(MemAdviseError::InvalidLength) => {},
                _ => { assert!(false); },
            }
        }

        #[test]
        fn test_windows_memadvise_unaligned_address() {
            let mut test = page_size::get() + 1;
            let address = &mut test as *mut usize as *mut ();

            match advise(address, 64, Advice::Normal) {
                Err(MemAdviseError::UnalignedAddress) => {},
                _ => { assert!(false); },
            }
        }

        // // I do not know of a good address range to test this on windows.
        // #[test]
        // fn test_windows_memadvise_invalid_range() {
        //     let address = page_size::get() as *mut usize as *mut ();

        //     match advise(address, 64, Advice::Normal) {
        //         Err(MemAdviseError::InvalidRange) => {},
        //         _ => { assert!(false); },
        //     }
        // }
    }
}

// Stub Section

#[cfg(not(any(unix, windows)))]
#[inline]
fn advise_helper(address: *mut (), length: usize, advice: Advice)
                            -> Result<(), MemAdviseError> {
    stub::advise(address, length, advice)
}

#[cfg(not(any(unix, windows)))]
mod stub {
    #[cfg(feature = "no_std")]
    use core::ptr;
    #[cfg(not(feature = "no_std"))]
    use std::ptr;

    use super::{Advice, MemAdviseError};
    
    #[inline]
    pub fn advise(address: *mut (),
                  length: usize,
                  advice: Advice)
                  -> Result<(), MemAdviseError>
    {
        // Check for null pointer.
        if address == ptr::null_mut() {
            return Err(MemAdviseError::NullAddress);
        }

        // Check for invalid length.
        if length == 0 {
            return Err(MemAdviseError::InvalidLength);
        }

        Ok(())
    }
    
    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn test_stub_memadvise() {
            let test: usize = 3;
            let address = &test as *mut usize as *mut ();

            match advise(address, 64, Advice::Normal) {
                Ok(_) => {},
                _ => { assert!(false); },
            }
        }

        #[test]
        fn test_windows_memadvise_null_address() {
            match advise(ptr::null_mut(), 0, Advice::Normal) {
                Err(MemAdviseError::NullAddress) => {},
                _ => { assert!(false); },
            }
        }

        #[test]
        fn test_windows_memadvise_zero_length() {
            let mut test: usize = 3;
            let address = &mut test as *mut usize as *mut ();

            match advise(address, 0, Advice::Normal) {
                Err(MemAdviseError::InvalidLength) => {},
                _ => { assert!(false); },
            }
        }
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "no_std")]
    use core::ptr;
    #[cfg(not(feature = "no_std"))]
    use std::ptr;

    use super::*;
    
    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd", target_os = "netbsd", target_os = "android"))]
    #[test]
    fn test_memadvise_most_unices() {
        use libc::{PROT_READ, MAP_PRIVATE, MAP_ANON, _SC_PAGESIZE, mmap, munmap, size_t, sysconf};
        
        let page_size = unsafe {
            sysconf(_SC_PAGESIZE) as size_t
        };
        
        let length = 2 * page_size;

        let address = unsafe {
            mmap(ptr::null_mut(),
                 length,
                 PROT_READ,
                 MAP_PRIVATE | MAP_ANON,
                 -1,
                 0)
        };
        
        assert_ne!(address, ptr::null_mut());
        
        match advise(address as *mut (),
                     length as usize,
                     Advice::WillNeed) {
            Ok(_) => {},
            _ => { assert!(false); },
        }
        
        match advise(address as *mut (),
                     length as usize,
                     Advice::DontNeed) {
            Ok(_) => {},
            _ => { assert!(false); },
        }

        let res = unsafe {
            munmap(address, length)
        };
        
        assert_eq!(res, 0);
    }

    #[cfg(windows)]
    #[test]
    fn test_memadvise_windows() {
        use kernel32::{VirtualAlloc, VirtualFree};

        use winapi::basetsd::SIZE_T;
        use winapi::minwindef::{BOOL, DWORD, LPVOID};
        use winapi::winnt::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE};

        let length = page_size::get() as SIZE_T;

        let address = unsafe {
            VirtualAlloc(
                ptr::null_mut() as LPVOID,
                length as SIZE_T,
                MEM_COMMIT | MEM_RESERVE,
                PAGE_READWRITE
            )
        };

        assert_ne!(address, ptr::null_mut() as LPVOID);

        let addr = address as *mut ();
        let len = length as usize;
        
        match advise(addr, len, Advice::WillNeed) {
            Ok(_) => {},
            _ => { assert!(false); },
        }
        
        match advise(addr, len, Advice::DontNeed) {
            Ok(_) => {},
            _ => { assert!(false); },
        }

        let res = unsafe { VirtualFree(address, 0, MEM_RELEASE) };

        assert_ne!(res, 0 as BOOL);
    }

    #[cfg(not(any(unix, windows)))]
    #[test]
    fn test_memadvise_stub() {
        advise(ptr::null_mut(), 0, Advice::Normal);
    }
}