Linux.com

Home News Software Applications All about Linux swap space

All about Linux swap space

 

By Gary Sims

Linux divides its physical RAM (random access memory) into chucks of memory called pages. Swapping is the process whereby a page of memory is copied to the preconfigured space on the hard disk, called swap space, to free up that page of memory. The combined sizes of the physical memory and the swap space is the amount of virtual memory available.

Swapping is necessary for two important reasons. First, when the system requires more memory than is physically available, the kernel swaps out less used pages and gives memory to the current application (process) that needs the memory immediately. Second, a significant number of the pages used by an application during its startup phase may only be used for initialization and then never used again. The system can swap out those pages and free the memory for other applications or even for the disk cache.

However, swapping does have a downside. Compared to memory, disks are very slow. Memory speeds can be measured in nanoseconds, while disks are measured in milliseconds, so accessing the disk can be tens of thousands times slower than accessing physical memory. The more swapping that occurs, the slower your system will be. Sometimes excessive swapping or thrashing occurs where a page is swapped out and then very soon swapped in and then swapped out again and so on. In such situations the system is struggling to find free memory and keep applications running at the same time. In this case only adding more RAM will help.

Linux has two forms of swap space: the swap partition and the swap file. The swap partition is an independent section of the hard disk used solely for swapping; no other files can reside there. The swap file is a special file in the filesystem that resides amongst your system and data files.

To see what swap space you have, use the command swapon -s. The output will look something like this:

Filename  Type       Size       Used Priority
/dev/sda5 partition  859436  0       -1

Each line lists a separate swap space being used by the system. Here, the 'Type' field indicates that this swap space is a partition rather than a file, and from 'Filename' we see that it is on the disk sda5. The 'Size' is listed in kilobytes, and the 'Used' field tells us how many kilobytes of swap space has been used (in this case none). 'Priority' tells Linux which swap space to use first. One great thing about the Linux swapping subsystem is that if you mount two (or more) swap spaces (preferably on two different devices) with the same priority, Linux will interleave its swapping activity between them, which can greatly increase swapping performance.

To add an extra swap partition to your system, you first need to prepare it. Step one is to ensure that the partition is marked as a swap partition and step two is to make the swap filesystem. To check that the partition is marked for swap, run as root:

fdisk -l /dev/hdb

Replace /dev/hdb with the device of the hard disk on your system with the swap partition on it. You should see output that looks like this:

Device Boot    Start      End           Blocks  Id      System
/dev/hdb1       2328    2434    859446  82      Linux swap / Solaris

If the partition isn't marked as swap you will need to alter it by running fdisk and using the 't' menu option. Be careful when working with partitions -- you don't want to delete important partitions by mistake or change the id of your system partition to swap by mistake. All data on a swap partition will be lost, so double-check every change you make. Also note that Solaris uses the same ID as Linux swap space for its partitions, so be careful not to kill your Solaris partitions by mistake.

Once a partition is marked as swap, you need to prepare it using the mkswap (make swap) command as root:

mkswap /dev/hdb1

If you see no errors, your swap space is ready to use. To activate it immediately, type:

swapon /dev/hdb1

You can verify that it is being used by running swapon -s. To mount the swap space automatically at boot time, you must add an entry to the /etc/fstab file, which contains a list of filesystems and swap spaces that need to be mounted at boot up. The format of each line is:

Since swap space is a special type of filesystem, many of these parameters aren't applicable. For swap space, add:

/dev/hdb1       none    swap    sw      0       0

where /dev/hdb1 is the swap partition. It doesn't have a specific mount point, hence none. It is of type swap with options of sw, and the last two parameters aren't used so they are entered as 0.

To check that your swap space is being automatically mounted without having to reboot, you can run the swapoff -a command (which turns off all swap spaces) and then swapon -a (which mounts all swap spaces listed in the /etc/fstab file) and then check it with swapon -s.

Swap file

As well as the swap partition, Linux also supports a swap file that you can create, prepare, and mount in a fashion similar to that of a swap partition. The advantage of swap files is that you don't need to find an empty partition or repartition a disk to add additional swap space.

To create a swap file, use the dd command to create an empty file. To create a 1GB file, type:

dd if=/dev/zero of=/swapfile bs=1024 count=1048576

/swapfile is the name of the swap file, and the count of 1048576 is the size in kilobytes (i.e. 1GB).

Prepare the swap file using mkswap just as you would a partition, but this time use the name of the swap file:

mkswap /swapfile

And similarly, mount it using the swapon command: swapon /swapfile.

The /etc/fstab entry for a swap file would look like this:

/swapfile       none    swap    sw      0       0

How big should my swap space be?

It is possible to run a Linux system without a swap space, and the system will run well if you have a large amount of memory -- but if you run out of physical memory then the system will crash, as it has nothing else it can do, so it is advisable to have a swap space, especially since disk space is relatively cheap.

The key question is how much? Older versions of Unix-type operating systems (such as Sun OS and Ultrix) demanded a swap space of two to three times that of physical memory. Modern implementations (such as Linux) don't require that much, but they can use it if you configure it. A rule of thumb is as follows: 1) for a desktop system, use a swap space of double system memory, as it will allow you to run a large number of applications (many of which may will be idle and easily swapped), making more RAM available for the active applications; 2) for a server, have a smaller amount of swap available (say half of physical memory) so that you have some flexibility for swapping when needed, but monitor the amount of swap space used and upgrade your RAM if necessary; 3) for older desktop machines (with say only 128MB), use as much swap space as you can spare, even up to 1GB.

The Linux 2.6 kernel added a new kernel parameter called swappiness to let administrators tweak the way Linux swaps. It is a number from 0 to 100. In essence, higher values lead to more pages being swapped, and lower values lead to more applications being kept in memory, even if they are idle. Kernel maintainer Andrew Morton has said that he runs his desktop machines with a swappiness of 100, stating that "My point is that decreasing the tendency of the kernel to swap stuff out is wrong. You really don't want hundreds of megabytes of BloatyApp's untouched memory floating about in the machine. Get it out on the disk, use the memory for something useful."

One downside to Morton's idea is that if memory is swapped out too quickly then application response time drops, because when the application's window is clicked the system has to swap the application back into memory, which will make it feel slow.

The default value for swappiness is 60. You can alter it temporarily (until you next reboot) by typing as root:

echo 50 > /proc/sys/vm/swappiness

If you want to alter it permanently then you need to change the vm.swappiness parameter in the /etc/sysctl.conf file.

Conclusion

Managing swap space is an essential aspect of system administration. With good planning and proper use swapping can provide many benefits. Don't be afraid to experiment, and always monitor your system to ensure you are getting the results you need.

 

Comments

Subscribe to Comments Feed
  • marc Said:

    Gary. I found your article very rewarding. I had that scavenged x32 laptop and, instead of buying a hdd I bought 2 CF cards and a CF/IDE adaptor to make it a "SSD" drive ;-) I installed my chosen distro but decided to put no swap partition. Well that was a mistake, I realized that CF cards are not very competitive front of traditional hard drive... So hdd are not that bad when tehy have a little of embedded cache:-) So I found your article and went on the installation of a swap file. It made it better. Despite the fact that hdparm show that CF are NOT built to swap... I think I will follow A.Morton advice too, and put some more swap file on / and /home partitions because I believe having a lonely swap thing is bad for the hdd health in a long run (especially while browsing the net on a desktop, a film running on another...) Thanks again for your clearly detailed post. From France. Marc.

  • Tango Said:

    An excellent article. The information on swapon etc was well explained and just what I was looking for. Thanks

  • Gaurav Said:

    An excellent article. The information is well explained is bang on. Exactly just what I was looking for. Thanks.

  • anon Said:

    This is a very good explanation of swap-space and basics! thanks!

  • debianuser Said:

    thank you very much for a great article!

  • Pat Said:

    Andrew never used NAND flash for a swap device. I do mostly embedded development on devices with internal flash for storage. While I try to avoid swap files completely, some projects have memory requirements that exceed the installed RAM. (Yeah, I know, cry me a river, right?) Swapping to NAND flash is very slow, an order or two of magnitude slower than disk; also, all flash wears out, so even with wear leveling, the on-board storage has a limited life span; depending on how frequently swap is used, the flash can wear out sooner than the devices' expected service life. All that adds up to wanting to minimize paging, rather than maximizing it.

  • uday Said:

    i have a doubt guys .... any one of you please give reply to me Swapping is the process whereby a page of memory is copied to the preconfigured space on the hard disk ..... AS ABOVE SAID MY DOUBT IS Page of memory is copied ........ok it depends on size of preconfigured space on hard disk that we allocated or it depends on pages that linux divides the RAM

  • Brandon Said:

    Is it possible to have too much Swap space?

  • stephen mumo Said:

    it will depend on the type and size of machine you are using.

  • Rohan A. Said:

    Very good article dictating swap space, partition and files; it's pros n cons.....i liked it...

  • alattia Said:

    why linux make creating SWAP file or space so difficult. So many commands has to be entered just to get to something essential in the install process, this should be already catered for by the OS with little or no need for commads. I am sure if Linux was made by Microsoft this ( complicated problem) would be just a breeze to accomplish. I just cannot find how to do this SWAP bussiness, when I see the menu of the partions to make such as, \ , ROOT, HOME there is no mention of SWAP any where. I am sorry to say the people behind the Linux Project are there to keep the Linux OS within their community and to do very little to simplify how to install Linux distros to others. If you get Windows OS you can install it in minutes all you need to do is stick the DVD in the machine and 30 minutes later your computer is ready and connected to the net with little personal effort. I am willing to spend 30 hours to install a Linux distro but could not for all its complications. I bought my first computer when there were no Windows around, when it was DOS 3.6 and every time you need some thing done you need to type a DOS command, but these commands where clear and easy to understand then again that was late 1980's more than 30 years ago, Linux is still living in that era what a shame what a pitty, Linux is light years behind Microsoft in the OS bussiness. alattia

  • lokesh soni Said:

    SWAP: --> create a partition with type 82 # mkswap // make it as swap # swapon // activate it --> create an entry in /etc/fstab extending swap using a file: # dd if= of= bs= count= # mkswap # chown root:root // permissions # chmod 0600 // permissions # swapon --> make an entry in /etc/fstab

  • Gerhard Mack Said:

    Good troll although rather outdated. Most (all commonly used) Linux distros provide a menu to either automatically determine the size of, or let you manually set a swap

  • benawhile Said:

    As a linux ubuntu user I think he has a point. I am upgrading my dual boot syatem to the latest ubuntu release and I have spent the best part of this week trying to find out in advance what to do to make sure I get my installation right. On installation of the original dual boot I was advised that the best option was to create my own partition manually so i was a good boy and did this, it was a challenge and educational, but finding info about upgrading is not so easy, there is no central resource for upgrading a dual boot, i have to trawl the forums for (usually contradictory) information. I posted a question on the ubuntu forum 24 hrs ago and not one reply yet.

  • ase1590 Said:

    Most desktop OS versions of linux do take care of this. All this guide does is teach you about a manual way to do it. Windows has similar features built into the CMD prompt if you care to learn how to do it. By default, Windows uses a directory in your C drive for PageFiles. This can actually be changed or you can add other drives as well. This isn't just a linux thing. Try Linux Mint or Ubuntu sometime on your computer. They set up right out of the box, much like windows.

  • kerimit Said:

    Good article. I just found out that linux can use a swap file

  • Gourav Soni Said:

    gr8, nice article to learn about swap. I have got the fine knowledge about swap. thnxxx

  • THE-DUDE Said:

    a question from a noob: if you are swapping lots of pages from ram to another device( as in swappiness =100 ), how much extra cpu load is used. if any ?. and if yes when does it become "not worth it" ? and what is the difference between (swappiness = 0 to 100 ) and ( swapon -P 0 to 32737 ) cheers

  • Ajit Said:

    well explained article......thanx Gary........:)

  • Achal lama Said:

    well explained...................i m very much happy after reading ur article..........tnx for giving this huge information abt swap........................Excellent!!!!!

  • jeshwanth kumar N K Said:

    Excellent article :).. Now I understood what swap is and how to tweak it :)

  • Juano76 Said:

    Gracias... Muy buen articulo para entender mucho mas sobre como funciona la Swap y su implementacion........

  • Ben Said:

    nice work. I like your distinction of "older systems". Yes, rule of thumb used to be swap = RAM, and if possible swap = 2xRAM in case of system crashes and core dumps. You'll see these numbers still referenced but they are very very outdated. This is also in the days when most servers had 4gig or maybe even 8gig of ram. These days unless the app has a hard requirement (such as Oracle) for swap space, you can generally get away with minimal: 2gig to 4gig swap. Great job!

  • ashishsjsu Said:

    Hi Gary, I found the article very interesting and worth reading. I have a doubt though, how swapping (as u explained) differs from Demand paging?

  • Aashish Mishra Said:

    Thanks a lot , Well explained with practical e.g. , Thanks for this article once again .

  • Jeff Said:

    Where should the swap partition be located? Before or after the linux ext4 partition?

  • benawhile Said:

    YOu do mean the ext4 / (OS) partition don't you/ You don't mean the extended partition. My swap is in front of the OS partition. I think the installation programme tells you to create the swap before the OS.

  • Iliyan Said:

    Hi, very usefull artical,. I use Linux Mint13 and after Hdd crash on dec 2013 recovered OS from image. And now Irealized that I dont have a swap partion mounted. Used command from artical, but it has to do on every restart - in my fdisk there is no -t option, and in /etc/fstab there is no any file. Similar file - etc_fstab-new I found in /var/log/boot-sav/log directory but don't know how to edit. BTW mounting is possible with gparted and swapon over the partion, but is not convinient to do on every restart. I'l be glad to have help.

  • Gerhard Mack Said:

    Iliyan In /etc/fstab there should be a line: /dev/swappartition none swap sw 0 0 Change /dev/swappartition to the location of your swap partition.

  • iliyan Said:

    Thank You for answer! the Line is :UUID xxxxxxxxxxxxxxxx none swap ......... I have got UUID and now everything is OK!

  • David Said:

    I'm a new Linux user and this article was very usefull for me. Thanks!

  • Akash Said:

    Very well explained.This is what i want to know....Thanx!!!!

  • Metcomm Said:

    Great article but can someone comment on the swap requirement if the HD is a Solid State device (SSD)? My fdisk -l is : /dev/sda5 189650944 193746943 2048000 82 Linux swap / Solaris I guess there is nothing to improve here but a solid device should be faster which is probably just acts like extra RAM anyway, right?

  • Akhil Said:

    Very much impressed with your article. it was useful in creating a swap file for Oracle client installation. thank you :)

  • SIJU MATHEW Said:

    VERY GOOD ARTICLE THAT I EVER READ...!!! hearty thanks to admn...

  • Sogood itsscary Said:

    This article rocked my world. My whole understanding of the universe has been expanded, in a positive direction.


Who we are ?

The Linux Foundation is a non-profit consortium dedicated to the growth of Linux.

More About the foundation...

Frequent Questions

Join / Linux Training / Board