Wednesday, 4 January 2012

Swapping on a File in Linux

This article shows how to create a standard file and configure your linux based system to activate swapping or paging on it.

CREATE THE SWAP FILE


First we create the swap file using dd command. cp is not useful here because swap file has not to contain holes.
# dd if=/dev/zero of=/mnt/swapfile bs=1M count=200 # We create a swap file of 200MByte in size.

For safety we disallow other users to read and modify the file:
# chown root.root /mnt/swapfile
# chmod 600 /mnt/swapfile

Swap size is unlimited for linux kernels after 2.3.3
Kernels after 2.4.10 support up to 32 swap areas.


SET UP THE SWAP FILE


# aptitude install util-linux # to obtain mkswap shell command.
# mkswap swapfile
Setting up swapspace version 1, size = 204796 KiB
no label, UUID=41a2be71-f0......


LINUX KERNEL CONFIGURATION


When compiling the linux kernel we need to enable swap option:
CONFIG_SWAP=y
or in menuconfig options:
General setup -> Support for paging of anonymous memory (swap)


ACTIVATE THE SWAP FILE


# aptitude install mount # to install swapon command.
# swapon -v swapfile
If we did not enabled swap option in the kernel we will get:
swapon: swapfile: swapon failed: Function not implemented

or if we used cp command to create the file or if we are exporting that file via Network File System (NFS):
# swapon -v swapfile
swapon: swapfile has holes
swapon: swapfile: swapon failed: Invalid argument

e.g, if everything went fine:
# swapon -v swapfile
swapon on swapfile
swapon: /mnt/swapfile: found swap signature: version 1, page-size 4, same byte order
swapon: /mnt/swapfile: pagesize=4096, swapsize=209715200, devsize=209715200
Adding 204796k swap on /mnt/swapfile. Priority:-1 extents:62 across:256620k SS


To check current active swap areas:
# cat /proc/swaps
Filename Type Size Used Priority
/mnt/swapfile file 204796 0 -1

We see it says file instead partition under Type because we are swapping on a file.


To deactivate swap area:
# swapoff -v swapfile


SETTING /etc/fstab FILE


We set /etc/fstab file to enable swapping at boot time:
/etc/fstab
# <file system> <mount point>   <type>  <options>       <dump>  <pass>

Do not forget to also mount partition where swap file is located!
e.g: if /dev/sda1 was mounted in /mnt
# echo "/dev/sda1 /mnt ext3 defaults 0 0" >> /etc/fstab

We add properly swap file configuration:
# echo "/mnt/swapfile none swap sw 0 0" >> /etc/fstab

And test if fstab file configuration works:
# swapon -a && cat /proc/swaps

After rebooting these commands will show us if swap file was mounted right.
# dmesg | grep -i swap
or
# cat /proc/swaps


YOU MAY ALSO BE INTERESTED IN:


How to BUILD the LINUX KERNEL for the ANDROID EMULATOR (Eclair version)

How to Compile the Linux Kernel in GNU/Debian and Ubuntu


REFERENCE


$ man 8 mkswap
$ man 8 swapon

0 comentarios: