code:
===============================
Documentation for /proc/sys/vm/
===============================

kernel version 2.6.29

Copyright (c) 1998, 1999,  Rik van Riel <riel@nl.linux.org>

Copyright (c) 2008         Peter W. Morreale <pmorreale@novell.com>

For general info and legal blurb, please look in index.rst.

------------------------------------------------------------------------------

This file contains the documentation for the sysctl files in
/proc/sys/vm and is valid for Linux kernel version 2.6.29.

The files in this directory can be used to tune the operation
of the virtual memory (VM) subsystem of the Linux kernel and
the writeout of dirty data to disk.

Default values and initialization routines for most of these
files can be found in mm/swap.c.

Currently, these files are in /proc/sys/vm:

- admin_reserve_kbytes
- compact_memory
- compaction_proactiveness
- compact_unevictable_allowed
- dirty_background_bytes
- dirty_background_ratio
- dirty_bytes
- dirty_expire_centisecs
- dirty_ratio
- dirtytime_expire_seconds
- dirty_writeback_centisecs
- drop_caches
- extfrag_threshold
- highmem_is_dirtyable
- hugetlb_shm_group
- laptop_mode
- legacy_va_layout
- lowmem_reserve_ratio
- max_map_count
- memory_failure_early_kill
- memory_failure_recovery
- min_free_kbytes
- min_slab_ratio
- min_unmapped_ratio
- mmap_min_addr
- mmap_rnd_bits
- mmap_rnd_compat_bits
- nr_hugepages
- nr_hugepages_mempolicy
- nr_overcommit_hugepages
- nr_trim_pages         (only if CONFIG_MMU=n)
- numa_zonelist_order
- oom_dump_tasks
- oom_kill_allocating_task
- overcommit_kbytes
- overcommit_memory
- overcommit_ratio
- page-cluster
- page_lock_unfairness
- panic_on_oom
- percpu_pagelist_high_fraction
- stat_interval
- stat_refresh
- numa_stat
- swappiness
- unprivileged_userfaultfd
- user_reserve_kbytes
- vfs_cache_pressure
- watermark_boost_factor
- watermark_scale_factor
- zone_reclaim_mode

admin_reserve_kbytes
====================

The amount of free memory in the system that should be reserved for users
with the capability cap_sys_admin.

admin_reserve_kbytes defaults to min(3% of free pages, 8MB)

That should provide enough for the admin to log in and kill a process,
if necessary, under the default overcommit 'guess' mode.

Systems running under overcommit 'never' should increase this to account
for the full Virtual Memory Size of programs used to recover. Otherwise,
root may not be able to log in to recover the system.

How do you calculate a minimum useful reserve?

sshd or login + bash (or some other shell) + top (or ps, kill, etc.)

For overcommit 'guess', we can sum resident set sizes (RSS).
On x86_64 this is about 8MB.

For overcommit 'never', we can take the max of their virtual sizes (VSZ)
and add the sum of their RSS.
On x86_64 this is about 128MB.

Changing this takes effect whenever an application requests memory.

compact_memory
==============

Available only when CONFIG_COMPACTION is set. When 1 is written to the file,
all zones are compacted such that free memory is available in contiguous
blocks where possible. This can be important for example in the allocation of
huge pages although processes will also directly compact memory as required.

compaction_proactiveness
========================

This tunable takes a value in the range [0, 100] with a default value of
20. This tunable determines how aggressively compaction is done in the
background. Write of a non zero value to this tunable will immediately
trigger the proactive compaction. Setting it to 0 disables proactive compaction.

Note that compaction has a non-trivial system-wide impact as pages
belonging to different processes are moved around, which could also lead
to latency spikes in unsuspecting applications. The kernel employs
various heuristics to avoid wasting CPU cycles if it detects that
proactive compaction is not being effective.

Be careful when setting it to extreme values like 100, as that may
cause excessive background compaction activity.

compact_unevictable_allowed
===========================

Available only when CONFIG_COMPACTION is set. When set to 1, compaction is
allowed to examine the unevictable lru (mlocked pages) for pages to compact.
This should be used on systems where stalls for minor page faults are an
acceptable trade for large contiguous free memory.  Set to 0 to prevent
compaction from moving pages that are unevictable.  Default value is 1.
On CONFIG_PREEMPT_RT the default value is 0 in order to avoid a page fault, due
to compaction, which would block the task from becoming active until the fault
is resolved.

dirty_background_bytes
======================

Contains the amount of dirty memory at which the background kernel
flusher threads will start writeback.

Note:
  dirty_background_bytes is the counterpart of dirty_background_ratio. Only
  one of them may be specified at a time. When one sysctl is written it is
  immediately taken into account to evaluate the dirty memory limits and the
  other appears as 0 when read.

dirty_background_ratio
======================

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.

The total available memory is not equal to total system memory.

dirty_bytes
===========

Contains the amount of dirty memory at which a process generating disk writes
will itself start writeback.

Note: dirty_bytes is the counterpart of dirty_ratio. Only one of them may be
specified at a time. When one sysctl is written it is immediately taken into
account to evaluate the dirty memory limits and the other appears as 0 when
read.

Note: the minimum value allowed for dirty_bytes is two pages (in bytes); any
value lower than this limit will be ignored and the old configuration will be
retained.

dirty_expire_centisecs
======================

This tunable is used to define when dirty data is old enough to be eligible
for writeout by the kernel flusher threads.  It is expressed in 100'ths
of a second.  Data which has been dirty in-memory for longer than this
interval will be written out next time a flusher thread wakes up.

dirty_ratio
===========

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.

The total available memory is not equal to total system memory.

dirtytime_expire_seconds
========================

When a lazytime inode is constantly having its pages dirtied, the inode with
an updated timestamp will never get chance to be written out.  And, if the
only thing that has happened on the file system is a dirtytime inode caused
by an atime update, a worker will be scheduled to make sure that inode
eventually gets pushed out to disk.  This tunable is used to define when dirty
inode is old enough to be eligible for writeback by the kernel flusher threads.
And, it is also used as the interval to wakeup dirtytime_writeback thread.

dirty_writeback_centisecs
=========================

The kernel flusher threads will periodically wake up and write `old` data
out to disk.  This tunable expresses the interval between those wakeups, in
100'ths of a second.

Setting this to zero disables periodic writeback altogether.

drop_caches
===========

Writing to this will cause the kernel to drop clean caches, as well as
reclaimable slab objects like dentries and inodes.  Once dropped, their
memory becomes free.

To free pagecache::

	echo 1 > /proc/sys/vm/drop_caches

To free reclaimable slab objects (includes dentries and inodes)::

	echo 2 > /proc/sys/vm/drop_caches

To free slab objects and pagecache::

	echo 3 > /proc/sys/vm/drop_caches

This is a non-destructive operation and will not free any dirty objects.
To increase the number of objects freed by this operation, the user may run
`sync` prior to writing to /proc/sys/vm/drop_caches.  This will minimize the
number of dirty objects on the system and create more candidates to be
dropped.

This file is not a means to control the growth of the various kernel caches
(inodes, dentries, pagecache, etc...)  These objects are automatically
reclaimed by the kernel when memory is needed elsewhere on the system.

Use of this file can cause performance problems.  Since it discards cached
objects, it may cost a significant amount of I/O and CPU to recreate the
dropped objects, especially if they were under heavy use.  Because of this,
use outside of a testing or debugging environment is not recommended.

You may see informational messages in your kernel log when this file is
used::

	cat (1234): drop_caches: 3

These are informational only.  They do not mean that anything is wrong
with your system.  To disable them, echo 4 (bit 2) into drop_caches.

extfrag_threshold
=================

This parameter affects whether the kernel will compact memory or direct
reclaim to satisfy a high-order allocation. The extfrag/extfrag_index file in
debugfs shows what the fragmentation index for each order is in each zone in
the system. Values tending towards 0 imply allocations would fail due to lack
of memory, values towards 1000 imply failures are due to fragmentation and -1
implies that the allocation will succeed as long as watermarks are met.

The kernel will not compact memory in a zone if the
fragmentation index is <= extfrag_threshold. The default value is 500.

highmem_is_dirtyable
====================

Available only for systems with CONFIG_HIGHMEM enabled (32b systems).

This parameter controls whether the high memory is considered for dirty
writers throttling.  This is not the case by default which means that
only the amount of memory directly visible/usable by the kernel can
be dirtied. As a result, on systems with a large amount of memory and
lowmem basically depleted writers might be throttled too early and
streaming writes can get very slow.

Changing the value to non zero would allow more memory to be dirtied
and thus allow writers to write more data which can be flushed to the
storage more effectively. Note this also comes with a risk of pre-mature
OOM killer because some writers (e.g. direct block device writes) can
only use the low memory and they can fill it up with dirty data without
any throttling.

hugetlb_shm_group
=================

hugetlb_shm_group contains group id that is allowed to create SysV
shared memory segment using hugetlb page.

laptop_mode
===========

laptop_mode is a knob that controls "laptop mode". All the things that are
controlled by this knob are discussed in Documentation/admin-guide/laptops/laptop-mode.rst.

legacy_va_layout
================

If non-zero, this sysctl disables the new 32-bit mmap layout - the kernel
will use the legacy (2.4) layout for all processes.

lowmem_reserve_ratio
====================

For some specialised workloads on highmem machines it is dangerous for
the kernel to allow process memory to be allocated from the "lowmem"
zone.  This is because that memory could then be pinned via the mlock()
system call, or by unavailability of swapspace.

And on large highmem machines this lack of reclaimable lowmem memory
can be fatal.

So the Linux page allocator has a mechanism which prevents allocations
which *could* use highmem from using too much lowmem.  This means that
a certain amount of lowmem is defended from the possibility of being
captured into pinned user memory.

(The same argument applies to the old 16 megabyte ISA DMA region.  This
mechanism will also defend that region from allocations which could use
highmem or lowmem).

The `lowmem_reserve_ratio` tunable determines how aggressive the kernel is
in defending these lower zones.

If you have a machine which uses highmem or ISA DMA and your
applications are using mlock(), or if you are running with no swap then
you probably should change the lowmem_reserve_ratio setting.

The lowmem_reserve_ratio is an array. You can see them by reading this file::

	% cat /proc/sys/vm/lowmem_reserve_ratio
	256     256     32

But, these values are not used directly. The kernel calculates # of protection
pages for each zones from them. These are shown as array of protection pages
in /proc/zoneinfo like followings. (This is an example of x86-64 box).
Each zone has an array of protection pages like this::

  Node 0, zone      DMA
    pages free     1355
          min      3
          low      3
          high     4
	:
	:
      numa_other   0
          protection: (0, 2004, 2004, 2004)
	^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    pagesets
      cpu: 0 pcp: 0
          :

These protections are added to score to judge whether this zone should be used
for page allocation or should be reclaimed.

In this example, if normal pages (index=2) are required to this DMA zone and
watermark[WMARK_HIGH] is used for watermark, the kernel judges this zone should
not be used because pages_free(1355) is smaller than watermark + protection[2]
(4 + 2004 = 2008). If this protection value is 0, this zone would be used for
normal page requirement. If requirement is DMA zone(index=0), protection[0]
(=0) is used.

zone[i]'s protection[j] is calculated by following expression::

  (i < j):
    zone[i]->protection[j]
    = (total sums of managed_pages from zone[i+1] to zone[j] on the node)
      / lowmem_reserve_ratio[i];
  (i = j):
     (should not be protected. = 0;
  (i > j):
     (not necessary, but looks 0)

The default values of lowmem_reserve_ratio[i] are

    === ====================================
    256 (if zone[i] means DMA or DMA32 zone)
    32  (others)
    === ====================================

As above expression, they are reciprocal number of ratio.
256 means 1/256. # of protection pages becomes about "0.39%" of total managed
pages of higher zones on the node.

If you would like to protect more pages, smaller values are effective.
The minimum value is 1 (1/1 -> 100%). The value less than 1 completely
disables protection of the pages.

max_map_count:
==============

This file contains the maximum number of memory map areas a process
may have. Memory map areas are used as a side-effect of calling
malloc, directly by mmap, mprotect, and madvise, and also when loading
shared libraries.

While most applications need less than a thousand maps, certain
programs, particularly malloc debuggers, may consume lots of them,
e.g., up to one or two maps per allocation.

The default value is 65530.

memory_failure_early_kill:
==========================

Control how to kill processes when uncorrected memory error (typically
a 2bit error in a memory module) is detected in the background by hardware
that cannot be handled by the kernel. In some cases (like the page
still having a valid copy on disk) the kernel will handle the failure
transparently without affecting any applications. But if there is
no other uptodate copy of the data it will kill to prevent any data
corruptions from propagating.

1: Kill all processes that have the corrupted and not reloadable page mapped
as soon as the corruption is detected.  Note this is not supported
for a few types of pages, like kernel internally allocated data or
the swap cache, but works for the majority of user pages.

0: Only unmap the corrupted page from all processes and only kill a process
who tries to access it.

The kill is done using a catchable SIGBUS with BUS_MCEERR_AO, so processes can
handle this if they want to.

This is only active on architectures/platforms with advanced machine
check handling and depends on the hardware capabilities.

Applications can override this setting individually with the PR_MCE_KILL prctl

memory_failure_recovery
=======================

Enable memory failure recovery (when supported by the platform)

1: Attempt recovery.

0: Always panic on a memory failure.

min_free_kbytes
===============

This is used to force the Linux VM to keep a minimum number
of kilobytes free.  The VM uses this number to compute a
watermark[WMARK_MIN] value for each lowmem zone in the system.
Each lowmem zone gets a number of reserved free pages based
proportionally on its size.

Some minimal amount of memory is needed to satisfy PF_MEMALLOC
allocations; if you set this to lower than 1024KB, your system will
become subtly broken, and prone to deadlock under high loads.

Setting this too high will OOM your machine instantly.

min_slab_ratio
==============

This is available only on NUMA kernels.

A percentage of the total pages in each zone.  On Zone reclaim
(fallback from the local zone occurs) slabs will be reclaimed if more
than this percentage of pages in a zone are reclaimable slab pages.
This insures that the slab growth stays under control even in NUMA
systems that rarely perform global reclaim.

The default is 5 percent.

Note that slab reclaim is triggered in a per zone / node fashion.
The process of reclaiming slab memory is currently not node specific
and may not be fast.

min_unmapped_ratio
==================

This is available only on NUMA kernels.

This is a percentage of the total pages in each zone. Zone reclaim will
only occur if more than this percentage of pages are in a state that
zone_reclaim_mode allows to be reclaimed.

If zone_reclaim_mode has the value 4 OR'd, then the percentage is compared
against all file-backed unmapped pages including swapcache pages and tmpfs
files. Otherwise, only unmapped pages backed by normal files but not tmpfs
files and similar are considered.

The default is 1 percent.

mmap_min_addr
=============

This file indicates the amount of address space  which a user process will
be restricted from mmapping.  Since kernel null dereference bugs could
accidentally operate based on the information in the first couple of pages
of memory userspace processes should not be allowed to write to them.  By
default this value is set to 0 and no protections will be enforced by the
security module.  Setting this value to something like 64k will allow the
vast majority of applications to work correctly and provide defense in depth
against future potential kernel bugs.

mmap_rnd_bits
=============

This value can be used to select the number of bits to use to
determine the random offset to the base address of vma regions
resulting from mmap allocations on architectures which support
tuning address space randomization.  This value will be bounded
by the architecture's minimum and maximum supported values.

This value can be changed after boot using the
/proc/sys/vm/mmap_rnd_bits tunable

mmap_rnd_compat_bits
====================

This value can be used to select the number of bits to use to
determine the random offset to the base address of vma regions
resulting from mmap allocations for applications run in
compatibility mode on architectures which support tuning address
space randomization.  This value will be bounded by the
architecture's minimum and maximum supported values.

This value can be changed after boot using the
/proc/sys/vm/mmap_rnd_compat_bits tunable

nr_hugepages
============

Change the minimum size of the hugepage pool.

See Documentation/admin-guide/mm/hugetlbpage.rst

hugetlb_optimize_vmemmap
========================

This knob is not available when the size of 'struct page' (a structure defined
in include/linux/mm_types.h) is not power of two (an unusual system config could
result in this).

Enable (set to 1) or disable (set to 0) HugeTLB Vmemmap Optimization (HVO).

Once enabled, the vmemmap pages of subsequent allocation of HugeTLB pages from
buddy allocator will be optimized (7 pages per 2MB HugeTLB page and 4095 pages
per 1GB HugeTLB page), whereas already allocated HugeTLB pages will not be
optimized.  When those optimized HugeTLB pages are freed from the HugeTLB pool
to the buddy allocator, the vmemmap pages representing that range needs to be
remapped again and the vmemmap pages discarded earlier need to be rellocated
again.  If your use case is that HugeTLB pages are allocated 'on the fly' (e.g.
never explicitly allocating HugeTLB pages with 'nr_hugepages' but only set
'nr_overcommit_hugepages', those overcommitted HugeTLB pages are allocated 'on
the fly') instead of being pulled from the HugeTLB pool, you should weigh the
benefits of memory savings against the more overhead (~2x slower than before)
of allocation or freeing HugeTLB pages between the HugeTLB pool and the buddy
allocator.  Another behavior to note is that if the system is under heavy memory
pressure, it could prevent the user from freeing HugeTLB pages from the HugeTLB
pool to the buddy allocator since the allocation of vmemmap pages could be
failed, you have to retry later if your system encounter this situation.

Once disabled, the vmemmap pages of subsequent allocation of HugeTLB pages from
buddy allocator will not be optimized meaning the extra overhead at allocation
time from buddy allocator disappears, whereas already optimized HugeTLB pages
will not be affected.  If you want to make sure there are no optimized HugeTLB
pages, you can set "nr_hugepages" to 0 first and then disable this.  Note that
writing 0 to nr_hugepages will make any "in use" HugeTLB pages become surplus
pages.  So, those surplus pages are still optimized until they are no longer
in use.  You would need to wait for those surplus pages to be released before
there are no optimized pages in the system.

nr_hugepages_mempolicy
======================

Change the size of the hugepage pool at run-time on a specific
set of NUMA nodes.

See Documentation/admin-guide/mm/hugetlbpage.rst

nr_overcommit_hugepages
=======================

Change the maximum size of the hugepage pool. The maximum is
nr_hugepages + nr_overcommit_hugepages.

See Documentation/admin-guide/mm/hugetlbpage.rst

nr_trim_pages
=============

This is available only on NOMMU kernels.

This value adjusts the excess page trimming behaviour of power-of-2 aligned
NOMMU mmap allocations.

A value of 0 disables trimming of allocations entirely, while a value of 1
trims excess pages aggressively. Any value >= 1 acts as the watermark where
trimming of allocations is initiated.

The default value is 1.

See Documentation/admin-guide/mm/nommu-mmap.rst for more information.

numa_zonelist_order
===================

This sysctl is only for NUMA and it is deprecated. Anything but
Node order will fail!

'where the memory is allocated from' is controlled by zonelists.

(This documentation ignores ZONE_HIGHMEM/ZONE_DMA32 for simple explanation.
you may be able to read ZONE_DMA as ZONE_DMA32...)

In non-NUMA case, a zonelist for GFP_KERNEL is ordered as following.
ZONE_NORMAL -> ZONE_DMA
This means that a memory allocation request for GFP_KERNEL will
get memory from ZONE_DMA only when ZONE_NORMAL is not available.

In NUMA case, you can think of following 2 types of order.
Assume 2 node NUMA and below is zonelist of Node(0)'s GFP_KERNEL::

  (A) Node(0) ZONE_NORMAL -> Node(0) ZONE_DMA -> Node(1) ZONE_NORMAL
  (B) Node(0) ZONE_NORMAL -> Node(1) ZONE_NORMAL -> Node(0) ZONE_DMA.

Type(A) offers the best locality for processes on Node(0), but ZONE_DMA
will be used before ZONE_NORMAL exhaustion. This increases possibility of
out-of-memory(OOM) of ZONE_DMA because ZONE_DMA is tend to be small.

Type(B) cannot offer the best locality but is more robust against OOM of
the DMA zone.

Type(A) is called as "Node" order. Type (B) is "Zone" order.

"Node order" orders the zonelists by node, then by zone within each node.
Specify "[Nn]ode" for node order

"Zone Order" orders the zonelists by zone type, then by node within each
zone.  Specify "[Zz]one" for zone order.

Specify "[Dd]efault" to request automatic configuration.

On 32-bit, the Normal zone needs to be preserved for allocations accessible
by the kernel, so "zone" order will be selected.

On 64-bit, devices that require DMA32/DMA are relatively rare, so "node"
order will be selected.

Default order is recommended unless this is causing problems for your
system/application.

oom_dump_tasks
==============

Enables a system-wide task dump (excluding kernel threads) to be produced
when the kernel performs an OOM-killing and includes such information as
pid, uid, tgid, vm size, rss, pgtables_bytes, swapents, oom_score_adj
score, and name.  This is helpful to determine why the OOM killer was
invoked, to identify the rogue task that caused it, and to determine why
the OOM killer chose the task it did to kill.

If this is set to zero, this information is suppressed.  On very
large systems with thousands of tasks it may not be feasible to dump
the memory state information for each one.  Such systems should not
be forced to incur a performance penalty in OOM conditions when the
information may not be desired.

If this is set to non-zero, this information is shown whenever the
OOM killer actually kills a memory-hogging task.

The default value is 1 (enabled).

oom_kill_allocating_task
========================

This enables or disables killing the OOM-triggering task in
out-of-memory situations.

If this is set to zero, the OOM killer will scan through the entire
tasklist and select a task based on heuristics to kill.  This normally
selects a rogue memory-hogging task that frees up a large amount of
memory when killed.

If this is set to non-zero, the OOM killer simply kills the task that
triggered the out-of-memory condition.  This avoids the expensive
tasklist scan.

If panic_on_oom is selected, it takes precedence over whatever value
is used in oom_kill_allocating_task.

The default value is 0.

overcommit_kbytes
=================

When overcommit_memory is set to 2, the committed address space is not
permitted to exceed swap plus this amount of physical RAM. See below.

Note: overcommit_kbytes is the counterpart of overcommit_ratio. Only one
of them may be specified at a time. Setting one disables the other (which
then appears as 0 when read).

overcommit_memory
=================

This value contains a flag that enables memory overcommitment.

When this flag is 0, the kernel attempts to estimate the amount
of free memory left when userspace requests more memory.

When this flag is 1, the kernel pretends there is always enough
memory until it actually runs out.

When this flag is 2, the kernel uses a "never overcommit"
policy that attempts to prevent any overcommit of memory.
Note that user_reserve_kbytes affects this policy.

This feature can be very useful because there are a lot of
programs that malloc() huge amounts of memory "just-in-case"
and don't use much of it.

The default value is 0.

See Documentation/mm/overcommit-accounting.rst and
mm/util.c::__vm_enough_memory() for more information.

overcommit_ratio
================

When overcommit_memory is set to 2, the committed address
space is not permitted to exceed swap plus this percentage
of physical RAM.  See above.

page-cluster
============

page-cluster controls the number of pages up to which consecutive pages
are read in from swap in a single attempt. This is the swap counterpart
to page cache readahead.
The mentioned consecutivity is not in terms of virtual/physical addresses,
but consecutive on swap space - that means they were swapped out together.

It is a logarithmic value - setting it to zero means "1 page", setting
it to 1 means "2 pages", setting it to 2 means "4 pages", etc.
Zero disables swap readahead completely.

The default value is three (eight pages at a time).  There may be some
small benefits in tuning this to a different value if your workload is
swap-intensive.

Lower values mean lower latencies for initial faults, but at the same time
extra faults and I/O delays for following faults if they would have been part of
that consecutive pages readahead would have brought in.

page_lock_unfairness
====================

This value determines the number of times that the page lock can be
stolen from under a waiter. After the lock is stolen the number of times
specified in this file (default is 5), the "fair lock handoff" semantics
will apply, and the waiter will only be awakened if the lock can be taken.

panic_on_oom
============

This enables or disables panic on out-of-memory feature.

If this is set to 0, the kernel will kill some rogue process,
called oom_killer.  Usually, oom_killer can kill rogue processes and
system will survive.

If this is set to 1, the kernel panics when out-of-memory happens.
However, if a process limits using nodes by mempolicy/cpusets,
and those nodes become memory exhaustion status, one process
may be killed by oom-killer. No panic occurs in this case.
Because other nodes' memory may be free. This means system total status
may be not fatal yet.

If this is set to 2, the kernel panics compulsorily even on the
above-mentioned. Even oom happens under memory cgroup, the whole
system panics.

The default value is 0.

1 and 2 are for failover of clustering. Please select either
according to your policy of failover.

panic_on_oom=2+kdump gives you very strong tool to investigate
why oom happens. You can get snapshot.

percpu_pagelist_high_fraction
=============================

This is the fraction of pages in each zone that are can be stored to
per-cpu page lists. It is an upper boundary that is divided depending
on the number of online CPUs. The min value for this is 8 which means
that we do not allow more than 1/8th of pages in each zone to be stored
on per-cpu page lists. This entry only changes the value of hot per-cpu
page lists. A user can specify a number like 100 to allocate 1/100th of
each zone between per-cpu lists.

The batch value of each per-cpu page list remains the same regardless of
the value of the high fraction so allocation latencies are unaffected.

The initial value is zero. Kernel uses this value to set the high pcp->high
mark based on the low watermark for the zone and the number of local
online CPUs.  If the user writes '0' to this sysctl, it will revert to
this default behavior.

stat_interval
=============

The time interval between which vm statistics are updated.  The default
is 1 second.

stat_refresh
============

Any read or write (by root only) flushes all the per-cpu vm statistics
into their global totals, for more accurate reports when testing
e.g. cat /proc/sys/vm/stat_refresh /proc/meminfo

As a side-effect, it also checks for negative totals (elsewhere reported
as 0) and "fails" with EINVAL if any are found, with a warning in dmesg.
(At time of writing, a few stats are known sometimes to be found negative,
with no ill effects: errors and warnings on these stats are suppressed.)

numa_stat
=========

This interface allows runtime configuration of numa statistics.

When page allocation performance becomes a bottleneck and you can tolerate
some possible tool breakage and decreased numa counter precision, you can
do::

	echo 0 > /proc/sys/vm/numa_stat

When page allocation performance is not a bottleneck and you want all
tooling to work, you can do::

	echo 1 > /proc/sys/vm/numa_stat

swappiness
==========

This control is used to define the rough relative IO cost of swapping
and filesystem paging, as a value between 0 and 200. At 100, the VM
assumes equal IO cost and will thus apply memory pressure to the page
cache and swap-backed pages equally; lower values signify more
expensive swap IO, higher values indicates cheaper.

Keep in mind that filesystem IO patterns under memory pressure tend to
be more efficient than swap's random IO. An optimal value will require
experimentation and will also be workload-dependent.

The default value is 60.

For in-memory swap, like zram or zswap, as well as hybrid setups that
have swap on faster devices than the filesystem, values beyond 100 can
be considered. For example, if the random IO against the swap device
is on average 2x faster than IO from the filesystem, swappiness should
be 133 (x + 2x = 200, 2x = 133.33).

At 0, the kernel will not initiate swap until the amount of free and
file-backed pages is less than the high watermark in a zone.

unprivileged_userfaultfd
========================

This flag controls the mode in which unprivileged users can use the
userfaultfd system calls. Set this to 0 to restrict unprivileged users
to handle page faults in user mode only. In this case, users without
SYS_CAP_PTRACE must pass UFFD_USER_MODE_ONLY in order for userfaultfd to
succeed. Prohibiting use of userfaultfd for handling faults from kernel
mode may make certain vulnerabilities more difficult to exploit.

Set this to 1 to allow unprivileged users to use the userfaultfd system
calls without any restrictions.

The default value is 0.

Another way to control permissions for userfaultfd is to use
/dev/userfaultfd instead of userfaultfd(2). See
Documentation/admin-guide/mm/userfaultfd.rst.

user_reserve_kbytes
===================

When overcommit_memory is set to 2, "never overcommit" mode, reserve
min(3% of current process size, user_reserve_kbytes) of free memory.
This is intended to prevent a user from starting a single memory hogging
process, such that they cannot recover (kill the hog).

user_reserve_kbytes defaults to min(3% of the current process size, 128MB).

If this is reduced to zero, then the user will be allowed to allocate
all free memory with a single process, minus admin_reserve_kbytes.
Any subsequent attempts to execute a command will result in
"fork: Cannot allocate memory".

Changing this takes effect whenever an application requests memory.

vfs_cache_pressure
==================

This percentage value controls the tendency of the kernel to reclaim
the memory which is used for caching of directory and inode objects.

At the default value of vfs_cache_pressure=100 the kernel will attempt to
reclaim dentries and inodes at a "fair" rate with respect to pagecache and
swapcache reclaim.  Decreasing vfs_cache_pressure causes the kernel to prefer
to retain dentry and inode caches. When vfs_cache_pressure=0, the kernel will
never reclaim dentries and inodes due to memory pressure and this can easily
lead to out-of-memory conditions. Increasing vfs_cache_pressure beyond 100
causes the kernel to prefer to reclaim dentries and inodes.

Increasing vfs_cache_pressure significantly beyond 100 may have negative
performance impact. Reclaim code needs to take various locks to find freeable
directory and inode objects. With vfs_cache_pressure=1000, it will look for
ten times more freeable objects than there are.

watermark_boost_factor
======================

This factor controls the level of reclaim when memory is being fragmented.
It defines the percentage of the high watermark of a zone that will be
reclaimed if pages of different mobility are being mixed within pageblocks.
The intent is that compaction has less work to do in the future and to
increase the success rate of future high-order allocations such as SLUB
allocations, THP and hugetlbfs pages.

To make it sensible with respect to the watermark_scale_factor
parameter, the unit is in fractions of 10,000. The default value of
15,000 means that up to 150% of the high watermark will be reclaimed in the
event of a pageblock being mixed due to fragmentation. The level of reclaim
is determined by the number of fragmentation events that occurred in the
recent past. If this value is smaller than a pageblock then a pageblocks
worth of pages will be reclaimed (e.g.  2MB on 64-bit x86). A boost factor
of 0 will disable the feature.

watermark_scale_factor
======================

This factor controls the aggressiveness of kswapd. It defines the
amount of memory left in a node/system before kswapd is woken up and
how much memory needs to be free before kswapd goes back to sleep.

The unit is in fractions of 10,000. The default value of 10 means the
distances between watermarks are 0.1% of the available memory in the
node/system. The maximum value is 3000, or 30% of memory.

A high rate of threads entering direct reclaim (allocstall) or kswapd
going to sleep prematurely (kswapd_low_wmark_hit_quickly) can indicate
that the number of free pages kswapd maintains for latency reasons is
too small for the allocation bursts occurring in the system. This knob
can then be used to tune kswapd aggressiveness accordingly.

zone_reclaim_mode
=================

Zone_reclaim_mode allows someone to set more or less aggressive approaches to
reclaim memory when a zone runs out of memory. If it is set to zero then no
zone reclaim occurs. Allocations will be satisfied from other zones / nodes
in the system.

This is value OR'ed together of

=	===================================
1	Zone reclaim on
2	Zone reclaim writes dirty pages out
4	Zone reclaim swaps pages
=	===================================

zone_reclaim_mode is disabled by default.  For file servers or workloads
that benefit from having their data cached, zone_reclaim_mode should be
left disabled as the caching effect is likely to be more important than
data locality.

Consider enabling one or more zone_reclaim mode bits if it's known that the
workload is partitioned such that each partition fits within a NUMA node
and that accessing remote memory would cause a measurable performance
reduction.  The page allocator will take additional actions before
allocating off node pages.

Allowing zone reclaim to write out pages stops processes that are
writing large amounts of data from dirtying pages on other nodes. Zone
reclaim will write out dirty pages if a zone fills up and so effectively
throttle the process. This may decrease the performance of a single process
since it cannot use all of system memory to buffer the outgoing writes
anymore but it preserve the memory on other nodes so that the performance
of other processes running on other nodes will not be affected.

Allowing regular swap effectively restricts allocations to the local
node unless explicitly overridden by memory policies or cpuset
configurations.


code:
Rules on how to access information in sysfs
===========================================

The kernel-exported sysfs exports internal kernel implementation details
and depends on internal kernel structures and layout. It is agreed upon
by the kernel developers that the Linux kernel does not provide a stable
internal API. Therefore, there are aspects of the sysfs interface that
may not be stable across kernel releases.

To minimize the risk of breaking users of sysfs, which are in most cases
low-level userspace applications, with a new kernel release, the users
of sysfs must follow some rules to use an as-abstract-as-possible way to
access this filesystem. The current udev and HAL programs already
implement this and users are encouraged to plug, if possible, into the
abstractions these programs provide instead of accessing sysfs directly.

But if you really do want or need to access sysfs directly, please follow
the following rules and then your programs should work with future
versions of the sysfs interface.

- Do not use libsysfs
    It makes assumptions about sysfs which are not true. Its API does not
    offer any abstraction, it exposes all the kernel driver-core
    implementation details in its own API. Therefore it is not better than
    reading directories and opening the files yourself.
    Also, it is not actively maintained, in the sense of reflecting the
    current kernel development. The goal of providing a stable interface
    to sysfs has failed; it causes more problems than it solves. It
    violates many of the rules in this document.

- sysfs is always at ``/sys``
    Parsing ``/proc/mounts`` is a waste of time. Other mount points are a
    system configuration bug you should not try to solve. For test cases,
    possibly support a ``SYSFS_PATH`` environment variable to overwrite the
    application's behavior, but never try to search for sysfs. Never try
    to mount it, if you are not an early boot script.

- devices are only "devices"
    There is no such thing like class-, bus-, physical devices,
    interfaces, and such that you can rely on in userspace. Everything is
    just simply a "device". Class-, bus-, physical, ... types are just
    kernel implementation details which should not be expected by
    applications that look for devices in sysfs.

    The properties of a device are:

    - devpath (``/devices/pci0000:00/0000:00:1d.1/usb2/2-2/2-2:1.0``)

      - identical to the DEVPATH value in the event sent from the kernel
        at device creation and removal
      - the unique key to the device at that point in time
      - the kernel's path to the device directory without the leading
        ``/sys``, and always starting with a slash
      - all elements of a devpath must be real directories. Symlinks
        pointing to /sys/devices must always be resolved to their real
        target and the target path must be used to access the device.
        That way the devpath to the device matches the devpath of the
        kernel used at event time.
      - using or exposing symlink values as elements in a devpath string
        is a bug in the application

    - kernel name (``sda``, ``tty``, ``0000:00:1f.2``, ...)

      - a directory name, identical to the last element of the devpath
      - applications need to handle spaces and characters like ``!`` in
        the name

    - subsystem (``block``, ``tty``, ``pci``, ...)

      - simple string, never a path or a link
      - retrieved by reading the "subsystem"-link and using only the
        last element of the target path

    - driver (``tg3``, ``ata_piix``, ``uhci_hcd``)

      - a simple string, which may contain spaces, never a path or a
        link
      - it is retrieved by reading the "driver"-link and using only the
        last element of the target path
      - devices which do not have "driver"-link just do not have a
        driver; copying the driver value in a child device context is a
        bug in the application

    - attributes

      - the files in the device directory or files below subdirectories
        of the same device directory
      - accessing attributes reached by a symlink pointing to another device,
        like the "device"-link, is a bug in the application

    Everything else is just a kernel driver-core implementation detail
    that should not be assumed to be stable across kernel releases.

- Properties of parent devices never belong into a child device.
    Always look at the parent devices themselves for determining device
    context properties. If the device ``eth0`` or ``sda`` does not have a
    "driver"-link, then this device does not have a driver. Its value is empty.
    Never copy any property of the parent-device into a child-device. Parent
    device properties may change dynamically without any notice to the
    child device.

- Hierarchy in a single device tree
    There is only one valid place in sysfs where hierarchy can be examined
    and this is below: ``/sys/devices.``
    It is planned that all device directories will end up in the tree
    below this directory.

- Classification by subsystem
    There are currently three places for classification of devices:
    ``/sys/block,`` ``/sys/class`` and ``/sys/bus.`` It is planned that these will
    not contain any device directories themselves, but only flat lists of
    symlinks pointing to the unified ``/sys/devices`` tree.
    All three places have completely different rules on how to access
    device information. It is planned to merge all three
    classification directories into one place at ``/sys/subsystem``,
    following the layout of the bus directories. All buses and
    classes, including the converted block subsystem, will show up
    there.
    The devices belonging to a subsystem will create a symlink in the
    "devices" directory at ``/sys/subsystem/<name>/devices``,

    If ``/sys/subsystem`` exists, ``/sys/bus``, ``/sys/class`` and ``/sys/block``
    can be ignored. If it does not exist, you always have to scan all three
    places, as the kernel is free to move a subsystem from one place to
    the other, as long as the devices are still reachable by the same
    subsystem name.

    Assuming ``/sys/class/<subsystem>`` and ``/sys/bus/<subsystem>``, or
    ``/sys/block`` and ``/sys/class/block`` are not interchangeable is a bug in
    the application.

- Block
    The converted block subsystem at ``/sys/class/block`` or
    ``/sys/subsystem/block`` will contain the links for disks and partitions
    at the same level, never in a hierarchy. Assuming the block subsystem to
    contain only disks and not partition devices in the same flat list is
    a bug in the application.

- "device"-link and <subsystem>:<kernel name>-links
    Never depend on the "device"-link. The "device"-link is a workaround
    for the old layout, where class devices are not created in
    ``/sys/devices/`` like the bus devices. If the link-resolving of a
    device directory does not end in ``/sys/devices/``, you can use the
    "device"-link to find the parent devices in ``/sys/devices/``, That is the
    single valid use of the "device"-link; it must never appear in any
    path as an element. Assuming the existence of the "device"-link for
    a device in ``/sys/devices/`` is a bug in the application.
    Accessing ``/sys/class/net/eth0/device`` is a bug in the application.

    Never depend on the class-specific links back to the ``/sys/class``
    directory.  These links are also a workaround for the design mistake
    that class devices are not created in ``/sys/devices.`` If a device
    directory does not contain directories for child devices, these links
    may be used to find the child devices in ``/sys/class.`` That is the single
    valid use of these links; they must never appear in any path as an
    element. Assuming the existence of these links for devices which are
    real child device directories in the ``/sys/devices`` tree is a bug in
    the application.

    It is planned to remove all these links when all class device
    directories live in ``/sys/devices.``

- Position of devices along device chain can change.
    Never depend on a specific parent device position in the devpath,
    or the chain of parent devices. The kernel is free to insert devices into
    the chain. You must always request the parent device you are looking for
    by its subsystem value. You need to walk up the chain until you find
    the device that matches the expected subsystem. Depending on a specific
    position of a parent device or exposing relative paths using ``../`` to
    access the chain of parents is a bug in the application.

- When reading and writing sysfs device attribute files, avoid dependency
    on specific error codes wherever possible. This minimizes coupling to
    the error handling implementation within the kernel.

    In general, failures to read or write sysfs device attributes shall
    propagate errors wherever possible. Common errors include, but are not
    limited to:

	``-EIO``: The read or store operation is not supported, typically
	returned by the sysfs system itself if the read or store pointer
	is ``NULL``.

	``-ENXIO``: The read or store operation failed

    Error codes will not be changed without good reason, and should a change
    to error codes result in user-space breakage, it will be fixed, or the
    the offending change will be reverted.

    Userspace applications can, however, expect the format and contents of
    the attribute files to remain consistent in the absence of a version
    attribute change in the context of a given attribute.

repo_name: angery/linux


code:
Linux Magic System Request Key Hacks
====================================

Documentation for sysrq.c

What is the magic SysRq key?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It is a 'magical' key combo you can hit which the kernel will respond to
regardless of whatever else it is doing, unless it is completely locked up.

How do I enable the magic SysRq key?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You need to say "yes" to 'Magic SysRq key (CONFIG_MAGIC_SYSRQ)' when
configuring the kernel. When running a kernel with SysRq compiled in,
/proc/sys/kernel/sysrq controls the functions allowed to be invoked via
the SysRq key. The default value in this file is set by the
CONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE config symbol, which itself defaults
to 1. Here is the list of possible values in /proc/sys/kernel/sysrq:

   -  0 - disable sysrq completely
   -  1 - enable all functions of sysrq
   - >1 - bitmask of allowed sysrq functions (see below for detailed function
     description)::

          2 =   0x2 - enable control of console logging level
          4 =   0x4 - enable control of keyboard (SAK, unraw)
          8 =   0x8 - enable debugging dumps of processes etc.
         16 =  0x10 - enable sync command
         32 =  0x20 - enable remount read-only
         64 =  0x40 - enable signalling of processes (term, kill, oom-kill)
        128 =  0x80 - allow reboot/poweroff
        256 = 0x100 - allow nicing of all RT tasks

You can set the value in the file by the following command::

    echo "number" >/proc/sys/kernel/sysrq

The number may be written here either as decimal or as hexadecimal
with the 0x prefix. CONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE must always be
written in hexadecimal.

Note that the value of ``/proc/sys/kernel/sysrq`` influences only the invocation
via a keyboard. Invocation of any operation via ``/proc/sysrq-trigger`` is
always allowed (by a user with admin privileges).

How do I use the magic SysRq key?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

On x86
	You press the key combo :kbd:`ALT-SysRq-<command key>`.

	.. note::
	   Some
           keyboards may not have a key labeled 'SysRq'. The 'SysRq' key is
           also known as the 'Print Screen' key. Also some keyboards cannot
	   handle so many keys being pressed at the same time, so you might
	   have better luck with press :kbd:`Alt`, press :kbd:`SysRq`,
	   release :kbd:`SysRq`, press :kbd:`<command key>`, release everything.

On SPARC
	You press :kbd:`ALT-STOP-<command key>`, I believe.

On the serial console (PC style standard serial ports only)
        You send a ``BREAK``, then within 5 seconds a command key. Sending
        ``BREAK`` twice is interpreted as a normal BREAK.

On PowerPC
	Press :kbd:`ALT - Print Screen` (or :kbd:`F13`) - :kbd:`<command key>`.
        :kbd:`Print Screen` (or :kbd:`F13`) - :kbd:`<command key>` may suffice.

On other
	If you know of the key combos for other architectures, please
	submit a patch to be included in this section.

On all
	Write a character to /proc/sysrq-trigger.  e.g.::

		echo t > /proc/sysrq-trigger

The :kbd:`<command key>` is case sensitive.

What are the 'command' keys?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

=========== ===================================================================
Command	    Function
=========== ===================================================================
``b``	    Will immediately reboot the system without syncing or unmounting
            your disks.

``c``	    Will perform a system crash and a crashdump will be taken
            if configured.

``d``	    Shows all locks that are held.

``e``	    Send a SIGTERM to all processes, except for init.

``f``	    Will call the oom killer to kill a memory hog process, but do not
	    panic if nothing can be killed.

``g``	    Used by kgdb (kernel debugger)

``h``	    Will display help (actually any other key than those listed
            here will display help. but ``h`` is easy to remember :-)

``i``	    Send a SIGKILL to all processes, except for init.

``j``	    Forcibly "Just thaw it" - filesystems frozen by the FIFREEZE ioctl.

``k``	    Secure Access Key (SAK) Kills all programs on the current virtual
            console. NOTE: See important comments below in SAK section.

``l``	    Shows a stack backtrace for all active CPUs.

``m``	    Will dump current memory info to your console.

``n``	    Used to make RT tasks nice-able

``o``	    Will shut your system off (if configured and supported).

``p``	    Will dump the current registers and flags to your console.

``q``	    Will dump per CPU lists of all armed hrtimers (but NOT regular
            timer_list timers) and detailed information about all
            clockevent devices.

``r``	    Turns off keyboard raw mode and sets it to XLATE.

``s``	    Will attempt to sync all mounted filesystems.

``t``	    Will dump a list of current tasks and their information to your
            console.

``u``	    Will attempt to remount all mounted filesystems read-only.

``v``	    Forcefully restores framebuffer console
``v``	    Causes ETM buffer dump [ARM-specific]

``w``	    Dumps tasks that are in uninterruptable (blocked) state.

``x``	    Used by xmon interface on ppc/powerpc platforms.
            Show global PMU Registers on sparc64.
            Dump all TLB entries on MIPS.

``y``	    Show global CPU Registers [SPARC-64 specific]

``z``	    Dump the ftrace buffer

``0``-``9`` Sets the console log level, controlling which kernel messages
            will be printed to your console. (``0``, for example would make
            it so that only emergency messages like PANICs or OOPSes would
            make it to your console.)
=========== ===================================================================

Okay, so what can I use them for?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Well, unraw(r) is very handy when your X server or a svgalib program crashes.

sak(k) (Secure Access Key) is useful when you want to be sure there is no
trojan program running at console which could grab your password
when you would try to login. It will kill all programs on given console,
thus letting you make sure that the login prompt you see is actually
the one from init, not some trojan program.

.. important::

   In its true form it is not a true SAK like the one in a
   c2 compliant system, and it should not be mistaken as
   such.

It seems others find it useful as (System Attention Key) which is
useful when you want to exit a program that will not let you switch consoles.
(For example, X or a svgalib program.)

``reboot(b)`` is good when you're unable to shut down, it is an equivalent
of pressing the "reset" button.

``crash(c)`` can be used to manually trigger a crashdump when the system is hung.
Note that this just triggers a crash if there is no dump mechanism available.

``sync(s)`` is handy before yanking removable medium or after using a rescue
shell that provides no graceful shutdown -- it will ensure your data is
safely written to the disk. Note that the sync hasn't taken place until you see
the "OK" and "Done" appear on the screen.

``umount(u)`` can be used to mark filesystems as properly unmounted. From the
running system's point of view, they will be remounted read-only. The remount
isn't complete until you see the "OK" and "Done" message appear on the screen.

The loglevels ``0``-``9`` are useful when your console is being flooded with
kernel messages you do not want to see. Selecting ``0`` will prevent all but
the most urgent kernel messages from reaching your console. (They will
still be logged if syslogd/klogd are alive, though.)

``term(e)`` and ``kill(i)`` are useful if you have some sort of runaway process
you are unable to kill any other way, especially if it's spawning other
processes.

"just thaw ``it(j)``" is useful if your system becomes unresponsive due to a
frozen (probably root) filesystem via the FIFREEZE ioctl.

Sometimes SysRq seems to get 'stuck' after using it, what can I do?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When this happens, try tapping shift, alt and control on both sides of the
keyboard, and hitting an invalid sysrq sequence again. (i.e., something like
:kbd:`alt-sysrq-z`).

Switching to another virtual console (:kbd:`ALT+Fn`) and then back again
should also help.

I hit SysRq, but nothing seems to happen, what's wrong?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There are some keyboards that produce a different keycode for SysRq than the
pre-defined value of 99
(see ``KEY_SYSRQ`` in ``include/uapi/linux/input-event-codes.h``), or
which don't have a SysRq key at all. In these cases, run ``showkey -s`` to find
an appropriate scancode sequence, and use ``setkeycodes <sequence> 99`` to map
this sequence to the usual SysRq code (e.g., ``setkeycodes e05b 99``). It's
probably best to put this command in a boot script. Oh, and by the way, you
exit ``showkey`` by not typing anything for ten seconds.

I want to add SysRQ key events to a module, how does it work?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In order to register a basic function with the table, you must first include
the header ``include/linux/sysrq.h``, this will define everything else you need.
Next, you must create a ``sysrq_key_op`` struct, and populate it with A) the key
handler function you will use, B) a help_msg string, that will print when SysRQ
prints help, and C) an action_msg string, that will print right before your
handler is called. Your handler must conform to the prototype in 'sysrq.h'.

After the ``sysrq_key_op`` is created, you can call the kernel function
``register_sysrq_key(int key, const struct sysrq_key_op *op_p);`` this will
register the operation pointed to by ``op_p`` at table key 'key',
if that slot in the table is blank. At module unload time, you must call
the function ``unregister_sysrq_key(int key, const struct sysrq_key_op *op_p)``,
which will remove the key op pointed to by 'op_p' from the key 'key', if and
only if it is currently registered in that slot. This is in case the slot has
been overwritten since you registered it.

The Magic SysRQ system works by registering key operations against a key op
lookup table, which is defined in 'drivers/tty/sysrq.c'. This key table has
a number of operations registered into it at compile time, but is mutable,
and 2 functions are exported for interface to it::

	register_sysrq_key and unregister_sysrq_key.

Of course, never ever leave an invalid pointer in the table. I.e., when
your module that called register_sysrq_key() exits, it must call
unregister_sysrq_key() to clean up the sysrq key table entry that it used.
Null pointers in the table are always safe. :)

If for some reason you feel the need to call the handle_sysrq function from
within a function called by handle_sysrq, you must be aware that you are in
a lock (you are also in an interrupt handler, which means don't sleep!), so
you must call ``__handle_sysrq_nolock`` instead.

When I hit a SysRq key combination only the header appears on the console?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sysrq output is subject to the same console loglevel control as all
other console output.  This means that if the kernel was booted 'quiet'
as is common on distro kernels the output may not appear on the actual
console, even though it will appear in the dmesg buffer, and be accessible
via the dmesg command and to the consumers of ``/proc/kmsg``.  As a specific
exception the header line from the sysrq command is passed to all console
consumers as if the current loglevel was maximum.  If only the header
is emitted it is almost certain that the kernel loglevel is too low.
Should you require the output on the console channel then you will need
to temporarily up the console loglevel using :kbd:`alt-sysrq-8` or::

    echo 8 > /proc/sysrq-trigger

Remember to return the loglevel to normal after triggering the sysrq
command you are interested in.

I have more questions, who can I ask?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Just ask them on the linux-kernel mailing list:
	linux-kernel@vger.kernel.org

Credits
~~~~~~~

- Written by Mydraal <vulpyne@vulpyne.net>
- Updated by Adam Sulmicki <adam@cfar.umd.edu>
- Updated by Jeremy M. Dolan <jmd@turbogeek.org> 2001/01/28 10:15:59
- Added to by Crutcher Dunnavant <crutcher+kernel@datastacks.com>


code:
Tainted kernels
---------------

The kernel will mark itself as 'tainted' when something occurs that might be
relevant later when investigating problems. Don't worry too much about this,
most of the time it's not a problem to run a tainted kernel; the information is
mainly of interest once someone wants to investigate some problem, as its real
cause might be the event that got the kernel tainted. That's why bug reports
from tainted kernels will often be ignored by developers, hence try to reproduce
problems with an untainted kernel.

Note the kernel will remain tainted even after you undo what caused the taint
(i.e. unload a proprietary kernel module), to indicate the kernel remains not
trustworthy. That's also why the kernel will print the tainted state when it
notices an internal problem (a 'kernel bug'), a recoverable error
('kernel oops') or a non-recoverable error ('kernel panic') and writes debug
information about this to the logs ``dmesg`` outputs. It's also possible to
check the tainted state at runtime through a file in ``/proc/``.

Tainted flag in bugs, oops or panics messages
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You find the tainted state near the top in a line starting with 'CPU:'; if or
why the kernel was tainted is shown after the Process ID ('PID:') and a shortened
name of the command ('Comm:') that triggered the event::

	BUG: unable to handle kernel NULL pointer dereference at 0000000000000000
	Oops: 0002 [#1] SMP PTI
	CPU: 0 PID: 4424 Comm: insmod Tainted: P        W  O      4.20.0-0.rc6.fc30 #1
	Hardware name: Red Hat KVM, BIOS 0.5.1 01/01/2011
	RIP: 0010:my_oops_init+0x13/0x1000 [kpanic]
	[...]

You'll find a 'Not tainted: ' there if the kernel was not tainted at the
time of the event; if it was, then it will print 'Tainted: ' and characters
either letters or blanks. In above example it looks like this::

	Tainted: P        W  O

The meaning of those characters is explained in the table below. In this case
the kernel got tainted earlier because a proprietary Module (``P``) was loaded,
a warning occurred (``W``), and an externally-built module was loaded (``O``).
To decode other letters use the table below.

Decoding tainted state at runtime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

At runtime, you can query the tainted state by reading
``cat /proc/sys/kernel/tainted``. If that returns ``0``, the kernel is not
tainted; any other number indicates the reasons why it is. The easiest way to
decode that number is the script ``tools/debugging/kernel-chktaint``, which your
distribution might ship as part of a package called ``linux-tools`` or
``kernel-tools``; if it doesn't you can download the script from
`git.kernel.org <https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/plain/tools/debugging/kernel-chktaint>`_
and execute it with ``sh kernel-chktaint``, which would print something like
this on the machine that had the statements in the logs that were quoted earlier::

	Kernel is Tainted for following reasons:
	 * Proprietary module was loaded (#0)
	 * Kernel issued warning (#9)
	 * Externally-built ('out-of-tree') module was loaded  (#12)
	See Documentation/admin-guide/tainted-kernels.rst in the Linux kernel or
	 https://www.kernel.org/doc/html/latest/admin-guide/tainted-kernels.html for
	 a more details explanation of the various taint flags.
	Raw taint value as int/string: 4609/'P        W  O     '

You can try to decode the number yourself. That's easy if there was only one
reason that got your kernel tainted, as in this case you can find the number
with the table below. If there were multiple reasons you need to decode the
number, as it is a bitfield, where each bit indicates the absence or presence of
a particular type of taint. It's best to leave that to the aforementioned
script, but if you need something quick you can use this shell command to check
which bits are set::

	$ for i in $(seq 18); do echo $(($i-1)) $(($(cat /proc/sys/kernel/tainted)>>($i-1)&1));done

Table for decoding tainted state
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

===  ===  ======  ========================================================
Bit  Log  Number  Reason that got the kernel tainted
===  ===  ======  ========================================================
  0  G/P       1  proprietary module was loaded
  1  _/F       2  module was force loaded
  2  _/S       4  kernel running on an out of specification system
  3  _/R       8  module was force unloaded
  4  _/M      16  processor reported a Machine Check Exception (MCE)
  5  _/B      32  bad page referenced or some unexpected page flags
  6  _/U      64  taint requested by userspace application
  7  _/D     128  kernel died recently, i.e. there was an OOPS or BUG
  8  _/A     256  ACPI table overridden by user
  9  _/W     512  kernel issued warning
 10  _/C    1024  staging driver was loaded
 11  _/I    2048  workaround for bug in platform firmware applied
 12  _/O    4096  externally-built ("out-of-tree") module was loaded
 13  _/E    8192  unsigned module was loaded
 14  _/L   16384  soft lockup occurred
 15  _/K   32768  kernel has been live patched
 16  _/X   65536  auxiliary taint, defined for and used by distros
 17  _/T  131072  kernel was built with the struct randomization plugin
 18  _/N  262144  an in-kernel test has been run
===  ===  ======  ========================================================

Note: The character ``_`` is representing a blank in this table to make reading
easier.

More detailed explanation for tainting
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 0)  ``G`` if all modules loaded have a GPL or compatible license, ``P`` if
     any proprietary module has been loaded.  Modules without a
     MODULE_LICENSE or with a MODULE_LICENSE that is not recognised by
     insmod as GPL compatible are assumed to be proprietary.

 1)  ``F`` if any module was force loaded by ``insmod -f``, ``' '`` if all
     modules were loaded normally.

 2)  ``S`` if the kernel is running on a processor or system that is out of
     specification: hardware has been put into an unsupported configuration,
     therefore proper execution cannot be guaranteed.
     Kernel will be tainted if, for example:

     - on x86: PAE is forced through forcepae on intel CPUs (such as Pentium M)
       which do not report PAE but may have a functional implementation, an SMP
       kernel is running on non officially capable SMP Athlon CPUs, MSRs are
       being poked at from userspace.
     - on arm: kernel running on certain CPUs (such as Keystone 2) without
       having certain kernel features enabled.
     - on arm64: there are mismatched hardware features between CPUs, the
       bootloader has booted CPUs in different modes.
     - certain drivers are being used on non supported architectures (such as
       scsi/snic on something else than x86_64, scsi/ips on non
       x86/x86_64/itanium, have broken firmware settings for the
       irqchip/irq-gic on arm64 ...).
     - x86/x86_64: Microcode late loading is dangerous and will result in
       tainting the kernel. It requires that all CPUs rendezvous to make sure
       the update happens when the system is as quiescent as possible. However,
       a higher priority MCE/SMI/NMI can move control flow away from that
       rendezvous and interrupt the update, which can be detrimental to the
       machine.

 3)  ``R`` if a module was force unloaded by ``rmmod -f``, ``' '`` if all
     modules were unloaded normally.

 4)  ``M`` if any processor has reported a Machine Check Exception,
     ``' '`` if no Machine Check Exceptions have occurred.

 5)  ``B`` If a page-release function has found a bad page reference or some
     unexpected page flags. This indicates a hardware problem or a kernel bug;
     there should be other information in the log indicating why this tainting
     occurred.

 6)  ``U`` if a user or user application specifically requested that the
     Tainted flag be set, ``' '`` otherwise.

 7)  ``D`` if the kernel has died recently, i.e. there was an OOPS or BUG.

 8)  ``A`` if an ACPI table has been overridden.

 9)  ``W`` if a warning has previously been issued by the kernel.
     (Though some warnings may set more specific taint flags.)

 10) ``C`` if a staging driver has been loaded.

 11) ``I`` if the kernel is working around a severe bug in the platform
     firmware (BIOS or similar).

 12) ``O`` if an externally-built ("out-of-tree") module has been loaded.

 13) ``E`` if an unsigned module has been loaded in a kernel supporting
     module signature.

 14) ``L`` if a soft lockup has previously occurred on the system.

 15) ``K`` if the kernel has been live patched.

 16) ``X`` Auxiliary taint, defined for and used by Linux distributors.

 17) ``T`` Kernel was build with the randstruct plugin, which can intentionally
     produce extremely unusual kernel structure layouts (even performance
     pathological ones), which is important to know when debugging. Set at
     build time.


code:
.. SPDX-License-Identifier: GPL-2.0

======================
 USB4 and Thunderbolt
======================
USB4 is the public specification based on Thunderbolt 3 protocol with
some differences at the register level among other things. Connection
manager is an entity running on the host router (host controller)
responsible for enumerating routers and establishing tunnels. A
connection manager can be implemented either in firmware or software.
Typically PCs come with a firmware connection manager for Thunderbolt 3
and early USB4 capable systems. Apple systems on the other hand use
software connection manager and the later USB4 compliant devices follow
the suit.

The Linux Thunderbolt driver supports both and can detect at runtime which
connection manager implementation is to be used. To be on the safe side the
software connection manager in Linux also advertises security level
``user`` which means PCIe tunneling is disabled by default. The
documentation below applies to both implementations with the exception that
the software connection manager only supports ``user`` security level and
is expected to be accompanied with an IOMMU based DMA protection.

Security levels and how to use them
-----------------------------------
The interface presented here is not meant for end users. Instead there
should be a userspace tool that handles all the low-level details, keeps
a database of the authorized devices and prompts users for new connections.

More details about the sysfs interface for Thunderbolt devices can be
found in ``Documentation/ABI/testing/sysfs-bus-thunderbolt``.

Those users who just want to connect any device without any sort of
manual work can add following line to
``/etc/udev/rules.d/99-local.rules``::

  ACTION=="add", SUBSYSTEM=="thunderbolt", ATTR{authorized}=="0", ATTR{authorized}="1"

This will authorize all devices automatically when they appear. However,
keep in mind that this bypasses the security levels and makes the system
vulnerable to DMA attacks.

Starting with Intel Falcon Ridge Thunderbolt controller there are 4
security levels available. Intel Titan Ridge added one more security level
(usbonly). The reason for these is the fact that the connected devices can
be DMA masters and thus read contents of the host memory without CPU and OS
knowing about it. There are ways to prevent this by setting up an IOMMU but
it is not always available for various reasons.

Some USB4 systems have a BIOS setting to disable PCIe tunneling. This is
treated as another security level (nopcie).

The security levels are as follows:

  none
    All devices are automatically connected by the firmware. No user
    approval is needed. In BIOS settings this is typically called
    *Legacy mode*.

  user
    User is asked whether the device is allowed to be connected.
    Based on the device identification information available through
    ``/sys/bus/thunderbolt/devices``, the user then can make the decision.
    In BIOS settings this is typically called *Unique ID*.

  secure
    User is asked whether the device is allowed to be connected. In
    addition to UUID the device (if it supports secure connect) is sent
    a challenge that should match the expected one based on a random key
    written to the ``key`` sysfs attribute. In BIOS settings this is
    typically called *One time saved key*.

  dponly
    The firmware automatically creates tunnels for Display Port and
    USB. No PCIe tunneling is done. In BIOS settings this is
    typically called *Display Port Only*.

  usbonly
    The firmware automatically creates tunnels for the USB controller and
    Display Port in a dock. All PCIe links downstream of the dock are
    removed.

  nopcie
    PCIe tunneling is disabled/forbidden from the BIOS. Available in some
    USB4 systems.

The current security level can be read from
``/sys/bus/thunderbolt/devices/domainX/security`` where ``domainX`` is
the Thunderbolt domain the host controller manages. There is typically
one domain per Thunderbolt host controller.

If the security level reads as ``user`` or ``secure`` the connected
device must be authorized by the user before PCIe tunnels are created
(e.g the PCIe device appears).

Each Thunderbolt device plugged in will appear in sysfs under
``/sys/bus/thunderbolt/devices``. The device directory carries
information that can be used to identify the particular device,
including its name and UUID.

Authorizing devices when security level is ``user`` or ``secure``
-----------------------------------------------------------------
When a device is plugged in it will appear in sysfs as follows::

  /sys/bus/thunderbolt/devices/0-1/authorized	- 0
  /sys/bus/thunderbolt/devices/0-1/device	- 0x8004
  /sys/bus/thunderbolt/devices/0-1/device_name	- Thunderbolt to FireWire Adapter
  /sys/bus/thunderbolt/devices/0-1/vendor	- 0x1
  /sys/bus/thunderbolt/devices/0-1/vendor_name	- Apple, Inc.
  /sys/bus/thunderbolt/devices/0-1/unique_id	- e0376f00-0300-0100-ffff-ffffffffffff

The ``authorized`` attribute reads 0 which means no PCIe tunnels are
created yet. The user can authorize the device by simply entering::

  # echo 1 > /sys/bus/thunderbolt/devices/0-1/authorized

This will create the PCIe tunnels and the device is now connected.

If the device supports secure connect, and the domain security level is
set to ``secure``, it has an additional attribute ``key`` which can hold
a random 32-byte value used for authorization and challenging the device in
future connects::

  /sys/bus/thunderbolt/devices/0-3/authorized	- 0
  /sys/bus/thunderbolt/devices/0-3/device	- 0x305
  /sys/bus/thunderbolt/devices/0-3/device_name	- AKiTiO Thunder3 PCIe Box
  /sys/bus/thunderbolt/devices/0-3/key		-
  /sys/bus/thunderbolt/devices/0-3/vendor	- 0x41
  /sys/bus/thunderbolt/devices/0-3/vendor_name	- inXtron
  /sys/bus/thunderbolt/devices/0-3/unique_id	- dc010000-0000-8508-a22d-32ca6421cb16

Notice the key is empty by default.

If the user does not want to use secure connect they can just ``echo 1``
to the ``authorized`` attribute and the PCIe tunnels will be created in
the same way as in the ``user`` security level.

If the user wants to use secure connect, the first time the device is
plugged a key needs to be created and sent to the device::

  # key=$(openssl rand -hex 32)
  # echo $key > /sys/bus/thunderbolt/devices/0-3/key
  # echo 1 > /sys/bus/thunderbolt/devices/0-3/authorized

Now the device is connected (PCIe tunnels are created) and in addition
the key is stored on the device NVM.

Next time the device is plugged in the user can verify (challenge) the
device using the same key::

  # echo $key > /sys/bus/thunderbolt/devices/0-3/key
  # echo 2 > /sys/bus/thunderbolt/devices/0-3/authorized

If the challenge the device returns back matches the one we expect based
on the key, the device is connected and the PCIe tunnels are created.
However, if the challenge fails no tunnels are created and error is
returned to the user.

If the user still wants to connect the device they can either approve
the device without a key or write a new key and write 1 to the
``authorized`` file to get the new key stored on the device NVM.

De-authorizing devices
----------------------
It is possible to de-authorize devices by writing ``0`` to their
``authorized`` attribute. This requires support from the connection
manager implementation and can be checked by reading domain
``deauthorization`` attribute. If it reads ``1`` then the feature is
supported.

When a device is de-authorized the PCIe tunnel from the parent device
PCIe downstream (or root) port to the device PCIe upstream port is torn
down. This is essentially the same thing as PCIe hot-remove and the PCIe
toplogy in question will not be accessible anymore until the device is
authorized again. If there is storage such as NVMe or similar involved,
there is a risk for data loss if the filesystem on that storage is not
properly shut down. You have been warned!

DMA protection utilizing IOMMU
------------------------------
Recent systems from 2018 and forward with Thunderbolt ports may natively
support IOMMU. This means that Thunderbolt security is handled by an IOMMU
so connected devices cannot access memory regions outside of what is
allocated for them by drivers. When Linux is running on such system it
automatically enables IOMMU if not enabled by the user already. These
systems can be identified by reading ``1`` from
``/sys/bus/thunderbolt/devices/domainX/iommu_dma_protection`` attribute.

The driver does not do anything special in this case but because DMA
protection is handled by the IOMMU, security levels (if set) are
redundant. For this reason some systems ship with security level set to
``none``. Other systems have security level set to ``user`` in order to
support downgrade to older OS, so users who want to automatically
authorize devices when IOMMU DMA protection is enabled can use the
following ``udev`` rule::

  ACTION=="add", SUBSYSTEM=="thunderbolt", ATTRS{iommu_dma_protection}=="1", ATTR{authorized}=="0", ATTR{authorized}="1"

Upgrading NVM on Thunderbolt device, host or retimer
----------------------------------------------------
Since most of the functionality is handled in firmware running on a
host controller or a device, it is important that the firmware can be
upgraded to the latest where possible bugs in it have been fixed.
Typically OEMs provide this firmware from their support site.

There is also a central site which has links where to download firmware
for some machines:

  `Thunderbolt Updates <https://thunderbolttechnology.net/updates>`_

Before you upgrade firmware on a device, host or retimer, please make
sure it is a suitable upgrade. Failing to do that may render the device
in a state where it cannot be used properly anymore without special
tools!

Host NVM upgrade on Apple Macs is not supported.

Once the NVM image has been downloaded, you need to plug in a
Thunderbolt device so that the host controller appears. It does not
matter which device is connected (unless you are upgrading NVM on a
device - then you need to connect that particular device).

Note an OEM-specific method to power the controller up ("force power") may
be available for your system in which case there is no need to plug in a
Thunderbolt device.

After that we can write the firmware to the non-active parts of the NVM
of the host or device. As an example here is how Intel NUC6i7KYK (Skull
Canyon) Thunderbolt controller NVM is upgraded::

  # dd if=KYK_TBT_FW_0018.bin of=/sys/bus/thunderbolt/devices/0-0/nvm_non_active0/nvmem

Once the operation completes we can trigger NVM authentication and
upgrade process as follows::

  # echo 1 > /sys/bus/thunderbolt/devices/0-0/nvm_authenticate

If no errors are returned, the host controller shortly disappears. Once
it comes back the driver notices it and initiates a full power cycle.
After a while the host controller appears again and this time it should
be fully functional.

We can verify that the new NVM firmware is active by running the following
commands::

  # cat /sys/bus/thunderbolt/devices/0-0/nvm_authenticate
  0x0
  # cat /sys/bus/thunderbolt/devices/0-0/nvm_version
  18.0

If ``nvm_authenticate`` contains anything other than 0x0 it is the error
code from the last authentication cycle, which means the authentication
of the NVM image failed.

Note names of the NVMem devices ``nvm_activeN`` and ``nvm_non_activeN``
depend on the order they are registered in the NVMem subsystem. N in
the name is the identifier added by the NVMem subsystem.

Upgrading on-board retimer NVM when there is no cable connected
---------------------------------------------------------------
If the platform supports, it may be possible to upgrade the retimer NVM
firmware even when there is nothing connected to the USB4
ports. When this is the case the ``usb4_portX`` devices have two special
attributes: ``offline`` and ``rescan``. The way to upgrade the firmware
is to first put the USB4 port into offline mode::

  # echo 1 > /sys/bus/thunderbolt/devices/0-0/usb4_port1/offline

This step makes sure the port does not respond to any hotplug events,
and also ensures the retimers are powered on. The next step is to scan
for the retimers::

  # echo 1 > /sys/bus/thunderbolt/devices/0-0/usb4_port1/rescan

This enumerates and adds the on-board retimers. Now retimer NVM can be
upgraded in the same way than with cable connected (see previous
section). However, the retimer is not disconnected as we are offline
mode) so after writing ``1`` to ``nvm_authenticate`` one should wait for
5 or more seconds before running rescan again::

  # echo 1 > /sys/bus/thunderbolt/devices/0-0/usb4_port1/rescan

This point if everything went fine, the port can be put back to
functional state again::

  # echo 0 > /sys/bus/thunderbolt/devices/0-0/usb4_port1/offline

Upgrading NVM when host controller is in safe mode
--------------------------------------------------
If the existing NVM is not properly authenticated (or is missing) the
host controller goes into safe mode which means that the only available
functionality is flashing a new NVM image. When in this mode, reading
``nvm_version`` fails with ``ENODATA`` and the device identification
information is missing.

To recover from this mode, one needs to flash a valid NVM image to the
host controller in the same way it is done in the previous chapter.

Networking over Thunderbolt cable
---------------------------------
Thunderbolt technology allows software communication between two hosts
connected by a Thunderbolt cable.

It is possible to tunnel any kind of traffic over a Thunderbolt link but
currently we only support Apple ThunderboltIP protocol.

If the other host is running Windows or macOS, the only thing you need to
do is to connect a Thunderbolt cable between the two hosts; the
``thunderbolt-net`` driver is loaded automatically. If the other host is
also Linux you should load ``thunderbolt-net`` manually on one host (it
does not matter which one)::

  # modprobe thunderbolt-net

This triggers module load on the other host automatically. If the driver
is built-in to the kernel image, there is no need to do anything.

The driver will create one virtual ethernet interface per Thunderbolt
port which are named like ``thunderbolt0`` and so on. From this point
you can either use standard userspace tools like ``ifconfig`` to
configure the interface or let your GUI handle it automatically.

Forcing power
-------------
Many OEMs include a method that can be used to force the power of a
Thunderbolt controller to an "On" state even if nothing is connected.
If supported by your machine this will be exposed by the WMI bus with
a sysfs attribute called "force_power".

For example the intel-wmi-thunderbolt driver exposes this attribute in:
  /sys/bus/wmi/devices/86CCFD48-205E-4A77-9C48-2021CBEDE341/force_power

  To force the power to on, write 1 to this attribute file.
  To disable force power, write 0 to this attribute file.

Note: it's currently not possible to query the force power state of a platform.


code:
=========
Using UFS
=========

mount -t ufs -o ufstype=type_of_ufs device dir

UFS Options
===========

ufstype=type_of_ufs
	UFS is a file system widely used in different operating systems.
	The problem are differences among implementations. Features of
	some implementations are undocumented, so its hard to recognize
	type of ufs automatically. That's why user must specify type of
	ufs manually by mount option ufstype. Possible values are:

	old
                old format of ufs
		default value, supported as read-only

	44bsd
                used in FreeBSD, NetBSD, OpenBSD
		supported as read-write

	ufs2
                used in FreeBSD 5.x
		supported as read-write

	5xbsd
                synonym for ufs2

	sun
                used in SunOS (Solaris)
		supported as read-write

	sunx86
                used in SunOS for Intel (Solarisx86)
		supported as read-write

	hp
                used in HP-UX
		supported as read-only

	nextstep
		used in NextStep
		supported as read-only

	nextstep-cd
		used for NextStep CDROMs (block_size == 2048)
		supported as read-only

	openstep
		used in OpenStep
		supported as read-only

Possible Problems
-----------------

See next section, if you have any.

Bug Reports
-----------

Any ufs bug report you can send to daniel.pirkl@email.cz or
to dushistov@mail.ru (do not send partition tables bug reports).


code:
Unicode support
===============

		 Last update: 2005-01-17, version 1.4

This file is maintained by H. Peter Anvin <unicode@lanana.org> as part
of the Linux Assigned Names And Numbers Authority (LANANA) project.
The current version can be found at:

	    http://www.lanana.org/docs/unicode/admin-guide/unicode.rst

Introduction
------------

The Linux kernel code has been rewritten to use Unicode to map
characters to fonts.  By downloading a single Unicode-to-font table,
both the eight-bit character sets and UTF-8 mode are changed to use
the font as indicated.

This changes the semantics of the eight-bit character tables subtly.
The four character tables are now:

=============== =============================== ================
Map symbol	Map name			Escape code (G0)
=============== =============================== ================
LAT1_MAP	Latin-1 (ISO 8859-1)		ESC ( B
GRAF_MAP	DEC VT100 pseudographics	ESC ( 0
IBMPC_MAP	IBM code page 437		ESC ( U
USER_MAP	User defined			ESC ( K
=============== =============================== ================

In particular, ESC ( U is no longer "straight to font", since the font
might be completely different than the IBM character set.  This
permits for example the use of block graphics even with a Latin-1 font
loaded.

Note that although these codes are similar to ISO 2022, neither the
codes nor their uses match ISO 2022; Linux has two 8-bit codes (G0 and
G1), whereas ISO 2022 has four 7-bit codes (G0-G3).

In accordance with the Unicode standard/ISO 10646 the range U+F000 to
U+F8FF has been reserved for OS-wide allocation (the Unicode Standard
refers to this as a "Corporate Zone", since this is inaccurate for
Linux we call it the "Linux Zone").  U+F000 was picked as the starting
point since it lets the direct-mapping area start on a large power of
two (in case 1024- or 2048-character fonts ever become necessary).
This leaves U+E000 to U+EFFF as End User Zone.

[v1.2]: The Unicodes range from U+F000 and up to U+F7FF have been
hard-coded to map directly to the loaded font, bypassing the
translation table.  The user-defined map now defaults to U+F000 to
U+F0FF, emulating the previous behaviour.  In practice, this range
might be shorter; for example, vgacon can only handle 256-character
(U+F000..U+F0FF) or 512-character (U+F000..U+F1FF) fonts.

Actual characters assigned in the Linux Zone
--------------------------------------------

In addition, the following characters not present in Unicode 1.1.4
have been defined; these are used by the DEC VT graphics map.  [v1.2]
THIS USE IS OBSOLETE AND SHOULD NO LONGER BE USED; PLEASE SEE BELOW.

====== ======================================
U+F800 DEC VT GRAPHICS HORIZONTAL LINE SCAN 1
U+F801 DEC VT GRAPHICS HORIZONTAL LINE SCAN 3
U+F803 DEC VT GRAPHICS HORIZONTAL LINE SCAN 7
U+F804 DEC VT GRAPHICS HORIZONTAL LINE SCAN 9
====== ======================================

The DEC VT220 uses a 6x10 character matrix, and these characters form
a smooth progression in the DEC VT graphics character set.  I have
omitted the scan 5 line, since it is also used as a block-graphics
character, and hence has been coded as U+2500 FORMS LIGHT HORIZONTAL.

[v1.3]: These characters have been officially added to Unicode 3.2.0;
they are added at U+23BA, U+23BB, U+23BC, U+23BD.  Linux now uses the
new values.

[v1.2]: The following characters have been added to represent common
keyboard symbols that are unlikely to ever be added to Unicode proper
since they are horribly vendor-specific.  This, of course, is an
excellent example of horrible design.

====== ======================================
U+F810 KEYBOARD SYMBOL FLYING FLAG
U+F811 KEYBOARD SYMBOL PULLDOWN MENU
U+F812 KEYBOARD SYMBOL OPEN APPLE
U+F813 KEYBOARD SYMBOL SOLID APPLE
====== ======================================

Klingon language support
------------------------

In 1996, Linux was the first operating system in the world to add
support for the artificial language Klingon, created by Marc Okrand
for the "Star Trek" television series.	This encoding was later
adopted by the ConScript Unicode Registry and proposed (but ultimately
rejected) for inclusion in Unicode Plane 1.  Thus, it remains as a
Linux/CSUR private assignment in the Linux Zone.

This encoding has been endorsed by the Klingon Language Institute.
For more information, contact them at:

	http://www.kli.org/

Since the characters in the beginning of the Linux CZ have been more
of the dingbats/symbols/forms type and this is a language, I have
located it at the end, on a 16-cell boundary in keeping with standard
Unicode practice.

.. note::

  This range is now officially managed by the ConScript Unicode
  Registry.  The normative reference is at:

	https://www.evertype.com/standards/csur/klingon.html

Klingon has an alphabet of 26 characters, a positional numeric writing
system with 10 digits, and is written left-to-right, top-to-bottom.

Several glyph forms for the Klingon alphabet have been proposed.
However, since the set of symbols appear to be consistent throughout,
with only the actual shapes being different, in keeping with standard
Unicode practice these differences are considered font variants.

======	=======================================================
U+F8D0	KLINGON LETTER A
U+F8D1	KLINGON LETTER B
U+F8D2	KLINGON LETTER CH
U+F8D3	KLINGON LETTER D
U+F8D4	KLINGON LETTER E
U+F8D5	KLINGON LETTER GH
U+F8D6	KLINGON LETTER H
U+F8D7	KLINGON LETTER I
U+F8D8	KLINGON LETTER J
U+F8D9	KLINGON LETTER L
U+F8DA	KLINGON LETTER M
U+F8DB	KLINGON LETTER N
U+F8DC	KLINGON LETTER NG
U+F8DD	KLINGON LETTER O
U+F8DE	KLINGON LETTER P
U+F8DF	KLINGON LETTER Q
	- Written <q> in standard Okrand Latin transliteration
U+F8E0	KLINGON LETTER QH
	- Written <Q> in standard Okrand Latin transliteration
U+F8E1	KLINGON LETTER R
U+F8E2	KLINGON LETTER S
U+F8E3	KLINGON LETTER T
U+F8E4	KLINGON LETTER TLH
U+F8E5	KLINGON LETTER U
U+F8E6	KLINGON LETTER V
U+F8E7	KLINGON LETTER W
U+F8E8	KLINGON LETTER Y
U+F8E9	KLINGON LETTER GLOTTAL STOP

U+F8F0	KLINGON DIGIT ZERO
U+F8F1	KLINGON DIGIT ONE
U+F8F2	KLINGON DIGIT TWO
U+F8F3	KLINGON DIGIT THREE
U+F8F4	KLINGON DIGIT FOUR
U+F8F5	KLINGON DIGIT FIVE
U+F8F6	KLINGON DIGIT SIX
U+F8F7	KLINGON DIGIT SEVEN
U+F8F8	KLINGON DIGIT EIGHT
U+F8F9	KLINGON DIGIT NINE

U+F8FD	KLINGON COMMA
U+F8FE	KLINGON FULL STOP
U+F8FF	KLINGON SYMBOL FOR EMPIRE
======	=======================================================

Other Fictional and Artificial Scripts
--------------------------------------

Since the assignment of the Klingon Linux Unicode block, a registry of
fictional and artificial scripts has been established by John Cowan
<jcowan@reutershealth.com> and Michael Everson <everson@evertype.com>.
The ConScript Unicode Registry is accessible at:

	  https://www.evertype.com/standards/csur/

The ranges used fall at the low end of the End User Zone and can hence
not be normatively assigned, but it is recommended that people who
wish to encode fictional scripts use these codes, in the interest of
interoperability.  For Klingon, CSUR has adopted the Linux encoding.
The CSUR people are driving adding Tengwar and Cirth into Unicode
Plane 1; the addition of Klingon to Unicode Plane 1 has been rejected
and so the above encoding remains official.


code:
Software cursor for VGA
=======================

by Pavel Machek <pavel@atrey.karlin.mff.cuni.cz>
and Martin Mares <mj@atrey.karlin.mff.cuni.cz>

Linux now has some ability to manipulate cursor appearance.  Normally,
you can set the size of hardware cursor.  You can now play a few new
tricks: you can make your cursor look like a non-blinking red block,
make it inverse background of the character it's over or to highlight
that character and still choose whether the original hardware cursor
should remain visible or not.  There may be other things I have never
thought of.

The cursor appearance is controlled by a ``<ESC>[?1;2;3c`` escape sequence
where 1, 2 and 3 are parameters described below. If you omit any of them,
they will default to zeroes.

first Parameter
	specifies cursor size::

		0=default
		1=invisible
		2=underline,
		...
		8=full block
		+ 16 if you want the software cursor to be applied
		+ 32 if you want to always change the background color
		+ 64 if you dislike having the background the same as the
		     foreground.

	Highlights are ignored for the last two flags.

second parameter
	selects character attribute bits you want to change
	(by simply XORing them with the value of this parameter). On standard
	VGA, the high four bits specify background and the low four the
	foreground. In both groups, low three bits set color (as in normal
	color codes used by the console) and the most significant one turns
	on highlight (or sometimes blinking -- it depends on the configuration
	of your VGA).

third parameter
	consists of character attribute bits you want to set.

	Bit setting takes place before bit toggling, so you can simply clear a
	bit by including it in both the set mask and the toggle mask.

Examples
--------

To get normal blinking underline, use::

	echo -e '\033[?2c'

To get blinking block, use::

	echo -e '\033[?6c'

To get red non-blinking block, use::

	echo -e '\033[?17;0;64c'


code:
Video Output Switcher Control
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

2006 luming.yu@intel.com

The output sysfs class driver provides an abstract video output layer that
can be used to hook platform specific methods to enable/disable video output
device through common sysfs interface. For example, on my IBM ThinkPad T42
laptop, The ACPI video driver registered its output devices and read/write
method for 'state' with output sysfs class. The user interface under sysfs is::

  linux:/sys/class/video_output # tree .
  .
  |-- CRT0
  |   |-- device -> ../../../devices/pci0000:00/0000:00:01.0
  |   |-- state
  |   |-- subsystem -> ../../../class/video_output
  |   `-- uevent
  |-- DVI0
  |   |-- device -> ../../../devices/pci0000:00/0000:00:01.0
  |   |-- state
  |   |-- subsystem -> ../../../class/video_output
  |   `-- uevent
  |-- LCD0
  |   |-- device -> ../../../devices/pci0000:00/0000:00:01.0
  |   |-- state
  |   |-- subsystem -> ../../../class/video_output
  |   `-- uevent
  `-- TV0
     |-- device -> ../../../devices/pci0000:00/0000:00:01.0
     |-- state
     |-- subsystem -> ../../../class/video_output
     `-- uevent