How Does Linux Handle RAM?

One of the most fundamental parts of any operating systems is managing memory; the subsystem conveniently known as the Memory Management Unit or MMU. This subsystem is a very complex one but, fortunately for us, it's very well documented.

When we're talking about memory, it's usually the physical RAM that we're referring to. Total physical RAM is one of the most important attributes you'd look for in a new PC or server. But it's the operating system that's ultimately involved in how that RAM is used and distributed. The OS serves as an abstraction layer between applications and the physical memory. This layer divides the physical RAM into virtual "pages", which are the smallest units of data an OS can use. By default, the page size is 4KB in a Linux system, as working with each bit individually would be too complex to be efficient. 

When Linux uses system RAM, it creates a virtual memory layer to then assigns processes to virtual memory. Virtual memory is actually a combination of both RAM and swap space; swap space is a section of your hard drive designated as available for use in case usable RAM runs out. This extra abstraction layer is here so that each running process doesn't overlap and try to use memory already being used by another process. This also means that virtual memory can be expanded beyond the physical RAM capacity, which can be useful in a pinch even if it's not very efficient.

As mentioned before, a process is allowed access to a section of RAM by the operating system; the process has no control over memory allocation whatsoever. As a result, the devs that work on applications, especially when they're written in high level code, don't really worry about working with memory. 

Usually any file or part of a file system is mapped using the system command mmap, and is referred to as a memory mapped file. If a memory page file doesn't have any file associated with it, it's referred to as anonymous memory and ut's allocated using the "malloc" function. Using the way file mapped memory and anonymous memory are allocated, the operating system can have processes using the same files working with the same virtual memory page thus using memory more efficiently. 

Sometimes it happens that a process is occupying memory that's needed for another one. In this case, the OS uses the OOM (out of memory) killer. This utility chooses a process and reallocates its memory pages to other processes. In Linux, this OOM killer is enabled by default. Disabling it would basically leave your system with no recourse when it runs out of memory other than extending to the hard drive. 

"Cgroups" is a utility used to isolate a process to a specific memory address, which groups processes into logical groups and allocates an amount of memory to them. The inclusion of cgroups in Linux actually laid the groundwork for containers used today, such as Docker and OpenVZ. 

Linux is also capable of working with multiprocessor systems using NUMA (non-uniform memory access). What this does is attempt to allocate memory to processes running on the CPU closest to the physical RAM. 

To break down how ram is handled by Linux systems, let's look at a typical readout of its operational memory information:

$ sudo cat /proc/meminfo

MemTotal:        3789684 kB
MemFree:         1765616 kB
MemAvailable:    3051416 kB
Buffers:          134112 kB
Cached:           990372 kB
SwapCached:            0 kB
Active:          1190556 kB
Inactive:         579688 kB
Active(anon):     646244 kB
Inactive(anon):     7252 kB
Active(file):     544312 kB
Inactive(file):   572436 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Dirty:              1936 kB
Writeback:             0 kB
AnonPages:        645756 kB
Mapped:           141264 kB
Shmem:              7740 kB
Slab:             214240 kB
SReclaimable:     197816 kB
SUnreclaim:        16424 kB
KernelStack:        2960 kB
PageTables:        17536 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     1894840 kB
Committed_AS:    1601240 kB
VmallocTotal:   34359738367 kB
VmallocUsed:        9668 kB
VmallocChunk:   34359720912 kB
HardwareCorrupted:     0 kB
AnonHugePages:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
DirectMap4k:       79820 kB
DirectMap2M:     2803712 kB
DirectMap1G:     1048576 kB

So let's go over what all this means, one by one.

MemTotal - as it implies, this is the total physical memory the system can see.
MemFree - displays available memory currently not used for any process.
Buffers - memory that's storing information currently waiting to be written to the hard drive. This allows processes to continue working with data without waiting for it to be written to disk.
Cached - the amount of memory taken up by file, database, process or device caches.
SwapCached - data that was written to a swap file that has then been moved back to RAM, but continues to exist in the swap file.
Active - volume of memory that's being frequently used by processes. As such, this section of memory is rarely free.
Inactive - memory that's occupied but not actually being used; this section of memory has priority for being written to a swap file if the need comes up.
Unevictable - for whatever reason, these pages can't be moved to swap.
Mlocked - memory that's allocated using the mlock function.
SwapTotal and SwapFree - same idea as MemTotal and MemFree; total volume of the swap file and how much of it is available for use.
Dirty - changed memory pages that are still occupying RAM but not yet written to disk.
Writeback - this is memory that's currently being written to disk. 
AnonPages - volume of anonymous memory.
Mapped - volume of memory allocated with mmap.
Slab - volume of pages allocated for smaller kernel structures
PageTables - memory allocated within tables.
NFS_Unstable - memory allocated to moving data over NFS v3+. 
Bounce - memory used for block devices.
CommitLimit - this is the total memory available to to be allocated based on the overcommit ratio. 
Committed_AS - volume of memory currently allocated by the operating system. 
VmallocTotal/VmallocUsed/VmallocChunk - a series of stats for virtual memory used by the kernel. 
HugePages_Total/HugePages_Free/HugePages_RSVD - series of stats for very large page files (huge).
Hugepagesize - amount of Huge page files.
DirectMap1G - memory allocated as Huge pages that are 1GB in size.

That about does it for our overview of how Linux handles memory. All of this is important to be aware of when trying to maximize server performance, and get the best value out of its production. If you are trying to make a Linux server work for you, try out ServerSuit (why not, first 30 days is free). Understanding how Linux uses memory lets you get the most out of using ServerSuit too. 

Until next time!

Follow ServerSuit on Twitter and Facebook

April 09 2018

Add or review comments

Please leave your comment

Existing comments

Comments 116


will martin
sync; echo 1 > /proc/sys/vm/drop_caches needed some room for immediate learning from this good overview. thanks
buying cialis online safe
Xenical Online Cheap haurrehigh [url=https://cialisse.com/]generic 5mg cialis best price[/url] Engeda cialis coupon Awagosoods <a href=https://cialisse.com/#>Cialis</a> noinly Viagra Cheap
buy real cialis online
Metformin Without A Prescription haurrehigh [url=https://artsocialist.com/]can you buy cialis online[/url] Engeda Propecia Estrogenos Awagosoods <a href=https://artsocialist.com/#>online cialis</a> noinly Kamagra Barcelona
best price cialis cialis kupovina online cialis daily cost generic cialis canadian pharmacy buy cialis online no rx
best price cialis cialis kupovina online cialis daily cost generic cialis canadian pharmacy buy cialis online no rx
BryanPayog
Hi, here on the forum guys advised a cool Dating site, be sure to register - you will not REGRET it [url=https://bit.ly/3hhve2N]https://bit.ly/3hhve2N[/url]
MatthewNoine
[url=https://hotmp3.xyz]песни 2021[/url]
Thomasprast
[url=https://diskomusic.xyz]песня танцуй[/url]
Richardjer
[url=https://kachaimp3.xyz]песнь года 2021[/url]
DennisSoype
[url=https://formusic.xyz]музыка онлайн 2020[/url]
ClintonCek
[url=https://mp3planet.xyz]новые песни[/url]
Timothyelalp
[url=https://mp3ru.xyz]группы песнь[/url]
JeffreyHox
[url=https://playmp3.xyz]песня давай давай даю даю[/url]
WilsonaBusy
[url=https://mp3sound.xyz]музыка mp3 бесплатно качество[/url]
Charlesamuse
[url=https://8tracks.xyz]бесплатно mp3 все песни в хорошем песни[/url]
Davidesose
[url=https://justmp3.xyz]слушающий музыку[/url]
Frankket
[url=https://omgmp3.xyz]дан дан дан песня[/url]
RobertKet
[url=https://mp3super.xyz]слушать музыку остановка[/url]
RaymondNor
[url=https://rapmp3.xyz]песни онлайн бесплатно[/url]
BrianBuima
[url=https://musplayer.xyz]песнь песней слушать[/url]
Michaelrurce
[url=https://soundplayer.xyz]песнь популярные[/url]
RandalScurn
[url=https://checkmusic.xyz]группы песнь[/url]
LeonardRab
[url=https://audiomp3.xyz]музыка на звонок[/url]
AaronSworb
[url=https://audiomuz.xyz]сборник музыки[/url]
ChrisLibre
[url=https://tonsofmp3.xyz]песнь лета[/url]
BennyOrivE
[url=https://topvolume.xyz]бесплатные новинки mp3[/url]
Jeremybania
[url=https://lotofmp3.xyz]качество песни онлайн[/url]
Claudestoro
[url=https://musicsoul.xyz]самая самая mp3[/url]
ErnestLig
[url=https://rusmusic.xyz]лучшие песни скачать бесплатно[/url]
Josephjomia
[url=https://rusmp3.xyz]качество музыки[/url]
Jarodskics
[url=https://vsemp3.xyz]слушать музыку онлайн бесплатно[/url]
IsraelOpeva
[url=https://gromko.xyz]качество музыки mp3[/url]
Lbgsesse
buy good cheap viagra <a href="http://genqpviag.com/#">viagra preГ§o</a> buy viagra usa online [url=http://genqpviag.com/]redtube viagra[/url] ’
Joshuaadelo
[url=https://laudsound.xyz]слушать русскую музыку бесплатно[/url]
Groverfonee
[url=https://mp3bass.xyz]песни скачать бесплатно mp3[/url]
MichaelSpeab
[url=https://anysong.xyz]новинки песен 2021[/url]
BrianJaw
[url=https://usemusic.xyz]самая самая mp3[/url]
Jamesneida
[url=https://musicway.xyz]детские песни[/url]
Thomasfub
[url=https://mpthree.xyz]музыка 2021 без[/url]
Lamaroredy
[url=https://mp3map.xyz]скачать музыку mp3[/url]
AndresWaign
[url=https://mp3energy.xyz]песни черных[/url]
Billynek
[url=https://grandmp3.xyz]новинки музыки 2021 бесплатно[/url]
KevinWoutt
[url=https://musbeat.xyz]скачать музыку бесплатно[/url]
Donaldundot
[url=https://mp3hit.xyz]песнь[/url]
MauriceFob
[url=https://smartmp3.xyz]музыка 2021 слушать[/url]
Prestonbeaky
[url=https://majorsong.xyz]аккорды песен[/url]
JamesNuh
[url=https://mp3tune.xyz]детские песни[/url]
WilliamCeaft
[url=https://mp3solo.xyz]песнь перевод[/url]
RobertFuG
[url=https://popmus.xyz]песни в хорошем качестве[/url]
Brooksges
[url=https://mp3forall.xyz]песня про[/url]
RobertRhine
[url=https://suchsong.xyz]скачать музыку[/url]
Ronaldstows
[url=https://suchsong.xyz]слушать песни[/url]
Norrisnop
[url=https://mp3choir.xyz]скачать песнь мп3[/url]
Clintonfiect
[url=https://mp3way.xyz]песни ремиксы[/url]
Abrahammar
[url=https://themp3.xyz]песнь песней перевод[/url]
StevenFuddy
[url=https://wildsong.xyz]алиса песни[/url]
MichaelTatte
[url=https://goldmusic.xyz]музыка без слов[/url]
JorgeCot
[url=https://mp3pause.xyz]песня дня[/url]
DavidLak
[url=https://mp3win.xyz]слушать песни в хорошем качестве[/url]
Josephquisk
[url=https://musicbit.xyz]песнь песней перевод[/url]
Davidbom
[url=https://songbeat.xyz]музыка играна[/url]
RichardHog
[url=https://oursongs.xyz]нова песня[/url]
NncsExole
buy viagra 100 <a href="http://lightvigra.com/ ">viagra a 100mg</a> buy viagra 100 mg
Kbcxhifs
generic viagra online pharmacy <a href="http://xuypharmacyonline.com/">pharmacy online</a> viagra super active
JbnbUript
pharmacy tech <a href="http://online21rxon.com/ ">hormones</a> go coupon
Jbbvsesse
online pharmacy school <a href="http://canadianpharmnorx.com/ ">canadian viagra</a> viagra pharmacy 100mg
Kuikinend
buy viagra usa <a href="http://viagerkr.com/ ">viagra online samples</a> 100mg viagra for sale
Lbsxsesse
tadalafil <a href="https://ssviagriia.com/ ">natural viagra for men</a> drugs from canada online
AqcfHemyinend
cialis buy online canada <a href="http://cialisvja.com/ ">cialis soft tabs</a> cialis
FvfcExole
how do i get viagra online <a href="http://hopeviagrin.com/ ">purchasing viagra in usa california</a> viagra no prescription
NbnhExole
viagra generic price in india <a href="http://vigedon.com/ ">sildenafil discount price </a> generic viagra price comparison
Kvaxhifs
cash advance interest daily <a href="http://rirocash.com/ ">absa bank payday loans</a> bdo amex cash advance pin
Ahbzsesse
cash advance in milwaukee <a href="http://daymoneygo.com/ ">loan and advance management</a> payday loans no brokers for unemployed
Labxsesse
cialis headache blood pressure <a href="https://jecialisbn.com/ ">viagra plus fort que cialis</a> cialis 20 mg yorumlar
Gerajoize
Не нравится - не читай! ------ [url=https://it.online-television.net/3303-1-kbr-vtk-kabardino-balkariya.html]https://it.online-television.net/3303-1-kbr-vtk-kabardino-balkariya.html[/url] а вот тут реально классные есть ------ [url=https://television-planet.tv/346-antena-neox.html]https://television-planet.tv/346-antena-neox.html[/url] А СЕРВЕР НЕ ПАШЕТ НА...... ------ [url=https://smm4top.com/]how to make smm panel website[/url] Я конечно, прошу прощения, но это мне не совсем подходит. ------ <a href=https://jubi-opt.com.ua/products/5-Mughskie-Trusy-Optom>трусы мужские семейные хлопок купить недорого</a> Я конечно, прошу прощения, но это мне совершенно не подходит. Может, есть ещё варианты? ------ [url=https://muzkaef.com/3810-metro-boomin-overdue-ft-travis-scott-slowed.html]https://muzkaef.com/3810-metro-boomin-overdue-ft-travis-scott-slowed.html[/url] Между нами говоря ответ на Ваш вопрос я нашёл в google.com ------ [url=https://muzku.net/6097-anacondaz-biorazlagaemy.html]https://muzku.net/6097-anacondaz-biorazlagaemy.html[/url] прикольно конечно НО смысл этого чуда ------ [url=https://nmuz.net/9303-anastasiya-sotnikova-polovinki.html]https://nmuz.net/9303-anastasiya-sotnikova-polovinki.html[/url] Я думаю, что Вы допускаете ошибку. Пишите мне в PM. ------ [url=http://noves-shop.ru/]купить instagram[/url] По моему мнению Вы пошли ошибочным путём. ------ [url=https://crazy-monkey-online1.ru/avtomaty_obezyanki_igrat.html]автоматы обезьянки играть онлайн бесплатно[/url] Вы допускаете ошибку. Предлагаю это обсудить. Пишите мне в PM. ------ [url=https://fruit-cocktail-online1.ru]клубнички игра[/url]
Vinsap
Прошу прощения, что вмешался... Мне знакома эта ситуация. Можно обсудить. Пишите здесь или в PM. ------ [url=https://mosgor-balkon.ru/]остекление балкона в хрущевке цена[/url] Какие слова... супер ------ [url=https://umelec24.ru/]https://umelec24.ru/[/url] В этом что-то есть. Буду знать, благодарю за информацию. ------ [url=https://venro.ru/]накрутка лайков на комментарии в инстаграме[/url] Подтверждаю. Я согласен со всем выше сказанным. Можем пообщаться на эту тему. ------ [url=https://lolz.guru/threads/1734084/]https://lolz.guru/threads/1734084/[/url] Мне не понравилось... ------ [url=https://lolz.guru/threads/1897438/]https://lolz.guru/threads/1897438/[/url] Я думаю, что Вы не правы. Я уверен. Могу отстоять свою позицию. Пишите мне в PM, обсудим. ------ [url=https://lolz.guru/market/steam/]цена аккаунта steam[/url] По-моему это уже обсуждалось ------ [url=http://noves-shop.ru/]http://noves-shop.ru/[/url] Я думаю, что это — заблуждение. Могу доказать. ------ [url=https://book-ofra-online.ru/igrovie_avtomati_knigki.html]игровые автоматы книга ра бесплатно без регистрации[/url] Толку от этого мало. ------ [url=https://igrovye-avtomati-online.com.ua/]игровые автоматы бесплатно[/url] Вы не правы. Я уверен. Давайте обсудим это. ------ [url=https://prava-seychas.ru/]купить водительские права гибдд[/url]
Kndnhifs
can you snort viagra <a href="http://viagratx.com/ ">viagra over the counter walgreens</a> how much is viagra
JetInvam
Вы допускаете ошибку. Давайте обсудим это. ------ <a href=https://xn--80aakfajgcdf8bbqzbrl1h3d.xn--p1ai/>дизайн интерьер сочи</a> Не могу сейчас поучаствовать в обсуждении - очень занят. Освобожусь - обязательно выскажу своё мнение. ------ <a href=https://xn--80adbhccsco0ahgdgbcre0b.xn--p1acf/>фундамент в сочи цены</a> реально улет!ждем с нетерпением релиза и будем зажигать!!!!!! ------ <a href=https://bg.helper.poker>Онлайн покер помощник за покер играчи</a> А еще варианты? ------ <a href=https://poker-tips.net>Pokerspiel-Tipps</a> Я считаю, что Вы допускаете ошибку. Давайте обсудим. Пишите мне в PM. ------ <a href=http://noves-shop.ru/>купить аккаунт фейсбук</a> Это хорошая идея. ------ <a href=https://muzking.net/4022-slame-nyu-pryanyj-rom.html>https://muzking.net/4022-slame-nyu-pryanyj-rom.html</a> Жаль, что сейчас не могу высказаться - опаздываю на встречу. Но вернусь - обязательно напишу что я думаю по этому вопросу. ------ <a href=http://www.okna-season.ru/balkon.html>остекление балкона хрущевки ключ</a> Мне тоже тупым кажеться ------ <a href=https://exfan.org/>купить ютуб канал недорого</a> Я вам не верю ------ <a href=https://casino-x-oficialniy-sayt.com/>casino x официальный сайт</a> Конечно. Это было и со мной. ------ <a href=https://japancasino-x.com/%e3%82%ab%e3%82%b8%e3%83%8ex-%e7%99%bb%e9%8c%b2/>https://japancasino-x.com/%e3%82%ab%e3%82%b8%e3%83%8ex-%e7%99%bb%e9%8c%b2/</a>
Brfghifs
[url=https://ljcialishe.com/]how long does cialis last?[/url] [url=https://cialisvja.com/]cialis insurance coverage blue cross[/url] [url=https://viagraonlinejc.com/]free viagra samples[/url] [url=https://viagratx.com/]viagra dosage by weight[/url] [url=https://buycialisxz.com/]cialis shelf life[/url]
GrvUript
[url=https://kloviagrli.com/]viagra for men free samples[/url] [url=https://vigedon.com/]women viagra[/url] [url=https://llecialisjaw.com/]lisinopril and cialis[/url] [url=https://jwcialislrt.com/]cialis erection[/url] [url=https://jecialisbn.com/]viagra vs cialis hardness[/url]
Lmoppsesse
[url=http://essaywriteris.com/]cheap essay writers[/url] best essay writers review <a href="http://essaywriteris.com/ ">write my essays</a> essay writers canada
Fbshsesse
[url=https://thesisacloud.com/]thesis editing[/url] thesis formatting <a href="http://thesisacloud.com/ ">best thesis writing</a> thesis publishing
Abgcsesse
[url=https://thesiswritingtob.com/]psychology thesis[/url] phd thesis database <a href="http://thesiswritingtob.com/ ">how to write a phd thesis</a> thesis writing service reviews
Lrbssesse
levitra and masturbation https://uslevitraanna.com/ buy levitra online without prescription
Jbsdsesse
best online pharmacy stores https://onlinecanda21.com/ Colospa
LhdvExole
cialis extra [url=https://asciled.com/ ]cialis online europe[/url] buy cheap cialis
RfvbExole
viagra vs cialis vs levitra reviews http://cileve.com/ cialis no prescription
Fbsfsesse
canadian pharcharmy http://uspharmus.com/ pharmacy intern
Abdgsesse
Finax [url=https://canadianeve21.com/ ]Zyvox[/url] Prograf
Bbdfhifs
viagra discount coupons https://gensitecil.com/ viagra erection
GvdbUript
cialis tadalafil 40 mg [url=http://boxtadafil.com/ ]can you purchase tadalafil in the us[/url] tadalafil vs sildenafil vs vardenafil
Lrbssesse
cialis or levitra http://uslevitraanna.com/ levitra pill size
Jebgsesse
discount pharmacy online http://pharmacylo.com/ approved canadian online pharmacies
LbsoExole
viragecialis http://ucialisdas.com/ rgeneric cialis
RebfExole
how long does cialis last http://rcialisgl.com/ how much does cialis cost without insurance
Fmrfsesse
paypal cialis tadalafil http://cialisee.com/ cialis brand no prescription needed
Lebnsesse
erectile dysfunction pills http://xlnpharmacy.com/ trusted online pharmacy
LbsoExole
cialis https://ucialisdas.com/ vigra and cialis
Jebgsesse
canada pharmacy not requiring prescription [url=http://pharmacylo.com/ ]Femara[/url] pharmacy website
Fmrfsesse
purchase cheap cialis https://cialisee.com/ cialis uk
RebfExole
genaric cialis [url=https://rcialisgl.com/ ]generic cialis 10mg[/url] where to buy generic cialis?
Bbshhifs
other uses for viagra [url=http://loxviagra.com/ ]is viagra sold over the counter[/url] canadian pharmacy viagra 50 mg
Anoosesse
viagra a vendre en france http://llviagra.com/ viagra levitra cialis melhor
GtnbUript
viagra meme https://jokviagra.com/ will 10 year old viagra work
Lebnsesse
buy drugs online https://xlnpharmacy.com/ Bystolic
LbsoExole
cialis no prescription overnight http://ucialisdas.com/ price of cialis
RebfExole
cialis canada and paypal http://rcialisgl.com/ professional viagra cialis
Lebnsesse
cheap online pharmacy [url=https://xlnpharmacy.com/ ]legit non prescription pharmacies[/url] Diltiazem
sesseDev
freds pharmacy store hours [url=https://cjepharmacy.com/ ]northwestpharmacy[/url] best drug store foundation
sesseGtv
pharmacy technician online program [url=https://pharmacyhrn.com/ ]walgreens pharmacy gig harbor store hours[/url] cialis 5 mg canada pharmacy
WavaThida
<a href=https://ponlinecialisk.com/>cialis online india[/url]
Exoleloh
how to get cialis sample [url=https://rcialisgl.com/ ]how to buy cialis from us stores[/url] side effects of cialis daily
ExoleVed
cialis viagra cocktail [url=https://krocialis.com/ ]rui cialis[/url] does cialis work
sesseHtf
buy cialis 36 hour [url=https://cialishav.com/ ]cialis (lillys)[/url] cheapest place to buy cialis
sesseHtf
cialis no perscrption [url=https://cialishav.com/ ]cialis 60[/url] cialis generic china
WavaThida
<a href=https://vsaccutanev.com>accutane price[/url]
WavaThida
<a href=https://fcialisj.com/>cialis price</a>