mempolicy.c 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Simple NUMA memory policy for the Linux kernel.
  4. *
  5. * Copyright 2003,2004 Andi Kleen, SuSE Labs.
  6. * (C) Copyright 2005 Christoph Lameter, Silicon Graphics, Inc.
  7. *
  8. * NUMA policy allows the user to give hints in which node(s) memory should
  9. * be allocated.
  10. *
  11. * Support four policies per VMA and per process:
  12. *
  13. * The VMA policy has priority over the process policy for a page fault.
  14. *
  15. * interleave Allocate memory interleaved over a set of nodes,
  16. * with normal fallback if it fails.
  17. * For VMA based allocations this interleaves based on the
  18. * offset into the backing object or offset into the mapping
  19. * for anonymous memory. For process policy an process counter
  20. * is used.
  21. *
  22. * weighted interleave
  23. * Allocate memory interleaved over a set of nodes based on
  24. * a set of weights (per-node), with normal fallback if it
  25. * fails. Otherwise operates the same as interleave.
  26. * Example: nodeset(0,1) & weights (2,1) - 2 pages allocated
  27. * on node 0 for every 1 page allocated on node 1.
  28. *
  29. * bind Only allocate memory on a specific set of nodes,
  30. * no fallback.
  31. * FIXME: memory is allocated starting with the first node
  32. * to the last. It would be better if bind would truly restrict
  33. * the allocation to memory nodes instead
  34. *
  35. * preferred Try a specific node first before normal fallback.
  36. * As a special case NUMA_NO_NODE here means do the allocation
  37. * on the local CPU. This is normally identical to default,
  38. * but useful to set in a VMA when you have a non default
  39. * process policy.
  40. *
  41. * preferred many Try a set of nodes first before normal fallback. This is
  42. * similar to preferred without the special case.
  43. *
  44. * default Allocate on the local node first, or when on a VMA
  45. * use the process policy. This is what Linux always did
  46. * in a NUMA aware kernel and still does by, ahem, default.
  47. *
  48. * The process policy is applied for most non interrupt memory allocations
  49. * in that process' context. Interrupts ignore the policies and always
  50. * try to allocate on the local CPU. The VMA policy is only applied for memory
  51. * allocations for a VMA in the VM.
  52. *
  53. * Currently there are a few corner cases in swapping where the policy
  54. * is not applied, but the majority should be handled. When process policy
  55. * is used it is not remembered over swap outs/swap ins.
  56. *
  57. * Only the highest zone in the zone hierarchy gets policied. Allocations
  58. * requesting a lower zone just use default policy. This implies that
  59. * on systems with highmem kernel lowmem allocation don't get policied.
  60. * Same with GFP_DMA allocations.
  61. *
  62. * For shmem/tmpfs shared memory the policy is shared between
  63. * all users and remembered even when nobody has memory mapped.
  64. */
  65. /* Notebook:
  66. fix mmap readahead to honour policy and enable policy for any page cache
  67. object
  68. statistics for bigpages
  69. global policy for page cache? currently it uses process policy. Requires
  70. first item above.
  71. handle mremap for shared memory (currently ignored for the policy)
  72. grows down?
  73. make bind policy root only? It can trigger oom much faster and the
  74. kernel is not always grateful with that.
  75. */
  76. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  77. #include <linux/mempolicy.h>
  78. #include <linux/pagewalk.h>
  79. #include <linux/highmem.h>
  80. #include <linux/hugetlb.h>
  81. #include <linux/kernel.h>
  82. #include <linux/sched.h>
  83. #include <linux/sched/mm.h>
  84. #include <linux/sched/numa_balancing.h>
  85. #include <linux/sched/task.h>
  86. #include <linux/nodemask.h>
  87. #include <linux/cpuset.h>
  88. #include <linux/slab.h>
  89. #include <linux/string.h>
  90. #include <linux/export.h>
  91. #include <linux/nsproxy.h>
  92. #include <linux/interrupt.h>
  93. #include <linux/init.h>
  94. #include <linux/compat.h>
  95. #include <linux/ptrace.h>
  96. #include <linux/swap.h>
  97. #include <linux/seq_file.h>
  98. #include <linux/proc_fs.h>
  99. #include <linux/migrate.h>
  100. #include <linux/ksm.h>
  101. #include <linux/rmap.h>
  102. #include <linux/security.h>
  103. #include <linux/syscalls.h>
  104. #include <linux/ctype.h>
  105. #include <linux/mm_inline.h>
  106. #include <linux/mmu_notifier.h>
  107. #include <linux/printk.h>
  108. #include <linux/swapops.h>
  109. #include <asm/tlbflush.h>
  110. #include <asm/tlb.h>
  111. #include <linux/uaccess.h>
  112. #include "internal.h"
  113. /* Internal flags */
  114. #define MPOL_MF_DISCONTIG_OK (MPOL_MF_INTERNAL << 0) /* Skip checks for continuous vmas */
  115. #define MPOL_MF_INVERT (MPOL_MF_INTERNAL << 1) /* Invert check for nodemask */
  116. #define MPOL_MF_WRLOCK (MPOL_MF_INTERNAL << 2) /* Write-lock walked vmas */
  117. static struct kmem_cache *policy_cache;
  118. static struct kmem_cache *sn_cache;
  119. /* Highest zone. An specific allocation for a zone below that is not
  120. policied. */
  121. enum zone_type policy_zone = 0;
  122. /*
  123. * run-time system-wide default policy => local allocation
  124. */
  125. static struct mempolicy default_policy = {
  126. .refcnt = ATOMIC_INIT(1), /* never free it */
  127. .mode = MPOL_LOCAL,
  128. };
  129. static struct mempolicy preferred_node_policy[MAX_NUMNODES];
  130. /*
  131. * iw_table is the sysfs-set interleave weight table, a value of 0 denotes
  132. * system-default value should be used. A NULL iw_table also denotes that
  133. * system-default values should be used. Until the system-default table
  134. * is implemented, the system-default is always 1.
  135. *
  136. * iw_table is RCU protected
  137. */
  138. static u8 __rcu *iw_table;
  139. static DEFINE_MUTEX(iw_table_lock);
  140. static u8 get_il_weight(int node)
  141. {
  142. u8 *table;
  143. u8 weight;
  144. rcu_read_lock();
  145. table = rcu_dereference(iw_table);
  146. /* if no iw_table, use system default */
  147. weight = table ? table[node] : 1;
  148. /* if value in iw_table is 0, use system default */
  149. weight = weight ? weight : 1;
  150. rcu_read_unlock();
  151. return weight;
  152. }
  153. /**
  154. * numa_nearest_node - Find nearest node by state
  155. * @node: Node id to start the search
  156. * @state: State to filter the search
  157. *
  158. * Lookup the closest node by distance if @nid is not in state.
  159. *
  160. * Return: this @node if it is in state, otherwise the closest node by distance
  161. */
  162. int numa_nearest_node(int node, unsigned int state)
  163. {
  164. int min_dist = INT_MAX, dist, n, min_node;
  165. if (state >= NR_NODE_STATES)
  166. return -EINVAL;
  167. if (node == NUMA_NO_NODE || node_state(node, state))
  168. return node;
  169. min_node = node;
  170. for_each_node_state(n, state) {
  171. dist = node_distance(node, n);
  172. if (dist < min_dist) {
  173. min_dist = dist;
  174. min_node = n;
  175. }
  176. }
  177. return min_node;
  178. }
  179. EXPORT_SYMBOL_GPL(numa_nearest_node);
  180. struct mempolicy *get_task_policy(struct task_struct *p)
  181. {
  182. struct mempolicy *pol = p->mempolicy;
  183. int node;
  184. if (pol)
  185. return pol;
  186. node = numa_node_id();
  187. if (node != NUMA_NO_NODE) {
  188. pol = &preferred_node_policy[node];
  189. /* preferred_node_policy is not initialised early in boot */
  190. if (pol->mode)
  191. return pol;
  192. }
  193. return &default_policy;
  194. }
  195. static const struct mempolicy_operations {
  196. int (*create)(struct mempolicy *pol, const nodemask_t *nodes);
  197. void (*rebind)(struct mempolicy *pol, const nodemask_t *nodes);
  198. } mpol_ops[MPOL_MAX];
  199. static inline int mpol_store_user_nodemask(const struct mempolicy *pol)
  200. {
  201. return pol->flags & MPOL_MODE_FLAGS;
  202. }
  203. static void mpol_relative_nodemask(nodemask_t *ret, const nodemask_t *orig,
  204. const nodemask_t *rel)
  205. {
  206. nodemask_t tmp;
  207. nodes_fold(tmp, *orig, nodes_weight(*rel));
  208. nodes_onto(*ret, tmp, *rel);
  209. }
  210. static int mpol_new_nodemask(struct mempolicy *pol, const nodemask_t *nodes)
  211. {
  212. if (nodes_empty(*nodes))
  213. return -EINVAL;
  214. pol->nodes = *nodes;
  215. return 0;
  216. }
  217. static int mpol_new_preferred(struct mempolicy *pol, const nodemask_t *nodes)
  218. {
  219. if (nodes_empty(*nodes))
  220. return -EINVAL;
  221. nodes_clear(pol->nodes);
  222. node_set(first_node(*nodes), pol->nodes);
  223. return 0;
  224. }
  225. /*
  226. * mpol_set_nodemask is called after mpol_new() to set up the nodemask, if
  227. * any, for the new policy. mpol_new() has already validated the nodes
  228. * parameter with respect to the policy mode and flags.
  229. *
  230. * Must be called holding task's alloc_lock to protect task's mems_allowed
  231. * and mempolicy. May also be called holding the mmap_lock for write.
  232. */
  233. static int mpol_set_nodemask(struct mempolicy *pol,
  234. const nodemask_t *nodes, struct nodemask_scratch *nsc)
  235. {
  236. int ret;
  237. /*
  238. * Default (pol==NULL) resp. local memory policies are not a
  239. * subject of any remapping. They also do not need any special
  240. * constructor.
  241. */
  242. if (!pol || pol->mode == MPOL_LOCAL)
  243. return 0;
  244. /* Check N_MEMORY */
  245. nodes_and(nsc->mask1,
  246. cpuset_current_mems_allowed, node_states[N_MEMORY]);
  247. VM_BUG_ON(!nodes);
  248. if (pol->flags & MPOL_F_RELATIVE_NODES)
  249. mpol_relative_nodemask(&nsc->mask2, nodes, &nsc->mask1);
  250. else
  251. nodes_and(nsc->mask2, *nodes, nsc->mask1);
  252. if (mpol_store_user_nodemask(pol))
  253. pol->w.user_nodemask = *nodes;
  254. else
  255. pol->w.cpuset_mems_allowed = cpuset_current_mems_allowed;
  256. ret = mpol_ops[pol->mode].create(pol, &nsc->mask2);
  257. return ret;
  258. }
  259. /*
  260. * This function just creates a new policy, does some check and simple
  261. * initialization. You must invoke mpol_set_nodemask() to set nodes.
  262. */
  263. static struct mempolicy *mpol_new(unsigned short mode, unsigned short flags,
  264. nodemask_t *nodes)
  265. {
  266. struct mempolicy *policy;
  267. if (mode == MPOL_DEFAULT) {
  268. if (nodes && !nodes_empty(*nodes))
  269. return ERR_PTR(-EINVAL);
  270. return NULL;
  271. }
  272. VM_BUG_ON(!nodes);
  273. /*
  274. * MPOL_PREFERRED cannot be used with MPOL_F_STATIC_NODES or
  275. * MPOL_F_RELATIVE_NODES if the nodemask is empty (local allocation).
  276. * All other modes require a valid pointer to a non-empty nodemask.
  277. */
  278. if (mode == MPOL_PREFERRED) {
  279. if (nodes_empty(*nodes)) {
  280. if (((flags & MPOL_F_STATIC_NODES) ||
  281. (flags & MPOL_F_RELATIVE_NODES)))
  282. return ERR_PTR(-EINVAL);
  283. mode = MPOL_LOCAL;
  284. }
  285. } else if (mode == MPOL_LOCAL) {
  286. if (!nodes_empty(*nodes) ||
  287. (flags & MPOL_F_STATIC_NODES) ||
  288. (flags & MPOL_F_RELATIVE_NODES))
  289. return ERR_PTR(-EINVAL);
  290. } else if (nodes_empty(*nodes))
  291. return ERR_PTR(-EINVAL);
  292. policy = kmem_cache_alloc(policy_cache, GFP_KERNEL);
  293. if (!policy)
  294. return ERR_PTR(-ENOMEM);
  295. atomic_set(&policy->refcnt, 1);
  296. policy->mode = mode;
  297. policy->flags = flags;
  298. policy->home_node = NUMA_NO_NODE;
  299. return policy;
  300. }
  301. /* Slow path of a mpol destructor. */
  302. void __mpol_put(struct mempolicy *pol)
  303. {
  304. if (!atomic_dec_and_test(&pol->refcnt))
  305. return;
  306. kmem_cache_free(policy_cache, pol);
  307. }
  308. static void mpol_rebind_default(struct mempolicy *pol, const nodemask_t *nodes)
  309. {
  310. }
  311. static void mpol_rebind_nodemask(struct mempolicy *pol, const nodemask_t *nodes)
  312. {
  313. nodemask_t tmp;
  314. if (pol->flags & MPOL_F_STATIC_NODES)
  315. nodes_and(tmp, pol->w.user_nodemask, *nodes);
  316. else if (pol->flags & MPOL_F_RELATIVE_NODES)
  317. mpol_relative_nodemask(&tmp, &pol->w.user_nodemask, nodes);
  318. else {
  319. nodes_remap(tmp, pol->nodes, pol->w.cpuset_mems_allowed,
  320. *nodes);
  321. pol->w.cpuset_mems_allowed = *nodes;
  322. }
  323. if (nodes_empty(tmp))
  324. tmp = *nodes;
  325. pol->nodes = tmp;
  326. }
  327. static void mpol_rebind_preferred(struct mempolicy *pol,
  328. const nodemask_t *nodes)
  329. {
  330. pol->w.cpuset_mems_allowed = *nodes;
  331. }
  332. /*
  333. * mpol_rebind_policy - Migrate a policy to a different set of nodes
  334. *
  335. * Per-vma policies are protected by mmap_lock. Allocations using per-task
  336. * policies are protected by task->mems_allowed_seq to prevent a premature
  337. * OOM/allocation failure due to parallel nodemask modification.
  338. */
  339. static void mpol_rebind_policy(struct mempolicy *pol, const nodemask_t *newmask)
  340. {
  341. if (!pol || pol->mode == MPOL_LOCAL)
  342. return;
  343. if (!mpol_store_user_nodemask(pol) &&
  344. nodes_equal(pol->w.cpuset_mems_allowed, *newmask))
  345. return;
  346. mpol_ops[pol->mode].rebind(pol, newmask);
  347. }
  348. /*
  349. * Wrapper for mpol_rebind_policy() that just requires task
  350. * pointer, and updates task mempolicy.
  351. *
  352. * Called with task's alloc_lock held.
  353. */
  354. void mpol_rebind_task(struct task_struct *tsk, const nodemask_t *new)
  355. {
  356. mpol_rebind_policy(tsk->mempolicy, new);
  357. }
  358. /*
  359. * Rebind each vma in mm to new nodemask.
  360. *
  361. * Call holding a reference to mm. Takes mm->mmap_lock during call.
  362. */
  363. void mpol_rebind_mm(struct mm_struct *mm, nodemask_t *new)
  364. {
  365. struct vm_area_struct *vma;
  366. VMA_ITERATOR(vmi, mm, 0);
  367. mmap_write_lock(mm);
  368. for_each_vma(vmi, vma) {
  369. vma_start_write(vma);
  370. mpol_rebind_policy(vma->vm_policy, new);
  371. }
  372. mmap_write_unlock(mm);
  373. }
  374. static const struct mempolicy_operations mpol_ops[MPOL_MAX] = {
  375. [MPOL_DEFAULT] = {
  376. .rebind = mpol_rebind_default,
  377. },
  378. [MPOL_INTERLEAVE] = {
  379. .create = mpol_new_nodemask,
  380. .rebind = mpol_rebind_nodemask,
  381. },
  382. [MPOL_PREFERRED] = {
  383. .create = mpol_new_preferred,
  384. .rebind = mpol_rebind_preferred,
  385. },
  386. [MPOL_BIND] = {
  387. .create = mpol_new_nodemask,
  388. .rebind = mpol_rebind_nodemask,
  389. },
  390. [MPOL_LOCAL] = {
  391. .rebind = mpol_rebind_default,
  392. },
  393. [MPOL_PREFERRED_MANY] = {
  394. .create = mpol_new_nodemask,
  395. .rebind = mpol_rebind_preferred,
  396. },
  397. [MPOL_WEIGHTED_INTERLEAVE] = {
  398. .create = mpol_new_nodemask,
  399. .rebind = mpol_rebind_nodemask,
  400. },
  401. };
  402. static bool migrate_folio_add(struct folio *folio, struct list_head *foliolist,
  403. unsigned long flags);
  404. static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *pol,
  405. pgoff_t ilx, int *nid);
  406. static bool strictly_unmovable(unsigned long flags)
  407. {
  408. /*
  409. * STRICT without MOVE flags lets do_mbind() fail immediately with -EIO
  410. * if any misplaced page is found.
  411. */
  412. return (flags & (MPOL_MF_STRICT | MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ==
  413. MPOL_MF_STRICT;
  414. }
  415. struct migration_mpol { /* for alloc_migration_target_by_mpol() */
  416. struct mempolicy *pol;
  417. pgoff_t ilx;
  418. };
  419. struct queue_pages {
  420. struct list_head *pagelist;
  421. unsigned long flags;
  422. nodemask_t *nmask;
  423. unsigned long start;
  424. unsigned long end;
  425. struct vm_area_struct *first;
  426. struct folio *large; /* note last large folio encountered */
  427. long nr_failed; /* could not be isolated at this time */
  428. };
  429. /*
  430. * Check if the folio's nid is in qp->nmask.
  431. *
  432. * If MPOL_MF_INVERT is set in qp->flags, check if the nid is
  433. * in the invert of qp->nmask.
  434. */
  435. static inline bool queue_folio_required(struct folio *folio,
  436. struct queue_pages *qp)
  437. {
  438. int nid = folio_nid(folio);
  439. unsigned long flags = qp->flags;
  440. return node_isset(nid, *qp->nmask) == !(flags & MPOL_MF_INVERT);
  441. }
  442. static void queue_folios_pmd(pmd_t *pmd, struct mm_walk *walk)
  443. {
  444. struct folio *folio;
  445. struct queue_pages *qp = walk->private;
  446. if (unlikely(is_pmd_migration_entry(*pmd))) {
  447. qp->nr_failed++;
  448. return;
  449. }
  450. folio = pmd_folio(*pmd);
  451. if (is_huge_zero_folio(folio)) {
  452. walk->action = ACTION_CONTINUE;
  453. return;
  454. }
  455. if (!queue_folio_required(folio, qp))
  456. return;
  457. if (!(qp->flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ||
  458. !vma_migratable(walk->vma) ||
  459. !migrate_folio_add(folio, qp->pagelist, qp->flags))
  460. qp->nr_failed++;
  461. }
  462. /*
  463. * Scan through folios, checking if they satisfy the required conditions,
  464. * moving them from LRU to local pagelist for migration if they do (or not).
  465. *
  466. * queue_folios_pte_range() has two possible return values:
  467. * 0 - continue walking to scan for more, even if an existing folio on the
  468. * wrong node could not be isolated and queued for migration.
  469. * -EIO - only MPOL_MF_STRICT was specified, without MPOL_MF_MOVE or ..._ALL,
  470. * and an existing folio was on a node that does not follow the policy.
  471. */
  472. static int queue_folios_pte_range(pmd_t *pmd, unsigned long addr,
  473. unsigned long end, struct mm_walk *walk)
  474. {
  475. struct vm_area_struct *vma = walk->vma;
  476. struct folio *folio;
  477. struct queue_pages *qp = walk->private;
  478. unsigned long flags = qp->flags;
  479. pte_t *pte, *mapped_pte;
  480. pte_t ptent;
  481. spinlock_t *ptl;
  482. ptl = pmd_trans_huge_lock(pmd, vma);
  483. if (ptl) {
  484. queue_folios_pmd(pmd, walk);
  485. spin_unlock(ptl);
  486. goto out;
  487. }
  488. mapped_pte = pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl);
  489. if (!pte) {
  490. walk->action = ACTION_AGAIN;
  491. return 0;
  492. }
  493. for (; addr != end; pte++, addr += PAGE_SIZE) {
  494. ptent = ptep_get(pte);
  495. if (pte_none(ptent))
  496. continue;
  497. if (!pte_present(ptent)) {
  498. if (is_migration_entry(pte_to_swp_entry(ptent)))
  499. qp->nr_failed++;
  500. continue;
  501. }
  502. folio = vm_normal_folio(vma, addr, ptent);
  503. if (!folio || folio_is_zone_device(folio))
  504. continue;
  505. /*
  506. * vm_normal_folio() filters out zero pages, but there might
  507. * still be reserved folios to skip, perhaps in a VDSO.
  508. */
  509. if (folio_test_reserved(folio))
  510. continue;
  511. if (!queue_folio_required(folio, qp))
  512. continue;
  513. if (folio_test_large(folio)) {
  514. /*
  515. * A large folio can only be isolated from LRU once,
  516. * but may be mapped by many PTEs (and Copy-On-Write may
  517. * intersperse PTEs of other, order 0, folios). This is
  518. * a common case, so don't mistake it for failure (but
  519. * there can be other cases of multi-mapped pages which
  520. * this quick check does not help to filter out - and a
  521. * search of the pagelist might grow to be prohibitive).
  522. *
  523. * migrate_pages(&pagelist) returns nr_failed folios, so
  524. * check "large" now so that queue_pages_range() returns
  525. * a comparable nr_failed folios. This does imply that
  526. * if folio could not be isolated for some racy reason
  527. * at its first PTE, later PTEs will not give it another
  528. * chance of isolation; but keeps the accounting simple.
  529. */
  530. if (folio == qp->large)
  531. continue;
  532. qp->large = folio;
  533. }
  534. if (!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ||
  535. !vma_migratable(vma) ||
  536. !migrate_folio_add(folio, qp->pagelist, flags)) {
  537. qp->nr_failed++;
  538. if (strictly_unmovable(flags))
  539. break;
  540. }
  541. }
  542. pte_unmap_unlock(mapped_pte, ptl);
  543. cond_resched();
  544. out:
  545. if (qp->nr_failed && strictly_unmovable(flags))
  546. return -EIO;
  547. return 0;
  548. }
  549. static int queue_folios_hugetlb(pte_t *pte, unsigned long hmask,
  550. unsigned long addr, unsigned long end,
  551. struct mm_walk *walk)
  552. {
  553. #ifdef CONFIG_HUGETLB_PAGE
  554. struct queue_pages *qp = walk->private;
  555. unsigned long flags = qp->flags;
  556. struct folio *folio;
  557. spinlock_t *ptl;
  558. pte_t entry;
  559. ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte);
  560. entry = huge_ptep_get(walk->mm, addr, pte);
  561. if (!pte_present(entry)) {
  562. if (unlikely(is_hugetlb_entry_migration(entry)))
  563. qp->nr_failed++;
  564. goto unlock;
  565. }
  566. folio = pfn_folio(pte_pfn(entry));
  567. if (!queue_folio_required(folio, qp))
  568. goto unlock;
  569. if (!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)) ||
  570. !vma_migratable(walk->vma)) {
  571. qp->nr_failed++;
  572. goto unlock;
  573. }
  574. /*
  575. * Unless MPOL_MF_MOVE_ALL, we try to avoid migrating a shared folio.
  576. * Choosing not to migrate a shared folio is not counted as a failure.
  577. *
  578. * See folio_likely_mapped_shared() on possible imprecision when we
  579. * cannot easily detect if a folio is shared.
  580. */
  581. if ((flags & MPOL_MF_MOVE_ALL) ||
  582. (!folio_likely_mapped_shared(folio) && !hugetlb_pmd_shared(pte)))
  583. if (!isolate_hugetlb(folio, qp->pagelist))
  584. qp->nr_failed++;
  585. unlock:
  586. spin_unlock(ptl);
  587. if (qp->nr_failed && strictly_unmovable(flags))
  588. return -EIO;
  589. #endif
  590. return 0;
  591. }
  592. #ifdef CONFIG_NUMA_BALANCING
  593. /*
  594. * This is used to mark a range of virtual addresses to be inaccessible.
  595. * These are later cleared by a NUMA hinting fault. Depending on these
  596. * faults, pages may be migrated for better NUMA placement.
  597. *
  598. * This is assuming that NUMA faults are handled using PROT_NONE. If
  599. * an architecture makes a different choice, it will need further
  600. * changes to the core.
  601. */
  602. unsigned long change_prot_numa(struct vm_area_struct *vma,
  603. unsigned long addr, unsigned long end)
  604. {
  605. struct mmu_gather tlb;
  606. long nr_updated;
  607. tlb_gather_mmu(&tlb, vma->vm_mm);
  608. nr_updated = change_protection(&tlb, vma, addr, end, MM_CP_PROT_NUMA);
  609. if (nr_updated > 0) {
  610. count_vm_numa_events(NUMA_PTE_UPDATES, nr_updated);
  611. count_memcg_events_mm(vma->vm_mm, NUMA_PTE_UPDATES, nr_updated);
  612. }
  613. tlb_finish_mmu(&tlb);
  614. return nr_updated;
  615. }
  616. #endif /* CONFIG_NUMA_BALANCING */
  617. static int queue_pages_test_walk(unsigned long start, unsigned long end,
  618. struct mm_walk *walk)
  619. {
  620. struct vm_area_struct *next, *vma = walk->vma;
  621. struct queue_pages *qp = walk->private;
  622. unsigned long flags = qp->flags;
  623. /* range check first */
  624. VM_BUG_ON_VMA(!range_in_vma(vma, start, end), vma);
  625. if (!qp->first) {
  626. qp->first = vma;
  627. if (!(flags & MPOL_MF_DISCONTIG_OK) &&
  628. (qp->start < vma->vm_start))
  629. /* hole at head side of range */
  630. return -EFAULT;
  631. }
  632. next = find_vma(vma->vm_mm, vma->vm_end);
  633. if (!(flags & MPOL_MF_DISCONTIG_OK) &&
  634. ((vma->vm_end < qp->end) &&
  635. (!next || vma->vm_end < next->vm_start)))
  636. /* hole at middle or tail of range */
  637. return -EFAULT;
  638. /*
  639. * Need check MPOL_MF_STRICT to return -EIO if possible
  640. * regardless of vma_migratable
  641. */
  642. if (!vma_migratable(vma) &&
  643. !(flags & MPOL_MF_STRICT))
  644. return 1;
  645. /*
  646. * Check page nodes, and queue pages to move, in the current vma.
  647. * But if no moving, and no strict checking, the scan can be skipped.
  648. */
  649. if (flags & (MPOL_MF_STRICT | MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
  650. return 0;
  651. return 1;
  652. }
  653. static const struct mm_walk_ops queue_pages_walk_ops = {
  654. .hugetlb_entry = queue_folios_hugetlb,
  655. .pmd_entry = queue_folios_pte_range,
  656. .test_walk = queue_pages_test_walk,
  657. .walk_lock = PGWALK_RDLOCK,
  658. };
  659. static const struct mm_walk_ops queue_pages_lock_vma_walk_ops = {
  660. .hugetlb_entry = queue_folios_hugetlb,
  661. .pmd_entry = queue_folios_pte_range,
  662. .test_walk = queue_pages_test_walk,
  663. .walk_lock = PGWALK_WRLOCK,
  664. };
  665. /*
  666. * Walk through page tables and collect pages to be migrated.
  667. *
  668. * If pages found in a given range are not on the required set of @nodes,
  669. * and migration is allowed, they are isolated and queued to @pagelist.
  670. *
  671. * queue_pages_range() may return:
  672. * 0 - all pages already on the right node, or successfully queued for moving
  673. * (or neither strict checking nor moving requested: only range checking).
  674. * >0 - this number of misplaced folios could not be queued for moving
  675. * (a hugetlbfs page or a transparent huge page being counted as 1).
  676. * -EIO - a misplaced page found, when MPOL_MF_STRICT specified without MOVEs.
  677. * -EFAULT - a hole in the memory range, when MPOL_MF_DISCONTIG_OK unspecified.
  678. */
  679. static long
  680. queue_pages_range(struct mm_struct *mm, unsigned long start, unsigned long end,
  681. nodemask_t *nodes, unsigned long flags,
  682. struct list_head *pagelist)
  683. {
  684. int err;
  685. struct queue_pages qp = {
  686. .pagelist = pagelist,
  687. .flags = flags,
  688. .nmask = nodes,
  689. .start = start,
  690. .end = end,
  691. .first = NULL,
  692. };
  693. const struct mm_walk_ops *ops = (flags & MPOL_MF_WRLOCK) ?
  694. &queue_pages_lock_vma_walk_ops : &queue_pages_walk_ops;
  695. err = walk_page_range(mm, start, end, ops, &qp);
  696. if (!qp.first)
  697. /* whole range in hole */
  698. err = -EFAULT;
  699. return err ? : qp.nr_failed;
  700. }
  701. /*
  702. * Apply policy to a single VMA
  703. * This must be called with the mmap_lock held for writing.
  704. */
  705. static int vma_replace_policy(struct vm_area_struct *vma,
  706. struct mempolicy *pol)
  707. {
  708. int err;
  709. struct mempolicy *old;
  710. struct mempolicy *new;
  711. vma_assert_write_locked(vma);
  712. new = mpol_dup(pol);
  713. if (IS_ERR(new))
  714. return PTR_ERR(new);
  715. if (vma->vm_ops && vma->vm_ops->set_policy) {
  716. err = vma->vm_ops->set_policy(vma, new);
  717. if (err)
  718. goto err_out;
  719. }
  720. old = vma->vm_policy;
  721. vma->vm_policy = new; /* protected by mmap_lock */
  722. mpol_put(old);
  723. return 0;
  724. err_out:
  725. mpol_put(new);
  726. return err;
  727. }
  728. /* Split or merge the VMA (if required) and apply the new policy */
  729. static int mbind_range(struct vma_iterator *vmi, struct vm_area_struct *vma,
  730. struct vm_area_struct **prev, unsigned long start,
  731. unsigned long end, struct mempolicy *new_pol)
  732. {
  733. unsigned long vmstart, vmend;
  734. vmend = min(end, vma->vm_end);
  735. if (start > vma->vm_start) {
  736. *prev = vma;
  737. vmstart = start;
  738. } else {
  739. vmstart = vma->vm_start;
  740. }
  741. if (mpol_equal(vma->vm_policy, new_pol)) {
  742. *prev = vma;
  743. return 0;
  744. }
  745. vma = vma_modify_policy(vmi, *prev, vma, vmstart, vmend, new_pol);
  746. if (IS_ERR(vma))
  747. return PTR_ERR(vma);
  748. *prev = vma;
  749. return vma_replace_policy(vma, new_pol);
  750. }
  751. /* Set the process memory policy */
  752. static long do_set_mempolicy(unsigned short mode, unsigned short flags,
  753. nodemask_t *nodes)
  754. {
  755. struct mempolicy *new, *old;
  756. NODEMASK_SCRATCH(scratch);
  757. int ret;
  758. if (!scratch)
  759. return -ENOMEM;
  760. new = mpol_new(mode, flags, nodes);
  761. if (IS_ERR(new)) {
  762. ret = PTR_ERR(new);
  763. goto out;
  764. }
  765. task_lock(current);
  766. ret = mpol_set_nodemask(new, nodes, scratch);
  767. if (ret) {
  768. task_unlock(current);
  769. mpol_put(new);
  770. goto out;
  771. }
  772. old = current->mempolicy;
  773. current->mempolicy = new;
  774. if (new && (new->mode == MPOL_INTERLEAVE ||
  775. new->mode == MPOL_WEIGHTED_INTERLEAVE)) {
  776. current->il_prev = MAX_NUMNODES-1;
  777. current->il_weight = 0;
  778. }
  779. task_unlock(current);
  780. mpol_put(old);
  781. ret = 0;
  782. out:
  783. NODEMASK_SCRATCH_FREE(scratch);
  784. return ret;
  785. }
  786. /*
  787. * Return nodemask for policy for get_mempolicy() query
  788. *
  789. * Called with task's alloc_lock held
  790. */
  791. static void get_policy_nodemask(struct mempolicy *pol, nodemask_t *nodes)
  792. {
  793. nodes_clear(*nodes);
  794. if (pol == &default_policy)
  795. return;
  796. switch (pol->mode) {
  797. case MPOL_BIND:
  798. case MPOL_INTERLEAVE:
  799. case MPOL_PREFERRED:
  800. case MPOL_PREFERRED_MANY:
  801. case MPOL_WEIGHTED_INTERLEAVE:
  802. *nodes = pol->nodes;
  803. break;
  804. case MPOL_LOCAL:
  805. /* return empty node mask for local allocation */
  806. break;
  807. default:
  808. BUG();
  809. }
  810. }
  811. static int lookup_node(struct mm_struct *mm, unsigned long addr)
  812. {
  813. struct page *p = NULL;
  814. int ret;
  815. ret = get_user_pages_fast(addr & PAGE_MASK, 1, 0, &p);
  816. if (ret > 0) {
  817. ret = page_to_nid(p);
  818. put_page(p);
  819. }
  820. return ret;
  821. }
  822. /* Retrieve NUMA policy */
  823. static long do_get_mempolicy(int *policy, nodemask_t *nmask,
  824. unsigned long addr, unsigned long flags)
  825. {
  826. int err;
  827. struct mm_struct *mm = current->mm;
  828. struct vm_area_struct *vma = NULL;
  829. struct mempolicy *pol = current->mempolicy, *pol_refcount = NULL;
  830. if (flags &
  831. ~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))
  832. return -EINVAL;
  833. if (flags & MPOL_F_MEMS_ALLOWED) {
  834. if (flags & (MPOL_F_NODE|MPOL_F_ADDR))
  835. return -EINVAL;
  836. *policy = 0; /* just so it's initialized */
  837. task_lock(current);
  838. *nmask = cpuset_current_mems_allowed;
  839. task_unlock(current);
  840. return 0;
  841. }
  842. if (flags & MPOL_F_ADDR) {
  843. pgoff_t ilx; /* ignored here */
  844. /*
  845. * Do NOT fall back to task policy if the
  846. * vma/shared policy at addr is NULL. We
  847. * want to return MPOL_DEFAULT in this case.
  848. */
  849. mmap_read_lock(mm);
  850. vma = vma_lookup(mm, addr);
  851. if (!vma) {
  852. mmap_read_unlock(mm);
  853. return -EFAULT;
  854. }
  855. pol = __get_vma_policy(vma, addr, &ilx);
  856. } else if (addr)
  857. return -EINVAL;
  858. if (!pol)
  859. pol = &default_policy; /* indicates default behavior */
  860. if (flags & MPOL_F_NODE) {
  861. if (flags & MPOL_F_ADDR) {
  862. /*
  863. * Take a refcount on the mpol, because we are about to
  864. * drop the mmap_lock, after which only "pol" remains
  865. * valid, "vma" is stale.
  866. */
  867. pol_refcount = pol;
  868. vma = NULL;
  869. mpol_get(pol);
  870. mmap_read_unlock(mm);
  871. err = lookup_node(mm, addr);
  872. if (err < 0)
  873. goto out;
  874. *policy = err;
  875. } else if (pol == current->mempolicy &&
  876. pol->mode == MPOL_INTERLEAVE) {
  877. *policy = next_node_in(current->il_prev, pol->nodes);
  878. } else if (pol == current->mempolicy &&
  879. pol->mode == MPOL_WEIGHTED_INTERLEAVE) {
  880. if (current->il_weight)
  881. *policy = current->il_prev;
  882. else
  883. *policy = next_node_in(current->il_prev,
  884. pol->nodes);
  885. } else {
  886. err = -EINVAL;
  887. goto out;
  888. }
  889. } else {
  890. *policy = pol == &default_policy ? MPOL_DEFAULT :
  891. pol->mode;
  892. /*
  893. * Internal mempolicy flags must be masked off before exposing
  894. * the policy to userspace.
  895. */
  896. *policy |= (pol->flags & MPOL_MODE_FLAGS);
  897. }
  898. err = 0;
  899. if (nmask) {
  900. if (mpol_store_user_nodemask(pol)) {
  901. *nmask = pol->w.user_nodemask;
  902. } else {
  903. task_lock(current);
  904. get_policy_nodemask(pol, nmask);
  905. task_unlock(current);
  906. }
  907. }
  908. out:
  909. mpol_cond_put(pol);
  910. if (vma)
  911. mmap_read_unlock(mm);
  912. if (pol_refcount)
  913. mpol_put(pol_refcount);
  914. return err;
  915. }
  916. #ifdef CONFIG_MIGRATION
  917. static bool migrate_folio_add(struct folio *folio, struct list_head *foliolist,
  918. unsigned long flags)
  919. {
  920. /*
  921. * Unless MPOL_MF_MOVE_ALL, we try to avoid migrating a shared folio.
  922. * Choosing not to migrate a shared folio is not counted as a failure.
  923. *
  924. * See folio_likely_mapped_shared() on possible imprecision when we
  925. * cannot easily detect if a folio is shared.
  926. */
  927. if ((flags & MPOL_MF_MOVE_ALL) || !folio_likely_mapped_shared(folio)) {
  928. if (folio_isolate_lru(folio)) {
  929. list_add_tail(&folio->lru, foliolist);
  930. node_stat_mod_folio(folio,
  931. NR_ISOLATED_ANON + folio_is_file_lru(folio),
  932. folio_nr_pages(folio));
  933. } else {
  934. /*
  935. * Non-movable folio may reach here. And, there may be
  936. * temporary off LRU folios or non-LRU movable folios.
  937. * Treat them as unmovable folios since they can't be
  938. * isolated, so they can't be moved at the moment.
  939. */
  940. return false;
  941. }
  942. }
  943. return true;
  944. }
  945. /*
  946. * Migrate pages from one node to a target node.
  947. * Returns error or the number of pages not migrated.
  948. */
  949. static long migrate_to_node(struct mm_struct *mm, int source, int dest,
  950. int flags)
  951. {
  952. nodemask_t nmask;
  953. struct vm_area_struct *vma;
  954. LIST_HEAD(pagelist);
  955. long nr_failed;
  956. long err = 0;
  957. struct migration_target_control mtc = {
  958. .nid = dest,
  959. .gfp_mask = GFP_HIGHUSER_MOVABLE | __GFP_THISNODE,
  960. .reason = MR_SYSCALL,
  961. };
  962. nodes_clear(nmask);
  963. node_set(source, nmask);
  964. VM_BUG_ON(!(flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL)));
  965. mmap_read_lock(mm);
  966. vma = find_vma(mm, 0);
  967. if (unlikely(!vma)) {
  968. mmap_read_unlock(mm);
  969. return 0;
  970. }
  971. /*
  972. * This does not migrate the range, but isolates all pages that
  973. * need migration. Between passing in the full user address
  974. * space range and MPOL_MF_DISCONTIG_OK, this call cannot fail,
  975. * but passes back the count of pages which could not be isolated.
  976. */
  977. nr_failed = queue_pages_range(mm, vma->vm_start, mm->task_size, &nmask,
  978. flags | MPOL_MF_DISCONTIG_OK, &pagelist);
  979. mmap_read_unlock(mm);
  980. if (!list_empty(&pagelist)) {
  981. err = migrate_pages(&pagelist, alloc_migration_target, NULL,
  982. (unsigned long)&mtc, MIGRATE_SYNC, MR_SYSCALL, NULL);
  983. if (err)
  984. putback_movable_pages(&pagelist);
  985. }
  986. if (err >= 0)
  987. err += nr_failed;
  988. return err;
  989. }
  990. /*
  991. * Move pages between the two nodesets so as to preserve the physical
  992. * layout as much as possible.
  993. *
  994. * Returns the number of page that could not be moved.
  995. */
  996. int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
  997. const nodemask_t *to, int flags)
  998. {
  999. long nr_failed = 0;
  1000. long err = 0;
  1001. nodemask_t tmp;
  1002. lru_cache_disable();
  1003. /*
  1004. * Find a 'source' bit set in 'tmp' whose corresponding 'dest'
  1005. * bit in 'to' is not also set in 'tmp'. Clear the found 'source'
  1006. * bit in 'tmp', and return that <source, dest> pair for migration.
  1007. * The pair of nodemasks 'to' and 'from' define the map.
  1008. *
  1009. * If no pair of bits is found that way, fallback to picking some
  1010. * pair of 'source' and 'dest' bits that are not the same. If the
  1011. * 'source' and 'dest' bits are the same, this represents a node
  1012. * that will be migrating to itself, so no pages need move.
  1013. *
  1014. * If no bits are left in 'tmp', or if all remaining bits left
  1015. * in 'tmp' correspond to the same bit in 'to', return false
  1016. * (nothing left to migrate).
  1017. *
  1018. * This lets us pick a pair of nodes to migrate between, such that
  1019. * if possible the dest node is not already occupied by some other
  1020. * source node, minimizing the risk of overloading the memory on a
  1021. * node that would happen if we migrated incoming memory to a node
  1022. * before migrating outgoing memory source that same node.
  1023. *
  1024. * A single scan of tmp is sufficient. As we go, we remember the
  1025. * most recent <s, d> pair that moved (s != d). If we find a pair
  1026. * that not only moved, but what's better, moved to an empty slot
  1027. * (d is not set in tmp), then we break out then, with that pair.
  1028. * Otherwise when we finish scanning from_tmp, we at least have the
  1029. * most recent <s, d> pair that moved. If we get all the way through
  1030. * the scan of tmp without finding any node that moved, much less
  1031. * moved to an empty node, then there is nothing left worth migrating.
  1032. */
  1033. tmp = *from;
  1034. while (!nodes_empty(tmp)) {
  1035. int s, d;
  1036. int source = NUMA_NO_NODE;
  1037. int dest = 0;
  1038. for_each_node_mask(s, tmp) {
  1039. /*
  1040. * do_migrate_pages() tries to maintain the relative
  1041. * node relationship of the pages established between
  1042. * threads and memory areas.
  1043. *
  1044. * However if the number of source nodes is not equal to
  1045. * the number of destination nodes we can not preserve
  1046. * this node relative relationship. In that case, skip
  1047. * copying memory from a node that is in the destination
  1048. * mask.
  1049. *
  1050. * Example: [2,3,4] -> [3,4,5] moves everything.
  1051. * [0-7] - > [3,4,5] moves only 0,1,2,6,7.
  1052. */
  1053. if ((nodes_weight(*from) != nodes_weight(*to)) &&
  1054. (node_isset(s, *to)))
  1055. continue;
  1056. d = node_remap(s, *from, *to);
  1057. if (s == d)
  1058. continue;
  1059. source = s; /* Node moved. Memorize */
  1060. dest = d;
  1061. /* dest not in remaining from nodes? */
  1062. if (!node_isset(dest, tmp))
  1063. break;
  1064. }
  1065. if (source == NUMA_NO_NODE)
  1066. break;
  1067. node_clear(source, tmp);
  1068. err = migrate_to_node(mm, source, dest, flags);
  1069. if (err > 0)
  1070. nr_failed += err;
  1071. if (err < 0)
  1072. break;
  1073. }
  1074. lru_cache_enable();
  1075. if (err < 0)
  1076. return err;
  1077. return (nr_failed < INT_MAX) ? nr_failed : INT_MAX;
  1078. }
  1079. /*
  1080. * Allocate a new folio for page migration, according to NUMA mempolicy.
  1081. */
  1082. static struct folio *alloc_migration_target_by_mpol(struct folio *src,
  1083. unsigned long private)
  1084. {
  1085. struct migration_mpol *mmpol = (struct migration_mpol *)private;
  1086. struct mempolicy *pol = mmpol->pol;
  1087. pgoff_t ilx = mmpol->ilx;
  1088. unsigned int order;
  1089. int nid = numa_node_id();
  1090. gfp_t gfp;
  1091. order = folio_order(src);
  1092. ilx += src->index >> order;
  1093. if (folio_test_hugetlb(src)) {
  1094. nodemask_t *nodemask;
  1095. struct hstate *h;
  1096. h = folio_hstate(src);
  1097. gfp = htlb_alloc_mask(h);
  1098. nodemask = policy_nodemask(gfp, pol, ilx, &nid);
  1099. return alloc_hugetlb_folio_nodemask(h, nid, nodemask, gfp,
  1100. htlb_allow_alloc_fallback(MR_MEMPOLICY_MBIND));
  1101. }
  1102. if (folio_test_large(src))
  1103. gfp = GFP_TRANSHUGE;
  1104. else
  1105. gfp = GFP_HIGHUSER_MOVABLE | __GFP_RETRY_MAYFAIL | __GFP_COMP;
  1106. return folio_alloc_mpol(gfp, order, pol, ilx, nid);
  1107. }
  1108. #else
  1109. static bool migrate_folio_add(struct folio *folio, struct list_head *foliolist,
  1110. unsigned long flags)
  1111. {
  1112. return false;
  1113. }
  1114. int do_migrate_pages(struct mm_struct *mm, const nodemask_t *from,
  1115. const nodemask_t *to, int flags)
  1116. {
  1117. return -ENOSYS;
  1118. }
  1119. static struct folio *alloc_migration_target_by_mpol(struct folio *src,
  1120. unsigned long private)
  1121. {
  1122. return NULL;
  1123. }
  1124. #endif
  1125. static long do_mbind(unsigned long start, unsigned long len,
  1126. unsigned short mode, unsigned short mode_flags,
  1127. nodemask_t *nmask, unsigned long flags)
  1128. {
  1129. struct mm_struct *mm = current->mm;
  1130. struct vm_area_struct *vma, *prev;
  1131. struct vma_iterator vmi;
  1132. struct migration_mpol mmpol;
  1133. struct mempolicy *new;
  1134. unsigned long end;
  1135. long err;
  1136. long nr_failed;
  1137. LIST_HEAD(pagelist);
  1138. if (flags & ~(unsigned long)MPOL_MF_VALID)
  1139. return -EINVAL;
  1140. if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
  1141. return -EPERM;
  1142. if (start & ~PAGE_MASK)
  1143. return -EINVAL;
  1144. if (mode == MPOL_DEFAULT)
  1145. flags &= ~MPOL_MF_STRICT;
  1146. len = PAGE_ALIGN(len);
  1147. end = start + len;
  1148. if (end < start)
  1149. return -EINVAL;
  1150. if (end == start)
  1151. return 0;
  1152. new = mpol_new(mode, mode_flags, nmask);
  1153. if (IS_ERR(new))
  1154. return PTR_ERR(new);
  1155. /*
  1156. * If we are using the default policy then operation
  1157. * on discontinuous address spaces is okay after all
  1158. */
  1159. if (!new)
  1160. flags |= MPOL_MF_DISCONTIG_OK;
  1161. if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
  1162. lru_cache_disable();
  1163. {
  1164. NODEMASK_SCRATCH(scratch);
  1165. if (scratch) {
  1166. mmap_write_lock(mm);
  1167. err = mpol_set_nodemask(new, nmask, scratch);
  1168. if (err)
  1169. mmap_write_unlock(mm);
  1170. } else
  1171. err = -ENOMEM;
  1172. NODEMASK_SCRATCH_FREE(scratch);
  1173. }
  1174. if (err)
  1175. goto mpol_out;
  1176. /*
  1177. * Lock the VMAs before scanning for pages to migrate,
  1178. * to ensure we don't miss a concurrently inserted page.
  1179. */
  1180. nr_failed = queue_pages_range(mm, start, end, nmask,
  1181. flags | MPOL_MF_INVERT | MPOL_MF_WRLOCK, &pagelist);
  1182. if (nr_failed < 0) {
  1183. err = nr_failed;
  1184. nr_failed = 0;
  1185. } else {
  1186. vma_iter_init(&vmi, mm, start);
  1187. prev = vma_prev(&vmi);
  1188. for_each_vma_range(vmi, vma, end) {
  1189. err = mbind_range(&vmi, vma, &prev, start, end, new);
  1190. if (err)
  1191. break;
  1192. }
  1193. }
  1194. if (!err && !list_empty(&pagelist)) {
  1195. /* Convert MPOL_DEFAULT's NULL to task or default policy */
  1196. if (!new) {
  1197. new = get_task_policy(current);
  1198. mpol_get(new);
  1199. }
  1200. mmpol.pol = new;
  1201. mmpol.ilx = 0;
  1202. /*
  1203. * In the interleaved case, attempt to allocate on exactly the
  1204. * targeted nodes, for the first VMA to be migrated; for later
  1205. * VMAs, the nodes will still be interleaved from the targeted
  1206. * nodemask, but one by one may be selected differently.
  1207. */
  1208. if (new->mode == MPOL_INTERLEAVE ||
  1209. new->mode == MPOL_WEIGHTED_INTERLEAVE) {
  1210. struct folio *folio;
  1211. unsigned int order;
  1212. unsigned long addr = -EFAULT;
  1213. list_for_each_entry(folio, &pagelist, lru) {
  1214. if (!folio_test_ksm(folio))
  1215. break;
  1216. }
  1217. if (!list_entry_is_head(folio, &pagelist, lru)) {
  1218. vma_iter_init(&vmi, mm, start);
  1219. for_each_vma_range(vmi, vma, end) {
  1220. addr = page_address_in_vma(
  1221. folio_page(folio, 0), vma);
  1222. if (addr != -EFAULT)
  1223. break;
  1224. }
  1225. }
  1226. if (addr != -EFAULT) {
  1227. order = folio_order(folio);
  1228. /* We already know the pol, but not the ilx */
  1229. mpol_cond_put(get_vma_policy(vma, addr, order,
  1230. &mmpol.ilx));
  1231. /* Set base from which to increment by index */
  1232. mmpol.ilx -= folio->index >> order;
  1233. }
  1234. }
  1235. }
  1236. mmap_write_unlock(mm);
  1237. if (!err && !list_empty(&pagelist)) {
  1238. nr_failed |= migrate_pages(&pagelist,
  1239. alloc_migration_target_by_mpol, NULL,
  1240. (unsigned long)&mmpol, MIGRATE_SYNC,
  1241. MR_MEMPOLICY_MBIND, NULL);
  1242. }
  1243. if (nr_failed && (flags & MPOL_MF_STRICT))
  1244. err = -EIO;
  1245. if (!list_empty(&pagelist))
  1246. putback_movable_pages(&pagelist);
  1247. mpol_out:
  1248. mpol_put(new);
  1249. if (flags & (MPOL_MF_MOVE | MPOL_MF_MOVE_ALL))
  1250. lru_cache_enable();
  1251. return err;
  1252. }
  1253. /*
  1254. * User space interface with variable sized bitmaps for nodelists.
  1255. */
  1256. static int get_bitmap(unsigned long *mask, const unsigned long __user *nmask,
  1257. unsigned long maxnode)
  1258. {
  1259. unsigned long nlongs = BITS_TO_LONGS(maxnode);
  1260. int ret;
  1261. if (in_compat_syscall())
  1262. ret = compat_get_bitmap(mask,
  1263. (const compat_ulong_t __user *)nmask,
  1264. maxnode);
  1265. else
  1266. ret = copy_from_user(mask, nmask,
  1267. nlongs * sizeof(unsigned long));
  1268. if (ret)
  1269. return -EFAULT;
  1270. if (maxnode % BITS_PER_LONG)
  1271. mask[nlongs - 1] &= (1UL << (maxnode % BITS_PER_LONG)) - 1;
  1272. return 0;
  1273. }
  1274. /* Copy a node mask from user space. */
  1275. static int get_nodes(nodemask_t *nodes, const unsigned long __user *nmask,
  1276. unsigned long maxnode)
  1277. {
  1278. --maxnode;
  1279. nodes_clear(*nodes);
  1280. if (maxnode == 0 || !nmask)
  1281. return 0;
  1282. if (maxnode > PAGE_SIZE*BITS_PER_BYTE)
  1283. return -EINVAL;
  1284. /*
  1285. * When the user specified more nodes than supported just check
  1286. * if the non supported part is all zero, one word at a time,
  1287. * starting at the end.
  1288. */
  1289. while (maxnode > MAX_NUMNODES) {
  1290. unsigned long bits = min_t(unsigned long, maxnode, BITS_PER_LONG);
  1291. unsigned long t;
  1292. if (get_bitmap(&t, &nmask[(maxnode - 1) / BITS_PER_LONG], bits))
  1293. return -EFAULT;
  1294. if (maxnode - bits >= MAX_NUMNODES) {
  1295. maxnode -= bits;
  1296. } else {
  1297. maxnode = MAX_NUMNODES;
  1298. t &= ~((1UL << (MAX_NUMNODES % BITS_PER_LONG)) - 1);
  1299. }
  1300. if (t)
  1301. return -EINVAL;
  1302. }
  1303. return get_bitmap(nodes_addr(*nodes), nmask, maxnode);
  1304. }
  1305. /* Copy a kernel node mask to user space */
  1306. static int copy_nodes_to_user(unsigned long __user *mask, unsigned long maxnode,
  1307. nodemask_t *nodes)
  1308. {
  1309. unsigned long copy = ALIGN(maxnode-1, 64) / 8;
  1310. unsigned int nbytes = BITS_TO_LONGS(nr_node_ids) * sizeof(long);
  1311. bool compat = in_compat_syscall();
  1312. if (compat)
  1313. nbytes = BITS_TO_COMPAT_LONGS(nr_node_ids) * sizeof(compat_long_t);
  1314. if (copy > nbytes) {
  1315. if (copy > PAGE_SIZE)
  1316. return -EINVAL;
  1317. if (clear_user((char __user *)mask + nbytes, copy - nbytes))
  1318. return -EFAULT;
  1319. copy = nbytes;
  1320. maxnode = nr_node_ids;
  1321. }
  1322. if (compat)
  1323. return compat_put_bitmap((compat_ulong_t __user *)mask,
  1324. nodes_addr(*nodes), maxnode);
  1325. return copy_to_user(mask, nodes_addr(*nodes), copy) ? -EFAULT : 0;
  1326. }
  1327. /* Basic parameter sanity check used by both mbind() and set_mempolicy() */
  1328. static inline int sanitize_mpol_flags(int *mode, unsigned short *flags)
  1329. {
  1330. *flags = *mode & MPOL_MODE_FLAGS;
  1331. *mode &= ~MPOL_MODE_FLAGS;
  1332. if ((unsigned int)(*mode) >= MPOL_MAX)
  1333. return -EINVAL;
  1334. if ((*flags & MPOL_F_STATIC_NODES) && (*flags & MPOL_F_RELATIVE_NODES))
  1335. return -EINVAL;
  1336. if (*flags & MPOL_F_NUMA_BALANCING) {
  1337. if (*mode == MPOL_BIND || *mode == MPOL_PREFERRED_MANY)
  1338. *flags |= (MPOL_F_MOF | MPOL_F_MORON);
  1339. else
  1340. return -EINVAL;
  1341. }
  1342. return 0;
  1343. }
  1344. static long kernel_mbind(unsigned long start, unsigned long len,
  1345. unsigned long mode, const unsigned long __user *nmask,
  1346. unsigned long maxnode, unsigned int flags)
  1347. {
  1348. unsigned short mode_flags;
  1349. nodemask_t nodes;
  1350. int lmode = mode;
  1351. int err;
  1352. start = untagged_addr(start);
  1353. err = sanitize_mpol_flags(&lmode, &mode_flags);
  1354. if (err)
  1355. return err;
  1356. err = get_nodes(&nodes, nmask, maxnode);
  1357. if (err)
  1358. return err;
  1359. return do_mbind(start, len, lmode, mode_flags, &nodes, flags);
  1360. }
  1361. SYSCALL_DEFINE4(set_mempolicy_home_node, unsigned long, start, unsigned long, len,
  1362. unsigned long, home_node, unsigned long, flags)
  1363. {
  1364. struct mm_struct *mm = current->mm;
  1365. struct vm_area_struct *vma, *prev;
  1366. struct mempolicy *new, *old;
  1367. unsigned long end;
  1368. int err = -ENOENT;
  1369. VMA_ITERATOR(vmi, mm, start);
  1370. start = untagged_addr(start);
  1371. if (start & ~PAGE_MASK)
  1372. return -EINVAL;
  1373. /*
  1374. * flags is used for future extension if any.
  1375. */
  1376. if (flags != 0)
  1377. return -EINVAL;
  1378. /*
  1379. * Check home_node is online to avoid accessing uninitialized
  1380. * NODE_DATA.
  1381. */
  1382. if (home_node >= MAX_NUMNODES || !node_online(home_node))
  1383. return -EINVAL;
  1384. len = PAGE_ALIGN(len);
  1385. end = start + len;
  1386. if (end < start)
  1387. return -EINVAL;
  1388. if (end == start)
  1389. return 0;
  1390. mmap_write_lock(mm);
  1391. prev = vma_prev(&vmi);
  1392. for_each_vma_range(vmi, vma, end) {
  1393. /*
  1394. * If any vma in the range got policy other than MPOL_BIND
  1395. * or MPOL_PREFERRED_MANY we return error. We don't reset
  1396. * the home node for vmas we already updated before.
  1397. */
  1398. old = vma_policy(vma);
  1399. if (!old) {
  1400. prev = vma;
  1401. continue;
  1402. }
  1403. if (old->mode != MPOL_BIND && old->mode != MPOL_PREFERRED_MANY) {
  1404. err = -EOPNOTSUPP;
  1405. break;
  1406. }
  1407. new = mpol_dup(old);
  1408. if (IS_ERR(new)) {
  1409. err = PTR_ERR(new);
  1410. break;
  1411. }
  1412. vma_start_write(vma);
  1413. new->home_node = home_node;
  1414. err = mbind_range(&vmi, vma, &prev, start, end, new);
  1415. mpol_put(new);
  1416. if (err)
  1417. break;
  1418. }
  1419. mmap_write_unlock(mm);
  1420. return err;
  1421. }
  1422. SYSCALL_DEFINE6(mbind, unsigned long, start, unsigned long, len,
  1423. unsigned long, mode, const unsigned long __user *, nmask,
  1424. unsigned long, maxnode, unsigned int, flags)
  1425. {
  1426. return kernel_mbind(start, len, mode, nmask, maxnode, flags);
  1427. }
  1428. /* Set the process memory policy */
  1429. static long kernel_set_mempolicy(int mode, const unsigned long __user *nmask,
  1430. unsigned long maxnode)
  1431. {
  1432. unsigned short mode_flags;
  1433. nodemask_t nodes;
  1434. int lmode = mode;
  1435. int err;
  1436. err = sanitize_mpol_flags(&lmode, &mode_flags);
  1437. if (err)
  1438. return err;
  1439. err = get_nodes(&nodes, nmask, maxnode);
  1440. if (err)
  1441. return err;
  1442. return do_set_mempolicy(lmode, mode_flags, &nodes);
  1443. }
  1444. SYSCALL_DEFINE3(set_mempolicy, int, mode, const unsigned long __user *, nmask,
  1445. unsigned long, maxnode)
  1446. {
  1447. return kernel_set_mempolicy(mode, nmask, maxnode);
  1448. }
  1449. static int kernel_migrate_pages(pid_t pid, unsigned long maxnode,
  1450. const unsigned long __user *old_nodes,
  1451. const unsigned long __user *new_nodes)
  1452. {
  1453. struct mm_struct *mm = NULL;
  1454. struct task_struct *task;
  1455. nodemask_t task_nodes;
  1456. int err;
  1457. nodemask_t *old;
  1458. nodemask_t *new;
  1459. NODEMASK_SCRATCH(scratch);
  1460. if (!scratch)
  1461. return -ENOMEM;
  1462. old = &scratch->mask1;
  1463. new = &scratch->mask2;
  1464. err = get_nodes(old, old_nodes, maxnode);
  1465. if (err)
  1466. goto out;
  1467. err = get_nodes(new, new_nodes, maxnode);
  1468. if (err)
  1469. goto out;
  1470. /* Find the mm_struct */
  1471. rcu_read_lock();
  1472. task = pid ? find_task_by_vpid(pid) : current;
  1473. if (!task) {
  1474. rcu_read_unlock();
  1475. err = -ESRCH;
  1476. goto out;
  1477. }
  1478. get_task_struct(task);
  1479. err = -EINVAL;
  1480. /*
  1481. * Check if this process has the right to modify the specified process.
  1482. * Use the regular "ptrace_may_access()" checks.
  1483. */
  1484. if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
  1485. rcu_read_unlock();
  1486. err = -EPERM;
  1487. goto out_put;
  1488. }
  1489. rcu_read_unlock();
  1490. task_nodes = cpuset_mems_allowed(task);
  1491. /* Is the user allowed to access the target nodes? */
  1492. if (!nodes_subset(*new, task_nodes) && !capable(CAP_SYS_NICE)) {
  1493. err = -EPERM;
  1494. goto out_put;
  1495. }
  1496. task_nodes = cpuset_mems_allowed(current);
  1497. nodes_and(*new, *new, task_nodes);
  1498. if (nodes_empty(*new))
  1499. goto out_put;
  1500. err = security_task_movememory(task);
  1501. if (err)
  1502. goto out_put;
  1503. mm = get_task_mm(task);
  1504. put_task_struct(task);
  1505. if (!mm) {
  1506. err = -EINVAL;
  1507. goto out;
  1508. }
  1509. err = do_migrate_pages(mm, old, new,
  1510. capable(CAP_SYS_NICE) ? MPOL_MF_MOVE_ALL : MPOL_MF_MOVE);
  1511. mmput(mm);
  1512. out:
  1513. NODEMASK_SCRATCH_FREE(scratch);
  1514. return err;
  1515. out_put:
  1516. put_task_struct(task);
  1517. goto out;
  1518. }
  1519. SYSCALL_DEFINE4(migrate_pages, pid_t, pid, unsigned long, maxnode,
  1520. const unsigned long __user *, old_nodes,
  1521. const unsigned long __user *, new_nodes)
  1522. {
  1523. return kernel_migrate_pages(pid, maxnode, old_nodes, new_nodes);
  1524. }
  1525. /* Retrieve NUMA policy */
  1526. static int kernel_get_mempolicy(int __user *policy,
  1527. unsigned long __user *nmask,
  1528. unsigned long maxnode,
  1529. unsigned long addr,
  1530. unsigned long flags)
  1531. {
  1532. int err;
  1533. int pval;
  1534. nodemask_t nodes;
  1535. if (nmask != NULL && maxnode < nr_node_ids)
  1536. return -EINVAL;
  1537. addr = untagged_addr(addr);
  1538. err = do_get_mempolicy(&pval, &nodes, addr, flags);
  1539. if (err)
  1540. return err;
  1541. if (policy && put_user(pval, policy))
  1542. return -EFAULT;
  1543. if (nmask)
  1544. err = copy_nodes_to_user(nmask, maxnode, &nodes);
  1545. return err;
  1546. }
  1547. SYSCALL_DEFINE5(get_mempolicy, int __user *, policy,
  1548. unsigned long __user *, nmask, unsigned long, maxnode,
  1549. unsigned long, addr, unsigned long, flags)
  1550. {
  1551. return kernel_get_mempolicy(policy, nmask, maxnode, addr, flags);
  1552. }
  1553. bool vma_migratable(struct vm_area_struct *vma)
  1554. {
  1555. if (vma->vm_flags & (VM_IO | VM_PFNMAP))
  1556. return false;
  1557. /*
  1558. * DAX device mappings require predictable access latency, so avoid
  1559. * incurring periodic faults.
  1560. */
  1561. if (vma_is_dax(vma))
  1562. return false;
  1563. if (is_vm_hugetlb_page(vma) &&
  1564. !hugepage_migration_supported(hstate_vma(vma)))
  1565. return false;
  1566. /*
  1567. * Migration allocates pages in the highest zone. If we cannot
  1568. * do so then migration (at least from node to node) is not
  1569. * possible.
  1570. */
  1571. if (vma->vm_file &&
  1572. gfp_zone(mapping_gfp_mask(vma->vm_file->f_mapping))
  1573. < policy_zone)
  1574. return false;
  1575. return true;
  1576. }
  1577. struct mempolicy *__get_vma_policy(struct vm_area_struct *vma,
  1578. unsigned long addr, pgoff_t *ilx)
  1579. {
  1580. *ilx = 0;
  1581. return (vma->vm_ops && vma->vm_ops->get_policy) ?
  1582. vma->vm_ops->get_policy(vma, addr, ilx) : vma->vm_policy;
  1583. }
  1584. /*
  1585. * get_vma_policy(@vma, @addr, @order, @ilx)
  1586. * @vma: virtual memory area whose policy is sought
  1587. * @addr: address in @vma for shared policy lookup
  1588. * @order: 0, or appropriate huge_page_order for interleaving
  1589. * @ilx: interleave index (output), for use only when MPOL_INTERLEAVE or
  1590. * MPOL_WEIGHTED_INTERLEAVE
  1591. *
  1592. * Returns effective policy for a VMA at specified address.
  1593. * Falls back to current->mempolicy or system default policy, as necessary.
  1594. * Shared policies [those marked as MPOL_F_SHARED] require an extra reference
  1595. * count--added by the get_policy() vm_op, as appropriate--to protect against
  1596. * freeing by another task. It is the caller's responsibility to free the
  1597. * extra reference for shared policies.
  1598. */
  1599. struct mempolicy *get_vma_policy(struct vm_area_struct *vma,
  1600. unsigned long addr, int order, pgoff_t *ilx)
  1601. {
  1602. struct mempolicy *pol;
  1603. pol = __get_vma_policy(vma, addr, ilx);
  1604. if (!pol)
  1605. pol = get_task_policy(current);
  1606. if (pol->mode == MPOL_INTERLEAVE ||
  1607. pol->mode == MPOL_WEIGHTED_INTERLEAVE) {
  1608. *ilx += vma->vm_pgoff >> order;
  1609. *ilx += (addr - vma->vm_start) >> (PAGE_SHIFT + order);
  1610. }
  1611. return pol;
  1612. }
  1613. bool vma_policy_mof(struct vm_area_struct *vma)
  1614. {
  1615. struct mempolicy *pol;
  1616. if (vma->vm_ops && vma->vm_ops->get_policy) {
  1617. bool ret = false;
  1618. pgoff_t ilx; /* ignored here */
  1619. pol = vma->vm_ops->get_policy(vma, vma->vm_start, &ilx);
  1620. if (pol && (pol->flags & MPOL_F_MOF))
  1621. ret = true;
  1622. mpol_cond_put(pol);
  1623. return ret;
  1624. }
  1625. pol = vma->vm_policy;
  1626. if (!pol)
  1627. pol = get_task_policy(current);
  1628. return pol->flags & MPOL_F_MOF;
  1629. }
  1630. bool apply_policy_zone(struct mempolicy *policy, enum zone_type zone)
  1631. {
  1632. enum zone_type dynamic_policy_zone = policy_zone;
  1633. BUG_ON(dynamic_policy_zone == ZONE_MOVABLE);
  1634. /*
  1635. * if policy->nodes has movable memory only,
  1636. * we apply policy when gfp_zone(gfp) = ZONE_MOVABLE only.
  1637. *
  1638. * policy->nodes is intersect with node_states[N_MEMORY].
  1639. * so if the following test fails, it implies
  1640. * policy->nodes has movable memory only.
  1641. */
  1642. if (!nodes_intersects(policy->nodes, node_states[N_HIGH_MEMORY]))
  1643. dynamic_policy_zone = ZONE_MOVABLE;
  1644. return zone >= dynamic_policy_zone;
  1645. }
  1646. static unsigned int weighted_interleave_nodes(struct mempolicy *policy)
  1647. {
  1648. unsigned int node;
  1649. unsigned int cpuset_mems_cookie;
  1650. retry:
  1651. /* to prevent miscount use tsk->mems_allowed_seq to detect rebind */
  1652. cpuset_mems_cookie = read_mems_allowed_begin();
  1653. node = current->il_prev;
  1654. if (!current->il_weight || !node_isset(node, policy->nodes)) {
  1655. node = next_node_in(node, policy->nodes);
  1656. if (read_mems_allowed_retry(cpuset_mems_cookie))
  1657. goto retry;
  1658. if (node == MAX_NUMNODES)
  1659. return node;
  1660. current->il_prev = node;
  1661. current->il_weight = get_il_weight(node);
  1662. }
  1663. current->il_weight--;
  1664. return node;
  1665. }
  1666. /* Do dynamic interleaving for a process */
  1667. static unsigned int interleave_nodes(struct mempolicy *policy)
  1668. {
  1669. unsigned int nid;
  1670. unsigned int cpuset_mems_cookie;
  1671. /* to prevent miscount, use tsk->mems_allowed_seq to detect rebind */
  1672. do {
  1673. cpuset_mems_cookie = read_mems_allowed_begin();
  1674. nid = next_node_in(current->il_prev, policy->nodes);
  1675. } while (read_mems_allowed_retry(cpuset_mems_cookie));
  1676. if (nid < MAX_NUMNODES)
  1677. current->il_prev = nid;
  1678. return nid;
  1679. }
  1680. /*
  1681. * Depending on the memory policy provide a node from which to allocate the
  1682. * next slab entry.
  1683. */
  1684. unsigned int mempolicy_slab_node(void)
  1685. {
  1686. struct mempolicy *policy;
  1687. int node = numa_mem_id();
  1688. if (!in_task())
  1689. return node;
  1690. policy = current->mempolicy;
  1691. if (!policy)
  1692. return node;
  1693. switch (policy->mode) {
  1694. case MPOL_PREFERRED:
  1695. return first_node(policy->nodes);
  1696. case MPOL_INTERLEAVE:
  1697. return interleave_nodes(policy);
  1698. case MPOL_WEIGHTED_INTERLEAVE:
  1699. return weighted_interleave_nodes(policy);
  1700. case MPOL_BIND:
  1701. case MPOL_PREFERRED_MANY:
  1702. {
  1703. struct zoneref *z;
  1704. /*
  1705. * Follow bind policy behavior and start allocation at the
  1706. * first node.
  1707. */
  1708. struct zonelist *zonelist;
  1709. enum zone_type highest_zoneidx = gfp_zone(GFP_KERNEL);
  1710. zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK];
  1711. z = first_zones_zonelist(zonelist, highest_zoneidx,
  1712. &policy->nodes);
  1713. return zonelist_zone(z) ? zonelist_node_idx(z) : node;
  1714. }
  1715. case MPOL_LOCAL:
  1716. return node;
  1717. default:
  1718. BUG();
  1719. }
  1720. }
  1721. static unsigned int read_once_policy_nodemask(struct mempolicy *pol,
  1722. nodemask_t *mask)
  1723. {
  1724. /*
  1725. * barrier stabilizes the nodemask locally so that it can be iterated
  1726. * over safely without concern for changes. Allocators validate node
  1727. * selection does not violate mems_allowed, so this is safe.
  1728. */
  1729. barrier();
  1730. memcpy(mask, &pol->nodes, sizeof(nodemask_t));
  1731. barrier();
  1732. return nodes_weight(*mask);
  1733. }
  1734. static unsigned int weighted_interleave_nid(struct mempolicy *pol, pgoff_t ilx)
  1735. {
  1736. nodemask_t nodemask;
  1737. unsigned int target, nr_nodes;
  1738. u8 *table;
  1739. unsigned int weight_total = 0;
  1740. u8 weight;
  1741. int nid;
  1742. nr_nodes = read_once_policy_nodemask(pol, &nodemask);
  1743. if (!nr_nodes)
  1744. return numa_node_id();
  1745. rcu_read_lock();
  1746. table = rcu_dereference(iw_table);
  1747. /* calculate the total weight */
  1748. for_each_node_mask(nid, nodemask) {
  1749. /* detect system default usage */
  1750. weight = table ? table[nid] : 1;
  1751. weight = weight ? weight : 1;
  1752. weight_total += weight;
  1753. }
  1754. /* Calculate the node offset based on totals */
  1755. target = ilx % weight_total;
  1756. nid = first_node(nodemask);
  1757. while (target) {
  1758. /* detect system default usage */
  1759. weight = table ? table[nid] : 1;
  1760. weight = weight ? weight : 1;
  1761. if (target < weight)
  1762. break;
  1763. target -= weight;
  1764. nid = next_node_in(nid, nodemask);
  1765. }
  1766. rcu_read_unlock();
  1767. return nid;
  1768. }
  1769. /*
  1770. * Do static interleaving for interleave index @ilx. Returns the ilx'th
  1771. * node in pol->nodes (starting from ilx=0), wrapping around if ilx
  1772. * exceeds the number of present nodes.
  1773. */
  1774. static unsigned int interleave_nid(struct mempolicy *pol, pgoff_t ilx)
  1775. {
  1776. nodemask_t nodemask;
  1777. unsigned int target, nnodes;
  1778. int i;
  1779. int nid;
  1780. nnodes = read_once_policy_nodemask(pol, &nodemask);
  1781. if (!nnodes)
  1782. return numa_node_id();
  1783. target = ilx % nnodes;
  1784. nid = first_node(nodemask);
  1785. for (i = 0; i < target; i++)
  1786. nid = next_node(nid, nodemask);
  1787. return nid;
  1788. }
  1789. /*
  1790. * Return a nodemask representing a mempolicy for filtering nodes for
  1791. * page allocation, together with preferred node id (or the input node id).
  1792. */
  1793. static nodemask_t *policy_nodemask(gfp_t gfp, struct mempolicy *pol,
  1794. pgoff_t ilx, int *nid)
  1795. {
  1796. nodemask_t *nodemask = NULL;
  1797. switch (pol->mode) {
  1798. case MPOL_PREFERRED:
  1799. /* Override input node id */
  1800. *nid = first_node(pol->nodes);
  1801. break;
  1802. case MPOL_PREFERRED_MANY:
  1803. nodemask = &pol->nodes;
  1804. if (pol->home_node != NUMA_NO_NODE)
  1805. *nid = pol->home_node;
  1806. break;
  1807. case MPOL_BIND:
  1808. /* Restrict to nodemask (but not on lower zones) */
  1809. if (apply_policy_zone(pol, gfp_zone(gfp)) &&
  1810. cpuset_nodemask_valid_mems_allowed(&pol->nodes))
  1811. nodemask = &pol->nodes;
  1812. if (pol->home_node != NUMA_NO_NODE)
  1813. *nid = pol->home_node;
  1814. /*
  1815. * __GFP_THISNODE shouldn't even be used with the bind policy
  1816. * because we might easily break the expectation to stay on the
  1817. * requested node and not break the policy.
  1818. */
  1819. WARN_ON_ONCE(gfp & __GFP_THISNODE);
  1820. break;
  1821. case MPOL_INTERLEAVE:
  1822. /* Override input node id */
  1823. *nid = (ilx == NO_INTERLEAVE_INDEX) ?
  1824. interleave_nodes(pol) : interleave_nid(pol, ilx);
  1825. break;
  1826. case MPOL_WEIGHTED_INTERLEAVE:
  1827. *nid = (ilx == NO_INTERLEAVE_INDEX) ?
  1828. weighted_interleave_nodes(pol) :
  1829. weighted_interleave_nid(pol, ilx);
  1830. break;
  1831. }
  1832. return nodemask;
  1833. }
  1834. #ifdef CONFIG_HUGETLBFS
  1835. /*
  1836. * huge_node(@vma, @addr, @gfp_flags, @mpol)
  1837. * @vma: virtual memory area whose policy is sought
  1838. * @addr: address in @vma for shared policy lookup and interleave policy
  1839. * @gfp_flags: for requested zone
  1840. * @mpol: pointer to mempolicy pointer for reference counted mempolicy
  1841. * @nodemask: pointer to nodemask pointer for 'bind' and 'prefer-many' policy
  1842. *
  1843. * Returns a nid suitable for a huge page allocation and a pointer
  1844. * to the struct mempolicy for conditional unref after allocation.
  1845. * If the effective policy is 'bind' or 'prefer-many', returns a pointer
  1846. * to the mempolicy's @nodemask for filtering the zonelist.
  1847. */
  1848. int huge_node(struct vm_area_struct *vma, unsigned long addr, gfp_t gfp_flags,
  1849. struct mempolicy **mpol, nodemask_t **nodemask)
  1850. {
  1851. pgoff_t ilx;
  1852. int nid;
  1853. nid = numa_node_id();
  1854. *mpol = get_vma_policy(vma, addr, hstate_vma(vma)->order, &ilx);
  1855. *nodemask = policy_nodemask(gfp_flags, *mpol, ilx, &nid);
  1856. return nid;
  1857. }
  1858. /*
  1859. * init_nodemask_of_mempolicy
  1860. *
  1861. * If the current task's mempolicy is "default" [NULL], return 'false'
  1862. * to indicate default policy. Otherwise, extract the policy nodemask
  1863. * for 'bind' or 'interleave' policy into the argument nodemask, or
  1864. * initialize the argument nodemask to contain the single node for
  1865. * 'preferred' or 'local' policy and return 'true' to indicate presence
  1866. * of non-default mempolicy.
  1867. *
  1868. * We don't bother with reference counting the mempolicy [mpol_get/put]
  1869. * because the current task is examining it's own mempolicy and a task's
  1870. * mempolicy is only ever changed by the task itself.
  1871. *
  1872. * N.B., it is the caller's responsibility to free a returned nodemask.
  1873. */
  1874. bool init_nodemask_of_mempolicy(nodemask_t *mask)
  1875. {
  1876. struct mempolicy *mempolicy;
  1877. if (!(mask && current->mempolicy))
  1878. return false;
  1879. task_lock(current);
  1880. mempolicy = current->mempolicy;
  1881. switch (mempolicy->mode) {
  1882. case MPOL_PREFERRED:
  1883. case MPOL_PREFERRED_MANY:
  1884. case MPOL_BIND:
  1885. case MPOL_INTERLEAVE:
  1886. case MPOL_WEIGHTED_INTERLEAVE:
  1887. *mask = mempolicy->nodes;
  1888. break;
  1889. case MPOL_LOCAL:
  1890. init_nodemask_of_node(mask, numa_node_id());
  1891. break;
  1892. default:
  1893. BUG();
  1894. }
  1895. task_unlock(current);
  1896. return true;
  1897. }
  1898. #endif
  1899. /*
  1900. * mempolicy_in_oom_domain
  1901. *
  1902. * If tsk's mempolicy is "bind", check for intersection between mask and
  1903. * the policy nodemask. Otherwise, return true for all other policies
  1904. * including "interleave", as a tsk with "interleave" policy may have
  1905. * memory allocated from all nodes in system.
  1906. *
  1907. * Takes task_lock(tsk) to prevent freeing of its mempolicy.
  1908. */
  1909. bool mempolicy_in_oom_domain(struct task_struct *tsk,
  1910. const nodemask_t *mask)
  1911. {
  1912. struct mempolicy *mempolicy;
  1913. bool ret = true;
  1914. if (!mask)
  1915. return ret;
  1916. task_lock(tsk);
  1917. mempolicy = tsk->mempolicy;
  1918. if (mempolicy && mempolicy->mode == MPOL_BIND)
  1919. ret = nodes_intersects(mempolicy->nodes, *mask);
  1920. task_unlock(tsk);
  1921. return ret;
  1922. }
  1923. static struct page *alloc_pages_preferred_many(gfp_t gfp, unsigned int order,
  1924. int nid, nodemask_t *nodemask)
  1925. {
  1926. struct page *page;
  1927. gfp_t preferred_gfp;
  1928. /*
  1929. * This is a two pass approach. The first pass will only try the
  1930. * preferred nodes but skip the direct reclaim and allow the
  1931. * allocation to fail, while the second pass will try all the
  1932. * nodes in system.
  1933. */
  1934. preferred_gfp = gfp | __GFP_NOWARN;
  1935. preferred_gfp &= ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
  1936. page = __alloc_pages_noprof(preferred_gfp, order, nid, nodemask);
  1937. if (!page)
  1938. page = __alloc_pages_noprof(gfp, order, nid, NULL);
  1939. return page;
  1940. }
  1941. /**
  1942. * alloc_pages_mpol - Allocate pages according to NUMA mempolicy.
  1943. * @gfp: GFP flags.
  1944. * @order: Order of the page allocation.
  1945. * @pol: Pointer to the NUMA mempolicy.
  1946. * @ilx: Index for interleave mempolicy (also distinguishes alloc_pages()).
  1947. * @nid: Preferred node (usually numa_node_id() but @mpol may override it).
  1948. *
  1949. * Return: The page on success or NULL if allocation fails.
  1950. */
  1951. struct page *alloc_pages_mpol_noprof(gfp_t gfp, unsigned int order,
  1952. struct mempolicy *pol, pgoff_t ilx, int nid)
  1953. {
  1954. nodemask_t *nodemask;
  1955. struct page *page;
  1956. nodemask = policy_nodemask(gfp, pol, ilx, &nid);
  1957. if (pol->mode == MPOL_PREFERRED_MANY)
  1958. return alloc_pages_preferred_many(gfp, order, nid, nodemask);
  1959. if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
  1960. /* filter "hugepage" allocation, unless from alloc_pages() */
  1961. order == HPAGE_PMD_ORDER && ilx != NO_INTERLEAVE_INDEX) {
  1962. /*
  1963. * For hugepage allocation and non-interleave policy which
  1964. * allows the current node (or other explicitly preferred
  1965. * node) we only try to allocate from the current/preferred
  1966. * node and don't fall back to other nodes, as the cost of
  1967. * remote accesses would likely offset THP benefits.
  1968. *
  1969. * If the policy is interleave or does not allow the current
  1970. * node in its nodemask, we allocate the standard way.
  1971. */
  1972. if (pol->mode != MPOL_INTERLEAVE &&
  1973. pol->mode != MPOL_WEIGHTED_INTERLEAVE &&
  1974. (!nodemask || node_isset(nid, *nodemask))) {
  1975. /*
  1976. * First, try to allocate THP only on local node, but
  1977. * don't reclaim unnecessarily, just compact.
  1978. */
  1979. page = __alloc_pages_node_noprof(nid,
  1980. gfp | __GFP_THISNODE | __GFP_NORETRY, order);
  1981. if (page || !(gfp & __GFP_DIRECT_RECLAIM))
  1982. return page;
  1983. /*
  1984. * If hugepage allocations are configured to always
  1985. * synchronous compact or the vma has been madvised
  1986. * to prefer hugepage backing, retry allowing remote
  1987. * memory with both reclaim and compact as well.
  1988. */
  1989. }
  1990. }
  1991. page = __alloc_pages_noprof(gfp, order, nid, nodemask);
  1992. if (unlikely(pol->mode == MPOL_INTERLEAVE) && page) {
  1993. /* skip NUMA_INTERLEAVE_HIT update if numa stats is disabled */
  1994. if (static_branch_likely(&vm_numa_stat_key) &&
  1995. page_to_nid(page) == nid) {
  1996. preempt_disable();
  1997. __count_numa_event(page_zone(page), NUMA_INTERLEAVE_HIT);
  1998. preempt_enable();
  1999. }
  2000. }
  2001. return page;
  2002. }
  2003. struct folio *folio_alloc_mpol_noprof(gfp_t gfp, unsigned int order,
  2004. struct mempolicy *pol, pgoff_t ilx, int nid)
  2005. {
  2006. return page_rmappable_folio(alloc_pages_mpol_noprof(gfp | __GFP_COMP,
  2007. order, pol, ilx, nid));
  2008. }
  2009. /**
  2010. * vma_alloc_folio - Allocate a folio for a VMA.
  2011. * @gfp: GFP flags.
  2012. * @order: Order of the folio.
  2013. * @vma: Pointer to VMA.
  2014. * @addr: Virtual address of the allocation. Must be inside @vma.
  2015. * @hugepage: Unused (was: For hugepages try only preferred node if possible).
  2016. *
  2017. * Allocate a folio for a specific address in @vma, using the appropriate
  2018. * NUMA policy. The caller must hold the mmap_lock of the mm_struct of the
  2019. * VMA to prevent it from going away. Should be used for all allocations
  2020. * for folios that will be mapped into user space, excepting hugetlbfs, and
  2021. * excepting where direct use of alloc_pages_mpol() is more appropriate.
  2022. *
  2023. * Return: The folio on success or NULL if allocation fails.
  2024. */
  2025. struct folio *vma_alloc_folio_noprof(gfp_t gfp, int order, struct vm_area_struct *vma,
  2026. unsigned long addr, bool hugepage)
  2027. {
  2028. struct mempolicy *pol;
  2029. pgoff_t ilx;
  2030. struct folio *folio;
  2031. if (vma->vm_flags & VM_DROPPABLE)
  2032. gfp |= __GFP_NOWARN;
  2033. pol = get_vma_policy(vma, addr, order, &ilx);
  2034. folio = folio_alloc_mpol_noprof(gfp, order, pol, ilx, numa_node_id());
  2035. mpol_cond_put(pol);
  2036. return folio;
  2037. }
  2038. EXPORT_SYMBOL(vma_alloc_folio_noprof);
  2039. /**
  2040. * alloc_pages - Allocate pages.
  2041. * @gfp: GFP flags.
  2042. * @order: Power of two of number of pages to allocate.
  2043. *
  2044. * Allocate 1 << @order contiguous pages. The physical address of the
  2045. * first page is naturally aligned (eg an order-3 allocation will be aligned
  2046. * to a multiple of 8 * PAGE_SIZE bytes). The NUMA policy of the current
  2047. * process is honoured when in process context.
  2048. *
  2049. * Context: Can be called from any context, providing the appropriate GFP
  2050. * flags are used.
  2051. * Return: The page on success or NULL if allocation fails.
  2052. */
  2053. struct page *alloc_pages_noprof(gfp_t gfp, unsigned int order)
  2054. {
  2055. struct mempolicy *pol = &default_policy;
  2056. /*
  2057. * No reference counting needed for current->mempolicy
  2058. * nor system default_policy
  2059. */
  2060. if (!in_interrupt() && !(gfp & __GFP_THISNODE))
  2061. pol = get_task_policy(current);
  2062. return alloc_pages_mpol_noprof(gfp, order, pol, NO_INTERLEAVE_INDEX,
  2063. numa_node_id());
  2064. }
  2065. EXPORT_SYMBOL(alloc_pages_noprof);
  2066. struct folio *folio_alloc_noprof(gfp_t gfp, unsigned int order)
  2067. {
  2068. return page_rmappable_folio(alloc_pages_noprof(gfp | __GFP_COMP, order));
  2069. }
  2070. EXPORT_SYMBOL(folio_alloc_noprof);
  2071. static unsigned long alloc_pages_bulk_array_interleave(gfp_t gfp,
  2072. struct mempolicy *pol, unsigned long nr_pages,
  2073. struct page **page_array)
  2074. {
  2075. int nodes;
  2076. unsigned long nr_pages_per_node;
  2077. int delta;
  2078. int i;
  2079. unsigned long nr_allocated;
  2080. unsigned long total_allocated = 0;
  2081. nodes = nodes_weight(pol->nodes);
  2082. nr_pages_per_node = nr_pages / nodes;
  2083. delta = nr_pages - nodes * nr_pages_per_node;
  2084. for (i = 0; i < nodes; i++) {
  2085. if (delta) {
  2086. nr_allocated = alloc_pages_bulk_noprof(gfp,
  2087. interleave_nodes(pol), NULL,
  2088. nr_pages_per_node + 1, NULL,
  2089. page_array);
  2090. delta--;
  2091. } else {
  2092. nr_allocated = alloc_pages_bulk_noprof(gfp,
  2093. interleave_nodes(pol), NULL,
  2094. nr_pages_per_node, NULL, page_array);
  2095. }
  2096. page_array += nr_allocated;
  2097. total_allocated += nr_allocated;
  2098. }
  2099. return total_allocated;
  2100. }
  2101. static unsigned long alloc_pages_bulk_array_weighted_interleave(gfp_t gfp,
  2102. struct mempolicy *pol, unsigned long nr_pages,
  2103. struct page **page_array)
  2104. {
  2105. struct task_struct *me = current;
  2106. unsigned int cpuset_mems_cookie;
  2107. unsigned long total_allocated = 0;
  2108. unsigned long nr_allocated = 0;
  2109. unsigned long rounds;
  2110. unsigned long node_pages, delta;
  2111. u8 *table, *weights, weight;
  2112. unsigned int weight_total = 0;
  2113. unsigned long rem_pages = nr_pages;
  2114. nodemask_t nodes;
  2115. int nnodes, node;
  2116. int resume_node = MAX_NUMNODES - 1;
  2117. u8 resume_weight = 0;
  2118. int prev_node;
  2119. int i;
  2120. if (!nr_pages)
  2121. return 0;
  2122. /* read the nodes onto the stack, retry if done during rebind */
  2123. do {
  2124. cpuset_mems_cookie = read_mems_allowed_begin();
  2125. nnodes = read_once_policy_nodemask(pol, &nodes);
  2126. } while (read_mems_allowed_retry(cpuset_mems_cookie));
  2127. /* if the nodemask has become invalid, we cannot do anything */
  2128. if (!nnodes)
  2129. return 0;
  2130. /* Continue allocating from most recent node and adjust the nr_pages */
  2131. node = me->il_prev;
  2132. weight = me->il_weight;
  2133. if (weight && node_isset(node, nodes)) {
  2134. node_pages = min(rem_pages, weight);
  2135. nr_allocated = __alloc_pages_bulk(gfp, node, NULL, node_pages,
  2136. NULL, page_array);
  2137. page_array += nr_allocated;
  2138. total_allocated += nr_allocated;
  2139. /* if that's all the pages, no need to interleave */
  2140. if (rem_pages <= weight) {
  2141. me->il_weight -= rem_pages;
  2142. return total_allocated;
  2143. }
  2144. /* Otherwise we adjust remaining pages, continue from there */
  2145. rem_pages -= weight;
  2146. }
  2147. /* clear active weight in case of an allocation failure */
  2148. me->il_weight = 0;
  2149. prev_node = node;
  2150. /* create a local copy of node weights to operate on outside rcu */
  2151. weights = kzalloc(nr_node_ids, GFP_KERNEL);
  2152. if (!weights)
  2153. return total_allocated;
  2154. rcu_read_lock();
  2155. table = rcu_dereference(iw_table);
  2156. if (table)
  2157. memcpy(weights, table, nr_node_ids);
  2158. rcu_read_unlock();
  2159. /* calculate total, detect system default usage */
  2160. for_each_node_mask(node, nodes) {
  2161. if (!weights[node])
  2162. weights[node] = 1;
  2163. weight_total += weights[node];
  2164. }
  2165. /*
  2166. * Calculate rounds/partial rounds to minimize __alloc_pages_bulk calls.
  2167. * Track which node weighted interleave should resume from.
  2168. *
  2169. * if (rounds > 0) and (delta == 0), resume_node will always be
  2170. * the node following prev_node and its weight.
  2171. */
  2172. rounds = rem_pages / weight_total;
  2173. delta = rem_pages % weight_total;
  2174. resume_node = next_node_in(prev_node, nodes);
  2175. resume_weight = weights[resume_node];
  2176. for (i = 0; i < nnodes; i++) {
  2177. node = next_node_in(prev_node, nodes);
  2178. weight = weights[node];
  2179. node_pages = weight * rounds;
  2180. /* If a delta exists, add this node's portion of the delta */
  2181. if (delta > weight) {
  2182. node_pages += weight;
  2183. delta -= weight;
  2184. } else if (delta) {
  2185. /* when delta is depleted, resume from that node */
  2186. node_pages += delta;
  2187. resume_node = node;
  2188. resume_weight = weight - delta;
  2189. delta = 0;
  2190. }
  2191. /* node_pages can be 0 if an allocation fails and rounds == 0 */
  2192. if (!node_pages)
  2193. break;
  2194. nr_allocated = __alloc_pages_bulk(gfp, node, NULL, node_pages,
  2195. NULL, page_array);
  2196. page_array += nr_allocated;
  2197. total_allocated += nr_allocated;
  2198. if (total_allocated == nr_pages)
  2199. break;
  2200. prev_node = node;
  2201. }
  2202. me->il_prev = resume_node;
  2203. me->il_weight = resume_weight;
  2204. kfree(weights);
  2205. return total_allocated;
  2206. }
  2207. static unsigned long alloc_pages_bulk_array_preferred_many(gfp_t gfp, int nid,
  2208. struct mempolicy *pol, unsigned long nr_pages,
  2209. struct page **page_array)
  2210. {
  2211. gfp_t preferred_gfp;
  2212. unsigned long nr_allocated = 0;
  2213. preferred_gfp = gfp | __GFP_NOWARN;
  2214. preferred_gfp &= ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
  2215. nr_allocated = alloc_pages_bulk_noprof(preferred_gfp, nid, &pol->nodes,
  2216. nr_pages, NULL, page_array);
  2217. if (nr_allocated < nr_pages)
  2218. nr_allocated += alloc_pages_bulk_noprof(gfp, numa_node_id(), NULL,
  2219. nr_pages - nr_allocated, NULL,
  2220. page_array + nr_allocated);
  2221. return nr_allocated;
  2222. }
  2223. /* alloc pages bulk and mempolicy should be considered at the
  2224. * same time in some situation such as vmalloc.
  2225. *
  2226. * It can accelerate memory allocation especially interleaving
  2227. * allocate memory.
  2228. */
  2229. unsigned long alloc_pages_bulk_array_mempolicy_noprof(gfp_t gfp,
  2230. unsigned long nr_pages, struct page **page_array)
  2231. {
  2232. struct mempolicy *pol = &default_policy;
  2233. nodemask_t *nodemask;
  2234. int nid;
  2235. if (!in_interrupt() && !(gfp & __GFP_THISNODE))
  2236. pol = get_task_policy(current);
  2237. if (pol->mode == MPOL_INTERLEAVE)
  2238. return alloc_pages_bulk_array_interleave(gfp, pol,
  2239. nr_pages, page_array);
  2240. if (pol->mode == MPOL_WEIGHTED_INTERLEAVE)
  2241. return alloc_pages_bulk_array_weighted_interleave(
  2242. gfp, pol, nr_pages, page_array);
  2243. if (pol->mode == MPOL_PREFERRED_MANY)
  2244. return alloc_pages_bulk_array_preferred_many(gfp,
  2245. numa_node_id(), pol, nr_pages, page_array);
  2246. nid = numa_node_id();
  2247. nodemask = policy_nodemask(gfp, pol, NO_INTERLEAVE_INDEX, &nid);
  2248. return alloc_pages_bulk_noprof(gfp, nid, nodemask,
  2249. nr_pages, NULL, page_array);
  2250. }
  2251. int vma_dup_policy(struct vm_area_struct *src, struct vm_area_struct *dst)
  2252. {
  2253. struct mempolicy *pol = mpol_dup(src->vm_policy);
  2254. if (IS_ERR(pol))
  2255. return PTR_ERR(pol);
  2256. dst->vm_policy = pol;
  2257. return 0;
  2258. }
  2259. /*
  2260. * If mpol_dup() sees current->cpuset == cpuset_being_rebound, then it
  2261. * rebinds the mempolicy its copying by calling mpol_rebind_policy()
  2262. * with the mems_allowed returned by cpuset_mems_allowed(). This
  2263. * keeps mempolicies cpuset relative after its cpuset moves. See
  2264. * further kernel/cpuset.c update_nodemask().
  2265. *
  2266. * current's mempolicy may be rebinded by the other task(the task that changes
  2267. * cpuset's mems), so we needn't do rebind work for current task.
  2268. */
  2269. /* Slow path of a mempolicy duplicate */
  2270. struct mempolicy *__mpol_dup(struct mempolicy *old)
  2271. {
  2272. struct mempolicy *new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
  2273. if (!new)
  2274. return ERR_PTR(-ENOMEM);
  2275. /* task's mempolicy is protected by alloc_lock */
  2276. if (old == current->mempolicy) {
  2277. task_lock(current);
  2278. *new = *old;
  2279. task_unlock(current);
  2280. } else
  2281. *new = *old;
  2282. if (current_cpuset_is_being_rebound()) {
  2283. nodemask_t mems = cpuset_mems_allowed(current);
  2284. mpol_rebind_policy(new, &mems);
  2285. }
  2286. atomic_set(&new->refcnt, 1);
  2287. return new;
  2288. }
  2289. /* Slow path of a mempolicy comparison */
  2290. bool __mpol_equal(struct mempolicy *a, struct mempolicy *b)
  2291. {
  2292. if (!a || !b)
  2293. return false;
  2294. if (a->mode != b->mode)
  2295. return false;
  2296. if (a->flags != b->flags)
  2297. return false;
  2298. if (a->home_node != b->home_node)
  2299. return false;
  2300. if (mpol_store_user_nodemask(a))
  2301. if (!nodes_equal(a->w.user_nodemask, b->w.user_nodemask))
  2302. return false;
  2303. switch (a->mode) {
  2304. case MPOL_BIND:
  2305. case MPOL_INTERLEAVE:
  2306. case MPOL_PREFERRED:
  2307. case MPOL_PREFERRED_MANY:
  2308. case MPOL_WEIGHTED_INTERLEAVE:
  2309. return !!nodes_equal(a->nodes, b->nodes);
  2310. case MPOL_LOCAL:
  2311. return true;
  2312. default:
  2313. BUG();
  2314. return false;
  2315. }
  2316. }
  2317. /*
  2318. * Shared memory backing store policy support.
  2319. *
  2320. * Remember policies even when nobody has shared memory mapped.
  2321. * The policies are kept in Red-Black tree linked from the inode.
  2322. * They are protected by the sp->lock rwlock, which should be held
  2323. * for any accesses to the tree.
  2324. */
  2325. /*
  2326. * lookup first element intersecting start-end. Caller holds sp->lock for
  2327. * reading or for writing
  2328. */
  2329. static struct sp_node *sp_lookup(struct shared_policy *sp,
  2330. pgoff_t start, pgoff_t end)
  2331. {
  2332. struct rb_node *n = sp->root.rb_node;
  2333. while (n) {
  2334. struct sp_node *p = rb_entry(n, struct sp_node, nd);
  2335. if (start >= p->end)
  2336. n = n->rb_right;
  2337. else if (end <= p->start)
  2338. n = n->rb_left;
  2339. else
  2340. break;
  2341. }
  2342. if (!n)
  2343. return NULL;
  2344. for (;;) {
  2345. struct sp_node *w = NULL;
  2346. struct rb_node *prev = rb_prev(n);
  2347. if (!prev)
  2348. break;
  2349. w = rb_entry(prev, struct sp_node, nd);
  2350. if (w->end <= start)
  2351. break;
  2352. n = prev;
  2353. }
  2354. return rb_entry(n, struct sp_node, nd);
  2355. }
  2356. /*
  2357. * Insert a new shared policy into the list. Caller holds sp->lock for
  2358. * writing.
  2359. */
  2360. static void sp_insert(struct shared_policy *sp, struct sp_node *new)
  2361. {
  2362. struct rb_node **p = &sp->root.rb_node;
  2363. struct rb_node *parent = NULL;
  2364. struct sp_node *nd;
  2365. while (*p) {
  2366. parent = *p;
  2367. nd = rb_entry(parent, struct sp_node, nd);
  2368. if (new->start < nd->start)
  2369. p = &(*p)->rb_left;
  2370. else if (new->end > nd->end)
  2371. p = &(*p)->rb_right;
  2372. else
  2373. BUG();
  2374. }
  2375. rb_link_node(&new->nd, parent, p);
  2376. rb_insert_color(&new->nd, &sp->root);
  2377. }
  2378. /* Find shared policy intersecting idx */
  2379. struct mempolicy *mpol_shared_policy_lookup(struct shared_policy *sp,
  2380. pgoff_t idx)
  2381. {
  2382. struct mempolicy *pol = NULL;
  2383. struct sp_node *sn;
  2384. if (!sp->root.rb_node)
  2385. return NULL;
  2386. read_lock(&sp->lock);
  2387. sn = sp_lookup(sp, idx, idx+1);
  2388. if (sn) {
  2389. mpol_get(sn->policy);
  2390. pol = sn->policy;
  2391. }
  2392. read_unlock(&sp->lock);
  2393. return pol;
  2394. }
  2395. static void sp_free(struct sp_node *n)
  2396. {
  2397. mpol_put(n->policy);
  2398. kmem_cache_free(sn_cache, n);
  2399. }
  2400. /**
  2401. * mpol_misplaced - check whether current folio node is valid in policy
  2402. *
  2403. * @folio: folio to be checked
  2404. * @vmf: structure describing the fault
  2405. * @addr: virtual address in @vma for shared policy lookup and interleave policy
  2406. *
  2407. * Lookup current policy node id for vma,addr and "compare to" folio's
  2408. * node id. Policy determination "mimics" alloc_page_vma().
  2409. * Called from fault path where we know the vma and faulting address.
  2410. *
  2411. * Return: NUMA_NO_NODE if the page is in a node that is valid for this
  2412. * policy, or a suitable node ID to allocate a replacement folio from.
  2413. */
  2414. int mpol_misplaced(struct folio *folio, struct vm_fault *vmf,
  2415. unsigned long addr)
  2416. {
  2417. struct mempolicy *pol;
  2418. pgoff_t ilx;
  2419. struct zoneref *z;
  2420. int curnid = folio_nid(folio);
  2421. struct vm_area_struct *vma = vmf->vma;
  2422. int thiscpu = raw_smp_processor_id();
  2423. int thisnid = numa_node_id();
  2424. int polnid = NUMA_NO_NODE;
  2425. int ret = NUMA_NO_NODE;
  2426. /*
  2427. * Make sure ptl is held so that we don't preempt and we
  2428. * have a stable smp processor id
  2429. */
  2430. lockdep_assert_held(vmf->ptl);
  2431. pol = get_vma_policy(vma, addr, folio_order(folio), &ilx);
  2432. if (!(pol->flags & MPOL_F_MOF))
  2433. goto out;
  2434. switch (pol->mode) {
  2435. case MPOL_INTERLEAVE:
  2436. polnid = interleave_nid(pol, ilx);
  2437. break;
  2438. case MPOL_WEIGHTED_INTERLEAVE:
  2439. polnid = weighted_interleave_nid(pol, ilx);
  2440. break;
  2441. case MPOL_PREFERRED:
  2442. if (node_isset(curnid, pol->nodes))
  2443. goto out;
  2444. polnid = first_node(pol->nodes);
  2445. break;
  2446. case MPOL_LOCAL:
  2447. polnid = numa_node_id();
  2448. break;
  2449. case MPOL_BIND:
  2450. case MPOL_PREFERRED_MANY:
  2451. /*
  2452. * Even though MPOL_PREFERRED_MANY can allocate pages outside
  2453. * policy nodemask we don't allow numa migration to nodes
  2454. * outside policy nodemask for now. This is done so that if we
  2455. * want demotion to slow memory to happen, before allocating
  2456. * from some DRAM node say 'x', we will end up using a
  2457. * MPOL_PREFERRED_MANY mask excluding node 'x'. In such scenario
  2458. * we should not promote to node 'x' from slow memory node.
  2459. */
  2460. if (pol->flags & MPOL_F_MORON) {
  2461. /*
  2462. * Optimize placement among multiple nodes
  2463. * via NUMA balancing
  2464. */
  2465. if (node_isset(thisnid, pol->nodes))
  2466. break;
  2467. goto out;
  2468. }
  2469. /*
  2470. * use current page if in policy nodemask,
  2471. * else select nearest allowed node, if any.
  2472. * If no allowed nodes, use current [!misplaced].
  2473. */
  2474. if (node_isset(curnid, pol->nodes))
  2475. goto out;
  2476. z = first_zones_zonelist(
  2477. node_zonelist(thisnid, GFP_HIGHUSER),
  2478. gfp_zone(GFP_HIGHUSER),
  2479. &pol->nodes);
  2480. polnid = zonelist_node_idx(z);
  2481. break;
  2482. default:
  2483. BUG();
  2484. }
  2485. /* Migrate the folio towards the node whose CPU is referencing it */
  2486. if (pol->flags & MPOL_F_MORON) {
  2487. polnid = thisnid;
  2488. if (!should_numa_migrate_memory(current, folio, curnid,
  2489. thiscpu))
  2490. goto out;
  2491. }
  2492. if (curnid != polnid)
  2493. ret = polnid;
  2494. out:
  2495. mpol_cond_put(pol);
  2496. return ret;
  2497. }
  2498. /*
  2499. * Drop the (possibly final) reference to task->mempolicy. It needs to be
  2500. * dropped after task->mempolicy is set to NULL so that any allocation done as
  2501. * part of its kmem_cache_free(), such as by KASAN, doesn't reference a freed
  2502. * policy.
  2503. */
  2504. void mpol_put_task_policy(struct task_struct *task)
  2505. {
  2506. struct mempolicy *pol;
  2507. task_lock(task);
  2508. pol = task->mempolicy;
  2509. task->mempolicy = NULL;
  2510. task_unlock(task);
  2511. mpol_put(pol);
  2512. }
  2513. static void sp_delete(struct shared_policy *sp, struct sp_node *n)
  2514. {
  2515. rb_erase(&n->nd, &sp->root);
  2516. sp_free(n);
  2517. }
  2518. static void sp_node_init(struct sp_node *node, unsigned long start,
  2519. unsigned long end, struct mempolicy *pol)
  2520. {
  2521. node->start = start;
  2522. node->end = end;
  2523. node->policy = pol;
  2524. }
  2525. static struct sp_node *sp_alloc(unsigned long start, unsigned long end,
  2526. struct mempolicy *pol)
  2527. {
  2528. struct sp_node *n;
  2529. struct mempolicy *newpol;
  2530. n = kmem_cache_alloc(sn_cache, GFP_KERNEL);
  2531. if (!n)
  2532. return NULL;
  2533. newpol = mpol_dup(pol);
  2534. if (IS_ERR(newpol)) {
  2535. kmem_cache_free(sn_cache, n);
  2536. return NULL;
  2537. }
  2538. newpol->flags |= MPOL_F_SHARED;
  2539. sp_node_init(n, start, end, newpol);
  2540. return n;
  2541. }
  2542. /* Replace a policy range. */
  2543. static int shared_policy_replace(struct shared_policy *sp, pgoff_t start,
  2544. pgoff_t end, struct sp_node *new)
  2545. {
  2546. struct sp_node *n;
  2547. struct sp_node *n_new = NULL;
  2548. struct mempolicy *mpol_new = NULL;
  2549. int ret = 0;
  2550. restart:
  2551. write_lock(&sp->lock);
  2552. n = sp_lookup(sp, start, end);
  2553. /* Take care of old policies in the same range. */
  2554. while (n && n->start < end) {
  2555. struct rb_node *next = rb_next(&n->nd);
  2556. if (n->start >= start) {
  2557. if (n->end <= end)
  2558. sp_delete(sp, n);
  2559. else
  2560. n->start = end;
  2561. } else {
  2562. /* Old policy spanning whole new range. */
  2563. if (n->end > end) {
  2564. if (!n_new)
  2565. goto alloc_new;
  2566. *mpol_new = *n->policy;
  2567. atomic_set(&mpol_new->refcnt, 1);
  2568. sp_node_init(n_new, end, n->end, mpol_new);
  2569. n->end = start;
  2570. sp_insert(sp, n_new);
  2571. n_new = NULL;
  2572. mpol_new = NULL;
  2573. break;
  2574. } else
  2575. n->end = start;
  2576. }
  2577. if (!next)
  2578. break;
  2579. n = rb_entry(next, struct sp_node, nd);
  2580. }
  2581. if (new)
  2582. sp_insert(sp, new);
  2583. write_unlock(&sp->lock);
  2584. ret = 0;
  2585. err_out:
  2586. if (mpol_new)
  2587. mpol_put(mpol_new);
  2588. if (n_new)
  2589. kmem_cache_free(sn_cache, n_new);
  2590. return ret;
  2591. alloc_new:
  2592. write_unlock(&sp->lock);
  2593. ret = -ENOMEM;
  2594. n_new = kmem_cache_alloc(sn_cache, GFP_KERNEL);
  2595. if (!n_new)
  2596. goto err_out;
  2597. mpol_new = kmem_cache_alloc(policy_cache, GFP_KERNEL);
  2598. if (!mpol_new)
  2599. goto err_out;
  2600. atomic_set(&mpol_new->refcnt, 1);
  2601. goto restart;
  2602. }
  2603. /**
  2604. * mpol_shared_policy_init - initialize shared policy for inode
  2605. * @sp: pointer to inode shared policy
  2606. * @mpol: struct mempolicy to install
  2607. *
  2608. * Install non-NULL @mpol in inode's shared policy rb-tree.
  2609. * On entry, the current task has a reference on a non-NULL @mpol.
  2610. * This must be released on exit.
  2611. * This is called at get_inode() calls and we can use GFP_KERNEL.
  2612. */
  2613. void mpol_shared_policy_init(struct shared_policy *sp, struct mempolicy *mpol)
  2614. {
  2615. int ret;
  2616. sp->root = RB_ROOT; /* empty tree == default mempolicy */
  2617. rwlock_init(&sp->lock);
  2618. if (mpol) {
  2619. struct sp_node *sn;
  2620. struct mempolicy *npol;
  2621. NODEMASK_SCRATCH(scratch);
  2622. if (!scratch)
  2623. goto put_mpol;
  2624. /* contextualize the tmpfs mount point mempolicy to this file */
  2625. npol = mpol_new(mpol->mode, mpol->flags, &mpol->w.user_nodemask);
  2626. if (IS_ERR(npol))
  2627. goto free_scratch; /* no valid nodemask intersection */
  2628. task_lock(current);
  2629. ret = mpol_set_nodemask(npol, &mpol->w.user_nodemask, scratch);
  2630. task_unlock(current);
  2631. if (ret)
  2632. goto put_npol;
  2633. /* alloc node covering entire file; adds ref to file's npol */
  2634. sn = sp_alloc(0, MAX_LFS_FILESIZE >> PAGE_SHIFT, npol);
  2635. if (sn)
  2636. sp_insert(sp, sn);
  2637. put_npol:
  2638. mpol_put(npol); /* drop initial ref on file's npol */
  2639. free_scratch:
  2640. NODEMASK_SCRATCH_FREE(scratch);
  2641. put_mpol:
  2642. mpol_put(mpol); /* drop our incoming ref on sb mpol */
  2643. }
  2644. }
  2645. int mpol_set_shared_policy(struct shared_policy *sp,
  2646. struct vm_area_struct *vma, struct mempolicy *pol)
  2647. {
  2648. int err;
  2649. struct sp_node *new = NULL;
  2650. unsigned long sz = vma_pages(vma);
  2651. if (pol) {
  2652. new = sp_alloc(vma->vm_pgoff, vma->vm_pgoff + sz, pol);
  2653. if (!new)
  2654. return -ENOMEM;
  2655. }
  2656. err = shared_policy_replace(sp, vma->vm_pgoff, vma->vm_pgoff + sz, new);
  2657. if (err && new)
  2658. sp_free(new);
  2659. return err;
  2660. }
  2661. /* Free a backing policy store on inode delete. */
  2662. void mpol_free_shared_policy(struct shared_policy *sp)
  2663. {
  2664. struct sp_node *n;
  2665. struct rb_node *next;
  2666. if (!sp->root.rb_node)
  2667. return;
  2668. write_lock(&sp->lock);
  2669. next = rb_first(&sp->root);
  2670. while (next) {
  2671. n = rb_entry(next, struct sp_node, nd);
  2672. next = rb_next(&n->nd);
  2673. sp_delete(sp, n);
  2674. }
  2675. write_unlock(&sp->lock);
  2676. }
  2677. #ifdef CONFIG_NUMA_BALANCING
  2678. static int __initdata numabalancing_override;
  2679. static void __init check_numabalancing_enable(void)
  2680. {
  2681. bool numabalancing_default = false;
  2682. if (IS_ENABLED(CONFIG_NUMA_BALANCING_DEFAULT_ENABLED))
  2683. numabalancing_default = true;
  2684. /* Parsed by setup_numabalancing. override == 1 enables, -1 disables */
  2685. if (numabalancing_override)
  2686. set_numabalancing_state(numabalancing_override == 1);
  2687. if (num_online_nodes() > 1 && !numabalancing_override) {
  2688. pr_info("%s automatic NUMA balancing. Configure with numa_balancing= or the kernel.numa_balancing sysctl\n",
  2689. numabalancing_default ? "Enabling" : "Disabling");
  2690. set_numabalancing_state(numabalancing_default);
  2691. }
  2692. }
  2693. static int __init setup_numabalancing(char *str)
  2694. {
  2695. int ret = 0;
  2696. if (!str)
  2697. goto out;
  2698. if (!strcmp(str, "enable")) {
  2699. numabalancing_override = 1;
  2700. ret = 1;
  2701. } else if (!strcmp(str, "disable")) {
  2702. numabalancing_override = -1;
  2703. ret = 1;
  2704. }
  2705. out:
  2706. if (!ret)
  2707. pr_warn("Unable to parse numa_balancing=\n");
  2708. return ret;
  2709. }
  2710. __setup("numa_balancing=", setup_numabalancing);
  2711. #else
  2712. static inline void __init check_numabalancing_enable(void)
  2713. {
  2714. }
  2715. #endif /* CONFIG_NUMA_BALANCING */
  2716. void __init numa_policy_init(void)
  2717. {
  2718. nodemask_t interleave_nodes;
  2719. unsigned long largest = 0;
  2720. int nid, prefer = 0;
  2721. policy_cache = kmem_cache_create("numa_policy",
  2722. sizeof(struct mempolicy),
  2723. 0, SLAB_PANIC, NULL);
  2724. sn_cache = kmem_cache_create("shared_policy_node",
  2725. sizeof(struct sp_node),
  2726. 0, SLAB_PANIC, NULL);
  2727. for_each_node(nid) {
  2728. preferred_node_policy[nid] = (struct mempolicy) {
  2729. .refcnt = ATOMIC_INIT(1),
  2730. .mode = MPOL_PREFERRED,
  2731. .flags = MPOL_F_MOF | MPOL_F_MORON,
  2732. .nodes = nodemask_of_node(nid),
  2733. };
  2734. }
  2735. /*
  2736. * Set interleaving policy for system init. Interleaving is only
  2737. * enabled across suitably sized nodes (default is >= 16MB), or
  2738. * fall back to the largest node if they're all smaller.
  2739. */
  2740. nodes_clear(interleave_nodes);
  2741. for_each_node_state(nid, N_MEMORY) {
  2742. unsigned long total_pages = node_present_pages(nid);
  2743. /* Preserve the largest node */
  2744. if (largest < total_pages) {
  2745. largest = total_pages;
  2746. prefer = nid;
  2747. }
  2748. /* Interleave this node? */
  2749. if ((total_pages << PAGE_SHIFT) >= (16 << 20))
  2750. node_set(nid, interleave_nodes);
  2751. }
  2752. /* All too small, use the largest */
  2753. if (unlikely(nodes_empty(interleave_nodes)))
  2754. node_set(prefer, interleave_nodes);
  2755. if (do_set_mempolicy(MPOL_INTERLEAVE, 0, &interleave_nodes))
  2756. pr_err("%s: interleaving failed\n", __func__);
  2757. check_numabalancing_enable();
  2758. }
  2759. /* Reset policy of current process to default */
  2760. void numa_default_policy(void)
  2761. {
  2762. do_set_mempolicy(MPOL_DEFAULT, 0, NULL);
  2763. }
  2764. /*
  2765. * Parse and format mempolicy from/to strings
  2766. */
  2767. static const char * const policy_modes[] =
  2768. {
  2769. [MPOL_DEFAULT] = "default",
  2770. [MPOL_PREFERRED] = "prefer",
  2771. [MPOL_BIND] = "bind",
  2772. [MPOL_INTERLEAVE] = "interleave",
  2773. [MPOL_WEIGHTED_INTERLEAVE] = "weighted interleave",
  2774. [MPOL_LOCAL] = "local",
  2775. [MPOL_PREFERRED_MANY] = "prefer (many)",
  2776. };
  2777. #ifdef CONFIG_TMPFS
  2778. /**
  2779. * mpol_parse_str - parse string to mempolicy, for tmpfs mpol mount option.
  2780. * @str: string containing mempolicy to parse
  2781. * @mpol: pointer to struct mempolicy pointer, returned on success.
  2782. *
  2783. * Format of input:
  2784. * <mode>[=<flags>][:<nodelist>]
  2785. *
  2786. * Return: %0 on success, else %1
  2787. */
  2788. int mpol_parse_str(char *str, struct mempolicy **mpol)
  2789. {
  2790. struct mempolicy *new = NULL;
  2791. unsigned short mode_flags;
  2792. nodemask_t nodes;
  2793. char *nodelist = strchr(str, ':');
  2794. char *flags = strchr(str, '=');
  2795. int err = 1, mode;
  2796. if (flags)
  2797. *flags++ = '\0'; /* terminate mode string */
  2798. if (nodelist) {
  2799. /* NUL-terminate mode or flags string */
  2800. *nodelist++ = '\0';
  2801. if (nodelist_parse(nodelist, nodes))
  2802. goto out;
  2803. if (!nodes_subset(nodes, node_states[N_MEMORY]))
  2804. goto out;
  2805. } else
  2806. nodes_clear(nodes);
  2807. mode = match_string(policy_modes, MPOL_MAX, str);
  2808. if (mode < 0)
  2809. goto out;
  2810. switch (mode) {
  2811. case MPOL_PREFERRED:
  2812. /*
  2813. * Insist on a nodelist of one node only, although later
  2814. * we use first_node(nodes) to grab a single node, so here
  2815. * nodelist (or nodes) cannot be empty.
  2816. */
  2817. if (nodelist) {
  2818. char *rest = nodelist;
  2819. while (isdigit(*rest))
  2820. rest++;
  2821. if (*rest)
  2822. goto out;
  2823. if (nodes_empty(nodes))
  2824. goto out;
  2825. }
  2826. break;
  2827. case MPOL_INTERLEAVE:
  2828. case MPOL_WEIGHTED_INTERLEAVE:
  2829. /*
  2830. * Default to online nodes with memory if no nodelist
  2831. */
  2832. if (!nodelist)
  2833. nodes = node_states[N_MEMORY];
  2834. break;
  2835. case MPOL_LOCAL:
  2836. /*
  2837. * Don't allow a nodelist; mpol_new() checks flags
  2838. */
  2839. if (nodelist)
  2840. goto out;
  2841. break;
  2842. case MPOL_DEFAULT:
  2843. /*
  2844. * Insist on a empty nodelist
  2845. */
  2846. if (!nodelist)
  2847. err = 0;
  2848. goto out;
  2849. case MPOL_PREFERRED_MANY:
  2850. case MPOL_BIND:
  2851. /*
  2852. * Insist on a nodelist
  2853. */
  2854. if (!nodelist)
  2855. goto out;
  2856. }
  2857. mode_flags = 0;
  2858. if (flags) {
  2859. /*
  2860. * Currently, we only support two mutually exclusive
  2861. * mode flags.
  2862. */
  2863. if (!strcmp(flags, "static"))
  2864. mode_flags |= MPOL_F_STATIC_NODES;
  2865. else if (!strcmp(flags, "relative"))
  2866. mode_flags |= MPOL_F_RELATIVE_NODES;
  2867. else
  2868. goto out;
  2869. }
  2870. new = mpol_new(mode, mode_flags, &nodes);
  2871. if (IS_ERR(new))
  2872. goto out;
  2873. /*
  2874. * Save nodes for mpol_to_str() to show the tmpfs mount options
  2875. * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.
  2876. */
  2877. if (mode != MPOL_PREFERRED) {
  2878. new->nodes = nodes;
  2879. } else if (nodelist) {
  2880. nodes_clear(new->nodes);
  2881. node_set(first_node(nodes), new->nodes);
  2882. } else {
  2883. new->mode = MPOL_LOCAL;
  2884. }
  2885. /*
  2886. * Save nodes for contextualization: this will be used to "clone"
  2887. * the mempolicy in a specific context [cpuset] at a later time.
  2888. */
  2889. new->w.user_nodemask = nodes;
  2890. err = 0;
  2891. out:
  2892. /* Restore string for error message */
  2893. if (nodelist)
  2894. *--nodelist = ':';
  2895. if (flags)
  2896. *--flags = '=';
  2897. if (!err)
  2898. *mpol = new;
  2899. return err;
  2900. }
  2901. #endif /* CONFIG_TMPFS */
  2902. /**
  2903. * mpol_to_str - format a mempolicy structure for printing
  2904. * @buffer: to contain formatted mempolicy string
  2905. * @maxlen: length of @buffer
  2906. * @pol: pointer to mempolicy to be formatted
  2907. *
  2908. * Convert @pol into a string. If @buffer is too short, truncate the string.
  2909. * Recommend a @maxlen of at least 51 for the longest mode, "weighted
  2910. * interleave", plus the longest flag flags, "relative|balancing", and to
  2911. * display at least a few node ids.
  2912. */
  2913. void mpol_to_str(char *buffer, int maxlen, struct mempolicy *pol)
  2914. {
  2915. char *p = buffer;
  2916. nodemask_t nodes = NODE_MASK_NONE;
  2917. unsigned short mode = MPOL_DEFAULT;
  2918. unsigned short flags = 0;
  2919. if (pol &&
  2920. pol != &default_policy &&
  2921. !(pol >= &preferred_node_policy[0] &&
  2922. pol <= &preferred_node_policy[ARRAY_SIZE(preferred_node_policy) - 1])) {
  2923. mode = pol->mode;
  2924. flags = pol->flags;
  2925. }
  2926. switch (mode) {
  2927. case MPOL_DEFAULT:
  2928. case MPOL_LOCAL:
  2929. break;
  2930. case MPOL_PREFERRED:
  2931. case MPOL_PREFERRED_MANY:
  2932. case MPOL_BIND:
  2933. case MPOL_INTERLEAVE:
  2934. case MPOL_WEIGHTED_INTERLEAVE:
  2935. nodes = pol->nodes;
  2936. break;
  2937. default:
  2938. WARN_ON_ONCE(1);
  2939. snprintf(p, maxlen, "unknown");
  2940. return;
  2941. }
  2942. p += snprintf(p, maxlen, "%s", policy_modes[mode]);
  2943. if (flags & MPOL_MODE_FLAGS) {
  2944. p += snprintf(p, buffer + maxlen - p, "=");
  2945. /*
  2946. * Static and relative are mutually exclusive.
  2947. */
  2948. if (flags & MPOL_F_STATIC_NODES)
  2949. p += snprintf(p, buffer + maxlen - p, "static");
  2950. else if (flags & MPOL_F_RELATIVE_NODES)
  2951. p += snprintf(p, buffer + maxlen - p, "relative");
  2952. if (flags & MPOL_F_NUMA_BALANCING) {
  2953. if (!is_power_of_2(flags & MPOL_MODE_FLAGS))
  2954. p += snprintf(p, buffer + maxlen - p, "|");
  2955. p += snprintf(p, buffer + maxlen - p, "balancing");
  2956. }
  2957. }
  2958. if (!nodes_empty(nodes))
  2959. p += scnprintf(p, buffer + maxlen - p, ":%*pbl",
  2960. nodemask_pr_args(&nodes));
  2961. }
  2962. #ifdef CONFIG_SYSFS
  2963. struct iw_node_attr {
  2964. struct kobj_attribute kobj_attr;
  2965. int nid;
  2966. };
  2967. static ssize_t node_show(struct kobject *kobj, struct kobj_attribute *attr,
  2968. char *buf)
  2969. {
  2970. struct iw_node_attr *node_attr;
  2971. u8 weight;
  2972. node_attr = container_of(attr, struct iw_node_attr, kobj_attr);
  2973. weight = get_il_weight(node_attr->nid);
  2974. return sysfs_emit(buf, "%d\n", weight);
  2975. }
  2976. static ssize_t node_store(struct kobject *kobj, struct kobj_attribute *attr,
  2977. const char *buf, size_t count)
  2978. {
  2979. struct iw_node_attr *node_attr;
  2980. u8 *new;
  2981. u8 *old;
  2982. u8 weight = 0;
  2983. node_attr = container_of(attr, struct iw_node_attr, kobj_attr);
  2984. if (count == 0 || sysfs_streq(buf, ""))
  2985. weight = 0;
  2986. else if (kstrtou8(buf, 0, &weight))
  2987. return -EINVAL;
  2988. new = kzalloc(nr_node_ids, GFP_KERNEL);
  2989. if (!new)
  2990. return -ENOMEM;
  2991. mutex_lock(&iw_table_lock);
  2992. old = rcu_dereference_protected(iw_table,
  2993. lockdep_is_held(&iw_table_lock));
  2994. if (old)
  2995. memcpy(new, old, nr_node_ids);
  2996. new[node_attr->nid] = weight;
  2997. rcu_assign_pointer(iw_table, new);
  2998. mutex_unlock(&iw_table_lock);
  2999. synchronize_rcu();
  3000. kfree(old);
  3001. return count;
  3002. }
  3003. static struct iw_node_attr **node_attrs;
  3004. static void sysfs_wi_node_release(struct iw_node_attr *node_attr,
  3005. struct kobject *parent)
  3006. {
  3007. if (!node_attr)
  3008. return;
  3009. sysfs_remove_file(parent, &node_attr->kobj_attr.attr);
  3010. kfree(node_attr->kobj_attr.attr.name);
  3011. kfree(node_attr);
  3012. }
  3013. static void sysfs_wi_release(struct kobject *wi_kobj)
  3014. {
  3015. int i;
  3016. for (i = 0; i < nr_node_ids; i++)
  3017. sysfs_wi_node_release(node_attrs[i], wi_kobj);
  3018. kobject_put(wi_kobj);
  3019. }
  3020. static const struct kobj_type wi_ktype = {
  3021. .sysfs_ops = &kobj_sysfs_ops,
  3022. .release = sysfs_wi_release,
  3023. };
  3024. static int add_weight_node(int nid, struct kobject *wi_kobj)
  3025. {
  3026. struct iw_node_attr *node_attr;
  3027. char *name;
  3028. node_attr = kzalloc(sizeof(*node_attr), GFP_KERNEL);
  3029. if (!node_attr)
  3030. return -ENOMEM;
  3031. name = kasprintf(GFP_KERNEL, "node%d", nid);
  3032. if (!name) {
  3033. kfree(node_attr);
  3034. return -ENOMEM;
  3035. }
  3036. sysfs_attr_init(&node_attr->kobj_attr.attr);
  3037. node_attr->kobj_attr.attr.name = name;
  3038. node_attr->kobj_attr.attr.mode = 0644;
  3039. node_attr->kobj_attr.show = node_show;
  3040. node_attr->kobj_attr.store = node_store;
  3041. node_attr->nid = nid;
  3042. if (sysfs_create_file(wi_kobj, &node_attr->kobj_attr.attr)) {
  3043. kfree(node_attr->kobj_attr.attr.name);
  3044. kfree(node_attr);
  3045. pr_err("failed to add attribute to weighted_interleave\n");
  3046. return -ENOMEM;
  3047. }
  3048. node_attrs[nid] = node_attr;
  3049. return 0;
  3050. }
  3051. static int add_weighted_interleave_group(struct kobject *root_kobj)
  3052. {
  3053. struct kobject *wi_kobj;
  3054. int nid, err;
  3055. wi_kobj = kzalloc(sizeof(struct kobject), GFP_KERNEL);
  3056. if (!wi_kobj)
  3057. return -ENOMEM;
  3058. err = kobject_init_and_add(wi_kobj, &wi_ktype, root_kobj,
  3059. "weighted_interleave");
  3060. if (err) {
  3061. kfree(wi_kobj);
  3062. return err;
  3063. }
  3064. for_each_node_state(nid, N_POSSIBLE) {
  3065. err = add_weight_node(nid, wi_kobj);
  3066. if (err) {
  3067. pr_err("failed to add sysfs [node%d]\n", nid);
  3068. break;
  3069. }
  3070. }
  3071. if (err)
  3072. kobject_put(wi_kobj);
  3073. return 0;
  3074. }
  3075. static void mempolicy_kobj_release(struct kobject *kobj)
  3076. {
  3077. u8 *old;
  3078. mutex_lock(&iw_table_lock);
  3079. old = rcu_dereference_protected(iw_table,
  3080. lockdep_is_held(&iw_table_lock));
  3081. rcu_assign_pointer(iw_table, NULL);
  3082. mutex_unlock(&iw_table_lock);
  3083. synchronize_rcu();
  3084. kfree(old);
  3085. kfree(node_attrs);
  3086. kfree(kobj);
  3087. }
  3088. static const struct kobj_type mempolicy_ktype = {
  3089. .release = mempolicy_kobj_release
  3090. };
  3091. static int __init mempolicy_sysfs_init(void)
  3092. {
  3093. int err;
  3094. static struct kobject *mempolicy_kobj;
  3095. mempolicy_kobj = kzalloc(sizeof(*mempolicy_kobj), GFP_KERNEL);
  3096. if (!mempolicy_kobj) {
  3097. err = -ENOMEM;
  3098. goto err_out;
  3099. }
  3100. node_attrs = kcalloc(nr_node_ids, sizeof(struct iw_node_attr *),
  3101. GFP_KERNEL);
  3102. if (!node_attrs) {
  3103. err = -ENOMEM;
  3104. goto mempol_out;
  3105. }
  3106. err = kobject_init_and_add(mempolicy_kobj, &mempolicy_ktype, mm_kobj,
  3107. "mempolicy");
  3108. if (err)
  3109. goto node_out;
  3110. err = add_weighted_interleave_group(mempolicy_kobj);
  3111. if (err) {
  3112. pr_err("mempolicy sysfs structure failed to initialize\n");
  3113. kobject_put(mempolicy_kobj);
  3114. return err;
  3115. }
  3116. return err;
  3117. node_out:
  3118. kfree(node_attrs);
  3119. mempol_out:
  3120. kfree(mempolicy_kobj);
  3121. err_out:
  3122. pr_err("failed to add mempolicy kobject to the system\n");
  3123. return err;
  3124. }
  3125. late_initcall(mempolicy_sysfs_init);
  3126. #endif /* CONFIG_SYSFS */