21

I am freshly installing a distribution and want to set up a swap partition so that it is compatible with hibernate.

First, I must determine the amount of physical memory the system has.

$ grep MemTotal /proc/meminfo
MemTotal:    38740876 kB

Now as far as I know:

  • 1 KiB = 1 kibibyte = 1024 bytes
  • 1 kB = 1 kilobyte = 1000 bytes

However, RHEL docs here say that the unit in /proc/meminfo is in kibibytes.

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/deployment_guide/s2-proc-meminfo

Who is wrong? The unit hard-coded in Linux, or the RHEL documentation?

2 Answers2

42

Both "kilobyte" and "kB" are also sometimes used to indicate binary (1024 byte) units. This usage well predates the invention of dedicated binary "kibi-" prefixes, especially in contexts where true decimal units would make little or no sense.

For example, RAM usage is always measured in binary units (e.g. a "4kB page" is always 4096 bytes, never 4000), so the more familiar "kilo-" or "mega-" prefixes are typically used even if the actual sizes are binary.

In your case (I checked the kernel code that creates the /proc/meminfo file), the kernel internally counts memory in terms of free pages (which are typically 4k or 16k but always power-of-two) and its show_val_kb() function uses a bit shift operation (which is equivalent to a multiplication by power-of-two, producing binary units again) to convert the page count into a kilobyte value:

static void show_val_kb(struct seq_file *m, const char *s, unsigned long num)
{
        seq_put_decimal_ull_width(m, s, num << (PAGE_SHIFT - 10), 8);
        seq_write(m, " kB\n", 4);
}

(On x86 and x86_64 systems PAGE_SHIFT is always 12, so a memory page is 1 << 12 bytes which is equal to 1×212 i.e. 4096, and the above function ends up multiplying the page count by 2(12−10) before displaying it as "kB".)


The 'lsblk' and 'fdisk' disk partitioning tools from util-linux also work with binary units by default. For example, +2G in fdisk is equivalent to +2GiB. (However, fdisk also accepts +2GB if you want a decimal-sized partition for some reason.)

grawity
  • 501,077
10

From the comments it seems you are under the impression that the unit kB means 1000 bytes and that if you meant 1024 bytes you would have to write KiB.

But that is not how it is used in computing.

kB has always meant 1024 bytes and pretty much still does.

The word "kibibyte" and the unit symbol KiB were introduced by IEC in 1998 in a well-intended attempt to clarify that the k/K in kB/KB are not an SI prefix.

In practice however those are rarely used, and apart from hard drive capacity (for marketing reasons) you can safely assume kB to mean 1024 bytes ("1 kilobyte"), especially in software that was introduced before 1998.

AndreKR
  • 673