PostgreSQL 8.1.4 Documentation
Prev | Fast Backward | Chapter 16. Operating System Environment | Fast Forward | Next

# 16.4. Managing Kernel Resources

A large PostgreSQL installation can quickly exhaust various operating system resource limits. (On some systems, the factory defaults are so low that you don't even need a really "large" installation.) If you have encountered this kind of problem, keep reading.

## 16.4.1. Shared Memory and Semaphores

Shared memory and semaphores are collectively referred to as "System V IPC" (together with message queues, which are not relevant for PostgreSQL). Almost all modern operating systems provide these features, but not all of them have them turned on or sufficiently sized by default, especially systems with BSD heritage. (For the Windows, QNX and BeOS ports, PostgreSQL provides its own replacement implementation of these facilities.)

The complete lack of these facilities is usually manifested by an Illegal system call error upon server start. In that case there's nothing left to do but to reconfigure your kernel. PostgreSQL won't work without them.

When PostgreSQL exceeds one of the various hard IPC limits, the server will refuse to start and should leave an instructive error message describing the problem encountered and what to do about it. (See also Section 16.3.1.) The relevant kernel parameters are named consistently across different systems; Table 16-1 gives an overview. The methods to set them, however, vary. Suggestions for some platforms are given below. Be warned that it is often necessary to reboot your machine, and possibly even recompile the kernel, to change these settings.

Table 16-1. System V IPC parameters

Name | Description | Reasonable values
--- | --- | ---
`SHMMAX` | Maximum size of shared memory segment (bytes) | at least several megabytes (see text)
`SHMMIN` | Minimum size of shared memory segment (bytes) | 1
`SHMALL` | Total amount of shared memory available (bytes or pages) | if bytes, same as `SHMMAX`; if pages, `ceil(SHMMAX/PAGE_SIZE)`
`SHMSEG` | Maximum number of shared memory segments per process | only 1 segment is needed, but the default is much higher
`SHMMNI` | Maximum number of shared memory segments system-wide | like `SHMSEG` plus room for other applications
`SEMMNI` | Maximum number of semaphore identifiers (i.e., sets) | at least `ceil(max_connections / 16)`
`SEMMNS` | Maximum number of semaphores system-wide | `ceil(max_connections / 16) * 17` plus room for other applications
`SEMMSL` | Maximum number of semaphores per set | at least 17
`SEMMAP` | Number of entries in semaphore map | see text
`SEMVMX` | Maximum value of semaphore | at least 1000 (The default is often 32767, don't change unless forced to)

The most important shared memory parameter is `SHMMAX`, the maximum size, in bytes, of a shared memory segment. If you get an error message from `shmget` like Invalid argument, it is likely that this limit has been exceeded. The size of the required shared memory segment varies depending on several PostgreSQL configuration parameters, as shown in Table 16-2. You can, as a temporary solution, lower some of those settings to avoid the failure. As a rough approximation, you can estimate the required segment size as 500 kB plus the variable amounts shown in the table. (Any error message you might get will include the exact size of the failed allocation request.) While it is possible to get PostgreSQL to run with `SHMMAX` as small as 1 MB, you need at least 4 MB for acceptable performance, and desirable settings are in the tens of megabytes.

Some systems also have a limit on the total amount of shared memory in the system (`SHMALL`). Make sure this is large enough for PostgreSQL plus any other applications that are using shared memory segments. (Caution: `SHMALL` is measured in pages rather than bytes on many systems.)

Less likely to cause problems is the minimum size for shared memory segments (`SHMMIN`), which should be at most approximately 500 kB for PostgreSQL (it is usually just 1). The maximum number of segments system-wide (`SHMMNI`) or per-process (`SHMSEG`) are unlikely to cause a problem unless your system has them set to zero.

PostgreSQL uses one semaphore per allowed connection (max_connections), in sets of 16. Each such set will also contain a 17th semaphore which contains a "magic number", to detect collision with semaphore sets used by other applications. The maximum number of semaphores in the system is set by `SEMMNS`, which consequently must be at least as high as `max_connections` plus one extra for each 16 allowed connections (see the formula in Table 16-1). The parameter `SEMMNI` determines the limit on the number of semaphore sets that can exist on the system at one time. Hence this parameter must be at least `ceil(max_connections / 16)`. Lowering the number of allowed connections is a temporary workaround for failures, which are usually confusingly worded No space left on device, from the function `semget`.

In some cases it might also be necessary to increase `SEMMAP` to be at least on the order of `SEMMNS`. This parameter defines the size of the semaphore resource map, in which each contiguous block of available semaphores needs an entry. When a semaphore set is freed it is either added to an existing entry that is adjacent to the freed block or it is registered under a new map entry. If the map is full, the freed semaphores get lost (until reboot). Fragmentation of the semaphore space could over time lead to fewer available semaphores than there should be.

The `SEMMSL` parameter, which determines how many semaphores can be in a set, must be at least 17 for PostgreSQL.

Various other settings related to "semaphore undo", such as `SEMMNU` and `SEMUME`, are not of concern for PostgreSQL.

BSD/OS

  Shared Memory. By default, only 4 MB of shared memory is supported. Keep in mind that shared memory is not pageable; it is locked in RAM. To increase the amount of shared memory supported by your system, add something like the following to your kernel configuration file:

      options "SHMALL=8192"
      options "SHMMAX=\(SHMALL*PAGE_SIZE\)"

  `SHMALL` is measured in 4KB pages, so a value of 1024 represents 4 MB of shared memory. Therefore the above increases the maximum shared memory area to 32 MB. For those running 4.3 or later, you will probably also need to increase `KERNEL_VIRTUAL_MB` above the default `248`. Once all changes have been made, recompile the kernel, and reboot.

  For those running 4.0 and earlier releases, use `bpatch` to find the `sysptsize` value in the current kernel. This is computed dynamically at boot time.

      $ bpatch -r sysptsize
      0x9 = 9

  Next, add `SYSPTSIZE` as a hard-coded value in the kernel configuration file. Increase the value you found using `bpatch`. Add 1 for every additional 4 MB of shared memory you desire.

      options "SYSPTSIZE=16"

  `sysptsize` cannot be changed by `sysctl`.

  Semaphores. You will probably want to increase the number of semaphores as well; the default system total of 60 will only allow about 50 PostgreSQL connections. Set the values you want in your kernel configuration file, e.g.:

      options "SEMMNI=40"
      options "SEMMNS=240"

FreeBSD

  The default settings are only suitable for small installations (for example, default `SHMMAX` is 32 MB). Changes can be made via the `sysctl` or `loader` interfaces. The following parameters can be set using `sysctl`:

      $ sysctl -w kern.ipc.shmall=32768
      $ sysctl -w kern.ipc.shmmax=134217728
      $ sysctl -w kern.ipc.semmap=256

  To have these settings persist over reboots, modify `/etc/sysctl.conf`.

  The remaining semaphore settings are read-only as far as `sysctl` is concerned, but can be changed before boot using the `loader` prompt:

      (loader) set kern.ipc.semmni=256
      (loader) set kern.ipc.semmns=512
      (loader) set kern.ipc.semmnu=256

  Similarly these can be saved between reboots in `/boot/loader.conf`.

  You might also want to configure your kernel to lock shared memory into RAM and prevent it from being paged out to swap. This can be accomplished using the `sysctl` setting `kern.ipc.shm_use_phys`.

  If running in FreeBSD jails by enabling sysctl's `security.jail.sysvipc_allowed`, postmasters running in different jails should be run by different operating system users. This improves security because it prevents non-root users from interfering with shared memory or semaphores in a different jail, and it allows the PostgreSQL IPC cleanup code to function properly. (In FreeBSD 6.0 and later the IPC cleanup code doesn't properly detect processes in other jails, preventing the running of postmasters on the same port in different jails.)

  FreeBSD versions before 4.0 work like NetBSD and OpenBSD (see below).

NetBSD
OpenBSD

  The options `SYSVSHM` and `SYSVSEM` need to be enabled when the kernel is compiled. (They are by default.) The maximum size of shared memory is determined by the option `SHMMAXPGS` (in pages). The following shows an example of how to set the various parameters (OpenBSD uses `option` instead):

      options        SYSVSHM
      options        SHMMAXPGS=4096
      options        SHMSEG=256

      options        SYSVSEM
      options        SEMMNI=256
      options        SEMMNS=512
      options        SEMMNU=256
      options        SEMMAP=256

  You might also want to configure your kernel to lock shared memory into RAM and prevent it from being paged out to swap. This can be accomplished using the `sysctl` setting `kern.ipc.shm_use_phys`.

HP-UX

  The default settings tend to suffice for normal installations. On HP-UX 10, the factory default for `SEMMNS` is 128, which might be too low for larger database sites.

  IPC parameters can be set in the System Administration Manager (SAM) under Kernel Configuration->Configurable Parameters. Hit Create A New Kernel when you're done.

Linux

  The default settings are only suitable for small installations (the default max segment size is 32 MB). However the remaining defaults are quite generously sized, and usually do not require changes. The max segment size can be changed via the `sysctl` interface. For example, to allow 128 MB, and explicitly set the maximum total shared memory size to 2097152 pages (the default):

      $ sysctl -w kernel.shmmax=134217728
      $ sysctl -w kernel.shmall=2097152

  In addition these settings can be saved between reboots in `/etc/sysctl.conf`.

  Older distributions may not have the `sysctl` program, but equivalent changes can be made by manipulating the `/proc` file system:

      $ echo 134217728 >/proc/sys/kernel/shmmax
      $ echo 2097152 >/proc/sys/kernel/shmall

MacOS X

  In OS X 10.2 and earlier, edit the file `/System/Library/StartupItems/SystemTuning/SystemTuning` and change the values in the following commands:

      sysctl -w kern.sysv.shmmax
      sysctl -w kern.sysv.shmmin
      sysctl -w kern.sysv.shmmni
      sysctl -w kern.sysv.shmseg
      sysctl -w kern.sysv.shmall

  In OS X 10.3 and later, these commands have been moved to `/etc/rc` and must be edited there. Note that `/etc/rc` is usually overwritten by OS X updates (such as 10.3.6 to 10.3.7) so you should expect to have to redo your editing after each update. In all versions, you'll need to reboot to make changes take effect.

  In OS X 10.3.9 and later, the file `/etc/sysctl.conf` allows shared memory setting to be saved across operating system upgrades, and is the recommended method for setting these parameters. When using this file, all five shared memory values must be set or the changes will be ignored.

  `SHMALL` is measured in 4KB pages on this platform, and recent releases of OS X reject attempts to set `SHMALL` and `SHMMAX` to a value that isn't an exact multiple of 4096.

SCO OpenServer

  In the default configuration, only 512 kB of shared memory per segment is allowed. To increase the setting, first change to the directory `/etc/conf/cf.d`. To display the current value of `SHMMAX`, run

      ./configure -y SHMMAX

  To set a new value for `SHMMAX`, run

      ./configure SHMMAX=value

  where `value` is the new value you want to use (in bytes). After setting `SHMMAX`, rebuild the kernel:

      ./link_unix

  and reboot.

AIX

  At least as of version 5.1, it should not be necessary to do any special configuration for such parameters as `SHMMAX`, as it appears this is configured to allow all memory to be used as shared memory. That is the sort of configuration commonly used for other databases such as DB/2.

  It may, however, be necessary to modify the global `ulimit` information in `/etc/security/limits`, as the default hard limits for file sizes (`fsize`) and numbers of files (`nofiles`) may be too low.

Solaris

  At least in version 2.6, the default maximum size of a shared memory segments is too low for PostgreSQL. The relevant settings can be changed in `/etc/system`, for example:

      set shmsys:shminfo_shmmax=0x2000000
      set shmsys:shminfo_shmmin=1
      set shmsys:shminfo_shmmni=256
      set shmsys:shminfo_shmseg=256

      set semsys:seminfo_semmap=256
      set semsys:seminfo_semmni=512
      set semsys:seminfo_semmns=512
      set semsys:seminfo_semmsl=32

  You need to reboot for the changes to take effect.

  See also http://sunsite.uakom.sk/sunworldonline/swol-09-1997/swol-09-insidesolaris.html for information on shared memory under Solaris.

UnixWare

  On UnixWare 7, the maximum size for shared memory segments is only 512 kB in the default configuration. To display the current value of `SHMMAX`, run

      /etc/conf/bin/idtune -g SHMMAX

  which displays the current, default, minimum, and maximum values. To set a new value for `SHMMAX`, run

      /etc/conf/bin/idtune SHMMAX value

  where `value` is the new value you want to use (in bytes). After setting `SHMMAX`, rebuild the kernel:

      /etc/conf/bin/idbuild -B

  and reboot.

Table 16-2. Configuration parameters affecting PostgreSQL's shared memory usage

Name | Approximate multiplier (bytes per increment)
--- | ---
max_connections | 400 + 220 * max_locks_per_transaction
max_prepared_transactions | 600 + 220 * max_locks_per_transaction
shared_buffers | 8300 (assuming 8K `BLCKSZ`)
wal_buffers | 8200 (assuming 8K `BLCKSZ`)
max_fsm_relations | 70
max_fsm_pages | 6

## 16.4.2. Resource Limits

Unix-like operating systems enforce various kinds of resource limits that might interfere with the operation of your PostgreSQL server. Of particular importance are limits on the number of processes per user, the number of open files per process, and the amount of memory available to each process. Each of these have a "hard" and a "soft" limit. The soft limit is what actually counts but it can be changed by the user up to the hard limit. The hard limit can only be changed by the root user. The system call `setrlimit` is responsible for setting these parameters. The shell's built-in command `ulimit` (Bourne shells) or `limit` (csh) is used to control the resource limits from the command line. On BSD-derived systems the file `/etc/login.conf` controls the various resource limits set during login. See the operating system documentation for details. The relevant parameters are `maxproc`, `openfiles`, and `datasize`. For example:

    default:\
    ...
            :datasize-cur=256M:\
            :maxproc-cur=256:\
            :openfiles-cur=256:\
    ...

(`-cur` is the soft limit. Append `-max` to set the hard limit.)

Kernels can also have system-wide limits on some resources.

- On Linux `/proc/sys/fs/file-max` determines the maximum number of open files that the kernel will support. It can be changed by writing a different number into the file or by adding an assignment in `/etc/sysctl.conf`. The maximum limit of files per process is fixed at the time the kernel is compiled; see `/usr/src/linux/Documentation/proc.txt` for more information.

The PostgreSQL server uses one process per connection so you should provide for at least as many processes as allowed connections, in addition to what you need for the rest of your system. This is usually not a problem but if you run several servers on one machine things might get tight.

The factory default limit on open files is often set to "socially friendly" values that allow many users to coexist on a machine without using an inappropriate fraction of the system resources. If you run many servers on a machine this is perhaps what you want, but on dedicated servers you may want to raise this limit.

On the other side of the coin, some systems allow individual processes to open large numbers of files; if more than a few processes do so then the system-wide limit can easily be exceeded. If you find this happening, and you do not want to alter the system-wide limit, you can set PostgreSQL's max_files_per_process configuration parameter to limit the consumption of open files.

## 16.4.3. Linux Memory Overcommit

In Linux 2.4 and later, the default virtual memory behavior is not optimal for PostgreSQL. Because of the way that the kernel implements memory overcommit, the kernel may terminate the PostgreSQL server (the `postmaster` process) if the memory demands of another process cause the system to run out of virtual memory.

If this happens, you will see a kernel message that looks like this (consult your system documentation and configuration on where to look for such a message):

    Out of Memory: Killed process 12345 (postmaster).

This indicates that the `postmaster` process has been terminated due to memory pressure. Although existing database connections will continue to function normally, no new connections will be accepted. To recover, PostgreSQL will need to be restarted.

One way to avoid this problem is to run PostgreSQL on a machine where you can be sure that other processes will not run the machine out of memory.

On Linux 2.6 and later, a better solution is to modify the kernel's behavior so that it will not "overcommit" memory. This is done by selecting strict overcommit mode via `sysctl`:

    sysctl -w vm.overcommit_memory=2

or placing an equivalent entry in `/etc/sysctl.conf`. You may also wish to modify the related setting `vm.overcommit_ratio`. For details see the kernel documentation file `Documentation/vm/overcommit-accounting`.

Some vendors' Linux 2.4 kernels are reported to have early versions of the 2.6 overcommit `sysctl` parameter. However, setting `vm.overcommit_memory` to 2 on a kernel that does not have the relevant code will make things worse not better. It is recommended that you inspect the actual kernel source code (see the function `vm_enough_memory` in the file `mm/mmap.c`) to verify what is supported in your copy before you try this in a 2.4 installation. The presence of the `overcommit-accounting` documentation file should not be taken as evidence that the feature is there. If in any doubt, consult a kernel expert or your kernel vendor.

Prev | Home | Next
Starting the Database Server | Up | Shutting Down the Server