khugepaged.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377
  1. // SPDX-License-Identifier: GPL-2.0
  2. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  3. #include <linux/mm.h>
  4. #include <linux/sched.h>
  5. #include <linux/sched/mm.h>
  6. #include <linux/sched/coredump.h>
  7. #include <linux/mmu_notifier.h>
  8. #include <linux/rmap.h>
  9. #include <linux/swap.h>
  10. #include <linux/mm_inline.h>
  11. #include <linux/kthread.h>
  12. #include <linux/khugepaged.h>
  13. #include <linux/freezer.h>
  14. #include <linux/mman.h>
  15. #include <linux/hashtable.h>
  16. #include <linux/userfaultfd_k.h>
  17. #include <linux/page_idle.h>
  18. #include <linux/swapops.h>
  19. #include <linux/shmem_fs.h>
  20. #include <asm/tlb.h>
  21. #include <asm/pgalloc.h>
  22. #include "internal.h"
  23. enum scan_result {
  24. SCAN_FAIL,
  25. SCAN_SUCCEED,
  26. SCAN_PMD_NULL,
  27. SCAN_EXCEED_NONE_PTE,
  28. SCAN_EXCEED_SWAP_PTE,
  29. SCAN_EXCEED_SHARED_PTE,
  30. SCAN_PTE_NON_PRESENT,
  31. SCAN_PTE_UFFD_WP,
  32. SCAN_PAGE_RO,
  33. SCAN_LACK_REFERENCED_PAGE,
  34. SCAN_PAGE_NULL,
  35. SCAN_SCAN_ABORT,
  36. SCAN_PAGE_COUNT,
  37. SCAN_PAGE_LRU,
  38. SCAN_PAGE_LOCK,
  39. SCAN_PAGE_ANON,
  40. SCAN_PAGE_COMPOUND,
  41. SCAN_ANY_PROCESS,
  42. SCAN_VMA_NULL,
  43. SCAN_VMA_CHECK,
  44. SCAN_ADDRESS_RANGE,
  45. SCAN_SWAP_CACHE_PAGE,
  46. SCAN_DEL_PAGE_LRU,
  47. SCAN_ALLOC_HUGE_PAGE_FAIL,
  48. SCAN_CGROUP_CHARGE_FAIL,
  49. SCAN_TRUNCATED,
  50. SCAN_PAGE_HAS_PRIVATE,
  51. };
  52. #define CREATE_TRACE_POINTS
  53. #include <trace/events/huge_memory.h>
  54. static struct task_struct *khugepaged_thread __read_mostly;
  55. static DEFINE_MUTEX(khugepaged_mutex);
  56. /* default scan 8*512 pte (or vmas) every 30 second */
  57. static unsigned int khugepaged_pages_to_scan __read_mostly;
  58. static unsigned int khugepaged_pages_collapsed;
  59. static unsigned int khugepaged_full_scans;
  60. static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000;
  61. /* during fragmentation poll the hugepage allocator once every minute */
  62. static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000;
  63. static unsigned long khugepaged_sleep_expire;
  64. static DEFINE_SPINLOCK(khugepaged_mm_lock);
  65. static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait);
  66. /*
  67. * default collapse hugepages if there is at least one pte mapped like
  68. * it would have happened if the vma was large enough during page
  69. * fault.
  70. */
  71. static unsigned int khugepaged_max_ptes_none __read_mostly;
  72. static unsigned int khugepaged_max_ptes_swap __read_mostly;
  73. static unsigned int khugepaged_max_ptes_shared __read_mostly;
  74. #define MM_SLOTS_HASH_BITS 10
  75. static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);
  76. static struct kmem_cache *mm_slot_cache __read_mostly;
  77. #define MAX_PTE_MAPPED_THP 8
  78. /**
  79. * struct mm_slot - hash lookup from mm to mm_slot
  80. * @hash: hash collision list
  81. * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head
  82. * @mm: the mm that this information is valid for
  83. */
  84. struct mm_slot {
  85. struct hlist_node hash;
  86. struct list_head mm_node;
  87. struct mm_struct *mm;
  88. /* pte-mapped THP in this mm */
  89. int nr_pte_mapped_thp;
  90. unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP];
  91. };
  92. /**
  93. * struct khugepaged_scan - cursor for scanning
  94. * @mm_head: the head of the mm list to scan
  95. * @mm_slot: the current mm_slot we are scanning
  96. * @address: the next address inside that to be scanned
  97. *
  98. * There is only the one khugepaged_scan instance of this cursor structure.
  99. */
  100. struct khugepaged_scan {
  101. struct list_head mm_head;
  102. struct mm_slot *mm_slot;
  103. unsigned long address;
  104. };
  105. static struct khugepaged_scan khugepaged_scan = {
  106. .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
  107. };
  108. #ifdef CONFIG_SYSFS
  109. static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
  110. struct kobj_attribute *attr,
  111. char *buf)
  112. {
  113. return sprintf(buf, "%u\n", khugepaged_scan_sleep_millisecs);
  114. }
  115. static ssize_t scan_sleep_millisecs_store(struct kobject *kobj,
  116. struct kobj_attribute *attr,
  117. const char *buf, size_t count)
  118. {
  119. unsigned long msecs;
  120. int err;
  121. err = kstrtoul(buf, 10, &msecs);
  122. if (err || msecs > UINT_MAX)
  123. return -EINVAL;
  124. khugepaged_scan_sleep_millisecs = msecs;
  125. khugepaged_sleep_expire = 0;
  126. wake_up_interruptible(&khugepaged_wait);
  127. return count;
  128. }
  129. static struct kobj_attribute scan_sleep_millisecs_attr =
  130. __ATTR(scan_sleep_millisecs, 0644, scan_sleep_millisecs_show,
  131. scan_sleep_millisecs_store);
  132. static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj,
  133. struct kobj_attribute *attr,
  134. char *buf)
  135. {
  136. return sprintf(buf, "%u\n", khugepaged_alloc_sleep_millisecs);
  137. }
  138. static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj,
  139. struct kobj_attribute *attr,
  140. const char *buf, size_t count)
  141. {
  142. unsigned long msecs;
  143. int err;
  144. err = kstrtoul(buf, 10, &msecs);
  145. if (err || msecs > UINT_MAX)
  146. return -EINVAL;
  147. khugepaged_alloc_sleep_millisecs = msecs;
  148. khugepaged_sleep_expire = 0;
  149. wake_up_interruptible(&khugepaged_wait);
  150. return count;
  151. }
  152. static struct kobj_attribute alloc_sleep_millisecs_attr =
  153. __ATTR(alloc_sleep_millisecs, 0644, alloc_sleep_millisecs_show,
  154. alloc_sleep_millisecs_store);
  155. static ssize_t pages_to_scan_show(struct kobject *kobj,
  156. struct kobj_attribute *attr,
  157. char *buf)
  158. {
  159. return sprintf(buf, "%u\n", khugepaged_pages_to_scan);
  160. }
  161. static ssize_t pages_to_scan_store(struct kobject *kobj,
  162. struct kobj_attribute *attr,
  163. const char *buf, size_t count)
  164. {
  165. int err;
  166. unsigned long pages;
  167. err = kstrtoul(buf, 10, &pages);
  168. if (err || !pages || pages > UINT_MAX)
  169. return -EINVAL;
  170. khugepaged_pages_to_scan = pages;
  171. return count;
  172. }
  173. static struct kobj_attribute pages_to_scan_attr =
  174. __ATTR(pages_to_scan, 0644, pages_to_scan_show,
  175. pages_to_scan_store);
  176. static ssize_t pages_collapsed_show(struct kobject *kobj,
  177. struct kobj_attribute *attr,
  178. char *buf)
  179. {
  180. return sprintf(buf, "%u\n", khugepaged_pages_collapsed);
  181. }
  182. static struct kobj_attribute pages_collapsed_attr =
  183. __ATTR_RO(pages_collapsed);
  184. static ssize_t full_scans_show(struct kobject *kobj,
  185. struct kobj_attribute *attr,
  186. char *buf)
  187. {
  188. return sprintf(buf, "%u\n", khugepaged_full_scans);
  189. }
  190. static struct kobj_attribute full_scans_attr =
  191. __ATTR_RO(full_scans);
  192. static ssize_t khugepaged_defrag_show(struct kobject *kobj,
  193. struct kobj_attribute *attr, char *buf)
  194. {
  195. return single_hugepage_flag_show(kobj, attr, buf,
  196. TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
  197. }
  198. static ssize_t khugepaged_defrag_store(struct kobject *kobj,
  199. struct kobj_attribute *attr,
  200. const char *buf, size_t count)
  201. {
  202. return single_hugepage_flag_store(kobj, attr, buf, count,
  203. TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
  204. }
  205. static struct kobj_attribute khugepaged_defrag_attr =
  206. __ATTR(defrag, 0644, khugepaged_defrag_show,
  207. khugepaged_defrag_store);
  208. /*
  209. * max_ptes_none controls if khugepaged should collapse hugepages over
  210. * any unmapped ptes in turn potentially increasing the memory
  211. * footprint of the vmas. When max_ptes_none is 0 khugepaged will not
  212. * reduce the available free memory in the system as it
  213. * runs. Increasing max_ptes_none will instead potentially reduce the
  214. * free memory in the system during the khugepaged scan.
  215. */
  216. static ssize_t khugepaged_max_ptes_none_show(struct kobject *kobj,
  217. struct kobj_attribute *attr,
  218. char *buf)
  219. {
  220. return sprintf(buf, "%u\n", khugepaged_max_ptes_none);
  221. }
  222. static ssize_t khugepaged_max_ptes_none_store(struct kobject *kobj,
  223. struct kobj_attribute *attr,
  224. const char *buf, size_t count)
  225. {
  226. int err;
  227. unsigned long max_ptes_none;
  228. err = kstrtoul(buf, 10, &max_ptes_none);
  229. if (err || max_ptes_none > HPAGE_PMD_NR-1)
  230. return -EINVAL;
  231. khugepaged_max_ptes_none = max_ptes_none;
  232. return count;
  233. }
  234. static struct kobj_attribute khugepaged_max_ptes_none_attr =
  235. __ATTR(max_ptes_none, 0644, khugepaged_max_ptes_none_show,
  236. khugepaged_max_ptes_none_store);
  237. static ssize_t khugepaged_max_ptes_swap_show(struct kobject *kobj,
  238. struct kobj_attribute *attr,
  239. char *buf)
  240. {
  241. return sprintf(buf, "%u\n", khugepaged_max_ptes_swap);
  242. }
  243. static ssize_t khugepaged_max_ptes_swap_store(struct kobject *kobj,
  244. struct kobj_attribute *attr,
  245. const char *buf, size_t count)
  246. {
  247. int err;
  248. unsigned long max_ptes_swap;
  249. err = kstrtoul(buf, 10, &max_ptes_swap);
  250. if (err || max_ptes_swap > HPAGE_PMD_NR-1)
  251. return -EINVAL;
  252. khugepaged_max_ptes_swap = max_ptes_swap;
  253. return count;
  254. }
  255. static struct kobj_attribute khugepaged_max_ptes_swap_attr =
  256. __ATTR(max_ptes_swap, 0644, khugepaged_max_ptes_swap_show,
  257. khugepaged_max_ptes_swap_store);
  258. static ssize_t khugepaged_max_ptes_shared_show(struct kobject *kobj,
  259. struct kobj_attribute *attr,
  260. char *buf)
  261. {
  262. return sprintf(buf, "%u\n", khugepaged_max_ptes_shared);
  263. }
  264. static ssize_t khugepaged_max_ptes_shared_store(struct kobject *kobj,
  265. struct kobj_attribute *attr,
  266. const char *buf, size_t count)
  267. {
  268. int err;
  269. unsigned long max_ptes_shared;
  270. err = kstrtoul(buf, 10, &max_ptes_shared);
  271. if (err || max_ptes_shared > HPAGE_PMD_NR-1)
  272. return -EINVAL;
  273. khugepaged_max_ptes_shared = max_ptes_shared;
  274. return count;
  275. }
  276. static struct kobj_attribute khugepaged_max_ptes_shared_attr =
  277. __ATTR(max_ptes_shared, 0644, khugepaged_max_ptes_shared_show,
  278. khugepaged_max_ptes_shared_store);
  279. static struct attribute *khugepaged_attr[] = {
  280. &khugepaged_defrag_attr.attr,
  281. &khugepaged_max_ptes_none_attr.attr,
  282. &khugepaged_max_ptes_swap_attr.attr,
  283. &khugepaged_max_ptes_shared_attr.attr,
  284. &pages_to_scan_attr.attr,
  285. &pages_collapsed_attr.attr,
  286. &full_scans_attr.attr,
  287. &scan_sleep_millisecs_attr.attr,
  288. &alloc_sleep_millisecs_attr.attr,
  289. NULL,
  290. };
  291. struct attribute_group khugepaged_attr_group = {
  292. .attrs = khugepaged_attr,
  293. .name = "khugepaged",
  294. };
  295. #endif /* CONFIG_SYSFS */
  296. int hugepage_madvise(struct vm_area_struct *vma,
  297. unsigned long *vm_flags, int advice)
  298. {
  299. switch (advice) {
  300. case MADV_HUGEPAGE:
  301. #ifdef CONFIG_S390
  302. /*
  303. * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390
  304. * can't handle this properly after s390_enable_sie, so we simply
  305. * ignore the madvise to prevent qemu from causing a SIGSEGV.
  306. */
  307. if (mm_has_pgste(vma->vm_mm))
  308. return 0;
  309. #endif
  310. *vm_flags &= ~VM_NOHUGEPAGE;
  311. *vm_flags |= VM_HUGEPAGE;
  312. /*
  313. * If the vma become good for khugepaged to scan,
  314. * register it here without waiting a page fault that
  315. * may not happen any time soon.
  316. */
  317. if (!(*vm_flags & VM_NO_KHUGEPAGED) &&
  318. khugepaged_enter_vma_merge(vma, *vm_flags))
  319. return -ENOMEM;
  320. break;
  321. case MADV_NOHUGEPAGE:
  322. *vm_flags &= ~VM_HUGEPAGE;
  323. *vm_flags |= VM_NOHUGEPAGE;
  324. /*
  325. * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
  326. * this vma even if we leave the mm registered in khugepaged if
  327. * it got registered before VM_NOHUGEPAGE was set.
  328. */
  329. break;
  330. }
  331. return 0;
  332. }
  333. int __init khugepaged_init(void)
  334. {
  335. mm_slot_cache = kmem_cache_create("khugepaged_mm_slot",
  336. sizeof(struct mm_slot),
  337. __alignof__(struct mm_slot), 0, NULL);
  338. if (!mm_slot_cache)
  339. return -ENOMEM;
  340. khugepaged_pages_to_scan = HPAGE_PMD_NR * 8;
  341. khugepaged_max_ptes_none = HPAGE_PMD_NR - 1;
  342. khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8;
  343. khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2;
  344. return 0;
  345. }
  346. void __init khugepaged_destroy(void)
  347. {
  348. kmem_cache_destroy(mm_slot_cache);
  349. }
  350. static inline struct mm_slot *alloc_mm_slot(void)
  351. {
  352. if (!mm_slot_cache) /* initialization failed */
  353. return NULL;
  354. return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL);
  355. }
  356. static inline void free_mm_slot(struct mm_slot *mm_slot)
  357. {
  358. kmem_cache_free(mm_slot_cache, mm_slot);
  359. }
  360. static struct mm_slot *get_mm_slot(struct mm_struct *mm)
  361. {
  362. struct mm_slot *mm_slot;
  363. hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm)
  364. if (mm == mm_slot->mm)
  365. return mm_slot;
  366. return NULL;
  367. }
  368. static void insert_to_mm_slots_hash(struct mm_struct *mm,
  369. struct mm_slot *mm_slot)
  370. {
  371. mm_slot->mm = mm;
  372. hash_add(mm_slots_hash, &mm_slot->hash, (long)mm);
  373. }
  374. static inline int khugepaged_test_exit(struct mm_struct *mm)
  375. {
  376. return atomic_read(&mm->mm_users) == 0;
  377. }
  378. static bool hugepage_vma_check(struct vm_area_struct *vma,
  379. unsigned long vm_flags)
  380. {
  381. if (!transhuge_vma_enabled(vma, vm_flags))
  382. return false;
  383. if (vma->vm_file && !IS_ALIGNED((vma->vm_start >> PAGE_SHIFT) -
  384. vma->vm_pgoff, HPAGE_PMD_NR))
  385. return false;
  386. /* Enabled via shmem mount options or sysfs settings. */
  387. if (shmem_file(vma->vm_file))
  388. return shmem_huge_enabled(vma);
  389. /* THP settings require madvise. */
  390. if (!(vm_flags & VM_HUGEPAGE) && !khugepaged_always())
  391. return false;
  392. /* Only regular file is valid */
  393. if (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && vma->vm_file &&
  394. !inode_is_open_for_write(vma->vm_file->f_inode) &&
  395. (vm_flags & VM_EXEC)) {
  396. struct inode *inode = vma->vm_file->f_inode;
  397. return S_ISREG(inode->i_mode);
  398. }
  399. if (!vma->anon_vma || vma->vm_ops)
  400. return false;
  401. if (vma_is_temporary_stack(vma))
  402. return false;
  403. return !(vm_flags & VM_NO_KHUGEPAGED);
  404. }
  405. int __khugepaged_enter(struct mm_struct *mm)
  406. {
  407. struct mm_slot *mm_slot;
  408. int wakeup;
  409. mm_slot = alloc_mm_slot();
  410. if (!mm_slot)
  411. return -ENOMEM;
  412. /* __khugepaged_exit() must not run from under us */
  413. VM_BUG_ON_MM(atomic_read(&mm->mm_users) == 0, mm);
  414. if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) {
  415. free_mm_slot(mm_slot);
  416. return 0;
  417. }
  418. spin_lock(&khugepaged_mm_lock);
  419. insert_to_mm_slots_hash(mm, mm_slot);
  420. /*
  421. * Insert just behind the scanning cursor, to let the area settle
  422. * down a little.
  423. */
  424. wakeup = list_empty(&khugepaged_scan.mm_head);
  425. list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head);
  426. spin_unlock(&khugepaged_mm_lock);
  427. mmgrab(mm);
  428. if (wakeup)
  429. wake_up_interruptible(&khugepaged_wait);
  430. return 0;
  431. }
  432. int khugepaged_enter_vma_merge(struct vm_area_struct *vma,
  433. unsigned long vm_flags)
  434. {
  435. unsigned long hstart, hend;
  436. /*
  437. * khugepaged only supports read-only files for non-shmem files.
  438. * khugepaged does not yet work on special mappings. And
  439. * file-private shmem THP is not supported.
  440. */
  441. if (!hugepage_vma_check(vma, vm_flags))
  442. return 0;
  443. hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
  444. hend = vma->vm_end & HPAGE_PMD_MASK;
  445. if (hstart < hend)
  446. return khugepaged_enter(vma, vm_flags);
  447. return 0;
  448. }
  449. void __khugepaged_exit(struct mm_struct *mm)
  450. {
  451. struct mm_slot *mm_slot;
  452. int free = 0;
  453. spin_lock(&khugepaged_mm_lock);
  454. mm_slot = get_mm_slot(mm);
  455. if (mm_slot && khugepaged_scan.mm_slot != mm_slot) {
  456. hash_del(&mm_slot->hash);
  457. list_del(&mm_slot->mm_node);
  458. free = 1;
  459. }
  460. spin_unlock(&khugepaged_mm_lock);
  461. if (free) {
  462. clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
  463. free_mm_slot(mm_slot);
  464. mmdrop(mm);
  465. } else if (mm_slot) {
  466. /*
  467. * This is required to serialize against
  468. * khugepaged_test_exit() (which is guaranteed to run
  469. * under mmap sem read mode). Stop here (after we
  470. * return all pagetables will be destroyed) until
  471. * khugepaged has finished working on the pagetables
  472. * under the mmap_lock.
  473. */
  474. mmap_write_lock(mm);
  475. mmap_write_unlock(mm);
  476. }
  477. }
  478. static void release_pte_page(struct page *page)
  479. {
  480. mod_node_page_state(page_pgdat(page),
  481. NR_ISOLATED_ANON + page_is_file_lru(page),
  482. -compound_nr(page));
  483. unlock_page(page);
  484. putback_lru_page(page);
  485. }
  486. static void release_pte_pages(pte_t *pte, pte_t *_pte,
  487. struct list_head *compound_pagelist)
  488. {
  489. struct page *page, *tmp;
  490. while (--_pte >= pte) {
  491. pte_t pteval = *_pte;
  492. page = pte_page(pteval);
  493. if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) &&
  494. !PageCompound(page))
  495. release_pte_page(page);
  496. }
  497. list_for_each_entry_safe(page, tmp, compound_pagelist, lru) {
  498. list_del(&page->lru);
  499. release_pte_page(page);
  500. }
  501. }
  502. static bool is_refcount_suitable(struct page *page)
  503. {
  504. int expected_refcount;
  505. expected_refcount = total_mapcount(page);
  506. if (PageSwapCache(page))
  507. expected_refcount += compound_nr(page);
  508. return page_count(page) == expected_refcount;
  509. }
  510. static int __collapse_huge_page_isolate(struct vm_area_struct *vma,
  511. unsigned long address,
  512. pte_t *pte,
  513. struct list_head *compound_pagelist)
  514. {
  515. struct page *page = NULL;
  516. pte_t *_pte;
  517. int none_or_zero = 0, shared = 0, result = 0, referenced = 0;
  518. bool writable = false;
  519. for (_pte = pte; _pte < pte+HPAGE_PMD_NR;
  520. _pte++, address += PAGE_SIZE) {
  521. pte_t pteval = *_pte;
  522. if (pte_none(pteval) || (pte_present(pteval) &&
  523. is_zero_pfn(pte_pfn(pteval)))) {
  524. if (!userfaultfd_armed(vma) &&
  525. ++none_or_zero <= khugepaged_max_ptes_none) {
  526. continue;
  527. } else {
  528. result = SCAN_EXCEED_NONE_PTE;
  529. goto out;
  530. }
  531. }
  532. if (!pte_present(pteval)) {
  533. result = SCAN_PTE_NON_PRESENT;
  534. goto out;
  535. }
  536. page = vm_normal_page(vma, address, pteval);
  537. if (unlikely(!page)) {
  538. result = SCAN_PAGE_NULL;
  539. goto out;
  540. }
  541. VM_BUG_ON_PAGE(!PageAnon(page), page);
  542. if (page_mapcount(page) > 1 &&
  543. ++shared > khugepaged_max_ptes_shared) {
  544. result = SCAN_EXCEED_SHARED_PTE;
  545. goto out;
  546. }
  547. if (PageCompound(page)) {
  548. struct page *p;
  549. page = compound_head(page);
  550. /*
  551. * Check if we have dealt with the compound page
  552. * already
  553. */
  554. list_for_each_entry(p, compound_pagelist, lru) {
  555. if (page == p)
  556. goto next;
  557. }
  558. }
  559. /*
  560. * We can do it before isolate_lru_page because the
  561. * page can't be freed from under us. NOTE: PG_lock
  562. * is needed to serialize against split_huge_page
  563. * when invoked from the VM.
  564. */
  565. if (!trylock_page(page)) {
  566. result = SCAN_PAGE_LOCK;
  567. goto out;
  568. }
  569. /*
  570. * Check if the page has any GUP (or other external) pins.
  571. *
  572. * The page table that maps the page has been already unlinked
  573. * from the page table tree and this process cannot get
  574. * an additinal pin on the page.
  575. *
  576. * New pins can come later if the page is shared across fork,
  577. * but not from this process. The other process cannot write to
  578. * the page, only trigger CoW.
  579. */
  580. if (!is_refcount_suitable(page)) {
  581. unlock_page(page);
  582. result = SCAN_PAGE_COUNT;
  583. goto out;
  584. }
  585. if (!pte_write(pteval) && PageSwapCache(page) &&
  586. !reuse_swap_page(page, NULL)) {
  587. /*
  588. * Page is in the swap cache and cannot be re-used.
  589. * It cannot be collapsed into a THP.
  590. */
  591. unlock_page(page);
  592. result = SCAN_SWAP_CACHE_PAGE;
  593. goto out;
  594. }
  595. /*
  596. * Isolate the page to avoid collapsing an hugepage
  597. * currently in use by the VM.
  598. */
  599. if (isolate_lru_page(page)) {
  600. unlock_page(page);
  601. result = SCAN_DEL_PAGE_LRU;
  602. goto out;
  603. }
  604. mod_node_page_state(page_pgdat(page),
  605. NR_ISOLATED_ANON + page_is_file_lru(page),
  606. compound_nr(page));
  607. VM_BUG_ON_PAGE(!PageLocked(page), page);
  608. VM_BUG_ON_PAGE(PageLRU(page), page);
  609. if (PageCompound(page))
  610. list_add_tail(&page->lru, compound_pagelist);
  611. next:
  612. /* There should be enough young pte to collapse the page */
  613. if (pte_young(pteval) ||
  614. page_is_young(page) || PageReferenced(page) ||
  615. mmu_notifier_test_young(vma->vm_mm, address))
  616. referenced++;
  617. if (pte_write(pteval))
  618. writable = true;
  619. }
  620. if (unlikely(!writable)) {
  621. result = SCAN_PAGE_RO;
  622. } else if (unlikely(!referenced)) {
  623. result = SCAN_LACK_REFERENCED_PAGE;
  624. } else {
  625. result = SCAN_SUCCEED;
  626. trace_mm_collapse_huge_page_isolate(page, none_or_zero,
  627. referenced, writable, result);
  628. return 1;
  629. }
  630. out:
  631. release_pte_pages(pte, _pte, compound_pagelist);
  632. trace_mm_collapse_huge_page_isolate(page, none_or_zero,
  633. referenced, writable, result);
  634. return 0;
  635. }
  636. static void __collapse_huge_page_copy(pte_t *pte, struct page *page,
  637. struct vm_area_struct *vma,
  638. unsigned long address,
  639. spinlock_t *ptl,
  640. struct list_head *compound_pagelist)
  641. {
  642. struct page *src_page, *tmp;
  643. pte_t *_pte;
  644. for (_pte = pte; _pte < pte + HPAGE_PMD_NR;
  645. _pte++, page++, address += PAGE_SIZE) {
  646. pte_t pteval = *_pte;
  647. if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
  648. clear_user_highpage(page, address);
  649. add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1);
  650. if (is_zero_pfn(pte_pfn(pteval))) {
  651. /*
  652. * ptl mostly unnecessary.
  653. */
  654. spin_lock(ptl);
  655. /*
  656. * paravirt calls inside pte_clear here are
  657. * superfluous.
  658. */
  659. pte_clear(vma->vm_mm, address, _pte);
  660. spin_unlock(ptl);
  661. }
  662. } else {
  663. src_page = pte_page(pteval);
  664. copy_user_highpage(page, src_page, address, vma);
  665. if (!PageCompound(src_page))
  666. release_pte_page(src_page);
  667. /*
  668. * ptl mostly unnecessary, but preempt has to
  669. * be disabled to update the per-cpu stats
  670. * inside page_remove_rmap().
  671. */
  672. spin_lock(ptl);
  673. /*
  674. * paravirt calls inside pte_clear here are
  675. * superfluous.
  676. */
  677. pte_clear(vma->vm_mm, address, _pte);
  678. page_remove_rmap(src_page, false);
  679. spin_unlock(ptl);
  680. free_page_and_swap_cache(src_page);
  681. }
  682. }
  683. list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) {
  684. list_del(&src_page->lru);
  685. release_pte_page(src_page);
  686. }
  687. }
  688. static void khugepaged_alloc_sleep(void)
  689. {
  690. DEFINE_WAIT(wait);
  691. add_wait_queue(&khugepaged_wait, &wait);
  692. freezable_schedule_timeout_interruptible(
  693. msecs_to_jiffies(khugepaged_alloc_sleep_millisecs));
  694. remove_wait_queue(&khugepaged_wait, &wait);
  695. }
  696. static int khugepaged_node_load[MAX_NUMNODES];
  697. static bool khugepaged_scan_abort(int nid)
  698. {
  699. int i;
  700. /*
  701. * If node_reclaim_mode is disabled, then no extra effort is made to
  702. * allocate memory locally.
  703. */
  704. if (!node_reclaim_mode)
  705. return false;
  706. /* If there is a count for this node already, it must be acceptable */
  707. if (khugepaged_node_load[nid])
  708. return false;
  709. for (i = 0; i < MAX_NUMNODES; i++) {
  710. if (!khugepaged_node_load[i])
  711. continue;
  712. if (node_distance(nid, i) > node_reclaim_distance)
  713. return true;
  714. }
  715. return false;
  716. }
  717. /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */
  718. static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void)
  719. {
  720. return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT;
  721. }
  722. #ifdef CONFIG_NUMA
  723. static int khugepaged_find_target_node(void)
  724. {
  725. static int last_khugepaged_target_node = NUMA_NO_NODE;
  726. int nid, target_node = 0, max_value = 0;
  727. /* find first node with max normal pages hit */
  728. for (nid = 0; nid < MAX_NUMNODES; nid++)
  729. if (khugepaged_node_load[nid] > max_value) {
  730. max_value = khugepaged_node_load[nid];
  731. target_node = nid;
  732. }
  733. /* do some balance if several nodes have the same hit record */
  734. if (target_node <= last_khugepaged_target_node)
  735. for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES;
  736. nid++)
  737. if (max_value == khugepaged_node_load[nid]) {
  738. target_node = nid;
  739. break;
  740. }
  741. last_khugepaged_target_node = target_node;
  742. return target_node;
  743. }
  744. static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
  745. {
  746. if (IS_ERR(*hpage)) {
  747. if (!*wait)
  748. return false;
  749. *wait = false;
  750. *hpage = NULL;
  751. khugepaged_alloc_sleep();
  752. } else if (*hpage) {
  753. put_page(*hpage);
  754. *hpage = NULL;
  755. }
  756. return true;
  757. }
  758. static struct page *
  759. khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
  760. {
  761. VM_BUG_ON_PAGE(*hpage, *hpage);
  762. *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER);
  763. if (unlikely(!*hpage)) {
  764. count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
  765. *hpage = ERR_PTR(-ENOMEM);
  766. return NULL;
  767. }
  768. prep_transhuge_page(*hpage);
  769. count_vm_event(THP_COLLAPSE_ALLOC);
  770. return *hpage;
  771. }
  772. #else
  773. static int khugepaged_find_target_node(void)
  774. {
  775. return 0;
  776. }
  777. static inline struct page *alloc_khugepaged_hugepage(void)
  778. {
  779. struct page *page;
  780. page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(),
  781. HPAGE_PMD_ORDER);
  782. if (page)
  783. prep_transhuge_page(page);
  784. return page;
  785. }
  786. static struct page *khugepaged_alloc_hugepage(bool *wait)
  787. {
  788. struct page *hpage;
  789. do {
  790. hpage = alloc_khugepaged_hugepage();
  791. if (!hpage) {
  792. count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
  793. if (!*wait)
  794. return NULL;
  795. *wait = false;
  796. khugepaged_alloc_sleep();
  797. } else
  798. count_vm_event(THP_COLLAPSE_ALLOC);
  799. } while (unlikely(!hpage) && likely(khugepaged_enabled()));
  800. return hpage;
  801. }
  802. static bool khugepaged_prealloc_page(struct page **hpage, bool *wait)
  803. {
  804. /*
  805. * If the hpage allocated earlier was briefly exposed in page cache
  806. * before collapse_file() failed, it is possible that racing lookups
  807. * have not yet completed, and would then be unpleasantly surprised by
  808. * finding the hpage reused for the same mapping at a different offset.
  809. * Just release the previous allocation if there is any danger of that.
  810. */
  811. if (*hpage && page_count(*hpage) > 1) {
  812. put_page(*hpage);
  813. *hpage = NULL;
  814. }
  815. if (!*hpage)
  816. *hpage = khugepaged_alloc_hugepage(wait);
  817. if (unlikely(!*hpage))
  818. return false;
  819. return true;
  820. }
  821. static struct page *
  822. khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node)
  823. {
  824. VM_BUG_ON(!*hpage);
  825. return *hpage;
  826. }
  827. #endif
  828. /*
  829. * If mmap_lock temporarily dropped, revalidate vma
  830. * before taking mmap_lock.
  831. * Return 0 if succeeds, otherwise return none-zero
  832. * value (scan code).
  833. */
  834. static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address,
  835. struct vm_area_struct **vmap)
  836. {
  837. struct vm_area_struct *vma;
  838. unsigned long hstart, hend;
  839. if (unlikely(khugepaged_test_exit(mm)))
  840. return SCAN_ANY_PROCESS;
  841. *vmap = vma = find_vma(mm, address);
  842. if (!vma)
  843. return SCAN_VMA_NULL;
  844. hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
  845. hend = vma->vm_end & HPAGE_PMD_MASK;
  846. if (address < hstart || address + HPAGE_PMD_SIZE > hend)
  847. return SCAN_ADDRESS_RANGE;
  848. if (!hugepage_vma_check(vma, vma->vm_flags))
  849. return SCAN_VMA_CHECK;
  850. /* Anon VMA expected */
  851. if (!vma->anon_vma || vma->vm_ops)
  852. return SCAN_VMA_CHECK;
  853. return 0;
  854. }
  855. /*
  856. * Bring missing pages in from swap, to complete THP collapse.
  857. * Only done if khugepaged_scan_pmd believes it is worthwhile.
  858. *
  859. * Called and returns without pte mapped or spinlocks held,
  860. * but with mmap_lock held to protect against vma changes.
  861. */
  862. static bool __collapse_huge_page_swapin(struct mm_struct *mm,
  863. struct vm_area_struct *vma,
  864. unsigned long haddr, pmd_t *pmd,
  865. int referenced)
  866. {
  867. int swapped_in = 0;
  868. vm_fault_t ret = 0;
  869. unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE);
  870. for (address = haddr; address < end; address += PAGE_SIZE) {
  871. struct vm_fault vmf = {
  872. .vma = vma,
  873. .address = address,
  874. .pgoff = linear_page_index(vma, haddr),
  875. .flags = FAULT_FLAG_ALLOW_RETRY,
  876. .pmd = pmd,
  877. .vma_flags = vma->vm_flags,
  878. .vma_page_prot = vma->vm_page_prot,
  879. };
  880. vmf.pte = pte_offset_map(pmd, address);
  881. vmf.orig_pte = *vmf.pte;
  882. if (!is_swap_pte(vmf.orig_pte)) {
  883. pte_unmap(vmf.pte);
  884. continue;
  885. }
  886. swapped_in++;
  887. ret = do_swap_page(&vmf);
  888. /* do_swap_page returns VM_FAULT_RETRY with released mmap_lock */
  889. if (ret & VM_FAULT_RETRY) {
  890. mmap_read_lock(mm);
  891. if (hugepage_vma_revalidate(mm, haddr, &vma)) {
  892. /* vma is no longer available, don't continue to swapin */
  893. trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
  894. return false;
  895. }
  896. /* check if the pmd is still valid */
  897. if (mm_find_pmd(mm, haddr) != pmd) {
  898. trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
  899. return false;
  900. }
  901. }
  902. if (ret & VM_FAULT_ERROR) {
  903. trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0);
  904. return false;
  905. }
  906. }
  907. /* Drain LRU add pagevec to remove extra pin on the swapped in pages */
  908. if (swapped_in)
  909. lru_add_drain();
  910. trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1);
  911. return true;
  912. }
  913. static void collapse_huge_page(struct mm_struct *mm,
  914. unsigned long address,
  915. struct page **hpage,
  916. int node, int referenced, int unmapped)
  917. {
  918. LIST_HEAD(compound_pagelist);
  919. pmd_t *pmd, _pmd;
  920. pte_t *pte;
  921. pgtable_t pgtable;
  922. struct page *new_page;
  923. spinlock_t *pmd_ptl, *pte_ptl;
  924. int isolated = 0, result = 0;
  925. struct vm_area_struct *vma;
  926. struct mmu_notifier_range range;
  927. gfp_t gfp;
  928. VM_BUG_ON(address & ~HPAGE_PMD_MASK);
  929. /* Only allocate from the target node */
  930. gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
  931. /*
  932. * Before allocating the hugepage, release the mmap_lock read lock.
  933. * The allocation can take potentially a long time if it involves
  934. * sync compaction, and we do not need to hold the mmap_lock during
  935. * that. We will recheck the vma after taking it again in write mode.
  936. */
  937. mmap_read_unlock(mm);
  938. new_page = khugepaged_alloc_page(hpage, gfp, node);
  939. if (!new_page) {
  940. result = SCAN_ALLOC_HUGE_PAGE_FAIL;
  941. goto out_nolock;
  942. }
  943. if (unlikely(mem_cgroup_charge(new_page, mm, gfp))) {
  944. result = SCAN_CGROUP_CHARGE_FAIL;
  945. goto out_nolock;
  946. }
  947. count_memcg_page_event(new_page, THP_COLLAPSE_ALLOC);
  948. mmap_read_lock(mm);
  949. result = hugepage_vma_revalidate(mm, address, &vma);
  950. if (result) {
  951. mmap_read_unlock(mm);
  952. goto out_nolock;
  953. }
  954. pmd = mm_find_pmd(mm, address);
  955. if (!pmd) {
  956. result = SCAN_PMD_NULL;
  957. mmap_read_unlock(mm);
  958. goto out_nolock;
  959. }
  960. /*
  961. * __collapse_huge_page_swapin always returns with mmap_lock locked.
  962. * If it fails, we release mmap_lock and jump out_nolock.
  963. * Continuing to collapse causes inconsistency.
  964. */
  965. if (unmapped && !__collapse_huge_page_swapin(mm, vma, address,
  966. pmd, referenced)) {
  967. mmap_read_unlock(mm);
  968. goto out_nolock;
  969. }
  970. mmap_read_unlock(mm);
  971. /*
  972. * Prevent all access to pagetables with the exception of
  973. * gup_fast later handled by the ptep_clear_flush and the VM
  974. * handled by the anon_vma lock + PG_lock.
  975. */
  976. mmap_write_lock(mm);
  977. result = hugepage_vma_revalidate(mm, address, &vma);
  978. if (result)
  979. goto out;
  980. /* check if the pmd is still valid */
  981. if (mm_find_pmd(mm, address) != pmd)
  982. goto out;
  983. vm_write_begin(vma);
  984. anon_vma_lock_write(vma->anon_vma);
  985. mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
  986. address, address + HPAGE_PMD_SIZE);
  987. mmu_notifier_invalidate_range_start(&range);
  988. pte = pte_offset_map(pmd, address);
  989. pte_ptl = pte_lockptr(mm, pmd);
  990. pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */
  991. /*
  992. * After this gup_fast can't run anymore. This also removes
  993. * any huge TLB entry from the CPU so we won't allow
  994. * huge and small TLB entries for the same virtual address
  995. * to avoid the risk of CPU bugs in that area.
  996. */
  997. _pmd = pmdp_collapse_flush(vma, address, pmd);
  998. spin_unlock(pmd_ptl);
  999. mmu_notifier_invalidate_range_end(&range);
  1000. spin_lock(pte_ptl);
  1001. isolated = __collapse_huge_page_isolate(vma, address, pte,
  1002. &compound_pagelist);
  1003. spin_unlock(pte_ptl);
  1004. if (unlikely(!isolated)) {
  1005. pte_unmap(pte);
  1006. spin_lock(pmd_ptl);
  1007. BUG_ON(!pmd_none(*pmd));
  1008. /*
  1009. * We can only use set_pmd_at when establishing
  1010. * hugepmds and never for establishing regular pmds that
  1011. * points to regular pagetables. Use pmd_populate for that
  1012. */
  1013. pmd_populate(mm, pmd, pmd_pgtable(_pmd));
  1014. spin_unlock(pmd_ptl);
  1015. anon_vma_unlock_write(vma->anon_vma);
  1016. vm_write_end(vma);
  1017. result = SCAN_FAIL;
  1018. goto out;
  1019. }
  1020. /*
  1021. * All pages are isolated and locked so anon_vma rmap
  1022. * can't run anymore.
  1023. */
  1024. anon_vma_unlock_write(vma->anon_vma);
  1025. __collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl,
  1026. &compound_pagelist);
  1027. pte_unmap(pte);
  1028. __SetPageUptodate(new_page);
  1029. pgtable = pmd_pgtable(_pmd);
  1030. _pmd = mk_huge_pmd(new_page, vma->vm_page_prot);
  1031. _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
  1032. /*
  1033. * spin_lock() below is not the equivalent of smp_wmb(), so
  1034. * this is needed to avoid the copy_huge_page writes to become
  1035. * visible after the set_pmd_at() write.
  1036. */
  1037. smp_wmb();
  1038. spin_lock(pmd_ptl);
  1039. BUG_ON(!pmd_none(*pmd));
  1040. page_add_new_anon_rmap(new_page, vma, address, true);
  1041. lru_cache_add_inactive_or_unevictable(new_page, vma);
  1042. pgtable_trans_huge_deposit(mm, pmd, pgtable);
  1043. set_pmd_at(mm, address, pmd, _pmd);
  1044. update_mmu_cache_pmd(vma, address, pmd);
  1045. spin_unlock(pmd_ptl);
  1046. vm_write_end(vma);
  1047. *hpage = NULL;
  1048. khugepaged_pages_collapsed++;
  1049. result = SCAN_SUCCEED;
  1050. out_up_write:
  1051. mmap_write_unlock(mm);
  1052. out_nolock:
  1053. if (!IS_ERR_OR_NULL(*hpage))
  1054. mem_cgroup_uncharge(*hpage);
  1055. trace_mm_collapse_huge_page(mm, isolated, result);
  1056. return;
  1057. out:
  1058. goto out_up_write;
  1059. }
  1060. static int khugepaged_scan_pmd(struct mm_struct *mm,
  1061. struct vm_area_struct *vma,
  1062. unsigned long address,
  1063. struct page **hpage)
  1064. {
  1065. pmd_t *pmd;
  1066. pte_t *pte, *_pte;
  1067. int ret = 0, result = 0, referenced = 0;
  1068. int none_or_zero = 0, shared = 0;
  1069. struct page *page = NULL;
  1070. unsigned long _address;
  1071. spinlock_t *ptl;
  1072. int node = NUMA_NO_NODE, unmapped = 0;
  1073. bool writable = false;
  1074. VM_BUG_ON(address & ~HPAGE_PMD_MASK);
  1075. pmd = mm_find_pmd(mm, address);
  1076. if (!pmd) {
  1077. result = SCAN_PMD_NULL;
  1078. goto out;
  1079. }
  1080. memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
  1081. pte = pte_offset_map_lock(mm, pmd, address, &ptl);
  1082. for (_address = address, _pte = pte; _pte < pte+HPAGE_PMD_NR;
  1083. _pte++, _address += PAGE_SIZE) {
  1084. pte_t pteval = *_pte;
  1085. if (is_swap_pte(pteval)) {
  1086. if (++unmapped <= khugepaged_max_ptes_swap) {
  1087. /*
  1088. * Always be strict with uffd-wp
  1089. * enabled swap entries. Please see
  1090. * comment below for pte_uffd_wp().
  1091. */
  1092. if (pte_swp_uffd_wp(pteval)) {
  1093. result = SCAN_PTE_UFFD_WP;
  1094. goto out_unmap;
  1095. }
  1096. continue;
  1097. } else {
  1098. result = SCAN_EXCEED_SWAP_PTE;
  1099. goto out_unmap;
  1100. }
  1101. }
  1102. if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) {
  1103. if (!userfaultfd_armed(vma) &&
  1104. ++none_or_zero <= khugepaged_max_ptes_none) {
  1105. continue;
  1106. } else {
  1107. result = SCAN_EXCEED_NONE_PTE;
  1108. goto out_unmap;
  1109. }
  1110. }
  1111. if (!pte_present(pteval)) {
  1112. result = SCAN_PTE_NON_PRESENT;
  1113. goto out_unmap;
  1114. }
  1115. if (pte_uffd_wp(pteval)) {
  1116. /*
  1117. * Don't collapse the page if any of the small
  1118. * PTEs are armed with uffd write protection.
  1119. * Here we can also mark the new huge pmd as
  1120. * write protected if any of the small ones is
  1121. * marked but that could bring uknown
  1122. * userfault messages that falls outside of
  1123. * the registered range. So, just be simple.
  1124. */
  1125. result = SCAN_PTE_UFFD_WP;
  1126. goto out_unmap;
  1127. }
  1128. if (pte_write(pteval))
  1129. writable = true;
  1130. page = vm_normal_page(vma, _address, pteval);
  1131. if (unlikely(!page)) {
  1132. result = SCAN_PAGE_NULL;
  1133. goto out_unmap;
  1134. }
  1135. if (page_mapcount(page) > 1 &&
  1136. ++shared > khugepaged_max_ptes_shared) {
  1137. result = SCAN_EXCEED_SHARED_PTE;
  1138. goto out_unmap;
  1139. }
  1140. page = compound_head(page);
  1141. /*
  1142. * Record which node the original page is from and save this
  1143. * information to khugepaged_node_load[].
  1144. * Khupaged will allocate hugepage from the node has the max
  1145. * hit record.
  1146. */
  1147. node = page_to_nid(page);
  1148. if (khugepaged_scan_abort(node)) {
  1149. result = SCAN_SCAN_ABORT;
  1150. goto out_unmap;
  1151. }
  1152. khugepaged_node_load[node]++;
  1153. if (!PageLRU(page)) {
  1154. result = SCAN_PAGE_LRU;
  1155. goto out_unmap;
  1156. }
  1157. if (PageLocked(page)) {
  1158. result = SCAN_PAGE_LOCK;
  1159. goto out_unmap;
  1160. }
  1161. if (!PageAnon(page)) {
  1162. result = SCAN_PAGE_ANON;
  1163. goto out_unmap;
  1164. }
  1165. /*
  1166. * Check if the page has any GUP (or other external) pins.
  1167. *
  1168. * Here the check is racy it may see totmal_mapcount > refcount
  1169. * in some cases.
  1170. * For example, one process with one forked child process.
  1171. * The parent has the PMD split due to MADV_DONTNEED, then
  1172. * the child is trying unmap the whole PMD, but khugepaged
  1173. * may be scanning the parent between the child has
  1174. * PageDoubleMap flag cleared and dec the mapcount. So
  1175. * khugepaged may see total_mapcount > refcount.
  1176. *
  1177. * But such case is ephemeral we could always retry collapse
  1178. * later. However it may report false positive if the page
  1179. * has excessive GUP pins (i.e. 512). Anyway the same check
  1180. * will be done again later the risk seems low.
  1181. */
  1182. if (!is_refcount_suitable(page)) {
  1183. result = SCAN_PAGE_COUNT;
  1184. goto out_unmap;
  1185. }
  1186. if (pte_young(pteval) ||
  1187. page_is_young(page) || PageReferenced(page) ||
  1188. mmu_notifier_test_young(vma->vm_mm, address))
  1189. referenced++;
  1190. }
  1191. if (!writable) {
  1192. result = SCAN_PAGE_RO;
  1193. } else if (!referenced || (unmapped && referenced < HPAGE_PMD_NR/2)) {
  1194. result = SCAN_LACK_REFERENCED_PAGE;
  1195. } else {
  1196. result = SCAN_SUCCEED;
  1197. ret = 1;
  1198. }
  1199. out_unmap:
  1200. pte_unmap_unlock(pte, ptl);
  1201. if (ret) {
  1202. node = khugepaged_find_target_node();
  1203. /* collapse_huge_page will return with the mmap_lock released */
  1204. collapse_huge_page(mm, address, hpage, node,
  1205. referenced, unmapped);
  1206. }
  1207. out:
  1208. trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced,
  1209. none_or_zero, result, unmapped);
  1210. return ret;
  1211. }
  1212. static void collect_mm_slot(struct mm_slot *mm_slot)
  1213. {
  1214. struct mm_struct *mm = mm_slot->mm;
  1215. lockdep_assert_held(&khugepaged_mm_lock);
  1216. if (khugepaged_test_exit(mm)) {
  1217. /* free mm_slot */
  1218. hash_del(&mm_slot->hash);
  1219. list_del(&mm_slot->mm_node);
  1220. /*
  1221. * Not strictly needed because the mm exited already.
  1222. *
  1223. * clear_bit(MMF_VM_HUGEPAGE, &mm->flags);
  1224. */
  1225. /* khugepaged_mm_lock actually not necessary for the below */
  1226. free_mm_slot(mm_slot);
  1227. mmdrop(mm);
  1228. }
  1229. }
  1230. #ifdef CONFIG_SHMEM
  1231. /*
  1232. * Notify khugepaged that given addr of the mm is pte-mapped THP. Then
  1233. * khugepaged should try to collapse the page table.
  1234. */
  1235. static int khugepaged_add_pte_mapped_thp(struct mm_struct *mm,
  1236. unsigned long addr)
  1237. {
  1238. struct mm_slot *mm_slot;
  1239. VM_BUG_ON(addr & ~HPAGE_PMD_MASK);
  1240. spin_lock(&khugepaged_mm_lock);
  1241. mm_slot = get_mm_slot(mm);
  1242. if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP))
  1243. mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr;
  1244. spin_unlock(&khugepaged_mm_lock);
  1245. return 0;
  1246. }
  1247. /**
  1248. * Try to collapse a pte-mapped THP for mm at address haddr.
  1249. *
  1250. * This function checks whether all the PTEs in the PMD are pointing to the
  1251. * right THP. If so, retract the page table so the THP can refault in with
  1252. * as pmd-mapped.
  1253. */
  1254. void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr)
  1255. {
  1256. unsigned long haddr = addr & HPAGE_PMD_MASK;
  1257. struct vm_area_struct *vma = find_vma(mm, haddr);
  1258. struct page *hpage;
  1259. pte_t *start_pte, *pte;
  1260. pmd_t *pmd, _pmd;
  1261. spinlock_t *ptl;
  1262. int count = 0;
  1263. int i;
  1264. if (!vma || !vma->vm_file ||
  1265. vma->vm_start > haddr || vma->vm_end < haddr + HPAGE_PMD_SIZE)
  1266. return;
  1267. /*
  1268. * This vm_flags may not have VM_HUGEPAGE if the page was not
  1269. * collapsed by this mm. But we can still collapse if the page is
  1270. * the valid THP. Add extra VM_HUGEPAGE so hugepage_vma_check()
  1271. * will not fail the vma for missing VM_HUGEPAGE
  1272. */
  1273. if (!hugepage_vma_check(vma, vma->vm_flags | VM_HUGEPAGE))
  1274. return;
  1275. hpage = find_lock_page(vma->vm_file->f_mapping,
  1276. linear_page_index(vma, haddr));
  1277. if (!hpage)
  1278. return;
  1279. if (!PageHead(hpage))
  1280. goto drop_hpage;
  1281. pmd = mm_find_pmd(mm, haddr);
  1282. if (!pmd)
  1283. goto drop_hpage;
  1284. start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl);
  1285. /* step 1: check all mapped PTEs are to the right huge page */
  1286. for (i = 0, addr = haddr, pte = start_pte;
  1287. i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
  1288. struct page *page;
  1289. /* empty pte, skip */
  1290. if (pte_none(*pte))
  1291. continue;
  1292. /* page swapped out, abort */
  1293. if (!pte_present(*pte))
  1294. goto abort;
  1295. page = vm_normal_page(vma, addr, *pte);
  1296. /*
  1297. * Note that uprobe, debugger, or MAP_PRIVATE may change the
  1298. * page table, but the new page will not be a subpage of hpage.
  1299. */
  1300. if (hpage + i != page)
  1301. goto abort;
  1302. count++;
  1303. }
  1304. /* step 2: adjust rmap */
  1305. for (i = 0, addr = haddr, pte = start_pte;
  1306. i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) {
  1307. struct page *page;
  1308. if (pte_none(*pte))
  1309. continue;
  1310. page = vm_normal_page(vma, addr, *pte);
  1311. page_remove_rmap(page, false);
  1312. }
  1313. pte_unmap_unlock(start_pte, ptl);
  1314. /* step 3: set proper refcount and mm_counters. */
  1315. if (count) {
  1316. page_ref_sub(hpage, count);
  1317. add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count);
  1318. }
  1319. /* step 4: collapse pmd */
  1320. ptl = pmd_lock(vma->vm_mm, pmd);
  1321. _pmd = pmdp_collapse_flush(vma, haddr, pmd);
  1322. spin_unlock(ptl);
  1323. mm_dec_nr_ptes(mm);
  1324. pte_free(mm, pmd_pgtable(_pmd));
  1325. drop_hpage:
  1326. unlock_page(hpage);
  1327. put_page(hpage);
  1328. return;
  1329. abort:
  1330. pte_unmap_unlock(start_pte, ptl);
  1331. goto drop_hpage;
  1332. }
  1333. static int khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
  1334. {
  1335. struct mm_struct *mm = mm_slot->mm;
  1336. int i;
  1337. if (likely(mm_slot->nr_pte_mapped_thp == 0))
  1338. return 0;
  1339. if (!mmap_write_trylock(mm))
  1340. return -EBUSY;
  1341. if (unlikely(khugepaged_test_exit(mm)))
  1342. goto out;
  1343. for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++)
  1344. collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i]);
  1345. out:
  1346. mm_slot->nr_pte_mapped_thp = 0;
  1347. mmap_write_unlock(mm);
  1348. return 0;
  1349. }
  1350. static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
  1351. {
  1352. struct vm_area_struct *vma;
  1353. struct mm_struct *mm;
  1354. unsigned long addr;
  1355. pmd_t *pmd, _pmd;
  1356. i_mmap_lock_write(mapping);
  1357. vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
  1358. /*
  1359. * Check vma->anon_vma to exclude MAP_PRIVATE mappings that
  1360. * got written to. These VMAs are likely not worth investing
  1361. * mmap_write_lock(mm) as PMD-mapping is likely to be split
  1362. * later.
  1363. *
  1364. * Not that vma->anon_vma check is racy: it can be set up after
  1365. * the check but before we took mmap_lock by the fault path.
  1366. * But page lock would prevent establishing any new ptes of the
  1367. * page, so we are safe.
  1368. *
  1369. * An alternative would be drop the check, but check that page
  1370. * table is clear before calling pmdp_collapse_flush() under
  1371. * ptl. It has higher chance to recover THP for the VMA, but
  1372. * has higher cost too.
  1373. */
  1374. if (vma->anon_vma)
  1375. continue;
  1376. addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
  1377. if (addr & ~HPAGE_PMD_MASK)
  1378. continue;
  1379. if (vma->vm_end < addr + HPAGE_PMD_SIZE)
  1380. continue;
  1381. mm = vma->vm_mm;
  1382. pmd = mm_find_pmd(mm, addr);
  1383. if (!pmd)
  1384. continue;
  1385. /*
  1386. * We need exclusive mmap_lock to retract page table.
  1387. *
  1388. * We use trylock due to lock inversion: we need to acquire
  1389. * mmap_lock while holding page lock. Fault path does it in
  1390. * reverse order. Trylock is a way to avoid deadlock.
  1391. */
  1392. if (mmap_write_trylock(mm)) {
  1393. if (!khugepaged_test_exit(mm)) {
  1394. spinlock_t *ptl = pmd_lock(mm, pmd);
  1395. /* assume page table is clear */
  1396. _pmd = pmdp_collapse_flush(vma, addr, pmd);
  1397. spin_unlock(ptl);
  1398. mm_dec_nr_ptes(mm);
  1399. pte_free(mm, pmd_pgtable(_pmd));
  1400. }
  1401. mmap_write_unlock(mm);
  1402. } else {
  1403. /* Try again later */
  1404. khugepaged_add_pte_mapped_thp(mm, addr);
  1405. }
  1406. }
  1407. i_mmap_unlock_write(mapping);
  1408. }
  1409. /**
  1410. * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
  1411. *
  1412. * Basic scheme is simple, details are more complex:
  1413. * - allocate and lock a new huge page;
  1414. * - scan page cache replacing old pages with the new one
  1415. * + swap/gup in pages if necessary;
  1416. * + fill in gaps;
  1417. * + keep old pages around in case rollback is required;
  1418. * - if replacing succeeds:
  1419. * + copy data over;
  1420. * + free old pages;
  1421. * + unlock huge page;
  1422. * - if replacing failed;
  1423. * + put all pages back and unfreeze them;
  1424. * + restore gaps in the page cache;
  1425. * + unlock and free huge page;
  1426. */
  1427. static void collapse_file(struct mm_struct *mm,
  1428. struct file *file, pgoff_t start,
  1429. struct page **hpage, int node)
  1430. {
  1431. struct address_space *mapping = file->f_mapping;
  1432. gfp_t gfp;
  1433. struct page *new_page;
  1434. pgoff_t index, end = start + HPAGE_PMD_NR;
  1435. LIST_HEAD(pagelist);
  1436. XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
  1437. int nr_none = 0, result = SCAN_SUCCEED;
  1438. bool is_shmem = shmem_file(file);
  1439. VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem);
  1440. VM_BUG_ON(start & (HPAGE_PMD_NR - 1));
  1441. /* Only allocate from the target node */
  1442. gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE;
  1443. new_page = khugepaged_alloc_page(hpage, gfp, node);
  1444. if (!new_page) {
  1445. result = SCAN_ALLOC_HUGE_PAGE_FAIL;
  1446. goto out;
  1447. }
  1448. if (unlikely(mem_cgroup_charge(new_page, mm, gfp))) {
  1449. result = SCAN_CGROUP_CHARGE_FAIL;
  1450. goto out;
  1451. }
  1452. count_memcg_page_event(new_page, THP_COLLAPSE_ALLOC);
  1453. /* This will be less messy when we use multi-index entries */
  1454. do {
  1455. xas_lock_irq(&xas);
  1456. xas_create_range(&xas);
  1457. if (!xas_error(&xas))
  1458. break;
  1459. xas_unlock_irq(&xas);
  1460. if (!xas_nomem(&xas, GFP_KERNEL)) {
  1461. result = SCAN_FAIL;
  1462. goto out;
  1463. }
  1464. } while (1);
  1465. __SetPageLocked(new_page);
  1466. if (is_shmem)
  1467. __SetPageSwapBacked(new_page);
  1468. new_page->index = start;
  1469. new_page->mapping = mapping;
  1470. /*
  1471. * At this point the new_page is locked and not up-to-date.
  1472. * It's safe to insert it into the page cache, because nobody would
  1473. * be able to map it or use it in another way until we unlock it.
  1474. */
  1475. xas_set(&xas, start);
  1476. for (index = start; index < end; index++) {
  1477. struct page *page = xas_next(&xas);
  1478. VM_BUG_ON(index != xas.xa_index);
  1479. if (is_shmem) {
  1480. if (!page) {
  1481. /*
  1482. * Stop if extent has been truncated or
  1483. * hole-punched, and is now completely
  1484. * empty.
  1485. */
  1486. if (index == start) {
  1487. if (!xas_next_entry(&xas, end - 1)) {
  1488. result = SCAN_TRUNCATED;
  1489. goto xa_locked;
  1490. }
  1491. xas_set(&xas, index);
  1492. }
  1493. if (!shmem_charge(mapping->host, 1)) {
  1494. result = SCAN_FAIL;
  1495. goto xa_locked;
  1496. }
  1497. xas_store(&xas, new_page);
  1498. nr_none++;
  1499. continue;
  1500. }
  1501. if (xa_is_value(page) || !PageUptodate(page)) {
  1502. xas_unlock_irq(&xas);
  1503. /* swap in or instantiate fallocated page */
  1504. if (shmem_getpage(mapping->host, index, &page,
  1505. SGP_NOHUGE)) {
  1506. result = SCAN_FAIL;
  1507. goto xa_unlocked;
  1508. }
  1509. } else if (trylock_page(page)) {
  1510. get_page(page);
  1511. xas_unlock_irq(&xas);
  1512. } else {
  1513. result = SCAN_PAGE_LOCK;
  1514. goto xa_locked;
  1515. }
  1516. } else { /* !is_shmem */
  1517. if (!page || xa_is_value(page)) {
  1518. xas_unlock_irq(&xas);
  1519. page_cache_sync_readahead(mapping, &file->f_ra,
  1520. file, index,
  1521. end - index);
  1522. /* drain pagevecs to help isolate_lru_page() */
  1523. lru_add_drain();
  1524. page = find_lock_page(mapping, index);
  1525. if (unlikely(page == NULL)) {
  1526. result = SCAN_FAIL;
  1527. goto xa_unlocked;
  1528. }
  1529. } else if (PageDirty(page)) {
  1530. /*
  1531. * khugepaged only works on read-only fd,
  1532. * so this page is dirty because it hasn't
  1533. * been flushed since first write. There
  1534. * won't be new dirty pages.
  1535. *
  1536. * Trigger async flush here and hope the
  1537. * writeback is done when khugepaged
  1538. * revisits this page.
  1539. *
  1540. * This is a one-off situation. We are not
  1541. * forcing writeback in loop.
  1542. */
  1543. xas_unlock_irq(&xas);
  1544. filemap_flush(mapping);
  1545. result = SCAN_FAIL;
  1546. goto xa_unlocked;
  1547. } else if (PageWriteback(page)) {
  1548. xas_unlock_irq(&xas);
  1549. result = SCAN_FAIL;
  1550. goto xa_unlocked;
  1551. } else if (trylock_page(page)) {
  1552. get_page(page);
  1553. xas_unlock_irq(&xas);
  1554. } else {
  1555. result = SCAN_PAGE_LOCK;
  1556. goto xa_locked;
  1557. }
  1558. }
  1559. /*
  1560. * The page must be locked, so we can drop the i_pages lock
  1561. * without racing with truncate.
  1562. */
  1563. VM_BUG_ON_PAGE(!PageLocked(page), page);
  1564. /* make sure the page is up to date */
  1565. if (unlikely(!PageUptodate(page))) {
  1566. result = SCAN_FAIL;
  1567. goto out_unlock;
  1568. }
  1569. /*
  1570. * If file was truncated then extended, or hole-punched, before
  1571. * we locked the first page, then a THP might be there already.
  1572. */
  1573. if (PageTransCompound(page)) {
  1574. result = SCAN_PAGE_COMPOUND;
  1575. goto out_unlock;
  1576. }
  1577. if (page_mapping(page) != mapping) {
  1578. result = SCAN_TRUNCATED;
  1579. goto out_unlock;
  1580. }
  1581. if (!is_shmem && (PageDirty(page) ||
  1582. PageWriteback(page))) {
  1583. /*
  1584. * khugepaged only works on read-only fd, so this
  1585. * page is dirty because it hasn't been flushed
  1586. * since first write.
  1587. */
  1588. result = SCAN_FAIL;
  1589. goto out_unlock;
  1590. }
  1591. if (isolate_lru_page(page)) {
  1592. result = SCAN_DEL_PAGE_LRU;
  1593. goto out_unlock;
  1594. }
  1595. if (page_has_private(page) &&
  1596. !try_to_release_page(page, GFP_KERNEL)) {
  1597. result = SCAN_PAGE_HAS_PRIVATE;
  1598. putback_lru_page(page);
  1599. goto out_unlock;
  1600. }
  1601. if (page_mapped(page))
  1602. unmap_mapping_pages(mapping, index, 1, false);
  1603. xas_lock_irq(&xas);
  1604. xas_set(&xas, index);
  1605. VM_BUG_ON_PAGE(page != xas_load(&xas), page);
  1606. VM_BUG_ON_PAGE(page_mapped(page), page);
  1607. /*
  1608. * The page is expected to have page_count() == 3:
  1609. * - we hold a pin on it;
  1610. * - one reference from page cache;
  1611. * - one from isolate_lru_page;
  1612. */
  1613. if (!page_ref_freeze(page, 3)) {
  1614. result = SCAN_PAGE_COUNT;
  1615. xas_unlock_irq(&xas);
  1616. putback_lru_page(page);
  1617. goto out_unlock;
  1618. }
  1619. /*
  1620. * Add the page to the list to be able to undo the collapse if
  1621. * something go wrong.
  1622. */
  1623. list_add_tail(&page->lru, &pagelist);
  1624. /* Finally, replace with the new page. */
  1625. xas_store(&xas, new_page);
  1626. continue;
  1627. out_unlock:
  1628. unlock_page(page);
  1629. put_page(page);
  1630. goto xa_unlocked;
  1631. }
  1632. if (is_shmem)
  1633. __inc_node_page_state(new_page, NR_SHMEM_THPS);
  1634. else {
  1635. __inc_node_page_state(new_page, NR_FILE_THPS);
  1636. filemap_nr_thps_inc(mapping);
  1637. /*
  1638. * Paired with smp_mb() in do_dentry_open() to ensure
  1639. * i_writecount is up to date and the update to nr_thps is
  1640. * visible. Ensures the page cache will be truncated if the
  1641. * file is opened writable.
  1642. */
  1643. smp_mb();
  1644. if (inode_is_open_for_write(mapping->host)) {
  1645. result = SCAN_FAIL;
  1646. __dec_node_page_state(new_page, NR_FILE_THPS);
  1647. filemap_nr_thps_dec(mapping);
  1648. goto xa_locked;
  1649. }
  1650. }
  1651. if (nr_none) {
  1652. __mod_lruvec_page_state(new_page, NR_FILE_PAGES, nr_none);
  1653. if (is_shmem)
  1654. __mod_lruvec_page_state(new_page, NR_SHMEM, nr_none);
  1655. }
  1656. xa_locked:
  1657. xas_unlock_irq(&xas);
  1658. xa_unlocked:
  1659. if (result == SCAN_SUCCEED) {
  1660. struct page *page, *tmp;
  1661. /*
  1662. * Replacing old pages with new one has succeeded, now we
  1663. * need to copy the content and free the old pages.
  1664. */
  1665. index = start;
  1666. list_for_each_entry_safe(page, tmp, &pagelist, lru) {
  1667. while (index < page->index) {
  1668. clear_highpage(new_page + (index % HPAGE_PMD_NR));
  1669. index++;
  1670. }
  1671. copy_highpage(new_page + (page->index % HPAGE_PMD_NR),
  1672. page);
  1673. list_del(&page->lru);
  1674. page->mapping = NULL;
  1675. page_ref_unfreeze(page, 1);
  1676. ClearPageActive(page);
  1677. ClearPageUnevictable(page);
  1678. unlock_page(page);
  1679. put_page(page);
  1680. index++;
  1681. }
  1682. while (index < end) {
  1683. clear_highpage(new_page + (index % HPAGE_PMD_NR));
  1684. index++;
  1685. }
  1686. SetPageUptodate(new_page);
  1687. page_ref_add(new_page, HPAGE_PMD_NR - 1);
  1688. if (is_shmem)
  1689. set_page_dirty(new_page);
  1690. lru_cache_add(new_page);
  1691. /*
  1692. * Remove pte page tables, so we can re-fault the page as huge.
  1693. */
  1694. retract_page_tables(mapping, start);
  1695. *hpage = NULL;
  1696. khugepaged_pages_collapsed++;
  1697. } else {
  1698. struct page *page;
  1699. /* Something went wrong: roll back page cache changes */
  1700. xas_lock_irq(&xas);
  1701. mapping->nrpages -= nr_none;
  1702. if (is_shmem)
  1703. shmem_uncharge(mapping->host, nr_none);
  1704. xas_set(&xas, start);
  1705. xas_for_each(&xas, page, end - 1) {
  1706. page = list_first_entry_or_null(&pagelist,
  1707. struct page, lru);
  1708. if (!page || xas.xa_index < page->index) {
  1709. if (!nr_none)
  1710. break;
  1711. nr_none--;
  1712. /* Put holes back where they were */
  1713. xas_store(&xas, NULL);
  1714. continue;
  1715. }
  1716. VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
  1717. /* Unfreeze the page. */
  1718. list_del(&page->lru);
  1719. page_ref_unfreeze(page, 2);
  1720. xas_store(&xas, page);
  1721. xas_pause(&xas);
  1722. xas_unlock_irq(&xas);
  1723. unlock_page(page);
  1724. putback_lru_page(page);
  1725. xas_lock_irq(&xas);
  1726. }
  1727. VM_BUG_ON(nr_none);
  1728. xas_unlock_irq(&xas);
  1729. new_page->mapping = NULL;
  1730. }
  1731. unlock_page(new_page);
  1732. out:
  1733. VM_BUG_ON(!list_empty(&pagelist));
  1734. if (!IS_ERR_OR_NULL(*hpage))
  1735. mem_cgroup_uncharge(*hpage);
  1736. /* TODO: tracepoints */
  1737. }
  1738. static void khugepaged_scan_file(struct mm_struct *mm,
  1739. struct file *file, pgoff_t start, struct page **hpage)
  1740. {
  1741. struct page *page = NULL;
  1742. struct address_space *mapping = file->f_mapping;
  1743. XA_STATE(xas, &mapping->i_pages, start);
  1744. int present, swap;
  1745. int node = NUMA_NO_NODE;
  1746. int result = SCAN_SUCCEED;
  1747. present = 0;
  1748. swap = 0;
  1749. memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load));
  1750. rcu_read_lock();
  1751. xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) {
  1752. if (xas_retry(&xas, page))
  1753. continue;
  1754. if (xa_is_value(page)) {
  1755. if (++swap > khugepaged_max_ptes_swap) {
  1756. result = SCAN_EXCEED_SWAP_PTE;
  1757. break;
  1758. }
  1759. continue;
  1760. }
  1761. if (PageTransCompound(page)) {
  1762. result = SCAN_PAGE_COMPOUND;
  1763. break;
  1764. }
  1765. node = page_to_nid(page);
  1766. if (khugepaged_scan_abort(node)) {
  1767. result = SCAN_SCAN_ABORT;
  1768. break;
  1769. }
  1770. khugepaged_node_load[node]++;
  1771. if (!PageLRU(page)) {
  1772. result = SCAN_PAGE_LRU;
  1773. break;
  1774. }
  1775. if (page_count(page) !=
  1776. 1 + page_mapcount(page) + page_has_private(page)) {
  1777. result = SCAN_PAGE_COUNT;
  1778. break;
  1779. }
  1780. /*
  1781. * We probably should check if the page is referenced here, but
  1782. * nobody would transfer pte_young() to PageReferenced() for us.
  1783. * And rmap walk here is just too costly...
  1784. */
  1785. present++;
  1786. if (need_resched()) {
  1787. xas_pause(&xas);
  1788. cond_resched_rcu();
  1789. }
  1790. }
  1791. rcu_read_unlock();
  1792. if (result == SCAN_SUCCEED) {
  1793. if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) {
  1794. result = SCAN_EXCEED_NONE_PTE;
  1795. } else {
  1796. node = khugepaged_find_target_node();
  1797. collapse_file(mm, file, start, hpage, node);
  1798. }
  1799. }
  1800. /* TODO: tracepoints */
  1801. }
  1802. #else
  1803. static void khugepaged_scan_file(struct mm_struct *mm,
  1804. struct file *file, pgoff_t start, struct page **hpage)
  1805. {
  1806. BUILD_BUG();
  1807. }
  1808. static int khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot)
  1809. {
  1810. return 0;
  1811. }
  1812. #endif
  1813. static unsigned int khugepaged_scan_mm_slot(unsigned int pages,
  1814. struct page **hpage)
  1815. __releases(&khugepaged_mm_lock)
  1816. __acquires(&khugepaged_mm_lock)
  1817. {
  1818. struct mm_slot *mm_slot;
  1819. struct mm_struct *mm;
  1820. struct vm_area_struct *vma;
  1821. int progress = 0;
  1822. VM_BUG_ON(!pages);
  1823. lockdep_assert_held(&khugepaged_mm_lock);
  1824. if (khugepaged_scan.mm_slot)
  1825. mm_slot = khugepaged_scan.mm_slot;
  1826. else {
  1827. mm_slot = list_entry(khugepaged_scan.mm_head.next,
  1828. struct mm_slot, mm_node);
  1829. khugepaged_scan.address = 0;
  1830. khugepaged_scan.mm_slot = mm_slot;
  1831. }
  1832. spin_unlock(&khugepaged_mm_lock);
  1833. khugepaged_collapse_pte_mapped_thps(mm_slot);
  1834. mm = mm_slot->mm;
  1835. /*
  1836. * Don't wait for semaphore (to avoid long wait times). Just move to
  1837. * the next mm on the list.
  1838. */
  1839. vma = NULL;
  1840. if (unlikely(!mmap_read_trylock(mm)))
  1841. goto breakouterloop_mmap_lock;
  1842. if (likely(!khugepaged_test_exit(mm)))
  1843. vma = find_vma(mm, khugepaged_scan.address);
  1844. progress++;
  1845. for (; vma; vma = vma->vm_next) {
  1846. unsigned long hstart, hend;
  1847. cond_resched();
  1848. if (unlikely(khugepaged_test_exit(mm))) {
  1849. progress++;
  1850. break;
  1851. }
  1852. if (!hugepage_vma_check(vma, vma->vm_flags)) {
  1853. skip:
  1854. progress++;
  1855. continue;
  1856. }
  1857. hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
  1858. hend = vma->vm_end & HPAGE_PMD_MASK;
  1859. if (hstart >= hend)
  1860. goto skip;
  1861. if (khugepaged_scan.address > hend)
  1862. goto skip;
  1863. if (khugepaged_scan.address < hstart)
  1864. khugepaged_scan.address = hstart;
  1865. VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK);
  1866. if (shmem_file(vma->vm_file) && !shmem_huge_enabled(vma))
  1867. goto skip;
  1868. while (khugepaged_scan.address < hend) {
  1869. int ret;
  1870. cond_resched();
  1871. if (unlikely(khugepaged_test_exit(mm)))
  1872. goto breakouterloop;
  1873. VM_BUG_ON(khugepaged_scan.address < hstart ||
  1874. khugepaged_scan.address + HPAGE_PMD_SIZE >
  1875. hend);
  1876. if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) {
  1877. struct file *file = get_file(vma->vm_file);
  1878. pgoff_t pgoff = linear_page_index(vma,
  1879. khugepaged_scan.address);
  1880. mmap_read_unlock(mm);
  1881. ret = 1;
  1882. khugepaged_scan_file(mm, file, pgoff, hpage);
  1883. fput(file);
  1884. } else {
  1885. ret = khugepaged_scan_pmd(mm, vma,
  1886. khugepaged_scan.address,
  1887. hpage);
  1888. }
  1889. /* move to next address */
  1890. khugepaged_scan.address += HPAGE_PMD_SIZE;
  1891. progress += HPAGE_PMD_NR;
  1892. if (ret)
  1893. /* we released mmap_lock so break loop */
  1894. goto breakouterloop_mmap_lock;
  1895. if (progress >= pages)
  1896. goto breakouterloop;
  1897. }
  1898. }
  1899. breakouterloop:
  1900. mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */
  1901. breakouterloop_mmap_lock:
  1902. spin_lock(&khugepaged_mm_lock);
  1903. VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot);
  1904. /*
  1905. * Release the current mm_slot if this mm is about to die, or
  1906. * if we scanned all vmas of this mm.
  1907. */
  1908. if (khugepaged_test_exit(mm) || !vma) {
  1909. /*
  1910. * Make sure that if mm_users is reaching zero while
  1911. * khugepaged runs here, khugepaged_exit will find
  1912. * mm_slot not pointing to the exiting mm.
  1913. */
  1914. if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) {
  1915. khugepaged_scan.mm_slot = list_entry(
  1916. mm_slot->mm_node.next,
  1917. struct mm_slot, mm_node);
  1918. khugepaged_scan.address = 0;
  1919. } else {
  1920. khugepaged_scan.mm_slot = NULL;
  1921. khugepaged_full_scans++;
  1922. }
  1923. collect_mm_slot(mm_slot);
  1924. }
  1925. return progress;
  1926. }
  1927. static int khugepaged_has_work(void)
  1928. {
  1929. return !list_empty(&khugepaged_scan.mm_head) &&
  1930. khugepaged_enabled();
  1931. }
  1932. static int khugepaged_wait_event(void)
  1933. {
  1934. return !list_empty(&khugepaged_scan.mm_head) ||
  1935. kthread_should_stop();
  1936. }
  1937. static void khugepaged_do_scan(void)
  1938. {
  1939. struct page *hpage = NULL;
  1940. unsigned int progress = 0, pass_through_head = 0;
  1941. unsigned int pages = khugepaged_pages_to_scan;
  1942. bool wait = true;
  1943. barrier(); /* write khugepaged_pages_to_scan to local stack */
  1944. lru_add_drain_all();
  1945. while (progress < pages) {
  1946. if (!khugepaged_prealloc_page(&hpage, &wait))
  1947. break;
  1948. cond_resched();
  1949. if (unlikely(kthread_should_stop() || try_to_freeze()))
  1950. break;
  1951. spin_lock(&khugepaged_mm_lock);
  1952. if (!khugepaged_scan.mm_slot)
  1953. pass_through_head++;
  1954. if (khugepaged_has_work() &&
  1955. pass_through_head < 2)
  1956. progress += khugepaged_scan_mm_slot(pages - progress,
  1957. &hpage);
  1958. else
  1959. progress = pages;
  1960. spin_unlock(&khugepaged_mm_lock);
  1961. }
  1962. if (!IS_ERR_OR_NULL(hpage))
  1963. put_page(hpage);
  1964. }
  1965. static bool khugepaged_should_wakeup(void)
  1966. {
  1967. return kthread_should_stop() ||
  1968. time_after_eq(jiffies, khugepaged_sleep_expire);
  1969. }
  1970. static void khugepaged_wait_work(void)
  1971. {
  1972. if (khugepaged_has_work()) {
  1973. const unsigned long scan_sleep_jiffies =
  1974. msecs_to_jiffies(khugepaged_scan_sleep_millisecs);
  1975. if (!scan_sleep_jiffies)
  1976. return;
  1977. khugepaged_sleep_expire = jiffies + scan_sleep_jiffies;
  1978. wait_event_freezable_timeout(khugepaged_wait,
  1979. khugepaged_should_wakeup(),
  1980. scan_sleep_jiffies);
  1981. return;
  1982. }
  1983. if (khugepaged_enabled())
  1984. wait_event_freezable(khugepaged_wait, khugepaged_wait_event());
  1985. }
  1986. static int khugepaged(void *none)
  1987. {
  1988. struct mm_slot *mm_slot;
  1989. set_freezable();
  1990. set_user_nice(current, MAX_NICE);
  1991. while (!kthread_should_stop()) {
  1992. khugepaged_do_scan();
  1993. khugepaged_wait_work();
  1994. }
  1995. spin_lock(&khugepaged_mm_lock);
  1996. mm_slot = khugepaged_scan.mm_slot;
  1997. khugepaged_scan.mm_slot = NULL;
  1998. if (mm_slot)
  1999. collect_mm_slot(mm_slot);
  2000. spin_unlock(&khugepaged_mm_lock);
  2001. return 0;
  2002. }
  2003. static void set_recommended_min_free_kbytes(void)
  2004. {
  2005. struct zone *zone;
  2006. int nr_zones = 0;
  2007. unsigned long recommended_min;
  2008. for_each_populated_zone(zone) {
  2009. /*
  2010. * We don't need to worry about fragmentation of
  2011. * ZONE_MOVABLE since it only has movable pages.
  2012. */
  2013. if (zone_idx(zone) > gfp_zone(GFP_USER))
  2014. continue;
  2015. nr_zones++;
  2016. }
  2017. /* Ensure 2 pageblocks are free to assist fragmentation avoidance */
  2018. recommended_min = pageblock_nr_pages * nr_zones * 2;
  2019. /*
  2020. * Make sure that on average at least two pageblocks are almost free
  2021. * of another type, one for a migratetype to fall back to and a
  2022. * second to avoid subsequent fallbacks of other types There are 3
  2023. * MIGRATE_TYPES we care about.
  2024. */
  2025. recommended_min += pageblock_nr_pages * nr_zones *
  2026. MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;
  2027. /* don't ever allow to reserve more than 5% of the lowmem */
  2028. recommended_min = min(recommended_min,
  2029. (unsigned long) nr_free_buffer_pages() / 20);
  2030. recommended_min <<= (PAGE_SHIFT-10);
  2031. if (recommended_min > min_free_kbytes) {
  2032. if (user_min_free_kbytes >= 0)
  2033. pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n",
  2034. min_free_kbytes, recommended_min);
  2035. min_free_kbytes = recommended_min;
  2036. }
  2037. setup_per_zone_wmarks();
  2038. }
  2039. int start_stop_khugepaged(void)
  2040. {
  2041. int err = 0;
  2042. mutex_lock(&khugepaged_mutex);
  2043. if (khugepaged_enabled()) {
  2044. if (!khugepaged_thread)
  2045. khugepaged_thread = kthread_run(khugepaged, NULL,
  2046. "khugepaged");
  2047. if (IS_ERR(khugepaged_thread)) {
  2048. pr_err("khugepaged: kthread_run(khugepaged) failed\n");
  2049. err = PTR_ERR(khugepaged_thread);
  2050. khugepaged_thread = NULL;
  2051. goto fail;
  2052. }
  2053. if (!list_empty(&khugepaged_scan.mm_head))
  2054. wake_up_interruptible(&khugepaged_wait);
  2055. set_recommended_min_free_kbytes();
  2056. } else if (khugepaged_thread) {
  2057. kthread_stop(khugepaged_thread);
  2058. khugepaged_thread = NULL;
  2059. }
  2060. fail:
  2061. mutex_unlock(&khugepaged_mutex);
  2062. return err;
  2063. }
  2064. void khugepaged_min_free_kbytes_update(void)
  2065. {
  2066. mutex_lock(&khugepaged_mutex);
  2067. if (khugepaged_enabled() && khugepaged_thread)
  2068. set_recommended_min_free_kbytes();
  2069. mutex_unlock(&khugepaged_mutex);
  2070. }