#mmap

2025-12-02

#Programming tip: if you want to allocate memory and explicitly tell the kernel you don't want the memory backed until you use it, try mmap(). Really useful.

An example of mmap being used this way. gitlab.com/golemwire/subsky/-/ (permalink gitlab.com/golemwire/subsky/-/ )
This is from my #SubSky emulator.

(p_cpu->p_memory = (uint8_t *) mmap(NULL, (size_t) 1 << 32, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0))

#mmap #kernel

2025-10-25

[Перевод] Как memory maps (mmap) обеспечивают в 25 раз более быстрый доступ к файлам в Go

Команда Go for Devs подготовила перевод статьи о том, как memory maps (mmap) обеспечивают молниеносный доступ к файлам в Go. Автор показывает, что замена обычного чтения и записи на работу с памятью может ускорить программу в 25 раз — и объясняет, почему это почти магия, но с нюансами.

habr.com/ru/articles/960120/

#Go #mmap #производительность #память #файлы #Unix #системные_вызовы #оптимизация #Varnish_Cache #io_uring

N-gated Hacker Newsngate
2025-10-23

🚀 Wow, can now access files 25 times faster with MMAP! But let's not get too excited—it's like putting a turbo on a tricycle. 🐢 Meanwhile, is still doing its best to sound like a fancy condiment. 🥒
info.varnish-software.com/blog

GripNewsGripNews
2025-10-14

🌗 Linux 核心 mmap() 檔案操作的淘汰進程
➤ 安全與效率並重:Linux 核心淘汰 mmap() 系統呼叫
lwn.net/Articles/1038715/
Linux 核心正逐步淘汰 mmap() 系統呼叫的檔案操作介面。此舉旨在改善核心的記憶體管理機制,降低驅動程式直接存取 VMA 結構所帶來的潛在風險與複雜性。新的 mmap_prepare() 介面將取代 mmap(),提供更精確的控制,並逐步引入 mmap_action 機制,以支援更廣泛的檔案映射需求,進一步提升核心的穩定性與安全性。
+ 這個改變聽起來很棒,能減少潛在的 bug 會是個大進步。
+ 淘汰 mmap() 感覺有點激進,希望新的 API 能夠完全涵蓋現有功能。
Kernel Operations

N-gated Hacker Newsngate
2025-10-14

🚀 Breaking news: mmap() is retiring! 🎩 in the will apparently do some without it. Maybe next we'll phase out files altogether and just read minds? 📚✨
lwn.net/Articles/1038715/

Vito Sartori (ヴィト) 🦊vito@ruby.social
2025-09-30
2025-09-17

PHP: Общая память

Хочется быстрый кеш или общение между процессами? Хочется использовать long-running PHP, но без long-running? Давайте разберёмся, как работать прямо с оперативной памятью: от System V до MapViewOfFile; От shmop до FFI. Расшарить оперативу

habr.com/ru/articles/947896/

#systemv #shmop #mmap #память #никто_не_читает_теги #ipc

2025-06-10

TIL: calling munmap() with wrong parameters can cause really strange occasional crashes in #AddressSanitizer or #Valgrind. Wrong parameters meaning in this case:
- passing wrong (too large) size,
- passing NULL,
- calling munmap() multiple times for the same pointer.

Debugging the crashes was painful. What helped in the end was "doing the boring right thing": adding error checking to all related system calls, adding debug logs, fixing code smells.

#softwareDevelopment #Linux #mmap

2025-05-07

MSYS2, GDB и управление памятью

Эта история началась с того, что мне захотелось поработать с интерпретатором одного очень экзотического языка программирования, а закончилась тем, что я освоил не менее экзотические (для меня) нюансы работы с памятью в С в Windows и POSIX, и того, как работает отладчик gdb в Windows. ну очень экзотического

habr.com/ru/articles/907662/

#msys2 #gdb #mmap #memset

Felix Palmen :freebsd: :c64:zirias@bsd.cafe
2025-04-28

digging a bit deeper to further improve this #async / #await implementation:

Keeping all the #stacks mapped certainly makes sense to avoid excessive #mmap overhead ... but on *some* (most?) systems (I checked #FreeBSD and #Linux docs for now), we can let the kernel know when the mapping just contains worthless scratch (which will be the case after a thread job finishes until another thread job claims the same stack). Then, if there's a need to free pages, the kernel can avoid pointlessly writing that garbage to #swap. 😎

github.com/Zirias/poser/commit

#C #coding

Felix Palmen :freebsd: :c64:zirias@bsd.cafe
2025-04-28

Revisiting #async / #await in #POSIX C, trying to "add some #security" 🙈

Recap: Consider a classic #reactor-style service in C with a #threadpool attached to run the individual request handlers. When such a handler needs to do some I/O, it'll have to wait for its completion, and doing so is kind of straight forward by just blocking the worker thread executing the job until whatever I/O was needed completes.

Now, blocking a thread is never a great thing to do and I recently tooted about an interesting alternative I found: Make use of the (unfortunately deprecated) POSIX user context switching to enable releasing the worker thread while waiting. In a nutshell, you create a context with #makecontext that has its own private #stack, and then you can use #swapcontext to get off the thread, and later again to get back on the thread. A minor issue is: It must be the *same* thread ... so you might have to wait until it completes something else before you can resume your job. But then, that's probably okayish, you can make sure in your job scheduling to only use worker threads with awaited tasks attached when no other thread is available.

In my first implementation, I just used #malloc to create a 64kiB private stack for each thread job. That's perfectly fine if you can guarantee your job will never consume more stack space, AND it won't have any vulnerabilities allowing some attacker to mess with the stack. But in practice, especially for a library offering this async/await implementation, it's nothing but a wild #CVE generator.

So, I now improved on that:

* Allocate a much larger stack of now 2MiB. That alone makes issues at least less likely. And on a sane modern OS, we can still assume pages will only be mapped "on demand".
* Only allocate the stack directly before running the thread job, and delegate allocation to some internal "stack manager" that keeps track of all allocated stacks and reuses them, only freeing them on exit. This should avoid most of the allocation overhead.
* If MAP_ANON / MAP_ANONYMOUS is available, use #mmap for allocating the stack. That at least gives a chance to stay away from other allocations ....
* But finally, if MAP_STACK is available, use this flag! From my research, #FreeBSD, #OpenBSD and #NetBSD will for example make sure there's at least one "guard page" below a stack mapped with this flag, so a stack overflow consistently takes the SIGSEGV emergency exit 😆. #Linux knows this flag as well, but doesn't seem to implement such protection at this time ... 🤔

#C #coding

2025-01-27

Please, feel free to share your own #MMAP songs.✊🏻

2025-01-27

Crazy idea:

This is gonna be the first of more songs dedicated to improve your labour week by starting it remembering that we must destroy this system; the #MMAP, Monday Mornings Anticapitalist Playlist

2025-01-27
Jesus Michał "Le Sigh" 🏔 (he)mgorny@treehouse.systems
2024-10-20

STOP DOING #MMAP!

• Files were not supposed to be treated like memory.
• Years of mmaping, yet no real-world use found for giving disk data memory addresses.
• Wanted to have a file in memory anyway, for a laugh? We had a tool for that, it was called "reading into a buffer".
• "Yes, please give me a SIGBUS when I run out of space. Please give me a SIGSEGV if I read past the file." — statements dreamed up by the utterly deranged.

#C #ProgrammersHumor

2024-07-16

So, in case you’ve ever wondered, this is how you map anonymous memory with vm-memory crate:

//! Copyright (c) Jarkko Sakkinen 2024

#![deny(clippy::all)]
#![deny(clippy::pedantic)]

use vm_memory::{GuestAddress, GuestMemoryMmap};

fn main() {
    let mem: GuestMemoryMmap<()> =
        GuestMemoryMmap::from_ranges(&[(GuestAddress(0u64), 8192usize)]).unwrap();
    println!("{:?}", mem);
}

The type parameter is for Bitmap.

I’ll do a small test program for each type of memory that we need in Enarx and after that make the changes to the project itself. Changes are simple but the code base is large so this is fastest way to formalize a decent patch.

So next step is /dev/kvm test.

#rust #rustlang #mmap #kvm

2024-06-10

[Перевод] Почему MMAP не лучший выход

Доступ к файлам через отображение-в-память ( mmap ) — это способность некоторых операционных систем отобразить содержимое какого-либо файла в адресное пространство программы. Сама программа получает доступ к содержимому файла через указатели, как если бы сам файл был бы целиком загружен в оперативную память. Операционная система прозрачно загружает части файла в оперативную память, и автоматически выгружает их, когда памяти не хватает. MMAP захватила умы программистов СУБД на многие десятилетия, как альтернатива буферу данных. И вот здесь следует отметить, что в mmap имеются серьёзные проблемы с корректностью и скоростью работы с данными в современных СУБД. В реальности, некоторые известные СУБД сперва использовали mmap для работы с "больше-чем-вмещается-в-память" базами данных, но вскоре обнаружили эти скрытые ограничения, которые принудили их к самостоятельному управлению файловым вводом/выводом, после заметных трат на инженерные исследования. В этом смысле mmap и СУБД подобны сочетанию кофе и острой пищи: неудачное сочетание, которое не очевидно, пока сам не попробуешь. Покуда разработчики по прежнему пытаются использовать mmap в новых СУБД, мы написали эту статью, чтобы предупредить остальных, что mmap это не подходящая замена привычному буферу. Далее мы обсудим основные недостатки mmap , а также покажем явные ограничения производительности, которые мы обнаружили в наших экспериментах. На основании этих находок мы поделимся рецептами, когда разработчикам СУБД следует избегать mmap для реализации файлового ввода/вывода.

habr.com/ru/articles/820591/

#СУБД #оптимизация_производительности #mmap

2024-03-26

:ubuntu: Ubuntu & gaming | More top games to work OOTB :yay: 🥡

Next month's Ubuntu Linux 24.04 LTS to be a delightful release - a little tweak improves the default gaming experience too.

Games amongst many to benefit:
◉Hogwarts Legacy
◉Payday 2
◉Counter-Strike 2
◉DayZ
◉Star Citizen

omgubuntu.co.uk/2024/03/ubuntu

@omgubuntu #Ubuntu #LinuxGaming #LTS #mmap

Client Info

Server: https://mastodon.social
Version: 2025.07
Repository: https://github.com/cyevgeniy/lmst