Linux swap filesystem


What is Swap Space?

From Below link :

https://access.redhat.com/site/documentation/en-US/Red_Hat_Enterprise_Linux/5/html/Deployment_Guide/ch-swapspace.html

Swap space in Linux is used when the amount of physical memory (RAM) is full. If the system needs more memory resources and the RAM is full, inactive pages in memory are moved to the swap space. While swap space can help machines with a small amount of RAM, it should not be considered a replacement for more RAM. Swap space is located on hard drives, which have a slower access time than physical memory.

Swap space can be a dedicated swap partition (recommended), a swap file, or a combination of swap partitions and swap files.

In years past, the recommended amount of swap space increased linearly with the amount of RAM in the system. But because the amount of memory in modern systems has increased into the hundreds of gigabytes, it is now recognized that the amount of swap space that a system needs is a function of the memory workload running on that system. However, given that swap space is usually designated at install time, and that it can be difficult to determine beforehand the memory workload of a system, we recommend determining system swap using the following table.

Table 7.1. Recommended System Swap Space
Amount of RAM in the System 	Recommended Amount of Swap Space
4GB of RAM or less 	a minimum of 2GB of swap space
4GB to 16GB of RAM 	a minimum of 4GB of swap space
16GB to 64GB of RAM 	a minimum of 8GB of swap space
64GB to 256GB of RAM 	a minimum of 16GB of swap space
256GB to 512GB of RAM 	a minimum of 32GB of swap space 

----

One more explanation : Swap Space Definition

Swap space is a portion of a hard disk drive (HDD) that is used for virtual memory.

Virtual memory is the use of space on a HDD to simulate additional main memory. Memory is used to hold portions of the operating system, programs and data that are currently in use or that are frequently used. Physically, main memory (also referred to as primary memory) consists of random access memory (RAM) chips that are combined into modules which, in turn, are inserted into slots on the motherboard (i.e., the main circuit board) on a computer. The times required to access different addresses (i.e., locations) in RAM are extremely short and nearly equal, in contrast to the longer and varying times required for accessing locations on the HDD and other storage devices.

In order to free up space in memory, an operating system with a virtual memory capability transfers data that is not immediately needed from memory to the HDD; when that data is needed again, it is copied back into memory. That is, when all of the RAM is being used (e.g., if there are many programs open simultaneously or if one very large program is in use), a computer with virtual memory enabled will swap data to the HDD and back to memory as needed, thus, in effect, increasing the total system memory.

It is generally recommended that for maximum system efficiency the swap space be twice the size of the main memory. This is true even for systems with large memory capacities, such a a gigabyte or more.

Swap space is usually a dedicated partition (i.e., a logically independent section of a HDD) that is created during the installation of the operating system. Such a partition is also referred to as a swap partition. However, swap space can also be a special file.

Although it is generally preferable to use a swap partition rather than a file, sometimes it is not practical to add or expand a partition when the amount of RAM is being increased. In such case, a new swap file can be created with the mkswap command. 
(reference http://www.linfo.org/swap_space.html)

Using partition as swap space example

Determining the disk storage device
[root@mailserver ~]# fdisk -l | grep Disk
Disk /dev/sda: 160.0 GB, 160041885696 bytes
Disk identifier: 0x00074fc3
Disk /dev/mapper/vg0-root: 41.9 GB, 41943040000 bytes
Disk identifier: 0x00000000
Disk /dev/mapper/vg0-swap: 4194 MB, 4194304000 bytes
Disk identifier: 0x00000000
[root@mailserver ~]#

Checking for some free partition on device with parted command

[root@mailserver ~]# parted /dev/sda print free
Model: ATA ST3160813AS (scsi)
Disk /dev/sda: 160GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type     File system  Flags
        32.3kB  1049kB  1016kB           Free Space
 1      1049kB  211MB   210MB   primary  ext4         boot
 2      211MB   105GB   105GB   primary               lvm
        105GB   160GB   55.0GB           Free Space
[root@mailserver ~]#

Create one partition for swapfile with fdisk

[root@mailserver ~]# fdisk /dev/sda

WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
         switch off the mode (command 'c') and change display units to
         sectors (command 'u').

Command (m for help): p

Disk /dev/sda: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00074fc3

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          26      204800   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2              26       12774   102400000   8e  Linux LVM

Command (m for help): n
Command action
   e   extended
   p   primary partition (1-4)
p
Partition number (1-4): 3
First cylinder (12774-19457, default 12774): (ENTER)
Using default value 12774
Last cylinder, +cylinders or +size{K,M,G} (12774-19457, default 19457): +500M

Command (m for help): p

Disk /dev/sda: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00074fc3

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          26      204800   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2              26       12774   102400000   8e  Linux LVM
/dev/sda3           12774       12838      515411   83  Linux

Command (m for help): t
Partition number (1-4): 3
Hex code (type L to list codes): l

 0  Empty           24  NEC DOS         81  Minix / old Lin bf  Solaris        
 1  FAT12           39  Plan 9          82  Linux swap / So c1  DRDOS/sec (FAT-
 2  XENIX root      3c  PartitionMagic  83  Linux           c4  DRDOS/sec (FAT-
 3  XENIX usr       40  Venix 80286     84  OS/2 hidden C:  c6  DRDOS/sec (FAT-
 4  FAT16 <32M      41  PPC PReP Boot   85  Linux extended  c7  Syrinx         
 5  Extended        42  SFS             86  NTFS volume set da  Non-FS data    
 6  FAT16           4d  QNX4.x          87  NTFS volume set db  CP/M / CTOS / .
 7  HPFS/NTFS       4e  QNX4.x 2nd part 88  Linux plaintext de  Dell Utility   
 8  AIX             4f  QNX4.x 3rd part 8e  Linux LVM       df  BootIt         
 9  AIX bootable    50  OnTrack DM      93  Amoeba          e1  DOS access     
 a  OS/2 Boot Manag 51  OnTrack DM6 Aux 94  Amoeba BBT      e3  DOS R/O        
 b  W95 FAT32       52  CP/M            9f  BSD/OS          e4  SpeedStor      
 c  W95 FAT32 (LBA) 53  OnTrack DM6 Aux a0  IBM Thinkpad hi eb  BeOS fs        
 e  W95 FAT16 (LBA) 54  OnTrackDM6      a5  FreeBSD         ee  GPT            
 f  W95 Ext'd (LBA) 55  EZ-Drive        a6  OpenBSD         ef  EFI (FAT-12/16/
10  OPUS            56  Golden Bow      a7  NeXTSTEP        f0  Linux/PA-RISC b
11  Hidden FAT12    5c  Priam Edisk     a8  Darwin UFS      f1  SpeedStor      
12  Compaq diagnost 61  SpeedStor       a9  NetBSD          f4  SpeedStor      
14  Hidden FAT16 <3 63  GNU HURD or Sys ab  Darwin boot     f2  DOS secondary  
16  Hidden FAT16    64  Novell Netware  af  HFS / HFS+      fb  VMware VMFS    
17  Hidden HPFS/NTF 65  Novell Netware  b7  BSDI fs         fc  VMware VMKCORE 
18  AST SmartSleep  70  DiskSecure Mult b8  BSDI swap       fd  Linux raid auto
1b  Hidden W95 FAT3 75  PC/IX           bb  Boot Wizard hid fe  LANstep        
1c  Hidden W95 FAT3 80  Old Minix       be  Solaris boot    ff  BBT            
1e  Hidden W95 FAT1
Hex code (type L to list codes): 82
Changed system type of partition 3 to 82 (Linux swap / Solaris)

Command (m for help): p

Disk /dev/sda: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00074fc3

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          26      204800   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2              26       12774   102400000   8e  Linux LVM
/dev/sda3           12774       12838      515411   82  Linux swap / Solaris

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.

Partition is created with fdisk on /dev/sda but as such kernel refer the partition table was at the time of booting, need to update kernel partition table with partx / partprobe or any other command or simple reboot.

Partx command to update kernel partition table

[root@mailserver ~]# partx -a /dev/sda

BLKPG: Device or resource busy
error adding partition 1
BLKPG: Device or resource busy
error adding partition 2

Check it is updated or not

[root@mailserver ~]# ls /dev/sda*
/dev/sda  /dev/sda1  /dev/sda2  /dev/sda3
[root@mailserver ~]#

Above command output /dev/sda3 is our partitions updated in kernel partition table.

Create swap file system on /dev/sda3 with mkswap command

[root@mailserver ~]# mkswap /dev/sda3
Setting up swapspace version 1, size = 515404 KiB
no label, UUID=c5dce38f-6e5a-43bf-9d73-a72ce3d1c9d5

Checking whether swap file system created on /dev/sda3 or not

[root@mailserver ~]# blkid
/dev/mapper/vg0-root: UUID="50ce8e5c-5eb2-4292-bfcf-4e3bc5888155" TYPE="ext4" 
/dev/sda1: UUID="a1e7bfe1-70b0-41a0-8eee-449f8fd19f3e" TYPE="ext4" 
/dev/sda2: UUID="RhcgDV-KJPm-QWOo-i168-JqEe-mYTq-0PPhUg" TYPE="LVM2_member" 
/dev/sda3: UUID="c5dce38f-6e5a-43bf-9d73-a72ce3d1c9d5" TYPE="swap" 
/dev/mapper/vg0-swap: UUID="7c861c1c-884c-41d4-ae52-812db1a27317" TYPE="swap" 
[root@mailserver ~]# 
Activate swap filesystem with swapon command 

[root@mailserver ~]# swapon /dev/sda3

Check the swapfile system status now 

[root@mailserver ~]# swapon -s
Filename				Type		Size	Used	Priority
/dev/dm-1                               partition	4095992	0	-1
/dev/sda3                               partition	515400	0	-2

To deactivate the swapfile system on /dev/sda3

[root@mailserver ~]# swapoff /dev/sda3

Check the swapfile system status now 

[root@mailserver ~]# swapon -s
Filename				Type		Size	Used	Priority
/dev/dm-1                               partition	4095992	0	-1
[root@mailserver ~]# 

Add entry to /etc/fstab so at the time of rebooting newly created swap filesystem will be activated

[root@mailserver ~]# vim /etc/fstab 

Swap file system entry in /etc/fstab

[root@mailserver ~]# cat /etc/fstab 

#
# /etc/fstab
# Created by anaconda on Wed Jun 11 13:52:50 2014
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/vg0-root    /                       ext4    defaults        1 1
UUID=a1e7bfe1-70b0-41a0-8eee-449f8fd19f3e /boot                   ext4    defaults        1 2
/dev/mapper/vg0-swap    swap                    swap    defaults        0 0
tmpfs                   /dev/shm                tmpfs   defaults        0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0

UUID=c5dce38f-6e5a-43bf-9d73-a72ce3d1c9d5    swap                    swap    defaults        0 0
[root@mailserver ~]# 

To read /etc/fstab and activate swap file system without rebooting ( like mount -a to mount all entry in fatab)

[root@mailserver ~]# swapon -a

Checking the swap file system status 

[root@mailserver ~]# swapon -s
Filename				Type		Size	Used	Priority
/dev/dm-1                               partition	4095992	0	-1
/dev/sda3                               partition	515400	0	-2
[root@mailserver ~]#

Creating swap space in / using file

Checking the swap file system status 
[root@mailserver ~]# swapon -s
Filename				Type		Size	Used	Priority
/dev/dm-1                               partition	4095992	0	-1
/dev/sda3                               partition	515400	0	-2

To deactivate the swapfile system on /dev/sda3
[root@mailserver ~]# swapoff /dev/sda3
To deactivate the swapfile system on /dev/dm-1
[root@mailserver ~]# swapoff /dev/dm-1
Checking the swap file system status 
[root@mailserver ~]# swapon -s
Filename				Type		Size	Used	Priority


Create 1 GB file for swap space with dd command.
[root@mailserver ~]# dd if=/dev/zero of=/tmp/swapfile bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 5.74826 s, 182 MB/s

Checking file and size
[root@mailserver ~]# du -sh /tmp/swapfile 
1001M	/tmp/swapfile

Creating swap file signature or converting swapfile in to swap space
[root@mailserver ~]# mkswap /tmp/swapfile 
mkswap: /tmp/swapfile: warning: don't erase bootbits sectors
        on whole disk. Use -f to force.
Setting up swapspace version 1, size = 1023996 KiB
no label, UUID=e37dbb64-8622-48b4-ac02-641892811560

Activate swap file system on /tmp/swapfile
[root@mailserver ~]# swapon /tmp/swapfile

Checking the swap file system status 
[root@mailserver ~]# swapon -s
Filename				Type		Size	Used	Priority
/tmp/swapfile                           file		1023992	0	-1
To deactivate the swapfile system on /tmp/swapfile
[root@mailserver ~]# swapoff /tmp/swapfile 
Checking the swap file system status 
[root@mailserver ~]# swapon -s
Filename				Type		Size	Used	Priority

Create entry in /etc/fstab

[root@mailserver ~]# vim /etc/fstab 
/tmp/swapfile    swap                    swap    defaults        0 0

Read /etc/fstab and activate all swap file system
[root@mailserver ~]# swapon -a

Checking the swap file system status 
[root@mailserver ~]# swapon -s
Filename				Type		Size	Used	Priority
/dev/dm-1                               partition	4095992	0	-1
/dev/sda3                               partition	515400	0	-2
/tmp/swapfile                           file		1023992	0	-3
[root@mailserver ~]#

swap space priority

from man swapon

 -p, --priority priority
              Specify the priority of the swap device.  priority is a value
              between 0 and 32767. Higher numbers indicate higher priority.
              See  swapon(2) for a full description of swap priorities. Add
              pri=value to the option field  of  /etc/fstab  for  use  with
              swapon -a.

from man 2 swapon

Priority
       Each swap area has a priority, either high or low.  The default pri-
       ority is low.  Within the low-priority areas, newer areas  are  even
       lower priority than older areas.

       All  priorities  set  with  swapflags are high-priority, higher than
       default.  They may have any non-negative value chosen by the caller.
       Higher numbers mean higher priority.

       Swap  pages are allocated from areas in priority order, highest pri-
       ority first.  For areas with different priorities, a higher-priority
       area  is  exhausted  before  using a lower-priority area.  If two or
       more areas have the same priority, and it is  the  highest  priority
       available,  pages are allocated on a round-robin basis between them.

       As of Linux 1.3.6, the kernel usually follows these rules, but there
       are exceptions.

Reference reading

http://www.linux-tutorial.info/modules.php?name=MContent&pageid=89