Tweaks for Linux

Introduce some tweaks for Linux.

Decrease swap usage

Decrease the value of vm.swappiness, which represents the percentage of the free memory before activating swap. The lower the value, the less swapping is used and the more memory pages are kept in physical memory.

The default value is 60. You can check current value with either command below.

cat /proc/sys/vm/swappiness
sysctl vm.swappiness

Recommended value is 0. To change it permanently, you need to add the following line in /etc/sysctl.conf:

vm.swappiness = 0

In some distributions, setting the value to 0 will lead to disabled swap. You may need to change the value to 1.

Deal with dirty pages

Set vm.dirty_background_ratio and vm.dirty_ratio properly. The former contains, as a percentage of total available memory that contains free pages and reclaimable pages, the number of pages at which the background kernel flusher threads will start writing out dirty data. And the latter contains, as a percentage of total available memory that contains free pages and reclaimable pages, the number of pages at which a process which is generating disk writes will itself start writing out dirty data.

In short, vm.dirty_background_ratio is the percentage of system memory which when dirty, system can start writing data to the disks, and vm.dirty_ratio is the percentage of system memory which when dirty, system will block the process that is doing writes and write out dirty pages to the disks.

Default values vary with different distributions. Check current values with the command below.

sysctl -a | grep dirty

You can smooth IO with low value of vm.dirty_background_ratio and high value of vm.dirty_ratio. Recommended values are vm.dirty_background_ratio = 5 and vm.dirty_ratio = 80. Open /etc/sysctl.conf and add the two lines below to change it.

vm.dirty_background_ratio = 5
vm.dirty_ratio = 80

And make sure vm.dirty_background_bytes and vm.dirty_bytes are both 0. Otherwise it will not take effect.

Create swap partition

Create a 1 GiB swap as an example. Simply run the commands below.

fallocate -l 1G /swap
chmod 600 /swap
mkswap /swap
swapon /swap

To make the change permanent, open /etc/fstab and add the line below.

/swap swap swap defaults 0 0

Run the command below to check current swap usage.

swapon --show

If you want to remove swap, simply adjust the /etc/fstab file and reboot, then delete the swap file.

Disable ping

Add the line below in /etc/sysctl.conf.

net.ipv4.icmp_echo_ignore_all = 1

Increase open file

Add these lines in /etc/security/limits.conf.

* soft nofile 51200
* hard nofile 51200

If that does not work, change * to your user name, e.g. root.

Use this command to check current value.

ulimit -n