numa_memory_policy.rst 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. ==================
  2. NUMA Memory Policy
  3. ==================
  4. What is NUMA Memory Policy?
  5. ============================
  6. In the Linux kernel, "memory policy" determines from which node the kernel will
  7. allocate memory in a NUMA system or in an emulated NUMA system. Linux has
  8. supported platforms with Non-Uniform Memory Access architectures since 2.4.?.
  9. The current memory policy support was added to Linux 2.6 around May 2004. This
  10. document attempts to describe the concepts and APIs of the 2.6 memory policy
  11. support.
  12. Memory policies should not be confused with cpusets
  13. (``Documentation/admin-guide/cgroup-v1/cpusets.rst``)
  14. which is an administrative mechanism for restricting the nodes from which
  15. memory may be allocated by a set of processes. Memory policies are a
  16. programming interface that a NUMA-aware application can take advantage of. When
  17. both cpusets and policies are applied to a task, the restrictions of the cpuset
  18. takes priority. See :ref:`Memory Policies and cpusets <mem_pol_and_cpusets>`
  19. below for more details.
  20. Memory Policy Concepts
  21. ======================
  22. Scope of Memory Policies
  23. ------------------------
  24. The Linux kernel supports _scopes_ of memory policy, described here from
  25. most general to most specific:
  26. System Default Policy
  27. this policy is "hard coded" into the kernel. It is the policy
  28. that governs all page allocations that aren't controlled by
  29. one of the more specific policy scopes discussed below. When
  30. the system is "up and running", the system default policy will
  31. use "local allocation" described below. However, during boot
  32. up, the system default policy will be set to interleave
  33. allocations across all nodes with "sufficient" memory, so as
  34. not to overload the initial boot node with boot-time
  35. allocations.
  36. Task/Process Policy
  37. this is an optional, per-task policy. When defined for a
  38. specific task, this policy controls all page allocations made
  39. by or on behalf of the task that aren't controlled by a more
  40. specific scope. If a task does not define a task policy, then
  41. all page allocations that would have been controlled by the
  42. task policy "fall back" to the System Default Policy.
  43. The task policy applies to the entire address space of a task. Thus,
  44. it is inheritable, and indeed is inherited, across both fork()
  45. [clone() w/o the CLONE_VM flag] and exec*(). This allows a parent task
  46. to establish the task policy for a child task exec()'d from an
  47. executable image that has no awareness of memory policy. See the
  48. :ref:`Memory Policy APIs <memory_policy_apis>` section,
  49. below, for an overview of the system call
  50. that a task may use to set/change its task/process policy.
  51. In a multi-threaded task, task policies apply only to the thread
  52. [Linux kernel task] that installs the policy and any threads
  53. subsequently created by that thread. Any sibling threads existing
  54. at the time a new task policy is installed retain their current
  55. policy.
  56. A task policy applies only to pages allocated after the policy is
  57. installed. Any pages already faulted in by the task when the task
  58. changes its task policy remain where they were allocated based on
  59. the policy at the time they were allocated.
  60. .. _vma_policy:
  61. VMA Policy
  62. A "VMA" or "Virtual Memory Area" refers to a range of a task's
  63. virtual address space. A task may define a specific policy for a range
  64. of its virtual address space. See the
  65. :ref:`Memory Policy APIs <memory_policy_apis>` section,
  66. below, for an overview of the mbind() system call used to set a VMA
  67. policy.
  68. A VMA policy will govern the allocation of pages that back
  69. this region of the address space. Any regions of the task's
  70. address space that don't have an explicit VMA policy will fall
  71. back to the task policy, which may itself fall back to the
  72. System Default Policy.
  73. VMA policies have a few complicating details:
  74. * VMA policy applies ONLY to anonymous pages. These include
  75. pages allocated for anonymous segments, such as the task
  76. stack and heap, and any regions of the address space
  77. mmap()ed with the MAP_ANONYMOUS flag. If a VMA policy is
  78. applied to a file mapping, it will be ignored if the mapping
  79. used the MAP_SHARED flag. If the file mapping used the
  80. MAP_PRIVATE flag, the VMA policy will only be applied when
  81. an anonymous page is allocated on an attempt to write to the
  82. mapping-- i.e., at Copy-On-Write.
  83. * VMA policies are shared between all tasks that share a
  84. virtual address space--a.k.a. threads--independent of when
  85. the policy is installed; and they are inherited across
  86. fork(). However, because VMA policies refer to a specific
  87. region of a task's address space, and because the address
  88. space is discarded and recreated on exec*(), VMA policies
  89. are NOT inheritable across exec(). Thus, only NUMA-aware
  90. applications may use VMA policies.
  91. * A task may install a new VMA policy on a sub-range of a
  92. previously mmap()ed region. When this happens, Linux splits
  93. the existing virtual memory area into 2 or 3 VMAs, each with
  94. its own policy.
  95. * By default, VMA policy applies only to pages allocated after
  96. the policy is installed. Any pages already faulted into the
  97. VMA range remain where they were allocated based on the
  98. policy at the time they were allocated. However, since
  99. 2.6.16, Linux supports page migration via the mbind() system
  100. call, so that page contents can be moved to match a newly
  101. installed policy.
  102. Shared Policy
  103. Conceptually, shared policies apply to "memory objects" mapped
  104. shared into one or more tasks' distinct address spaces. An
  105. application installs shared policies the same way as VMA
  106. policies--using the mbind() system call specifying a range of
  107. virtual addresses that map the shared object. However, unlike
  108. VMA policies, which can be considered to be an attribute of a
  109. range of a task's address space, shared policies apply
  110. directly to the shared object. Thus, all tasks that attach to
  111. the object share the policy, and all pages allocated for the
  112. shared object, by any task, will obey the shared policy.
  113. As of 2.6.22, only shared memory segments, created by shmget() or
  114. mmap(MAP_ANONYMOUS|MAP_SHARED), support shared policy. When shared
  115. policy support was added to Linux, the associated data structures were
  116. added to hugetlbfs shmem segments. At the time, hugetlbfs did not
  117. support allocation at fault time--a.k.a lazy allocation--so hugetlbfs
  118. shmem segments were never "hooked up" to the shared policy support.
  119. Although hugetlbfs segments now support lazy allocation, their support
  120. for shared policy has not been completed.
  121. As mentioned above in :ref:`VMA policies <vma_policy>` section,
  122. allocations of page cache pages for regular files mmap()ed
  123. with MAP_SHARED ignore any VMA policy installed on the virtual
  124. address range backed by the shared file mapping. Rather,
  125. shared page cache pages, including pages backing private
  126. mappings that have not yet been written by the task, follow
  127. task policy, if any, else System Default Policy.
  128. The shared policy infrastructure supports different policies on subset
  129. ranges of the shared object. However, Linux still splits the VMA of
  130. the task that installs the policy for each range of distinct policy.
  131. Thus, different tasks that attach to a shared memory segment can have
  132. different VMA configurations mapping that one shared object. This
  133. can be seen by examining the /proc/<pid>/numa_maps of tasks sharing
  134. a shared memory region, when one task has installed shared policy on
  135. one or more ranges of the region.
  136. Components of Memory Policies
  137. -----------------------------
  138. A NUMA memory policy consists of a "mode", optional mode flags, and
  139. an optional set of nodes. The mode determines the behavior of the
  140. policy, the optional mode flags determine the behavior of the mode,
  141. and the optional set of nodes can be viewed as the arguments to the
  142. policy behavior.
  143. Internally, memory policies are implemented by a reference counted
  144. structure, struct mempolicy. Details of this structure will be
  145. discussed in context, below, as required to explain the behavior.
  146. NUMA memory policy supports the following 4 behavioral modes:
  147. Default Mode--MPOL_DEFAULT
  148. This mode is only used in the memory policy APIs. Internally,
  149. MPOL_DEFAULT is converted to the NULL memory policy in all
  150. policy scopes. Any existing non-default policy will simply be
  151. removed when MPOL_DEFAULT is specified. As a result,
  152. MPOL_DEFAULT means "fall back to the next most specific policy
  153. scope."
  154. For example, a NULL or default task policy will fall back to the
  155. system default policy. A NULL or default vma policy will fall
  156. back to the task policy.
  157. When specified in one of the memory policy APIs, the Default mode
  158. does not use the optional set of nodes.
  159. It is an error for the set of nodes specified for this policy to
  160. be non-empty.
  161. MPOL_BIND
  162. This mode specifies that memory must come from the set of
  163. nodes specified by the policy. Memory will be allocated from
  164. the node in the set with sufficient free memory that is
  165. closest to the node where the allocation takes place.
  166. MPOL_PREFERRED
  167. This mode specifies that the allocation should be attempted
  168. from the single node specified in the policy. If that
  169. allocation fails, the kernel will search other nodes, in order
  170. of increasing distance from the preferred node based on
  171. information provided by the platform firmware.
  172. Internally, the Preferred policy uses a single node--the
  173. preferred_node member of struct mempolicy. When the internal
  174. mode flag MPOL_F_LOCAL is set, the preferred_node is ignored
  175. and the policy is interpreted as local allocation. "Local"
  176. allocation policy can be viewed as a Preferred policy that
  177. starts at the node containing the cpu where the allocation
  178. takes place.
  179. It is possible for the user to specify that local allocation
  180. is always preferred by passing an empty nodemask with this
  181. mode. If an empty nodemask is passed, the policy cannot use
  182. the MPOL_F_STATIC_NODES or MPOL_F_RELATIVE_NODES flags
  183. described below.
  184. MPOL_INTERLEAVED
  185. This mode specifies that page allocations be interleaved, on a
  186. page granularity, across the nodes specified in the policy.
  187. This mode also behaves slightly differently, based on the
  188. context where it is used:
  189. For allocation of anonymous pages and shared memory pages,
  190. Interleave mode indexes the set of nodes specified by the
  191. policy using the page offset of the faulting address into the
  192. segment [VMA] containing the address modulo the number of
  193. nodes specified by the policy. It then attempts to allocate a
  194. page, starting at the selected node, as if the node had been
  195. specified by a Preferred policy or had been selected by a
  196. local allocation. That is, allocation will follow the per
  197. node zonelist.
  198. For allocation of page cache pages, Interleave mode indexes
  199. the set of nodes specified by the policy using a node counter
  200. maintained per task. This counter wraps around to the lowest
  201. specified node after it reaches the highest specified node.
  202. This will tend to spread the pages out over the nodes
  203. specified by the policy based on the order in which they are
  204. allocated, rather than based on any page offset into an
  205. address range or file. During system boot up, the temporary
  206. interleaved system default policy works in this mode.
  207. MPOL_PREFERRED_MANY
  208. This mode specifies that the allocation should be preferably
  209. satisfied from the nodemask specified in the policy. If there is
  210. a memory pressure on all nodes in the nodemask, the allocation
  211. can fall back to all existing numa nodes. This is effectively
  212. MPOL_PREFERRED allowed for a mask rather than a single node.
  213. MPOL_WEIGHTED_INTERLEAVE
  214. This mode operates the same as MPOL_INTERLEAVE, except that
  215. interleaving behavior is executed based on weights set in
  216. /sys/kernel/mm/mempolicy/weighted_interleave/
  217. Weighted interleave allocates pages on nodes according to a
  218. weight. For example if nodes [0,1] are weighted [5,2], 5 pages
  219. will be allocated on node0 for every 2 pages allocated on node1.
  220. NUMA memory policy supports the following optional mode flags:
  221. MPOL_F_STATIC_NODES
  222. This flag specifies that the nodemask passed by
  223. the user should not be remapped if the task or VMA's set of allowed
  224. nodes changes after the memory policy has been defined.
  225. Without this flag, any time a mempolicy is rebound because of a
  226. change in the set of allowed nodes, the preferred nodemask (Preferred
  227. Many), preferred node (Preferred) or nodemask (Bind, Interleave) is
  228. remapped to the new set of allowed nodes. This may result in nodes
  229. being used that were previously undesired.
  230. With this flag, if the user-specified nodes overlap with the
  231. nodes allowed by the task's cpuset, then the memory policy is
  232. applied to their intersection. If the two sets of nodes do not
  233. overlap, the Default policy is used.
  234. For example, consider a task that is attached to a cpuset with
  235. mems 1-3 that sets an Interleave policy over the same set. If
  236. the cpuset's mems change to 3-5, the Interleave will now occur
  237. over nodes 3, 4, and 5. With this flag, however, since only node
  238. 3 is allowed from the user's nodemask, the "interleave" only
  239. occurs over that node. If no nodes from the user's nodemask are
  240. now allowed, the Default behavior is used.
  241. MPOL_F_STATIC_NODES cannot be combined with the
  242. MPOL_F_RELATIVE_NODES flag. It also cannot be used for
  243. MPOL_PREFERRED policies that were created with an empty nodemask
  244. (local allocation).
  245. MPOL_F_RELATIVE_NODES
  246. This flag specifies that the nodemask passed
  247. by the user will be mapped relative to the set of the task or VMA's
  248. set of allowed nodes. The kernel stores the user-passed nodemask,
  249. and if the allowed nodes changes, then that original nodemask will
  250. be remapped relative to the new set of allowed nodes.
  251. Without this flag (and without MPOL_F_STATIC_NODES), anytime a
  252. mempolicy is rebound because of a change in the set of allowed
  253. nodes, the node (Preferred) or nodemask (Bind, Interleave) is
  254. remapped to the new set of allowed nodes. That remap may not
  255. preserve the relative nature of the user's passed nodemask to its
  256. set of allowed nodes upon successive rebinds: a nodemask of
  257. 1,3,5 may be remapped to 7-9 and then to 1-3 if the set of
  258. allowed nodes is restored to its original state.
  259. With this flag, the remap is done so that the node numbers from
  260. the user's passed nodemask are relative to the set of allowed
  261. nodes. In other words, if nodes 0, 2, and 4 are set in the user's
  262. nodemask, the policy will be effected over the first (and in the
  263. Bind or Interleave case, the third and fifth) nodes in the set of
  264. allowed nodes. The nodemask passed by the user represents nodes
  265. relative to task or VMA's set of allowed nodes.
  266. If the user's nodemask includes nodes that are outside the range
  267. of the new set of allowed nodes (for example, node 5 is set in
  268. the user's nodemask when the set of allowed nodes is only 0-3),
  269. then the remap wraps around to the beginning of the nodemask and,
  270. if not already set, sets the node in the mempolicy nodemask.
  271. For example, consider a task that is attached to a cpuset with
  272. mems 2-5 that sets an Interleave policy over the same set with
  273. MPOL_F_RELATIVE_NODES. If the cpuset's mems change to 3-7, the
  274. interleave now occurs over nodes 3,5-7. If the cpuset's mems
  275. then change to 0,2-3,5, then the interleave occurs over nodes
  276. 0,2-3,5.
  277. Thanks to the consistent remapping, applications preparing
  278. nodemasks to specify memory policies using this flag should
  279. disregard their current, actual cpuset imposed memory placement
  280. and prepare the nodemask as if they were always located on
  281. memory nodes 0 to N-1, where N is the number of memory nodes the
  282. policy is intended to manage. Let the kernel then remap to the
  283. set of memory nodes allowed by the task's cpuset, as that may
  284. change over time.
  285. MPOL_F_RELATIVE_NODES cannot be combined with the
  286. MPOL_F_STATIC_NODES flag. It also cannot be used for
  287. MPOL_PREFERRED policies that were created with an empty nodemask
  288. (local allocation).
  289. Memory Policy Reference Counting
  290. ================================
  291. To resolve use/free races, struct mempolicy contains an atomic reference
  292. count field. Internal interfaces, mpol_get()/mpol_put() increment and
  293. decrement this reference count, respectively. mpol_put() will only free
  294. the structure back to the mempolicy kmem cache when the reference count
  295. goes to zero.
  296. When a new memory policy is allocated, its reference count is initialized
  297. to '1', representing the reference held by the task that is installing the
  298. new policy. When a pointer to a memory policy structure is stored in another
  299. structure, another reference is added, as the task's reference will be dropped
  300. on completion of the policy installation.
  301. During run-time "usage" of the policy, we attempt to minimize atomic operations
  302. on the reference count, as this can lead to cache lines bouncing between cpus
  303. and NUMA nodes. "Usage" here means one of the following:
  304. 1) querying of the policy, either by the task itself [using the get_mempolicy()
  305. API discussed below] or by another task using the /proc/<pid>/numa_maps
  306. interface.
  307. 2) examination of the policy to determine the policy mode and associated node
  308. or node lists, if any, for page allocation. This is considered a "hot
  309. path". Note that for MPOL_BIND, the "usage" extends across the entire
  310. allocation process, which may sleep during page reclamation, because the
  311. BIND policy nodemask is used, by reference, to filter ineligible nodes.
  312. We can avoid taking an extra reference during the usages listed above as
  313. follows:
  314. 1) we never need to get/free the system default policy as this is never
  315. changed nor freed, once the system is up and running.
  316. 2) for querying the policy, we do not need to take an extra reference on the
  317. target task's task policy nor vma policies because we always acquire the
  318. task's mm's mmap_lock for read during the query. The set_mempolicy() and
  319. mbind() APIs [see below] always acquire the mmap_lock for write when
  320. installing or replacing task or vma policies. Thus, there is no possibility
  321. of a task or thread freeing a policy while another task or thread is
  322. querying it.
  323. 3) Page allocation usage of task or vma policy occurs in the fault path where
  324. we hold them mmap_lock for read. Again, because replacing the task or vma
  325. policy requires that the mmap_lock be held for write, the policy can't be
  326. freed out from under us while we're using it for page allocation.
  327. 4) Shared policies require special consideration. One task can replace a
  328. shared memory policy while another task, with a distinct mmap_lock, is
  329. querying or allocating a page based on the policy. To resolve this
  330. potential race, the shared policy infrastructure adds an extra reference
  331. to the shared policy during lookup while holding a spin lock on the shared
  332. policy management structure. This requires that we drop this extra
  333. reference when we're finished "using" the policy. We must drop the
  334. extra reference on shared policies in the same query/allocation paths
  335. used for non-shared policies. For this reason, shared policies are marked
  336. as such, and the extra reference is dropped "conditionally"--i.e., only
  337. for shared policies.
  338. Because of this extra reference counting, and because we must lookup
  339. shared policies in a tree structure under spinlock, shared policies are
  340. more expensive to use in the page allocation path. This is especially
  341. true for shared policies on shared memory regions shared by tasks running
  342. on different NUMA nodes. This extra overhead can be avoided by always
  343. falling back to task or system default policy for shared memory regions,
  344. or by prefaulting the entire shared memory region into memory and locking
  345. it down. However, this might not be appropriate for all applications.
  346. .. _memory_policy_apis:
  347. Memory Policy APIs
  348. ==================
  349. Linux supports 4 system calls for controlling memory policy. These APIS
  350. always affect only the calling task, the calling task's address space, or
  351. some shared object mapped into the calling task's address space.
  352. .. note::
  353. the headers that define these APIs and the parameter data types for
  354. user space applications reside in a package that is not part of the
  355. Linux kernel. The kernel system call interfaces, with the 'sys\_'
  356. prefix, are defined in <linux/syscalls.h>; the mode and flag
  357. definitions are defined in <linux/mempolicy.h>.
  358. Set [Task] Memory Policy::
  359. long set_mempolicy(int mode, const unsigned long *nmask,
  360. unsigned long maxnode);
  361. Set's the calling task's "task/process memory policy" to mode
  362. specified by the 'mode' argument and the set of nodes defined by
  363. 'nmask'. 'nmask' points to a bit mask of node ids containing at least
  364. 'maxnode' ids. Optional mode flags may be passed by combining the
  365. 'mode' argument with the flag (for example: MPOL_INTERLEAVE |
  366. MPOL_F_STATIC_NODES).
  367. See the set_mempolicy(2) man page for more details
  368. Get [Task] Memory Policy or Related Information::
  369. long get_mempolicy(int *mode,
  370. const unsigned long *nmask, unsigned long maxnode,
  371. void *addr, int flags);
  372. Queries the "task/process memory policy" of the calling task, or the
  373. policy or location of a specified virtual address, depending on the
  374. 'flags' argument.
  375. See the get_mempolicy(2) man page for more details
  376. Install VMA/Shared Policy for a Range of Task's Address Space::
  377. long mbind(void *start, unsigned long len, int mode,
  378. const unsigned long *nmask, unsigned long maxnode,
  379. unsigned flags);
  380. mbind() installs the policy specified by (mode, nmask, maxnodes) as a
  381. VMA policy for the range of the calling task's address space specified
  382. by the 'start' and 'len' arguments. Additional actions may be
  383. requested via the 'flags' argument.
  384. See the mbind(2) man page for more details.
  385. Set home node for a Range of Task's Address Spacec::
  386. long sys_set_mempolicy_home_node(unsigned long start, unsigned long len,
  387. unsigned long home_node,
  388. unsigned long flags);
  389. sys_set_mempolicy_home_node set the home node for a VMA policy present in the
  390. task's address range. The system call updates the home node only for the existing
  391. mempolicy range. Other address ranges are ignored. A home node is the NUMA node
  392. closest to which page allocation will come from. Specifying the home node override
  393. the default allocation policy to allocate memory close to the local node for an
  394. executing CPU.
  395. Memory Policy Command Line Interface
  396. ====================================
  397. Although not strictly part of the Linux implementation of memory policy,
  398. a command line tool, numactl(8), exists that allows one to:
  399. + set the task policy for a specified program via set_mempolicy(2), fork(2) and
  400. exec(2)
  401. + set the shared policy for a shared memory segment via mbind(2)
  402. The numactl(8) tool is packaged with the run-time version of the library
  403. containing the memory policy system call wrappers. Some distributions
  404. package the headers and compile-time libraries in a separate development
  405. package.
  406. .. _mem_pol_and_cpusets:
  407. Memory Policies and cpusets
  408. ===========================
  409. Memory policies work within cpusets as described above. For memory policies
  410. that require a node or set of nodes, the nodes are restricted to the set of
  411. nodes whose memories are allowed by the cpuset constraints. If the nodemask
  412. specified for the policy contains nodes that are not allowed by the cpuset and
  413. MPOL_F_RELATIVE_NODES is not used, the intersection of the set of nodes
  414. specified for the policy and the set of nodes with memory is used. If the
  415. result is the empty set, the policy is considered invalid and cannot be
  416. installed. If MPOL_F_RELATIVE_NODES is used, the policy's nodes are mapped
  417. onto and folded into the task's set of allowed nodes as previously described.
  418. The interaction of memory policies and cpusets can be problematic when tasks
  419. in two cpusets share access to a memory region, such as shared memory segments
  420. created by shmget() of mmap() with the MAP_ANONYMOUS and MAP_SHARED flags, and
  421. any of the tasks install shared policy on the region, only nodes whose
  422. memories are allowed in both cpusets may be used in the policies. Obtaining
  423. this information requires "stepping outside" the memory policy APIs to use the
  424. cpuset information and requires that one know in what cpusets other task might
  425. be attaching to the shared region. Furthermore, if the cpusets' allowed
  426. memory sets are disjoint, "local" allocation is the only valid policy.