memory-failure.c 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (C) 2008, 2009 Intel Corporation
  4. * Authors: Andi Kleen, Fengguang Wu
  5. *
  6. * High level machine check handler. Handles pages reported by the
  7. * hardware as being corrupted usually due to a multi-bit ECC memory or cache
  8. * failure.
  9. *
  10. * In addition there is a "soft offline" entry point that allows stop using
  11. * not-yet-corrupted-by-suspicious pages without killing anything.
  12. *
  13. * Handles page cache pages in various states. The tricky part
  14. * here is that we can access any page asynchronously in respect to
  15. * other VM users, because memory failures could happen anytime and
  16. * anywhere. This could violate some of their assumptions. This is why
  17. * this code has to be extremely careful. Generally it tries to use
  18. * normal locking rules, as in get the standard locks, even if that means
  19. * the error handling takes potentially a long time.
  20. *
  21. * It can be very tempting to add handling for obscure cases here.
  22. * In general any code for handling new cases should only be added iff:
  23. * - You know how to test it.
  24. * - You have a test that can be added to mce-test
  25. * https://git.kernel.org/cgit/utils/cpu/mce/mce-test.git/
  26. * - The case actually shows up as a frequent (top 10) page state in
  27. * tools/mm/page-types when running a real workload.
  28. *
  29. * There are several operations here with exponential complexity because
  30. * of unsuitable VM data structures. For example the operation to map back
  31. * from RMAP chains to processes has to walk the complete process list and
  32. * has non linear complexity with the number. But since memory corruptions
  33. * are rare we hope to get away with this. This avoids impacting the core
  34. * VM.
  35. */
  36. #define pr_fmt(fmt) "Memory failure: " fmt
  37. #include <linux/kernel.h>
  38. #include <linux/mm.h>
  39. #include <linux/memory-failure.h>
  40. #include <linux/page-flags.h>
  41. #include <linux/sched/signal.h>
  42. #include <linux/sched/task.h>
  43. #include <linux/dax.h>
  44. #include <linux/ksm.h>
  45. #include <linux/rmap.h>
  46. #include <linux/export.h>
  47. #include <linux/pagemap.h>
  48. #include <linux/swap.h>
  49. #include <linux/backing-dev.h>
  50. #include <linux/migrate.h>
  51. #include <linux/slab.h>
  52. #include <linux/leafops.h>
  53. #include <linux/hugetlb.h>
  54. #include <linux/memory_hotplug.h>
  55. #include <linux/mm_inline.h>
  56. #include <linux/memremap.h>
  57. #include <linux/kfifo.h>
  58. #include <linux/ratelimit.h>
  59. #include <linux/pagewalk.h>
  60. #include <linux/shmem_fs.h>
  61. #include <linux/sysctl.h>
  62. #define CREATE_TRACE_POINTS
  63. #include <trace/events/memory-failure.h>
  64. #include "swap.h"
  65. #include "internal.h"
  66. static int sysctl_memory_failure_early_kill __read_mostly;
  67. static int sysctl_memory_failure_recovery __read_mostly = 1;
  68. static int sysctl_enable_soft_offline __read_mostly = 1;
  69. atomic_long_t num_poisoned_pages __read_mostly = ATOMIC_LONG_INIT(0);
  70. static bool hw_memory_failure __read_mostly = false;
  71. static DEFINE_MUTEX(mf_mutex);
  72. void num_poisoned_pages_inc(unsigned long pfn)
  73. {
  74. atomic_long_inc(&num_poisoned_pages);
  75. memblk_nr_poison_inc(pfn);
  76. }
  77. void num_poisoned_pages_sub(unsigned long pfn, long i)
  78. {
  79. atomic_long_sub(i, &num_poisoned_pages);
  80. if (pfn != -1UL)
  81. memblk_nr_poison_sub(pfn, i);
  82. }
  83. /**
  84. * MF_ATTR_RO - Create sysfs entry for each memory failure statistics.
  85. * @_name: name of the file in the per NUMA sysfs directory.
  86. */
  87. #define MF_ATTR_RO(_name) \
  88. static ssize_t _name##_show(struct device *dev, \
  89. struct device_attribute *attr, \
  90. char *buf) \
  91. { \
  92. struct memory_failure_stats *mf_stats = \
  93. &NODE_DATA(dev->id)->mf_stats; \
  94. return sysfs_emit(buf, "%lu\n", mf_stats->_name); \
  95. } \
  96. static DEVICE_ATTR_RO(_name)
  97. MF_ATTR_RO(total);
  98. MF_ATTR_RO(ignored);
  99. MF_ATTR_RO(failed);
  100. MF_ATTR_RO(delayed);
  101. MF_ATTR_RO(recovered);
  102. static struct attribute *memory_failure_attr[] = {
  103. &dev_attr_total.attr,
  104. &dev_attr_ignored.attr,
  105. &dev_attr_failed.attr,
  106. &dev_attr_delayed.attr,
  107. &dev_attr_recovered.attr,
  108. NULL,
  109. };
  110. const struct attribute_group memory_failure_attr_group = {
  111. .name = "memory_failure",
  112. .attrs = memory_failure_attr,
  113. };
  114. static const struct ctl_table memory_failure_table[] = {
  115. {
  116. .procname = "memory_failure_early_kill",
  117. .data = &sysctl_memory_failure_early_kill,
  118. .maxlen = sizeof(sysctl_memory_failure_early_kill),
  119. .mode = 0644,
  120. .proc_handler = proc_dointvec_minmax,
  121. .extra1 = SYSCTL_ZERO,
  122. .extra2 = SYSCTL_ONE,
  123. },
  124. {
  125. .procname = "memory_failure_recovery",
  126. .data = &sysctl_memory_failure_recovery,
  127. .maxlen = sizeof(sysctl_memory_failure_recovery),
  128. .mode = 0644,
  129. .proc_handler = proc_dointvec_minmax,
  130. .extra1 = SYSCTL_ZERO,
  131. .extra2 = SYSCTL_ONE,
  132. },
  133. {
  134. .procname = "enable_soft_offline",
  135. .data = &sysctl_enable_soft_offline,
  136. .maxlen = sizeof(sysctl_enable_soft_offline),
  137. .mode = 0644,
  138. .proc_handler = proc_dointvec_minmax,
  139. .extra1 = SYSCTL_ZERO,
  140. .extra2 = SYSCTL_ONE,
  141. }
  142. };
  143. static struct rb_root_cached pfn_space_itree = RB_ROOT_CACHED;
  144. static DEFINE_MUTEX(pfn_space_lock);
  145. /*
  146. * Return values:
  147. * 1: the page is dissolved (if needed) and taken off from buddy,
  148. * 0: the page is dissolved (if needed) and not taken off from buddy,
  149. * < 0: failed to dissolve.
  150. */
  151. static int __page_handle_poison(struct page *page)
  152. {
  153. int ret;
  154. /*
  155. * zone_pcp_disable() can't be used here. It will
  156. * hold pcp_batch_high_lock and dissolve_free_hugetlb_folio() might hold
  157. * cpu_hotplug_lock via static_key_slow_dec() when hugetlb vmemmap
  158. * optimization is enabled. This will break current lock dependency
  159. * chain and leads to deadlock.
  160. * Disabling pcp before dissolving the page was a deterministic
  161. * approach because we made sure that those pages cannot end up in any
  162. * PCP list. Draining PCP lists expels those pages to the buddy system,
  163. * but nothing guarantees that those pages do not get back to a PCP
  164. * queue if we need to refill those.
  165. */
  166. ret = dissolve_free_hugetlb_folio(page_folio(page));
  167. if (!ret) {
  168. drain_all_pages(page_zone(page));
  169. ret = take_page_off_buddy(page);
  170. }
  171. return ret;
  172. }
  173. static bool page_handle_poison(struct page *page, bool hugepage_or_freepage, bool release)
  174. {
  175. if (hugepage_or_freepage) {
  176. /*
  177. * Doing this check for free pages is also fine since
  178. * dissolve_free_hugetlb_folio() returns 0 for non-hugetlb folios as well.
  179. */
  180. if (__page_handle_poison(page) <= 0)
  181. /*
  182. * We could fail to take off the target page from buddy
  183. * for example due to racy page allocation, but that's
  184. * acceptable because soft-offlined page is not broken
  185. * and if someone really want to use it, they should
  186. * take it.
  187. */
  188. return false;
  189. }
  190. SetPageHWPoison(page);
  191. if (release)
  192. put_page(page);
  193. page_ref_inc(page);
  194. num_poisoned_pages_inc(page_to_pfn(page));
  195. return true;
  196. }
  197. static hwpoison_filter_func_t __rcu *hwpoison_filter_func __read_mostly;
  198. void hwpoison_filter_register(hwpoison_filter_func_t *filter)
  199. {
  200. rcu_assign_pointer(hwpoison_filter_func, filter);
  201. }
  202. EXPORT_SYMBOL_GPL(hwpoison_filter_register);
  203. void hwpoison_filter_unregister(void)
  204. {
  205. RCU_INIT_POINTER(hwpoison_filter_func, NULL);
  206. synchronize_rcu();
  207. }
  208. EXPORT_SYMBOL_GPL(hwpoison_filter_unregister);
  209. static int hwpoison_filter(struct page *p)
  210. {
  211. int ret = 0;
  212. hwpoison_filter_func_t *filter;
  213. rcu_read_lock();
  214. filter = rcu_dereference(hwpoison_filter_func);
  215. if (filter)
  216. ret = filter(p);
  217. rcu_read_unlock();
  218. return ret;
  219. }
  220. /*
  221. * Kill all processes that have a poisoned page mapped and then isolate
  222. * the page.
  223. *
  224. * General strategy:
  225. * Find all processes having the page mapped and kill them.
  226. * But we keep a page reference around so that the page is not
  227. * actually freed yet.
  228. * Then stash the page away
  229. *
  230. * There's no convenient way to get back to mapped processes
  231. * from the VMAs. So do a brute-force search over all
  232. * running processes.
  233. *
  234. * Remember that machine checks are not common (or rather
  235. * if they are common you have other problems), so this shouldn't
  236. * be a performance issue.
  237. *
  238. * Also there are some races possible while we get from the
  239. * error detection to actually handle it.
  240. */
  241. struct to_kill {
  242. struct list_head nd;
  243. struct task_struct *tsk;
  244. unsigned long addr;
  245. short size_shift;
  246. };
  247. /*
  248. * Send all the processes who have the page mapped a signal.
  249. * ``action optional'' if they are not immediately affected by the error
  250. * ``action required'' if error happened in current execution context
  251. */
  252. static int kill_proc(struct to_kill *tk, unsigned long pfn, int flags)
  253. {
  254. struct task_struct *t = tk->tsk;
  255. short addr_lsb = tk->size_shift;
  256. int ret = 0;
  257. pr_err("%#lx: Sending SIGBUS to %s:%d due to hardware memory corruption\n",
  258. pfn, t->comm, task_pid_nr(t));
  259. if ((flags & MF_ACTION_REQUIRED) && (t == current))
  260. ret = force_sig_mceerr(BUS_MCEERR_AR,
  261. (void __user *)tk->addr, addr_lsb);
  262. else
  263. /*
  264. * Signal other processes sharing the page if they have
  265. * PF_MCE_EARLY set.
  266. * Don't use force here, it's convenient if the signal
  267. * can be temporarily blocked.
  268. */
  269. ret = send_sig_mceerr(BUS_MCEERR_AO, (void __user *)tk->addr,
  270. addr_lsb, t);
  271. if (ret < 0)
  272. pr_info("Error sending signal to %s:%d: %d\n",
  273. t->comm, task_pid_nr(t), ret);
  274. return ret;
  275. }
  276. /*
  277. * Unknown page type encountered. Try to check whether it can turn PageLRU by
  278. * lru_add_drain_all.
  279. */
  280. void shake_folio(struct folio *folio)
  281. {
  282. if (folio_test_hugetlb(folio))
  283. return;
  284. /*
  285. * TODO: Could shrink slab caches here if a lightweight range-based
  286. * shrinker will be available.
  287. */
  288. if (folio_test_slab(folio))
  289. return;
  290. lru_add_drain_all();
  291. }
  292. EXPORT_SYMBOL_GPL(shake_folio);
  293. static void shake_page(struct page *page)
  294. {
  295. shake_folio(page_folio(page));
  296. }
  297. static unsigned long dev_pagemap_mapping_shift(struct vm_area_struct *vma,
  298. unsigned long address)
  299. {
  300. unsigned long ret = 0;
  301. pgd_t *pgd;
  302. p4d_t *p4d;
  303. pud_t *pud;
  304. pmd_t *pmd;
  305. pte_t *pte;
  306. pte_t ptent;
  307. VM_BUG_ON_VMA(address == -EFAULT, vma);
  308. pgd = pgd_offset(vma->vm_mm, address);
  309. if (!pgd_present(*pgd))
  310. return 0;
  311. p4d = p4d_offset(pgd, address);
  312. if (!p4d_present(*p4d))
  313. return 0;
  314. pud = pud_offset(p4d, address);
  315. if (!pud_present(*pud))
  316. return 0;
  317. if (pud_trans_huge(*pud))
  318. return PUD_SHIFT;
  319. pmd = pmd_offset(pud, address);
  320. if (!pmd_present(*pmd))
  321. return 0;
  322. if (pmd_trans_huge(*pmd))
  323. return PMD_SHIFT;
  324. pte = pte_offset_map(pmd, address);
  325. if (!pte)
  326. return 0;
  327. ptent = ptep_get(pte);
  328. if (pte_present(ptent))
  329. ret = PAGE_SHIFT;
  330. pte_unmap(pte);
  331. return ret;
  332. }
  333. /*
  334. * Failure handling: if we can't find or can't kill a process there's
  335. * not much we can do. We just print a message and ignore otherwise.
  336. */
  337. /*
  338. * Schedule a process for later kill.
  339. * Uses GFP_ATOMIC allocations to avoid potential recursions in the VM.
  340. */
  341. static void __add_to_kill(struct task_struct *tsk, const struct page *p,
  342. struct vm_area_struct *vma, struct list_head *to_kill,
  343. unsigned long addr)
  344. {
  345. struct to_kill *tk;
  346. tk = kmalloc_obj(struct to_kill, GFP_ATOMIC);
  347. if (!tk) {
  348. pr_err("Out of memory while machine check handling\n");
  349. return;
  350. }
  351. tk->addr = addr;
  352. if (is_zone_device_page(p))
  353. tk->size_shift = dev_pagemap_mapping_shift(vma, tk->addr);
  354. else
  355. tk->size_shift = folio_shift(page_folio(p));
  356. /*
  357. * Send SIGKILL if "tk->addr == -EFAULT". Also, as
  358. * "tk->size_shift" is always non-zero for !is_zone_device_page(),
  359. * so "tk->size_shift == 0" effectively checks no mapping on
  360. * ZONE_DEVICE. Indeed, when a devdax page is mmapped N times
  361. * to a process' address space, it's possible not all N VMAs
  362. * contain mappings for the page, but at least one VMA does.
  363. * Only deliver SIGBUS with payload derived from the VMA that
  364. * has a mapping for the page.
  365. */
  366. if (tk->addr == -EFAULT) {
  367. pr_info("Unable to find user space address %lx in %s\n",
  368. page_to_pfn(p), tsk->comm);
  369. } else if (tk->size_shift == 0) {
  370. kfree(tk);
  371. return;
  372. }
  373. get_task_struct(tsk);
  374. tk->tsk = tsk;
  375. list_add_tail(&tk->nd, to_kill);
  376. }
  377. static void add_to_kill_anon_file(struct task_struct *tsk, const struct page *p,
  378. struct vm_area_struct *vma, struct list_head *to_kill,
  379. unsigned long addr)
  380. {
  381. if (addr == -EFAULT)
  382. return;
  383. __add_to_kill(tsk, p, vma, to_kill, addr);
  384. }
  385. #ifdef CONFIG_KSM
  386. static bool task_in_to_kill_list(struct list_head *to_kill,
  387. struct task_struct *tsk)
  388. {
  389. struct to_kill *tk, *next;
  390. list_for_each_entry_safe(tk, next, to_kill, nd) {
  391. if (tk->tsk == tsk)
  392. return true;
  393. }
  394. return false;
  395. }
  396. void add_to_kill_ksm(struct task_struct *tsk, const struct page *p,
  397. struct vm_area_struct *vma, struct list_head *to_kill,
  398. unsigned long addr)
  399. {
  400. if (!task_in_to_kill_list(to_kill, tsk))
  401. __add_to_kill(tsk, p, vma, to_kill, addr);
  402. }
  403. #endif
  404. /*
  405. * Kill the processes that have been collected earlier.
  406. *
  407. * Only do anything when FORCEKILL is set, otherwise just free the
  408. * list (this is used for clean pages which do not need killing)
  409. */
  410. static void kill_procs(struct list_head *to_kill, int forcekill,
  411. unsigned long pfn, int flags)
  412. {
  413. struct to_kill *tk, *next;
  414. list_for_each_entry_safe(tk, next, to_kill, nd) {
  415. if (forcekill) {
  416. if (tk->addr == -EFAULT) {
  417. pr_err("%#lx: forcibly killing %s:%d because of failure to unmap corrupted page\n",
  418. pfn, tk->tsk->comm, task_pid_nr(tk->tsk));
  419. do_send_sig_info(SIGKILL, SEND_SIG_PRIV,
  420. tk->tsk, PIDTYPE_PID);
  421. }
  422. /*
  423. * In theory the process could have mapped
  424. * something else on the address in-between. We could
  425. * check for that, but we need to tell the
  426. * process anyways.
  427. */
  428. else if (kill_proc(tk, pfn, flags) < 0)
  429. pr_err("%#lx: Cannot send advisory machine check signal to %s:%d\n",
  430. pfn, tk->tsk->comm, task_pid_nr(tk->tsk));
  431. }
  432. list_del(&tk->nd);
  433. put_task_struct(tk->tsk);
  434. kfree(tk);
  435. }
  436. }
  437. /*
  438. * Find a dedicated thread which is supposed to handle SIGBUS(BUS_MCEERR_AO)
  439. * on behalf of the thread group. Return task_struct of the (first found)
  440. * dedicated thread if found, and return NULL otherwise.
  441. *
  442. * We already hold rcu lock in the caller, so we don't have to call
  443. * rcu_read_lock/unlock() in this function.
  444. */
  445. static struct task_struct *find_early_kill_thread(struct task_struct *tsk)
  446. {
  447. struct task_struct *t;
  448. for_each_thread(tsk, t) {
  449. if (t->flags & PF_MCE_PROCESS) {
  450. if (t->flags & PF_MCE_EARLY)
  451. return t;
  452. } else {
  453. if (sysctl_memory_failure_early_kill)
  454. return t;
  455. }
  456. }
  457. return NULL;
  458. }
  459. /*
  460. * Determine whether a given process is "early kill" process which expects
  461. * to be signaled when some page under the process is hwpoisoned.
  462. * Return task_struct of the dedicated thread (main thread unless explicitly
  463. * specified) if the process is "early kill" and otherwise returns NULL.
  464. *
  465. * Note that the above is true for Action Optional case. For Action Required
  466. * case, it's only meaningful to the current thread which need to be signaled
  467. * with SIGBUS, this error is Action Optional for other non current
  468. * processes sharing the same error page,if the process is "early kill", the
  469. * task_struct of the dedicated thread will also be returned.
  470. */
  471. struct task_struct *task_early_kill(struct task_struct *tsk, int force_early)
  472. {
  473. if (!tsk->mm)
  474. return NULL;
  475. /*
  476. * Comparing ->mm here because current task might represent
  477. * a subthread, while tsk always points to the main thread.
  478. */
  479. if (force_early && tsk->mm == current->mm)
  480. return current;
  481. return find_early_kill_thread(tsk);
  482. }
  483. /*
  484. * Collect processes when the error hit an anonymous page.
  485. */
  486. static void collect_procs_anon(const struct folio *folio,
  487. const struct page *page, struct list_head *to_kill,
  488. int force_early)
  489. {
  490. struct task_struct *tsk;
  491. struct anon_vma *av;
  492. pgoff_t pgoff;
  493. av = folio_lock_anon_vma_read(folio, NULL);
  494. if (av == NULL) /* Not actually mapped anymore */
  495. return;
  496. pgoff = page_pgoff(folio, page);
  497. rcu_read_lock();
  498. for_each_process(tsk) {
  499. struct vm_area_struct *vma;
  500. struct anon_vma_chain *vmac;
  501. struct task_struct *t = task_early_kill(tsk, force_early);
  502. unsigned long addr;
  503. if (!t)
  504. continue;
  505. anon_vma_interval_tree_foreach(vmac, &av->rb_root,
  506. pgoff, pgoff) {
  507. vma = vmac->vma;
  508. if (vma->vm_mm != t->mm)
  509. continue;
  510. addr = page_mapped_in_vma(page, vma);
  511. add_to_kill_anon_file(t, page, vma, to_kill, addr);
  512. }
  513. }
  514. rcu_read_unlock();
  515. anon_vma_unlock_read(av);
  516. }
  517. /*
  518. * Collect processes when the error hit a file mapped page.
  519. */
  520. static void collect_procs_file(const struct folio *folio,
  521. const struct page *page, struct list_head *to_kill,
  522. int force_early)
  523. {
  524. struct vm_area_struct *vma;
  525. struct task_struct *tsk;
  526. struct address_space *mapping = folio->mapping;
  527. pgoff_t pgoff;
  528. i_mmap_lock_read(mapping);
  529. rcu_read_lock();
  530. pgoff = page_pgoff(folio, page);
  531. for_each_process(tsk) {
  532. struct task_struct *t = task_early_kill(tsk, force_early);
  533. unsigned long addr;
  534. if (!t)
  535. continue;
  536. vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff,
  537. pgoff) {
  538. /*
  539. * Send early kill signal to tasks where a vma covers
  540. * the page but the corrupted page is not necessarily
  541. * mapped in its pte.
  542. * Assume applications who requested early kill want
  543. * to be informed of all such data corruptions.
  544. */
  545. if (vma->vm_mm != t->mm)
  546. continue;
  547. addr = page_address_in_vma(folio, page, vma);
  548. add_to_kill_anon_file(t, page, vma, to_kill, addr);
  549. }
  550. }
  551. rcu_read_unlock();
  552. i_mmap_unlock_read(mapping);
  553. }
  554. #ifdef CONFIG_FS_DAX
  555. static void add_to_kill_fsdax(struct task_struct *tsk, const struct page *p,
  556. struct vm_area_struct *vma,
  557. struct list_head *to_kill, pgoff_t pgoff)
  558. {
  559. unsigned long addr = vma_address(vma, pgoff, 1);
  560. __add_to_kill(tsk, p, vma, to_kill, addr);
  561. }
  562. /*
  563. * Collect processes when the error hit a fsdax page.
  564. */
  565. static void collect_procs_fsdax(const struct page *page,
  566. struct address_space *mapping, pgoff_t pgoff,
  567. struct list_head *to_kill, bool pre_remove)
  568. {
  569. struct vm_area_struct *vma;
  570. struct task_struct *tsk;
  571. i_mmap_lock_read(mapping);
  572. rcu_read_lock();
  573. for_each_process(tsk) {
  574. struct task_struct *t = tsk;
  575. /*
  576. * Search for all tasks while MF_MEM_PRE_REMOVE is set, because
  577. * the current may not be the one accessing the fsdax page.
  578. * Otherwise, search for the current task.
  579. */
  580. if (!pre_remove)
  581. t = task_early_kill(tsk, true);
  582. if (!t)
  583. continue;
  584. vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) {
  585. if (vma->vm_mm == t->mm)
  586. add_to_kill_fsdax(t, page, vma, to_kill, pgoff);
  587. }
  588. }
  589. rcu_read_unlock();
  590. i_mmap_unlock_read(mapping);
  591. }
  592. #endif /* CONFIG_FS_DAX */
  593. /*
  594. * Collect the processes who have the corrupted page mapped to kill.
  595. */
  596. static void collect_procs(const struct folio *folio, const struct page *page,
  597. struct list_head *tokill, int force_early)
  598. {
  599. if (!folio->mapping)
  600. return;
  601. if (unlikely(folio_test_ksm(folio)))
  602. collect_procs_ksm(folio, page, tokill, force_early);
  603. else if (folio_test_anon(folio))
  604. collect_procs_anon(folio, page, tokill, force_early);
  605. else
  606. collect_procs_file(folio, page, tokill, force_early);
  607. }
  608. struct hwpoison_walk {
  609. struct to_kill tk;
  610. unsigned long pfn;
  611. int flags;
  612. };
  613. static void set_to_kill(struct to_kill *tk, unsigned long addr, short shift)
  614. {
  615. tk->addr = addr;
  616. tk->size_shift = shift;
  617. }
  618. static int check_hwpoisoned_entry(pte_t pte, unsigned long addr, short shift,
  619. unsigned long poisoned_pfn, struct to_kill *tk)
  620. {
  621. unsigned long pfn = 0;
  622. unsigned long hwpoison_vaddr;
  623. unsigned long mask;
  624. if (pte_present(pte)) {
  625. pfn = pte_pfn(pte);
  626. } else {
  627. const softleaf_t entry = softleaf_from_pte(pte);
  628. if (softleaf_is_hwpoison(entry))
  629. pfn = softleaf_to_pfn(entry);
  630. }
  631. mask = ~((1UL << (shift - PAGE_SHIFT)) - 1);
  632. if (!pfn || pfn != (poisoned_pfn & mask))
  633. return 0;
  634. hwpoison_vaddr = addr + ((poisoned_pfn - pfn) << PAGE_SHIFT);
  635. set_to_kill(tk, hwpoison_vaddr, shift);
  636. return 1;
  637. }
  638. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  639. static int check_hwpoisoned_pmd_entry(pmd_t *pmdp, unsigned long addr,
  640. struct hwpoison_walk *hwp)
  641. {
  642. pmd_t pmd = *pmdp;
  643. unsigned long pfn;
  644. unsigned long hwpoison_vaddr;
  645. if (!pmd_present(pmd))
  646. return 0;
  647. pfn = pmd_pfn(pmd);
  648. if (pfn <= hwp->pfn && hwp->pfn < pfn + HPAGE_PMD_NR) {
  649. hwpoison_vaddr = addr + ((hwp->pfn - pfn) << PAGE_SHIFT);
  650. set_to_kill(&hwp->tk, hwpoison_vaddr, PAGE_SHIFT);
  651. return 1;
  652. }
  653. return 0;
  654. }
  655. #else
  656. static int check_hwpoisoned_pmd_entry(pmd_t *pmdp, unsigned long addr,
  657. struct hwpoison_walk *hwp)
  658. {
  659. return 0;
  660. }
  661. #endif
  662. static int hwpoison_pte_range(pmd_t *pmdp, unsigned long addr,
  663. unsigned long end, struct mm_walk *walk)
  664. {
  665. struct hwpoison_walk *hwp = walk->private;
  666. int ret = 0;
  667. pte_t *ptep, *mapped_pte;
  668. spinlock_t *ptl;
  669. ptl = pmd_trans_huge_lock(pmdp, walk->vma);
  670. if (ptl) {
  671. ret = check_hwpoisoned_pmd_entry(pmdp, addr, hwp);
  672. spin_unlock(ptl);
  673. goto out;
  674. }
  675. mapped_pte = ptep = pte_offset_map_lock(walk->vma->vm_mm, pmdp,
  676. addr, &ptl);
  677. if (!ptep)
  678. goto out;
  679. for (; addr != end; ptep++, addr += PAGE_SIZE) {
  680. ret = check_hwpoisoned_entry(ptep_get(ptep), addr, PAGE_SHIFT,
  681. hwp->pfn, &hwp->tk);
  682. if (ret == 1)
  683. break;
  684. }
  685. pte_unmap_unlock(mapped_pte, ptl);
  686. out:
  687. cond_resched();
  688. return ret;
  689. }
  690. #ifdef CONFIG_HUGETLB_PAGE
  691. static int hwpoison_hugetlb_range(pte_t *ptep, unsigned long hmask,
  692. unsigned long addr, unsigned long end,
  693. struct mm_walk *walk)
  694. {
  695. struct hwpoison_walk *hwp = walk->private;
  696. struct hstate *h = hstate_vma(walk->vma);
  697. spinlock_t *ptl;
  698. pte_t pte;
  699. int ret;
  700. ptl = huge_pte_lock(h, walk->mm, ptep);
  701. pte = huge_ptep_get(walk->mm, addr, ptep);
  702. ret = check_hwpoisoned_entry(pte, addr, huge_page_shift(h),
  703. hwp->pfn, &hwp->tk);
  704. spin_unlock(ptl);
  705. return ret;
  706. }
  707. #else
  708. #define hwpoison_hugetlb_range NULL
  709. #endif
  710. static int hwpoison_test_walk(unsigned long start, unsigned long end,
  711. struct mm_walk *walk)
  712. {
  713. /* We also want to consider pages mapped into VM_PFNMAP. */
  714. return 0;
  715. }
  716. static const struct mm_walk_ops hwpoison_walk_ops = {
  717. .pmd_entry = hwpoison_pte_range,
  718. .hugetlb_entry = hwpoison_hugetlb_range,
  719. .test_walk = hwpoison_test_walk,
  720. .walk_lock = PGWALK_RDLOCK,
  721. };
  722. /*
  723. * Sends SIGBUS to the current process with error info.
  724. *
  725. * This function is intended to handle "Action Required" MCEs on already
  726. * hardware poisoned pages. They could happen, for example, when
  727. * memory_failure() failed to unmap the error page at the first call, or
  728. * when multiple local machine checks happened on different CPUs.
  729. *
  730. * MCE handler currently has no easy access to the error virtual address,
  731. * so this function walks page table to find it. The returned virtual address
  732. * is proper in most cases, but it could be wrong when the application
  733. * process has multiple entries mapping the error page.
  734. */
  735. static int kill_accessing_process(struct task_struct *p, unsigned long pfn,
  736. int flags)
  737. {
  738. int ret;
  739. struct hwpoison_walk priv = {
  740. .pfn = pfn,
  741. };
  742. priv.tk.tsk = p;
  743. if (!p->mm)
  744. return -EFAULT;
  745. mmap_read_lock(p->mm);
  746. ret = walk_page_range(p->mm, 0, TASK_SIZE, &hwpoison_walk_ops,
  747. (void *)&priv);
  748. /*
  749. * ret = 1 when CMCI wins, regardless of whether try_to_unmap()
  750. * succeeds or fails, then kill the process with SIGBUS.
  751. * ret = 0 when poison page is a clean page and it's dropped, no
  752. * SIGBUS is needed.
  753. */
  754. if (ret == 1 && priv.tk.addr)
  755. kill_proc(&priv.tk, pfn, flags);
  756. mmap_read_unlock(p->mm);
  757. return ret > 0 ? -EHWPOISON : 0;
  758. }
  759. /*
  760. * MF_IGNORED - The m-f() handler marks the page as PG_hwpoisoned'ed.
  761. * But it could not do more to isolate the page from being accessed again,
  762. * nor does it kill the process. This is extremely rare and one of the
  763. * potential causes is that the page state has been changed due to
  764. * underlying race condition. This is the most severe outcomes.
  765. *
  766. * MF_FAILED - The m-f() handler marks the page as PG_hwpoisoned'ed.
  767. * It should have killed the process, but it can't isolate the page,
  768. * due to conditions such as extra pin, unmap failure, etc. Accessing
  769. * the page again may trigger another MCE and the process will be killed
  770. * by the m-f() handler immediately.
  771. *
  772. * MF_DELAYED - The m-f() handler marks the page as PG_hwpoisoned'ed.
  773. * The page is unmapped, and is removed from the LRU or file mapping.
  774. * An attempt to access the page again will trigger page fault and the
  775. * PF handler will kill the process.
  776. *
  777. * MF_RECOVERED - The m-f() handler marks the page as PG_hwpoisoned'ed.
  778. * The page has been completely isolated, that is, unmapped, taken out of
  779. * the buddy system, or hole-punched out of the file mapping.
  780. */
  781. static const char *action_name[] = {
  782. [MF_IGNORED] = "Ignored",
  783. [MF_FAILED] = "Failed",
  784. [MF_DELAYED] = "Delayed",
  785. [MF_RECOVERED] = "Recovered",
  786. };
  787. static const char * const action_page_types[] = {
  788. [MF_MSG_KERNEL] = "reserved kernel page",
  789. [MF_MSG_KERNEL_HIGH_ORDER] = "high-order kernel page",
  790. [MF_MSG_HUGE] = "huge page",
  791. [MF_MSG_FREE_HUGE] = "free huge page",
  792. [MF_MSG_GET_HWPOISON] = "get hwpoison page",
  793. [MF_MSG_UNMAP_FAILED] = "unmapping failed page",
  794. [MF_MSG_DIRTY_SWAPCACHE] = "dirty swapcache page",
  795. [MF_MSG_CLEAN_SWAPCACHE] = "clean swapcache page",
  796. [MF_MSG_DIRTY_MLOCKED_LRU] = "dirty mlocked LRU page",
  797. [MF_MSG_CLEAN_MLOCKED_LRU] = "clean mlocked LRU page",
  798. [MF_MSG_DIRTY_UNEVICTABLE_LRU] = "dirty unevictable LRU page",
  799. [MF_MSG_CLEAN_UNEVICTABLE_LRU] = "clean unevictable LRU page",
  800. [MF_MSG_DIRTY_LRU] = "dirty LRU page",
  801. [MF_MSG_CLEAN_LRU] = "clean LRU page",
  802. [MF_MSG_TRUNCATED_LRU] = "already truncated LRU page",
  803. [MF_MSG_BUDDY] = "free buddy page",
  804. [MF_MSG_DAX] = "dax page",
  805. [MF_MSG_UNSPLIT_THP] = "unsplit thp",
  806. [MF_MSG_ALREADY_POISONED] = "already poisoned page",
  807. [MF_MSG_PFN_MAP] = "non struct page pfn",
  808. [MF_MSG_UNKNOWN] = "unknown page",
  809. };
  810. /*
  811. * XXX: It is possible that a page is isolated from LRU cache,
  812. * and then kept in swap cache or failed to remove from page cache.
  813. * The page count will stop it from being freed by unpoison.
  814. * Stress tests should be aware of this memory leak problem.
  815. */
  816. static int delete_from_lru_cache(struct folio *folio)
  817. {
  818. if (folio_isolate_lru(folio)) {
  819. /*
  820. * Clear sensible page flags, so that the buddy system won't
  821. * complain when the folio is unpoison-and-freed.
  822. */
  823. folio_clear_active(folio);
  824. folio_clear_unevictable(folio);
  825. /*
  826. * Poisoned page might never drop its ref count to 0 so we have
  827. * to uncharge it manually from its memcg.
  828. */
  829. mem_cgroup_uncharge(folio);
  830. /*
  831. * drop the refcount elevated by folio_isolate_lru()
  832. */
  833. folio_put(folio);
  834. return 0;
  835. }
  836. return -EIO;
  837. }
  838. static int truncate_error_folio(struct folio *folio, unsigned long pfn,
  839. struct address_space *mapping)
  840. {
  841. int ret = MF_FAILED;
  842. if (mapping->a_ops->error_remove_folio) {
  843. int err = mapping->a_ops->error_remove_folio(mapping, folio);
  844. if (err != 0)
  845. pr_info("%#lx: Failed to punch page: %d\n", pfn, err);
  846. else if (!filemap_release_folio(folio, GFP_NOIO))
  847. pr_info("%#lx: failed to release buffers\n", pfn);
  848. else
  849. ret = MF_RECOVERED;
  850. } else {
  851. /*
  852. * If the file system doesn't support it just invalidate
  853. * This fails on dirty or anything with private pages
  854. */
  855. if (mapping_evict_folio(mapping, folio))
  856. ret = MF_RECOVERED;
  857. else
  858. pr_info("%#lx: Failed to invalidate\n", pfn);
  859. }
  860. return ret;
  861. }
  862. struct page_state {
  863. unsigned long mask;
  864. unsigned long res;
  865. enum mf_action_page_type type;
  866. /* Callback ->action() has to unlock the relevant page inside it. */
  867. int (*action)(struct page_state *ps, struct page *p);
  868. };
  869. /*
  870. * Return true if page is still referenced by others, otherwise return
  871. * false.
  872. *
  873. * The extra_pins is true when one extra refcount is expected.
  874. */
  875. static bool has_extra_refcount(struct page_state *ps, struct page *p,
  876. bool extra_pins)
  877. {
  878. int count = page_count(p) - 1;
  879. if (extra_pins)
  880. count -= folio_nr_pages(page_folio(p));
  881. if (count > 0) {
  882. pr_err("%#lx: %s still referenced by %d users\n",
  883. page_to_pfn(p), action_page_types[ps->type], count);
  884. return true;
  885. }
  886. return false;
  887. }
  888. /*
  889. * Error hit kernel page.
  890. * Do nothing, try to be lucky and not touch this instead. For a few cases we
  891. * could be more sophisticated.
  892. */
  893. static int me_kernel(struct page_state *ps, struct page *p)
  894. {
  895. unlock_page(p);
  896. return MF_IGNORED;
  897. }
  898. /*
  899. * Page in unknown state. Do nothing.
  900. * This is a catch-all in case we fail to make sense of the page state.
  901. */
  902. static int me_unknown(struct page_state *ps, struct page *p)
  903. {
  904. pr_err("%#lx: Unknown page state\n", page_to_pfn(p));
  905. unlock_page(p);
  906. return MF_IGNORED;
  907. }
  908. /*
  909. * Clean (or cleaned) page cache page.
  910. */
  911. static int me_pagecache_clean(struct page_state *ps, struct page *p)
  912. {
  913. struct folio *folio = page_folio(p);
  914. int ret;
  915. struct address_space *mapping;
  916. bool extra_pins;
  917. delete_from_lru_cache(folio);
  918. /*
  919. * For anonymous folios the only reference left
  920. * should be the one m_f() holds.
  921. */
  922. if (folio_test_anon(folio)) {
  923. ret = MF_RECOVERED;
  924. goto out;
  925. }
  926. /*
  927. * Now truncate the page in the page cache. This is really
  928. * more like a "temporary hole punch"
  929. * Don't do this for block devices when someone else
  930. * has a reference, because it could be file system metadata
  931. * and that's not safe to truncate.
  932. */
  933. mapping = folio_mapping(folio);
  934. if (!mapping) {
  935. /* Folio has been torn down in the meantime */
  936. ret = MF_FAILED;
  937. goto out;
  938. }
  939. /*
  940. * The shmem page is kept in page cache instead of truncating
  941. * so is expected to have an extra refcount after error-handling.
  942. */
  943. extra_pins = shmem_mapping(mapping);
  944. /*
  945. * Truncation is a bit tricky. Enable it per file system for now.
  946. *
  947. * Open: to take i_rwsem or not for this? Right now we don't.
  948. */
  949. ret = truncate_error_folio(folio, page_to_pfn(p), mapping);
  950. if (has_extra_refcount(ps, p, extra_pins))
  951. ret = MF_FAILED;
  952. out:
  953. folio_unlock(folio);
  954. return ret;
  955. }
  956. /*
  957. * Dirty pagecache page
  958. * Issues: when the error hit a hole page the error is not properly
  959. * propagated.
  960. */
  961. static int me_pagecache_dirty(struct page_state *ps, struct page *p)
  962. {
  963. struct folio *folio = page_folio(p);
  964. struct address_space *mapping = folio_mapping(folio);
  965. /* TBD: print more information about the file. */
  966. if (mapping) {
  967. /*
  968. * IO error will be reported by write(), fsync(), etc.
  969. * who check the mapping.
  970. * This way the application knows that something went
  971. * wrong with its dirty file data.
  972. */
  973. mapping_set_error(mapping, -EIO);
  974. }
  975. return me_pagecache_clean(ps, p);
  976. }
  977. /*
  978. * Clean and dirty swap cache.
  979. *
  980. * Dirty swap cache page is tricky to handle. The page could live both in page
  981. * table and swap cache(ie. page is freshly swapped in). So it could be
  982. * referenced concurrently by 2 types of PTEs:
  983. * normal PTEs and swap PTEs. We try to handle them consistently by calling
  984. * try_to_unmap(!TTU_HWPOISON) to convert the normal PTEs to swap PTEs,
  985. * and then
  986. * - clear dirty bit to prevent IO
  987. * - remove from LRU
  988. * - but keep in the swap cache, so that when we return to it on
  989. * a later page fault, we know the application is accessing
  990. * corrupted data and shall be killed (we installed simple
  991. * interception code in do_swap_page to catch it).
  992. *
  993. * Clean swap cache pages can be directly isolated. A later page fault will
  994. * bring in the known good data from disk.
  995. */
  996. static int me_swapcache_dirty(struct page_state *ps, struct page *p)
  997. {
  998. struct folio *folio = page_folio(p);
  999. int ret;
  1000. bool extra_pins = false;
  1001. folio_clear_dirty(folio);
  1002. /* Trigger EIO in shmem: */
  1003. folio_clear_uptodate(folio);
  1004. ret = delete_from_lru_cache(folio) ? MF_FAILED : MF_DELAYED;
  1005. folio_unlock(folio);
  1006. if (ret == MF_DELAYED)
  1007. extra_pins = true;
  1008. if (has_extra_refcount(ps, p, extra_pins))
  1009. ret = MF_FAILED;
  1010. return ret;
  1011. }
  1012. static int me_swapcache_clean(struct page_state *ps, struct page *p)
  1013. {
  1014. struct folio *folio = page_folio(p);
  1015. int ret;
  1016. swap_cache_del_folio(folio);
  1017. ret = delete_from_lru_cache(folio) ? MF_FAILED : MF_RECOVERED;
  1018. folio_unlock(folio);
  1019. if (has_extra_refcount(ps, p, false))
  1020. ret = MF_FAILED;
  1021. return ret;
  1022. }
  1023. /*
  1024. * Huge pages. Needs work.
  1025. * Issues:
  1026. * - Error on hugepage is contained in hugepage unit (not in raw page unit.)
  1027. * To narrow down kill region to one page, we need to break up pmd.
  1028. */
  1029. static int me_huge_page(struct page_state *ps, struct page *p)
  1030. {
  1031. struct folio *folio = page_folio(p);
  1032. int res;
  1033. struct address_space *mapping;
  1034. bool extra_pins = false;
  1035. mapping = folio_mapping(folio);
  1036. if (mapping) {
  1037. res = truncate_error_folio(folio, page_to_pfn(p), mapping);
  1038. /* The page is kept in page cache. */
  1039. extra_pins = true;
  1040. folio_unlock(folio);
  1041. } else {
  1042. folio_unlock(folio);
  1043. /*
  1044. * migration entry prevents later access on error hugepage,
  1045. * so we can free and dissolve it into buddy to save healthy
  1046. * subpages.
  1047. */
  1048. folio_put(folio);
  1049. if (__page_handle_poison(p) > 0) {
  1050. page_ref_inc(p);
  1051. res = MF_RECOVERED;
  1052. } else {
  1053. res = MF_FAILED;
  1054. }
  1055. }
  1056. if (has_extra_refcount(ps, p, extra_pins))
  1057. res = MF_FAILED;
  1058. return res;
  1059. }
  1060. /*
  1061. * Various page states we can handle.
  1062. *
  1063. * A page state is defined by its current page->flags bits.
  1064. * The table matches them in order and calls the right handler.
  1065. *
  1066. * This is quite tricky because we can access page at any time
  1067. * in its live cycle, so all accesses have to be extremely careful.
  1068. *
  1069. * This is not complete. More states could be added.
  1070. * For any missing state don't attempt recovery.
  1071. */
  1072. #define dirty (1UL << PG_dirty)
  1073. #define sc ((1UL << PG_swapcache) | (1UL << PG_swapbacked))
  1074. #define unevict (1UL << PG_unevictable)
  1075. #define mlock (1UL << PG_mlocked)
  1076. #define lru (1UL << PG_lru)
  1077. #define head (1UL << PG_head)
  1078. #define reserved (1UL << PG_reserved)
  1079. static struct page_state error_states[] = {
  1080. { reserved, reserved, MF_MSG_KERNEL, me_kernel },
  1081. /*
  1082. * free pages are specially detected outside this table:
  1083. * PG_buddy pages only make a small fraction of all free pages.
  1084. */
  1085. { head, head, MF_MSG_HUGE, me_huge_page },
  1086. { sc|dirty, sc|dirty, MF_MSG_DIRTY_SWAPCACHE, me_swapcache_dirty },
  1087. { sc|dirty, sc, MF_MSG_CLEAN_SWAPCACHE, me_swapcache_clean },
  1088. { mlock|dirty, mlock|dirty, MF_MSG_DIRTY_MLOCKED_LRU, me_pagecache_dirty },
  1089. { mlock|dirty, mlock, MF_MSG_CLEAN_MLOCKED_LRU, me_pagecache_clean },
  1090. { unevict|dirty, unevict|dirty, MF_MSG_DIRTY_UNEVICTABLE_LRU, me_pagecache_dirty },
  1091. { unevict|dirty, unevict, MF_MSG_CLEAN_UNEVICTABLE_LRU, me_pagecache_clean },
  1092. { lru|dirty, lru|dirty, MF_MSG_DIRTY_LRU, me_pagecache_dirty },
  1093. { lru|dirty, lru, MF_MSG_CLEAN_LRU, me_pagecache_clean },
  1094. /*
  1095. * Catchall entry: must be at end.
  1096. */
  1097. { 0, 0, MF_MSG_UNKNOWN, me_unknown },
  1098. };
  1099. #undef dirty
  1100. #undef sc
  1101. #undef unevict
  1102. #undef mlock
  1103. #undef lru
  1104. #undef head
  1105. #undef reserved
  1106. static void update_per_node_mf_stats(unsigned long pfn,
  1107. enum mf_result result)
  1108. {
  1109. int nid = MAX_NUMNODES;
  1110. struct memory_failure_stats *mf_stats = NULL;
  1111. nid = pfn_to_nid(pfn);
  1112. if (unlikely(nid < 0 || nid >= MAX_NUMNODES)) {
  1113. WARN_ONCE(1, "Memory failure: pfn=%#lx, invalid nid=%d", pfn, nid);
  1114. return;
  1115. }
  1116. mf_stats = &NODE_DATA(nid)->mf_stats;
  1117. switch (result) {
  1118. case MF_IGNORED:
  1119. ++mf_stats->ignored;
  1120. break;
  1121. case MF_FAILED:
  1122. ++mf_stats->failed;
  1123. break;
  1124. case MF_DELAYED:
  1125. ++mf_stats->delayed;
  1126. break;
  1127. case MF_RECOVERED:
  1128. ++mf_stats->recovered;
  1129. break;
  1130. default:
  1131. WARN_ONCE(1, "Memory failure: mf_result=%d is not properly handled", result);
  1132. break;
  1133. }
  1134. ++mf_stats->total;
  1135. }
  1136. /*
  1137. * "Dirty/Clean" indication is not 100% accurate due to the possibility of
  1138. * setting PG_dirty outside page lock. See also comment above set_page_dirty().
  1139. */
  1140. static int action_result(unsigned long pfn, enum mf_action_page_type type,
  1141. enum mf_result result)
  1142. {
  1143. trace_memory_failure_event(pfn, type, result);
  1144. if (type != MF_MSG_ALREADY_POISONED && type != MF_MSG_PFN_MAP) {
  1145. num_poisoned_pages_inc(pfn);
  1146. update_per_node_mf_stats(pfn, result);
  1147. }
  1148. pr_err("%#lx: recovery action for %s: %s\n",
  1149. pfn, action_page_types[type], action_name[result]);
  1150. return (result == MF_RECOVERED || result == MF_DELAYED) ? 0 : -EBUSY;
  1151. }
  1152. static int page_action(struct page_state *ps, struct page *p,
  1153. unsigned long pfn)
  1154. {
  1155. int result;
  1156. /* page p should be unlocked after returning from ps->action(). */
  1157. result = ps->action(ps, p);
  1158. /* Could do more checks here if page looks ok */
  1159. /*
  1160. * Could adjust zone counters here to correct for the missing page.
  1161. */
  1162. return action_result(pfn, ps->type, result);
  1163. }
  1164. static inline bool PageHWPoisonTakenOff(struct page *page)
  1165. {
  1166. return PageHWPoison(page) && page_private(page) == MAGIC_HWPOISON;
  1167. }
  1168. void SetPageHWPoisonTakenOff(struct page *page)
  1169. {
  1170. set_page_private(page, MAGIC_HWPOISON);
  1171. }
  1172. void ClearPageHWPoisonTakenOff(struct page *page)
  1173. {
  1174. if (PageHWPoison(page))
  1175. set_page_private(page, 0);
  1176. }
  1177. /*
  1178. * Return true if a page type of a given page is supported by hwpoison
  1179. * mechanism (while handling could fail), otherwise false. This function
  1180. * does not return true for hugetlb or device memory pages, so it's assumed
  1181. * to be called only in the context where we never have such pages.
  1182. */
  1183. static inline bool HWPoisonHandlable(struct page *page, unsigned long flags)
  1184. {
  1185. if (PageSlab(page))
  1186. return false;
  1187. /* Soft offline could migrate movable_ops pages */
  1188. if ((flags & MF_SOFT_OFFLINE) && page_has_movable_ops(page))
  1189. return true;
  1190. return PageLRU(page) || is_free_buddy_page(page);
  1191. }
  1192. static int __get_hwpoison_page(struct page *page, unsigned long flags)
  1193. {
  1194. struct folio *folio = page_folio(page);
  1195. int ret = 0;
  1196. bool hugetlb = false;
  1197. ret = get_hwpoison_hugetlb_folio(folio, &hugetlb, false);
  1198. if (hugetlb) {
  1199. /* Make sure hugetlb demotion did not happen from under us. */
  1200. if (folio == page_folio(page))
  1201. return ret;
  1202. if (ret > 0) {
  1203. folio_put(folio);
  1204. folio = page_folio(page);
  1205. }
  1206. }
  1207. /*
  1208. * This check prevents from calling folio_try_get() for any
  1209. * unsupported type of folio in order to reduce the risk of unexpected
  1210. * races caused by taking a folio refcount.
  1211. */
  1212. if (!HWPoisonHandlable(&folio->page, flags))
  1213. return -EBUSY;
  1214. if (folio_try_get(folio)) {
  1215. if (folio == page_folio(page))
  1216. return 1;
  1217. pr_info("%#lx cannot catch tail\n", page_to_pfn(page));
  1218. folio_put(folio);
  1219. }
  1220. return 0;
  1221. }
  1222. #define GET_PAGE_MAX_RETRY_NUM 3
  1223. static int get_any_page(struct page *p, unsigned long flags)
  1224. {
  1225. int ret = 0, pass = 0;
  1226. bool count_increased = false;
  1227. if (flags & MF_COUNT_INCREASED)
  1228. count_increased = true;
  1229. try_again:
  1230. if (!count_increased) {
  1231. ret = __get_hwpoison_page(p, flags);
  1232. if (!ret) {
  1233. if (page_count(p)) {
  1234. /* We raced with an allocation, retry. */
  1235. if (pass++ < GET_PAGE_MAX_RETRY_NUM)
  1236. goto try_again;
  1237. ret = -EBUSY;
  1238. } else if (!PageHuge(p) && !is_free_buddy_page(p)) {
  1239. /* We raced with put_page, retry. */
  1240. if (pass++ < GET_PAGE_MAX_RETRY_NUM)
  1241. goto try_again;
  1242. ret = -EIO;
  1243. }
  1244. goto out;
  1245. } else if (ret == -EBUSY) {
  1246. /*
  1247. * We raced with (possibly temporary) unhandlable
  1248. * page, retry.
  1249. */
  1250. if (pass++ < 3) {
  1251. shake_page(p);
  1252. goto try_again;
  1253. }
  1254. ret = -EIO;
  1255. goto out;
  1256. }
  1257. }
  1258. if (PageHuge(p) || HWPoisonHandlable(p, flags)) {
  1259. ret = 1;
  1260. } else {
  1261. /*
  1262. * A page we cannot handle. Check whether we can turn
  1263. * it into something we can handle.
  1264. */
  1265. if (pass++ < GET_PAGE_MAX_RETRY_NUM) {
  1266. put_page(p);
  1267. shake_page(p);
  1268. count_increased = false;
  1269. goto try_again;
  1270. }
  1271. put_page(p);
  1272. ret = -EIO;
  1273. }
  1274. out:
  1275. if (ret == -EIO)
  1276. pr_err("%#lx: unhandlable page.\n", page_to_pfn(p));
  1277. return ret;
  1278. }
  1279. static int __get_unpoison_page(struct page *page)
  1280. {
  1281. struct folio *folio = page_folio(page);
  1282. int ret = 0;
  1283. bool hugetlb = false;
  1284. ret = get_hwpoison_hugetlb_folio(folio, &hugetlb, true);
  1285. if (hugetlb) {
  1286. /* Make sure hugetlb demotion did not happen from under us. */
  1287. if (folio == page_folio(page))
  1288. return ret;
  1289. if (ret > 0)
  1290. folio_put(folio);
  1291. }
  1292. /*
  1293. * PageHWPoisonTakenOff pages are not only marked as PG_hwpoison,
  1294. * but also isolated from buddy freelist, so need to identify the
  1295. * state and have to cancel both operations to unpoison.
  1296. */
  1297. if (PageHWPoisonTakenOff(page))
  1298. return -EHWPOISON;
  1299. return get_page_unless_zero(page) ? 1 : 0;
  1300. }
  1301. /**
  1302. * get_hwpoison_page() - Get refcount for memory error handling
  1303. * @p: Raw error page (hit by memory error)
  1304. * @flags: Flags controlling behavior of error handling
  1305. *
  1306. * get_hwpoison_page() takes a page refcount of an error page to handle memory
  1307. * error on it, after checking that the error page is in a well-defined state
  1308. * (defined as a page-type we can successfully handle the memory error on it,
  1309. * such as LRU page and hugetlb page).
  1310. *
  1311. * Memory error handling could be triggered at any time on any type of page,
  1312. * so it's prone to race with typical memory management lifecycle (like
  1313. * allocation and free). So to avoid such races, get_hwpoison_page() takes
  1314. * extra care for the error page's state (as done in __get_hwpoison_page()),
  1315. * and has some retry logic in get_any_page().
  1316. *
  1317. * When called from unpoison_memory(), the caller should already ensure that
  1318. * the given page has PG_hwpoison. So it's never reused for other page
  1319. * allocations, and __get_unpoison_page() never races with them.
  1320. *
  1321. * Return: 0 on failure or free buddy (hugetlb) page,
  1322. * 1 on success for in-use pages in a well-defined state,
  1323. * -EIO for pages on which we can not handle memory errors,
  1324. * -EBUSY when get_hwpoison_page() has raced with page lifecycle
  1325. * operations like allocation and free,
  1326. * -EHWPOISON when the page is hwpoisoned and taken off from buddy.
  1327. */
  1328. static int get_hwpoison_page(struct page *p, unsigned long flags)
  1329. {
  1330. int ret;
  1331. zone_pcp_disable(page_zone(p));
  1332. if (flags & MF_UNPOISON)
  1333. ret = __get_unpoison_page(p);
  1334. else
  1335. ret = get_any_page(p, flags);
  1336. zone_pcp_enable(page_zone(p));
  1337. return ret;
  1338. }
  1339. /*
  1340. * The caller must guarantee the folio isn't large folio, except hugetlb.
  1341. * try_to_unmap() can't handle it.
  1342. */
  1343. int unmap_poisoned_folio(struct folio *folio, unsigned long pfn, bool must_kill)
  1344. {
  1345. enum ttu_flags ttu = TTU_IGNORE_MLOCK | TTU_SYNC | TTU_HWPOISON;
  1346. struct address_space *mapping;
  1347. if (folio_test_swapcache(folio)) {
  1348. pr_err("%#lx: keeping poisoned page in swap cache\n", pfn);
  1349. ttu &= ~TTU_HWPOISON;
  1350. }
  1351. /*
  1352. * Propagate the dirty bit from PTEs to struct page first, because we
  1353. * need this to decide if we should kill or just drop the page.
  1354. * XXX: the dirty test could be racy: set_page_dirty() may not always
  1355. * be called inside page lock (it's recommended but not enforced).
  1356. */
  1357. mapping = folio_mapping(folio);
  1358. if (!must_kill && !folio_test_dirty(folio) && mapping &&
  1359. mapping_can_writeback(mapping)) {
  1360. if (folio_mkclean(folio)) {
  1361. folio_set_dirty(folio);
  1362. } else {
  1363. ttu &= ~TTU_HWPOISON;
  1364. pr_info("%#lx: corrupted page was clean: dropped without side effects\n",
  1365. pfn);
  1366. }
  1367. }
  1368. if (folio_test_hugetlb(folio) && !folio_test_anon(folio)) {
  1369. /*
  1370. * For hugetlb folios in shared mappings, try_to_unmap
  1371. * could potentially call huge_pmd_unshare. Because of
  1372. * this, take semaphore in write mode here and set
  1373. * TTU_RMAP_LOCKED to indicate we have taken the lock
  1374. * at this higher level.
  1375. */
  1376. mapping = hugetlb_folio_mapping_lock_write(folio);
  1377. if (!mapping) {
  1378. pr_info("%#lx: could not lock mapping for mapped hugetlb folio\n",
  1379. folio_pfn(folio));
  1380. return -EBUSY;
  1381. }
  1382. try_to_unmap(folio, ttu|TTU_RMAP_LOCKED);
  1383. i_mmap_unlock_write(mapping);
  1384. } else {
  1385. try_to_unmap(folio, ttu);
  1386. }
  1387. return folio_mapped(folio) ? -EBUSY : 0;
  1388. }
  1389. /*
  1390. * Do all that is necessary to remove user space mappings. Unmap
  1391. * the pages and send SIGBUS to the processes if the data was dirty.
  1392. */
  1393. static bool hwpoison_user_mappings(struct folio *folio, struct page *p,
  1394. unsigned long pfn, int flags)
  1395. {
  1396. LIST_HEAD(tokill);
  1397. bool unmap_success;
  1398. int forcekill;
  1399. bool mlocked = folio_test_mlocked(folio);
  1400. /*
  1401. * Here we are interested only in user-mapped pages, so skip any
  1402. * other types of pages.
  1403. */
  1404. if (folio_test_reserved(folio) || folio_test_slab(folio) ||
  1405. folio_test_pgtable(folio) || folio_test_offline(folio))
  1406. return true;
  1407. if (!(folio_test_lru(folio) || folio_test_hugetlb(folio)))
  1408. return true;
  1409. /*
  1410. * This check implies we don't kill processes if their pages
  1411. * are in the swap cache early. Those are always late kills.
  1412. */
  1413. if (!folio_mapped(folio))
  1414. return true;
  1415. /*
  1416. * First collect all the processes that have the page
  1417. * mapped in dirty form. This has to be done before try_to_unmap,
  1418. * because ttu takes the rmap data structures down.
  1419. */
  1420. collect_procs(folio, p, &tokill, flags & MF_ACTION_REQUIRED);
  1421. unmap_success = !unmap_poisoned_folio(folio, pfn, flags & MF_MUST_KILL);
  1422. if (!unmap_success)
  1423. pr_err("%#lx: failed to unmap page (folio mapcount=%d)\n",
  1424. pfn, folio_mapcount(folio));
  1425. /*
  1426. * try_to_unmap() might put mlocked page in lru cache, so call
  1427. * shake_page() again to ensure that it's flushed.
  1428. */
  1429. if (mlocked)
  1430. shake_folio(folio);
  1431. /*
  1432. * Now that the dirty bit has been propagated to the
  1433. * struct page and all unmaps done we can decide if
  1434. * killing is needed or not. Only kill when the page
  1435. * was dirty or the process is not restartable,
  1436. * otherwise the tokill list is merely
  1437. * freed. When there was a problem unmapping earlier
  1438. * use a more force-full uncatchable kill to prevent
  1439. * any accesses to the poisoned memory.
  1440. */
  1441. forcekill = folio_test_dirty(folio) || (flags & MF_MUST_KILL) ||
  1442. !unmap_success;
  1443. kill_procs(&tokill, forcekill, pfn, flags);
  1444. return unmap_success;
  1445. }
  1446. static int identify_page_state(unsigned long pfn, struct page *p,
  1447. unsigned long page_flags)
  1448. {
  1449. struct page_state *ps;
  1450. /*
  1451. * The first check uses the current page flags which may not have any
  1452. * relevant information. The second check with the saved page flags is
  1453. * carried out only if the first check can't determine the page status.
  1454. */
  1455. for (ps = error_states;; ps++)
  1456. if ((p->flags.f & ps->mask) == ps->res)
  1457. break;
  1458. page_flags |= (p->flags.f & (1UL << PG_dirty));
  1459. if (!ps->mask)
  1460. for (ps = error_states;; ps++)
  1461. if ((page_flags & ps->mask) == ps->res)
  1462. break;
  1463. return page_action(ps, p, pfn);
  1464. }
  1465. /*
  1466. * When 'release' is 'false', it means that if thp split has failed,
  1467. * there is still more to do, hence the page refcount we took earlier
  1468. * is still needed.
  1469. */
  1470. static int try_to_split_thp_page(struct page *page, unsigned int new_order,
  1471. bool release)
  1472. {
  1473. int ret;
  1474. lock_page(page);
  1475. ret = split_huge_page_to_order(page, new_order);
  1476. unlock_page(page);
  1477. if (ret && release)
  1478. put_page(page);
  1479. return ret;
  1480. }
  1481. static void unmap_and_kill(struct list_head *to_kill, unsigned long pfn,
  1482. struct address_space *mapping, pgoff_t index, int flags)
  1483. {
  1484. struct to_kill *tk;
  1485. unsigned long size = 0;
  1486. list_for_each_entry(tk, to_kill, nd)
  1487. if (tk->size_shift)
  1488. size = max(size, 1UL << tk->size_shift);
  1489. if (size) {
  1490. /*
  1491. * Unmap the largest mapping to avoid breaking up device-dax
  1492. * mappings which are constant size. The actual size of the
  1493. * mapping being torn down is communicated in siginfo, see
  1494. * kill_proc()
  1495. */
  1496. loff_t start = ((loff_t)index << PAGE_SHIFT) & ~(size - 1);
  1497. unmap_mapping_range(mapping, start, size, 0);
  1498. }
  1499. kill_procs(to_kill, flags & MF_MUST_KILL, pfn, flags);
  1500. }
  1501. /*
  1502. * Only dev_pagemap pages get here, such as fsdax when the filesystem
  1503. * either do not claim or fails to claim a hwpoison event, or devdax.
  1504. * The fsdax pages are initialized per base page, and the devdax pages
  1505. * could be initialized either as base pages, or as compound pages with
  1506. * vmemmap optimization enabled. Devdax is simplistic in its dealing with
  1507. * hwpoison, such that, if a subpage of a compound page is poisoned,
  1508. * simply mark the compound head page is by far sufficient.
  1509. */
  1510. static int mf_generic_kill_procs(unsigned long long pfn, int flags,
  1511. struct dev_pagemap *pgmap)
  1512. {
  1513. struct folio *folio = pfn_folio(pfn);
  1514. LIST_HEAD(to_kill);
  1515. dax_entry_t cookie;
  1516. int rc = 0;
  1517. /*
  1518. * Prevent the inode from being freed while we are interrogating
  1519. * the address_space, typically this would be handled by
  1520. * lock_page(), but dax pages do not use the page lock. This
  1521. * also prevents changes to the mapping of this pfn until
  1522. * poison signaling is complete.
  1523. */
  1524. cookie = dax_lock_folio(folio);
  1525. if (!cookie)
  1526. return -EBUSY;
  1527. if (hwpoison_filter(&folio->page)) {
  1528. rc = -EOPNOTSUPP;
  1529. goto unlock;
  1530. }
  1531. switch (pgmap->type) {
  1532. case MEMORY_DEVICE_PRIVATE:
  1533. case MEMORY_DEVICE_COHERENT:
  1534. /*
  1535. * TODO: Handle device pages which may need coordination
  1536. * with device-side memory.
  1537. */
  1538. rc = -ENXIO;
  1539. goto unlock;
  1540. default:
  1541. break;
  1542. }
  1543. /*
  1544. * Use this flag as an indication that the dax page has been
  1545. * remapped UC to prevent speculative consumption of poison.
  1546. */
  1547. SetPageHWPoison(&folio->page);
  1548. /*
  1549. * Unlike System-RAM there is no possibility to swap in a
  1550. * different physical page at a given virtual address, so all
  1551. * userspace consumption of ZONE_DEVICE memory necessitates
  1552. * SIGBUS (i.e. MF_MUST_KILL)
  1553. */
  1554. flags |= MF_ACTION_REQUIRED | MF_MUST_KILL;
  1555. collect_procs(folio, &folio->page, &to_kill, true);
  1556. unmap_and_kill(&to_kill, pfn, folio->mapping, folio->index, flags);
  1557. unlock:
  1558. dax_unlock_folio(folio, cookie);
  1559. return rc;
  1560. }
  1561. #ifdef CONFIG_FS_DAX
  1562. /**
  1563. * mf_dax_kill_procs - Collect and kill processes who are using this file range
  1564. * @mapping: address_space of the file in use
  1565. * @index: start pgoff of the range within the file
  1566. * @count: length of the range, in unit of PAGE_SIZE
  1567. * @mf_flags: memory failure flags
  1568. */
  1569. int mf_dax_kill_procs(struct address_space *mapping, pgoff_t index,
  1570. unsigned long count, int mf_flags)
  1571. {
  1572. LIST_HEAD(to_kill);
  1573. dax_entry_t cookie;
  1574. struct page *page;
  1575. size_t end = index + count;
  1576. bool pre_remove = mf_flags & MF_MEM_PRE_REMOVE;
  1577. mf_flags |= MF_ACTION_REQUIRED | MF_MUST_KILL;
  1578. for (; index < end; index++) {
  1579. page = NULL;
  1580. cookie = dax_lock_mapping_entry(mapping, index, &page);
  1581. if (!cookie)
  1582. return -EBUSY;
  1583. if (!page)
  1584. goto unlock;
  1585. if (!pre_remove)
  1586. SetPageHWPoison(page);
  1587. /*
  1588. * The pre_remove case is revoking access, the memory is still
  1589. * good and could theoretically be put back into service.
  1590. */
  1591. collect_procs_fsdax(page, mapping, index, &to_kill, pre_remove);
  1592. unmap_and_kill(&to_kill, page_to_pfn(page), mapping,
  1593. index, mf_flags);
  1594. unlock:
  1595. dax_unlock_mapping_entry(mapping, index, cookie);
  1596. }
  1597. return 0;
  1598. }
  1599. EXPORT_SYMBOL_GPL(mf_dax_kill_procs);
  1600. #endif /* CONFIG_FS_DAX */
  1601. #ifdef CONFIG_HUGETLB_PAGE
  1602. /*
  1603. * Struct raw_hwp_page represents information about "raw error page",
  1604. * constructing singly linked list from ->_hugetlb_hwpoison field of folio.
  1605. */
  1606. struct raw_hwp_page {
  1607. struct llist_node node;
  1608. struct page *page;
  1609. };
  1610. static inline struct llist_head *raw_hwp_list_head(struct folio *folio)
  1611. {
  1612. return (struct llist_head *)&folio->_hugetlb_hwpoison;
  1613. }
  1614. bool is_raw_hwpoison_page_in_hugepage(struct page *page)
  1615. {
  1616. struct llist_head *raw_hwp_head;
  1617. struct raw_hwp_page *p;
  1618. struct folio *folio = page_folio(page);
  1619. bool ret = false;
  1620. if (!folio_test_hwpoison(folio))
  1621. return false;
  1622. if (!folio_test_hugetlb(folio))
  1623. return PageHWPoison(page);
  1624. /*
  1625. * When RawHwpUnreliable is set, kernel lost track of which subpages
  1626. * are HWPOISON. So return as if ALL subpages are HWPOISONed.
  1627. */
  1628. if (folio_test_hugetlb_raw_hwp_unreliable(folio))
  1629. return true;
  1630. mutex_lock(&mf_mutex);
  1631. raw_hwp_head = raw_hwp_list_head(folio);
  1632. llist_for_each_entry(p, raw_hwp_head->first, node) {
  1633. if (page == p->page) {
  1634. ret = true;
  1635. break;
  1636. }
  1637. }
  1638. mutex_unlock(&mf_mutex);
  1639. return ret;
  1640. }
  1641. static unsigned long __folio_free_raw_hwp(struct folio *folio, bool move_flag)
  1642. {
  1643. struct llist_node *head;
  1644. struct raw_hwp_page *p, *next;
  1645. unsigned long count = 0;
  1646. head = llist_del_all(raw_hwp_list_head(folio));
  1647. llist_for_each_entry_safe(p, next, head, node) {
  1648. if (move_flag)
  1649. SetPageHWPoison(p->page);
  1650. else
  1651. num_poisoned_pages_sub(page_to_pfn(p->page), 1);
  1652. kfree(p);
  1653. count++;
  1654. }
  1655. return count;
  1656. }
  1657. #define MF_HUGETLB_FREED 0 /* freed hugepage */
  1658. #define MF_HUGETLB_IN_USED 1 /* in-use hugepage */
  1659. #define MF_HUGETLB_NON_HUGEPAGE 2 /* not a hugepage */
  1660. #define MF_HUGETLB_FOLIO_PRE_POISONED 3 /* folio already poisoned */
  1661. #define MF_HUGETLB_PAGE_PRE_POISONED 4 /* exact page already poisoned */
  1662. #define MF_HUGETLB_RETRY 5 /* hugepage is busy, retry */
  1663. /*
  1664. * Set hugetlb folio as hwpoisoned, update folio private raw hwpoison list
  1665. * to keep track of the poisoned pages.
  1666. */
  1667. static int hugetlb_update_hwpoison(struct folio *folio, struct page *page)
  1668. {
  1669. struct llist_head *head;
  1670. struct raw_hwp_page *raw_hwp;
  1671. struct raw_hwp_page *p;
  1672. int ret = folio_test_set_hwpoison(folio) ? MF_HUGETLB_FOLIO_PRE_POISONED : 0;
  1673. /*
  1674. * Once the hwpoison hugepage has lost reliable raw error info,
  1675. * there is little meaning to keep additional error info precisely,
  1676. * so skip to add additional raw error info.
  1677. */
  1678. if (folio_test_hugetlb_raw_hwp_unreliable(folio))
  1679. return MF_HUGETLB_FOLIO_PRE_POISONED;
  1680. head = raw_hwp_list_head(folio);
  1681. llist_for_each_entry(p, head->first, node) {
  1682. if (p->page == page)
  1683. return MF_HUGETLB_PAGE_PRE_POISONED;
  1684. }
  1685. raw_hwp = kmalloc_obj(struct raw_hwp_page, GFP_ATOMIC);
  1686. if (raw_hwp) {
  1687. raw_hwp->page = page;
  1688. llist_add(&raw_hwp->node, head);
  1689. } else {
  1690. /*
  1691. * Failed to save raw error info. We no longer trace all
  1692. * hwpoisoned subpages, and we need refuse to free/dissolve
  1693. * this hwpoisoned hugepage.
  1694. */
  1695. folio_set_hugetlb_raw_hwp_unreliable(folio);
  1696. /*
  1697. * Once hugetlb_raw_hwp_unreliable is set, raw_hwp_page is not
  1698. * used any more, so free it.
  1699. */
  1700. __folio_free_raw_hwp(folio, false);
  1701. }
  1702. return ret;
  1703. }
  1704. static unsigned long folio_free_raw_hwp(struct folio *folio, bool move_flag)
  1705. {
  1706. /*
  1707. * hugetlb_vmemmap_optimized hugepages can't be freed because struct
  1708. * pages for tail pages are required but they don't exist.
  1709. */
  1710. if (move_flag && folio_test_hugetlb_vmemmap_optimized(folio))
  1711. return 0;
  1712. /*
  1713. * hugetlb_raw_hwp_unreliable hugepages shouldn't be unpoisoned by
  1714. * definition.
  1715. */
  1716. if (folio_test_hugetlb_raw_hwp_unreliable(folio))
  1717. return 0;
  1718. return __folio_free_raw_hwp(folio, move_flag);
  1719. }
  1720. void folio_clear_hugetlb_hwpoison(struct folio *folio)
  1721. {
  1722. if (folio_test_hugetlb_raw_hwp_unreliable(folio))
  1723. return;
  1724. if (folio_test_hugetlb_vmemmap_optimized(folio))
  1725. return;
  1726. folio_clear_hwpoison(folio);
  1727. folio_free_raw_hwp(folio, true);
  1728. }
  1729. /*
  1730. * Called from hugetlb code with hugetlb_lock held.
  1731. */
  1732. int __get_huge_page_for_hwpoison(unsigned long pfn, int flags,
  1733. bool *migratable_cleared)
  1734. {
  1735. struct page *page = pfn_to_page(pfn);
  1736. struct folio *folio = page_folio(page);
  1737. bool count_increased = false;
  1738. int ret, rc;
  1739. if (!folio_test_hugetlb(folio)) {
  1740. ret = MF_HUGETLB_NON_HUGEPAGE;
  1741. goto out;
  1742. } else if (flags & MF_COUNT_INCREASED) {
  1743. ret = MF_HUGETLB_IN_USED;
  1744. count_increased = true;
  1745. } else if (folio_test_hugetlb_freed(folio)) {
  1746. ret = MF_HUGETLB_FREED;
  1747. } else if (folio_test_hugetlb_migratable(folio)) {
  1748. if (folio_try_get(folio)) {
  1749. ret = MF_HUGETLB_IN_USED;
  1750. count_increased = true;
  1751. } else {
  1752. ret = MF_HUGETLB_FREED;
  1753. }
  1754. } else {
  1755. ret = MF_HUGETLB_RETRY;
  1756. if (!(flags & MF_NO_RETRY))
  1757. goto out;
  1758. }
  1759. rc = hugetlb_update_hwpoison(folio, page);
  1760. if (rc >= MF_HUGETLB_FOLIO_PRE_POISONED) {
  1761. ret = rc;
  1762. goto out;
  1763. }
  1764. /*
  1765. * Clearing hugetlb_migratable for hwpoisoned hugepages to prevent them
  1766. * from being migrated by memory hotremove.
  1767. */
  1768. if (count_increased && folio_test_hugetlb_migratable(folio)) {
  1769. folio_clear_hugetlb_migratable(folio);
  1770. *migratable_cleared = true;
  1771. }
  1772. return ret;
  1773. out:
  1774. if (count_increased)
  1775. folio_put(folio);
  1776. return ret;
  1777. }
  1778. /*
  1779. * Taking refcount of hugetlb pages needs extra care about race conditions
  1780. * with basic operations like hugepage allocation/free/demotion.
  1781. * So some of prechecks for hwpoison (pinning, and testing/setting
  1782. * PageHWPoison) should be done in single hugetlb_lock range.
  1783. * Returns:
  1784. * 0 - not hugetlb, or recovered
  1785. * -EBUSY - not recovered
  1786. * -EOPNOTSUPP - hwpoison_filter'ed
  1787. * -EHWPOISON - folio or exact page already poisoned
  1788. * -EFAULT - kill_accessing_process finds current->mm null
  1789. */
  1790. static int try_memory_failure_hugetlb(unsigned long pfn, int flags, int *hugetlb)
  1791. {
  1792. int res, rv;
  1793. struct page *p = pfn_to_page(pfn);
  1794. struct folio *folio;
  1795. unsigned long page_flags;
  1796. bool migratable_cleared = false;
  1797. *hugetlb = 1;
  1798. retry:
  1799. res = get_huge_page_for_hwpoison(pfn, flags, &migratable_cleared);
  1800. switch (res) {
  1801. case MF_HUGETLB_NON_HUGEPAGE: /* fallback to normal page handling */
  1802. *hugetlb = 0;
  1803. return 0;
  1804. case MF_HUGETLB_RETRY:
  1805. if (!(flags & MF_NO_RETRY)) {
  1806. flags |= MF_NO_RETRY;
  1807. goto retry;
  1808. }
  1809. return action_result(pfn, MF_MSG_GET_HWPOISON, MF_IGNORED);
  1810. case MF_HUGETLB_FOLIO_PRE_POISONED:
  1811. case MF_HUGETLB_PAGE_PRE_POISONED:
  1812. rv = -EHWPOISON;
  1813. if (flags & MF_ACTION_REQUIRED)
  1814. rv = kill_accessing_process(current, pfn, flags);
  1815. if (res == MF_HUGETLB_PAGE_PRE_POISONED)
  1816. action_result(pfn, MF_MSG_ALREADY_POISONED, MF_FAILED);
  1817. else
  1818. action_result(pfn, MF_MSG_HUGE, MF_FAILED);
  1819. return rv;
  1820. default:
  1821. WARN_ON((res != MF_HUGETLB_FREED) && (res != MF_HUGETLB_IN_USED));
  1822. break;
  1823. }
  1824. folio = page_folio(p);
  1825. folio_lock(folio);
  1826. if (hwpoison_filter(p)) {
  1827. folio_clear_hugetlb_hwpoison(folio);
  1828. if (migratable_cleared)
  1829. folio_set_hugetlb_migratable(folio);
  1830. folio_unlock(folio);
  1831. if (res == MF_HUGETLB_IN_USED)
  1832. folio_put(folio);
  1833. return -EOPNOTSUPP;
  1834. }
  1835. /*
  1836. * Handling free hugepage. The possible race with hugepage allocation
  1837. * or demotion can be prevented by PageHWPoison flag.
  1838. */
  1839. if (res == MF_HUGETLB_FREED) {
  1840. folio_unlock(folio);
  1841. if (__page_handle_poison(p) > 0) {
  1842. page_ref_inc(p);
  1843. res = MF_RECOVERED;
  1844. } else {
  1845. res = MF_FAILED;
  1846. }
  1847. return action_result(pfn, MF_MSG_FREE_HUGE, res);
  1848. }
  1849. page_flags = folio->flags.f;
  1850. if (!hwpoison_user_mappings(folio, p, pfn, flags)) {
  1851. folio_unlock(folio);
  1852. return action_result(pfn, MF_MSG_UNMAP_FAILED, MF_FAILED);
  1853. }
  1854. return identify_page_state(pfn, p, page_flags);
  1855. }
  1856. #else
  1857. static inline int try_memory_failure_hugetlb(unsigned long pfn, int flags, int *hugetlb)
  1858. {
  1859. return 0;
  1860. }
  1861. static inline unsigned long folio_free_raw_hwp(struct folio *folio, bool flag)
  1862. {
  1863. return 0;
  1864. }
  1865. #endif /* CONFIG_HUGETLB_PAGE */
  1866. /* Drop the extra refcount in case we come from madvise() */
  1867. static void put_ref_page(unsigned long pfn, int flags)
  1868. {
  1869. if (!(flags & MF_COUNT_INCREASED))
  1870. return;
  1871. put_page(pfn_to_page(pfn));
  1872. }
  1873. static int memory_failure_dev_pagemap(unsigned long pfn, int flags,
  1874. struct dev_pagemap *pgmap)
  1875. {
  1876. int rc = -ENXIO;
  1877. /* device metadata space is not recoverable */
  1878. if (!pgmap_pfn_valid(pgmap, pfn))
  1879. goto out;
  1880. /*
  1881. * Call driver's implementation to handle the memory failure, otherwise
  1882. * fall back to generic handler.
  1883. */
  1884. if (pgmap_has_memory_failure(pgmap)) {
  1885. rc = pgmap->ops->memory_failure(pgmap, pfn, 1, flags);
  1886. /*
  1887. * Fall back to generic handler too if operation is not
  1888. * supported inside the driver/device/filesystem.
  1889. */
  1890. if (rc != -EOPNOTSUPP)
  1891. goto out;
  1892. }
  1893. rc = mf_generic_kill_procs(pfn, flags, pgmap);
  1894. out:
  1895. /* drop pgmap ref acquired in caller */
  1896. put_dev_pagemap(pgmap);
  1897. if (rc != -EOPNOTSUPP)
  1898. action_result(pfn, MF_MSG_DAX, rc ? MF_FAILED : MF_RECOVERED);
  1899. return rc;
  1900. }
  1901. /*
  1902. * The calling condition is as such: thp split failed, page might have
  1903. * been RDMA pinned, not much can be done for recovery.
  1904. * But a SIGBUS should be delivered with vaddr provided so that the user
  1905. * application has a chance to recover. Also, application processes'
  1906. * election for MCE early killed will be honored.
  1907. */
  1908. static void kill_procs_now(struct page *p, unsigned long pfn, int flags,
  1909. struct folio *folio)
  1910. {
  1911. LIST_HEAD(tokill);
  1912. folio_lock(folio);
  1913. collect_procs(folio, p, &tokill, flags & MF_ACTION_REQUIRED);
  1914. folio_unlock(folio);
  1915. kill_procs(&tokill, true, pfn, flags);
  1916. }
  1917. int register_pfn_address_space(struct pfn_address_space *pfn_space)
  1918. {
  1919. guard(mutex)(&pfn_space_lock);
  1920. if (!pfn_space->pfn_to_vma_pgoff)
  1921. return -EINVAL;
  1922. if (interval_tree_iter_first(&pfn_space_itree,
  1923. pfn_space->node.start,
  1924. pfn_space->node.last))
  1925. return -EBUSY;
  1926. interval_tree_insert(&pfn_space->node, &pfn_space_itree);
  1927. return 0;
  1928. }
  1929. EXPORT_SYMBOL_GPL(register_pfn_address_space);
  1930. void unregister_pfn_address_space(struct pfn_address_space *pfn_space)
  1931. {
  1932. guard(mutex)(&pfn_space_lock);
  1933. if (interval_tree_iter_first(&pfn_space_itree,
  1934. pfn_space->node.start,
  1935. pfn_space->node.last))
  1936. interval_tree_remove(&pfn_space->node, &pfn_space_itree);
  1937. }
  1938. EXPORT_SYMBOL_GPL(unregister_pfn_address_space);
  1939. static void add_to_kill_pgoff(struct task_struct *tsk,
  1940. struct vm_area_struct *vma,
  1941. struct list_head *to_kill,
  1942. pgoff_t pgoff)
  1943. {
  1944. struct to_kill *tk;
  1945. tk = kmalloc_obj(*tk, GFP_ATOMIC);
  1946. if (!tk) {
  1947. pr_info("Unable to kill proc %d\n", tsk->pid);
  1948. return;
  1949. }
  1950. /* Check for pgoff not backed by struct page */
  1951. tk->addr = vma_address(vma, pgoff, 1);
  1952. tk->size_shift = PAGE_SHIFT;
  1953. if (tk->addr == -EFAULT)
  1954. pr_info("Unable to find address %lx in %s\n",
  1955. pgoff, tsk->comm);
  1956. get_task_struct(tsk);
  1957. tk->tsk = tsk;
  1958. list_add_tail(&tk->nd, to_kill);
  1959. }
  1960. /*
  1961. * Collect processes when the error hit a PFN not backed by struct page.
  1962. */
  1963. static void collect_procs_pfn(struct pfn_address_space *pfn_space,
  1964. unsigned long pfn, struct list_head *to_kill)
  1965. {
  1966. struct vm_area_struct *vma;
  1967. struct task_struct *tsk;
  1968. struct address_space *mapping = pfn_space->mapping;
  1969. i_mmap_lock_read(mapping);
  1970. rcu_read_lock();
  1971. for_each_process(tsk) {
  1972. struct task_struct *t = tsk;
  1973. t = task_early_kill(tsk, true);
  1974. if (!t)
  1975. continue;
  1976. vma_interval_tree_foreach(vma, &mapping->i_mmap, 0, ULONG_MAX) {
  1977. pgoff_t pgoff;
  1978. if (vma->vm_mm == t->mm &&
  1979. !pfn_space->pfn_to_vma_pgoff(vma, pfn, &pgoff))
  1980. add_to_kill_pgoff(t, vma, to_kill, pgoff);
  1981. }
  1982. }
  1983. rcu_read_unlock();
  1984. i_mmap_unlock_read(mapping);
  1985. }
  1986. /**
  1987. * memory_failure_pfn - Handle memory failure on a page not backed by
  1988. * struct page.
  1989. * @pfn: Page Number of the corrupted page
  1990. * @flags: fine tune action taken
  1991. *
  1992. * Return:
  1993. * 0 - success,
  1994. * -EBUSY - Page PFN does not belong to any address space mapping.
  1995. */
  1996. static int memory_failure_pfn(unsigned long pfn, int flags)
  1997. {
  1998. struct interval_tree_node *node;
  1999. LIST_HEAD(tokill);
  2000. scoped_guard(mutex, &pfn_space_lock) {
  2001. bool mf_handled = false;
  2002. /*
  2003. * Modules registers with MM the address space mapping to
  2004. * the device memory they manage. Iterate to identify
  2005. * exactly which address space has mapped to this failing
  2006. * PFN.
  2007. */
  2008. for (node = interval_tree_iter_first(&pfn_space_itree, pfn, pfn); node;
  2009. node = interval_tree_iter_next(node, pfn, pfn)) {
  2010. struct pfn_address_space *pfn_space =
  2011. container_of(node, struct pfn_address_space, node);
  2012. collect_procs_pfn(pfn_space, pfn, &tokill);
  2013. mf_handled = true;
  2014. }
  2015. if (!mf_handled)
  2016. return action_result(pfn, MF_MSG_PFN_MAP, MF_IGNORED);
  2017. }
  2018. /*
  2019. * Unlike System-RAM there is no possibility to swap in a different
  2020. * physical page at a given virtual address, so all userspace
  2021. * consumption of direct PFN memory necessitates SIGBUS (i.e.
  2022. * MF_MUST_KILL)
  2023. */
  2024. flags |= MF_ACTION_REQUIRED | MF_MUST_KILL;
  2025. kill_procs(&tokill, true, pfn, flags);
  2026. return action_result(pfn, MF_MSG_PFN_MAP, MF_RECOVERED);
  2027. }
  2028. /**
  2029. * memory_failure - Handle memory failure of a page.
  2030. * @pfn: Page Number of the corrupted page
  2031. * @flags: fine tune action taken
  2032. *
  2033. * This function is called by the low level machine check code
  2034. * of an architecture when it detects hardware memory corruption
  2035. * of a page. It tries its best to recover, which includes
  2036. * dropping pages, killing processes etc.
  2037. *
  2038. * The function is primarily of use for corruptions that
  2039. * happen outside the current execution context (e.g. when
  2040. * detected by a background scrubber)
  2041. *
  2042. * Must run in process context (e.g. a work queue) with interrupts
  2043. * enabled and no spinlocks held.
  2044. *
  2045. * Return:
  2046. * 0 - success,
  2047. * -ENXIO - memory not managed by the kernel
  2048. * -EOPNOTSUPP - hwpoison_filter() filtered the error event,
  2049. * -EHWPOISON - the page was already poisoned, potentially
  2050. * kill process,
  2051. * other negative values - failure.
  2052. */
  2053. int memory_failure(unsigned long pfn, int flags)
  2054. {
  2055. struct page *p;
  2056. struct folio *folio;
  2057. struct dev_pagemap *pgmap;
  2058. int res = 0;
  2059. unsigned long page_flags;
  2060. bool retry = true;
  2061. int hugetlb = 0;
  2062. if (!sysctl_memory_failure_recovery)
  2063. panic("Memory failure on page %lx", pfn);
  2064. mutex_lock(&mf_mutex);
  2065. if (!(flags & MF_SW_SIMULATED))
  2066. hw_memory_failure = true;
  2067. p = pfn_to_online_page(pfn);
  2068. if (!p) {
  2069. res = arch_memory_failure(pfn, flags);
  2070. if (res == 0)
  2071. goto unlock_mutex;
  2072. if (!pfn_valid(pfn) && !arch_is_platform_page(PFN_PHYS(pfn))) {
  2073. /*
  2074. * The PFN is not backed by struct page.
  2075. */
  2076. res = memory_failure_pfn(pfn, flags);
  2077. goto unlock_mutex;
  2078. }
  2079. if (pfn_valid(pfn)) {
  2080. pgmap = get_dev_pagemap(pfn);
  2081. put_ref_page(pfn, flags);
  2082. if (pgmap) {
  2083. res = memory_failure_dev_pagemap(pfn, flags,
  2084. pgmap);
  2085. goto unlock_mutex;
  2086. }
  2087. }
  2088. pr_err("%#lx: memory outside kernel control\n", pfn);
  2089. res = -ENXIO;
  2090. goto unlock_mutex;
  2091. }
  2092. try_again:
  2093. res = try_memory_failure_hugetlb(pfn, flags, &hugetlb);
  2094. if (hugetlb)
  2095. goto unlock_mutex;
  2096. if (TestSetPageHWPoison(p)) {
  2097. res = -EHWPOISON;
  2098. if (flags & MF_ACTION_REQUIRED)
  2099. res = kill_accessing_process(current, pfn, flags);
  2100. if (flags & MF_COUNT_INCREASED)
  2101. put_page(p);
  2102. action_result(pfn, MF_MSG_ALREADY_POISONED, MF_FAILED);
  2103. goto unlock_mutex;
  2104. }
  2105. /*
  2106. * We need/can do nothing about count=0 pages.
  2107. * 1) it's a free page, and therefore in safe hand:
  2108. * check_new_page() will be the gate keeper.
  2109. * 2) it's part of a non-compound high order page.
  2110. * Implies some kernel user: cannot stop them from
  2111. * R/W the page; let's pray that the page has been
  2112. * used and will be freed some time later.
  2113. * In fact it's dangerous to directly bump up page count from 0,
  2114. * that may make page_ref_freeze()/page_ref_unfreeze() mismatch.
  2115. */
  2116. res = get_hwpoison_page(p, flags);
  2117. if (!res) {
  2118. if (is_free_buddy_page(p)) {
  2119. if (take_page_off_buddy(p)) {
  2120. page_ref_inc(p);
  2121. res = MF_RECOVERED;
  2122. } else {
  2123. /* We lost the race, try again */
  2124. if (retry) {
  2125. ClearPageHWPoison(p);
  2126. retry = false;
  2127. goto try_again;
  2128. }
  2129. res = MF_FAILED;
  2130. }
  2131. res = action_result(pfn, MF_MSG_BUDDY, res);
  2132. } else {
  2133. res = action_result(pfn, MF_MSG_KERNEL_HIGH_ORDER, MF_IGNORED);
  2134. }
  2135. goto unlock_mutex;
  2136. } else if (res < 0) {
  2137. res = action_result(pfn, MF_MSG_GET_HWPOISON, MF_IGNORED);
  2138. goto unlock_mutex;
  2139. }
  2140. folio = page_folio(p);
  2141. /* filter pages that are protected from hwpoison test by users */
  2142. folio_lock(folio);
  2143. if (hwpoison_filter(p)) {
  2144. ClearPageHWPoison(p);
  2145. folio_unlock(folio);
  2146. folio_put(folio);
  2147. res = -EOPNOTSUPP;
  2148. goto unlock_mutex;
  2149. }
  2150. folio_unlock(folio);
  2151. if (folio_test_large(folio)) {
  2152. const int new_order = min_order_for_split(folio);
  2153. int err;
  2154. /*
  2155. * The flag must be set after the refcount is bumped
  2156. * otherwise it may race with THP split.
  2157. * And the flag can't be set in get_hwpoison_page() since
  2158. * it is called by soft offline too and it is just called
  2159. * for !MF_COUNT_INCREASED. So here seems to be the best
  2160. * place.
  2161. *
  2162. * Don't need care about the above error handling paths for
  2163. * get_hwpoison_page() since they handle either free page
  2164. * or unhandlable page. The refcount is bumped iff the
  2165. * page is a valid handlable page.
  2166. */
  2167. folio_set_has_hwpoisoned(folio);
  2168. err = try_to_split_thp_page(p, new_order, /* release= */ false);
  2169. /*
  2170. * If splitting a folio to order-0 fails, kill the process.
  2171. * Split the folio regardless to minimize unusable pages.
  2172. * Because the memory failure code cannot handle large
  2173. * folios, this split is always treated as if it failed.
  2174. */
  2175. if (err || new_order) {
  2176. /* get folio again in case the original one is split */
  2177. folio = page_folio(p);
  2178. res = -EHWPOISON;
  2179. kill_procs_now(p, pfn, flags, folio);
  2180. put_page(p);
  2181. action_result(pfn, MF_MSG_UNSPLIT_THP, MF_FAILED);
  2182. goto unlock_mutex;
  2183. }
  2184. VM_BUG_ON_PAGE(!page_count(p), p);
  2185. folio = page_folio(p);
  2186. }
  2187. /*
  2188. * We ignore non-LRU pages for good reasons.
  2189. * - PG_locked is only well defined for LRU pages and a few others
  2190. * - to avoid races with __SetPageLocked()
  2191. * - to avoid races with __SetPageSlab*() (and more non-atomic ops)
  2192. * The check (unnecessarily) ignores LRU pages being isolated and
  2193. * walked by the page reclaim code, however that's not a big loss.
  2194. */
  2195. shake_folio(folio);
  2196. folio_lock(folio);
  2197. /*
  2198. * We're only intended to deal with the non-Compound page here.
  2199. * The page cannot become compound pages again as folio has been
  2200. * splited and extra refcnt is held.
  2201. */
  2202. WARN_ON(folio_test_large(folio));
  2203. /*
  2204. * We use page flags to determine what action should be taken, but
  2205. * the flags can be modified by the error containment action. One
  2206. * example is an mlocked page, where PG_mlocked is cleared by
  2207. * folio_remove_rmap_*() in try_to_unmap_one(). So to determine page
  2208. * status correctly, we save a copy of the page flags at this time.
  2209. */
  2210. page_flags = folio->flags.f;
  2211. /*
  2212. * __munlock_folio() may clear a writeback folio's LRU flag without
  2213. * the folio lock. We need to wait for writeback completion for this
  2214. * folio or it may trigger a vfs BUG while evicting inode.
  2215. */
  2216. if (!folio_test_lru(folio) && !folio_test_writeback(folio))
  2217. goto identify_page_state;
  2218. /*
  2219. * It's very difficult to mess with pages currently under IO
  2220. * and in many cases impossible, so we just avoid it here.
  2221. */
  2222. folio_wait_writeback(folio);
  2223. /*
  2224. * Now take care of user space mappings.
  2225. * Abort on fail: __filemap_remove_folio() assumes unmapped page.
  2226. */
  2227. if (!hwpoison_user_mappings(folio, p, pfn, flags)) {
  2228. res = action_result(pfn, MF_MSG_UNMAP_FAILED, MF_FAILED);
  2229. goto unlock_page;
  2230. }
  2231. /*
  2232. * Torn down by someone else?
  2233. */
  2234. if (folio_test_lru(folio) && !folio_test_swapcache(folio) &&
  2235. folio->mapping == NULL) {
  2236. res = action_result(pfn, MF_MSG_TRUNCATED_LRU, MF_IGNORED);
  2237. goto unlock_page;
  2238. }
  2239. identify_page_state:
  2240. res = identify_page_state(pfn, p, page_flags);
  2241. mutex_unlock(&mf_mutex);
  2242. return res;
  2243. unlock_page:
  2244. folio_unlock(folio);
  2245. unlock_mutex:
  2246. mutex_unlock(&mf_mutex);
  2247. return res;
  2248. }
  2249. EXPORT_SYMBOL_GPL(memory_failure);
  2250. #define MEMORY_FAILURE_FIFO_ORDER 4
  2251. #define MEMORY_FAILURE_FIFO_SIZE (1 << MEMORY_FAILURE_FIFO_ORDER)
  2252. struct memory_failure_entry {
  2253. unsigned long pfn;
  2254. int flags;
  2255. };
  2256. struct memory_failure_cpu {
  2257. DECLARE_KFIFO(fifo, struct memory_failure_entry,
  2258. MEMORY_FAILURE_FIFO_SIZE);
  2259. raw_spinlock_t lock;
  2260. struct work_struct work;
  2261. };
  2262. static DEFINE_PER_CPU(struct memory_failure_cpu, memory_failure_cpu);
  2263. /**
  2264. * memory_failure_queue - Schedule handling memory failure of a page.
  2265. * @pfn: Page Number of the corrupted page
  2266. * @flags: Flags for memory failure handling
  2267. *
  2268. * This function is called by the low level hardware error handler
  2269. * when it detects hardware memory corruption of a page. It schedules
  2270. * the recovering of error page, including dropping pages, killing
  2271. * processes etc.
  2272. *
  2273. * The function is primarily of use for corruptions that
  2274. * happen outside the current execution context (e.g. when
  2275. * detected by a background scrubber)
  2276. *
  2277. * Can run in IRQ context.
  2278. */
  2279. void memory_failure_queue(unsigned long pfn, int flags)
  2280. {
  2281. struct memory_failure_cpu *mf_cpu;
  2282. unsigned long proc_flags;
  2283. bool buffer_overflow;
  2284. struct memory_failure_entry entry = {
  2285. .pfn = pfn,
  2286. .flags = flags,
  2287. };
  2288. mf_cpu = &get_cpu_var(memory_failure_cpu);
  2289. raw_spin_lock_irqsave(&mf_cpu->lock, proc_flags);
  2290. buffer_overflow = !kfifo_put(&mf_cpu->fifo, entry);
  2291. if (!buffer_overflow)
  2292. schedule_work_on(smp_processor_id(), &mf_cpu->work);
  2293. raw_spin_unlock_irqrestore(&mf_cpu->lock, proc_flags);
  2294. put_cpu_var(memory_failure_cpu);
  2295. if (buffer_overflow)
  2296. pr_err("buffer overflow when queuing memory failure at %#lx\n",
  2297. pfn);
  2298. }
  2299. EXPORT_SYMBOL_GPL(memory_failure_queue);
  2300. static void memory_failure_work_func(struct work_struct *work)
  2301. {
  2302. struct memory_failure_cpu *mf_cpu;
  2303. struct memory_failure_entry entry = { 0, };
  2304. unsigned long proc_flags;
  2305. int gotten;
  2306. mf_cpu = container_of(work, struct memory_failure_cpu, work);
  2307. for (;;) {
  2308. raw_spin_lock_irqsave(&mf_cpu->lock, proc_flags);
  2309. gotten = kfifo_get(&mf_cpu->fifo, &entry);
  2310. raw_spin_unlock_irqrestore(&mf_cpu->lock, proc_flags);
  2311. if (!gotten)
  2312. break;
  2313. if (entry.flags & MF_SOFT_OFFLINE)
  2314. soft_offline_page(entry.pfn, entry.flags);
  2315. else
  2316. memory_failure(entry.pfn, entry.flags);
  2317. }
  2318. }
  2319. static int __init memory_failure_init(void)
  2320. {
  2321. struct memory_failure_cpu *mf_cpu;
  2322. int cpu;
  2323. for_each_possible_cpu(cpu) {
  2324. mf_cpu = &per_cpu(memory_failure_cpu, cpu);
  2325. raw_spin_lock_init(&mf_cpu->lock);
  2326. INIT_KFIFO(mf_cpu->fifo);
  2327. INIT_WORK(&mf_cpu->work, memory_failure_work_func);
  2328. }
  2329. register_sysctl_init("vm", memory_failure_table);
  2330. return 0;
  2331. }
  2332. core_initcall(memory_failure_init);
  2333. #undef pr_fmt
  2334. #define pr_fmt(fmt) "Unpoison: " fmt
  2335. #define unpoison_pr_info(fmt, pfn, rs) \
  2336. ({ \
  2337. if (__ratelimit(rs)) \
  2338. pr_info(fmt, pfn); \
  2339. })
  2340. /**
  2341. * unpoison_memory - Unpoison a previously poisoned page
  2342. * @pfn: Page number of the to be unpoisoned page
  2343. *
  2344. * Software-unpoison a page that has been poisoned by
  2345. * memory_failure() earlier.
  2346. *
  2347. * This is only done on the software-level, so it only works
  2348. * for linux injected failures, not real hardware failures
  2349. *
  2350. * Returns 0 for success, otherwise -errno.
  2351. */
  2352. int unpoison_memory(unsigned long pfn)
  2353. {
  2354. struct folio *folio;
  2355. struct page *p;
  2356. int ret = -EBUSY, ghp;
  2357. unsigned long count;
  2358. bool huge = false;
  2359. static DEFINE_RATELIMIT_STATE(unpoison_rs, DEFAULT_RATELIMIT_INTERVAL,
  2360. DEFAULT_RATELIMIT_BURST);
  2361. p = pfn_to_online_page(pfn);
  2362. if (!p)
  2363. return -EIO;
  2364. folio = page_folio(p);
  2365. mutex_lock(&mf_mutex);
  2366. if (hw_memory_failure) {
  2367. unpoison_pr_info("%#lx: disabled after HW memory failure\n",
  2368. pfn, &unpoison_rs);
  2369. ret = -EOPNOTSUPP;
  2370. goto unlock_mutex;
  2371. }
  2372. if (is_huge_zero_folio(folio)) {
  2373. unpoison_pr_info("%#lx: huge zero page is not supported\n",
  2374. pfn, &unpoison_rs);
  2375. ret = -EOPNOTSUPP;
  2376. goto unlock_mutex;
  2377. }
  2378. if (!PageHWPoison(p)) {
  2379. unpoison_pr_info("%#lx: page was already unpoisoned\n",
  2380. pfn, &unpoison_rs);
  2381. goto unlock_mutex;
  2382. }
  2383. if (folio_ref_count(folio) > 1) {
  2384. unpoison_pr_info("%#lx: someone grabs the hwpoison page\n",
  2385. pfn, &unpoison_rs);
  2386. goto unlock_mutex;
  2387. }
  2388. if (folio_test_slab(folio) || folio_test_pgtable(folio) ||
  2389. folio_test_reserved(folio) || folio_test_offline(folio))
  2390. goto unlock_mutex;
  2391. if (folio_mapped(folio)) {
  2392. unpoison_pr_info("%#lx: someone maps the hwpoison page\n",
  2393. pfn, &unpoison_rs);
  2394. goto unlock_mutex;
  2395. }
  2396. if (folio_mapping(folio)) {
  2397. unpoison_pr_info("%#lx: the hwpoison page has non-NULL mapping\n",
  2398. pfn, &unpoison_rs);
  2399. goto unlock_mutex;
  2400. }
  2401. ghp = get_hwpoison_page(p, MF_UNPOISON);
  2402. if (!ghp) {
  2403. if (folio_test_hugetlb(folio)) {
  2404. huge = true;
  2405. count = folio_free_raw_hwp(folio, false);
  2406. if (count == 0)
  2407. goto unlock_mutex;
  2408. }
  2409. ret = folio_test_clear_hwpoison(folio) ? 0 : -EBUSY;
  2410. } else if (ghp < 0) {
  2411. if (ghp == -EHWPOISON) {
  2412. ret = put_page_back_buddy(p) ? 0 : -EBUSY;
  2413. } else {
  2414. ret = ghp;
  2415. unpoison_pr_info("%#lx: failed to grab page\n",
  2416. pfn, &unpoison_rs);
  2417. }
  2418. } else {
  2419. if (folio_test_hugetlb(folio)) {
  2420. huge = true;
  2421. count = folio_free_raw_hwp(folio, false);
  2422. if (count == 0) {
  2423. folio_put(folio);
  2424. goto unlock_mutex;
  2425. }
  2426. }
  2427. folio_put(folio);
  2428. if (TestClearPageHWPoison(p)) {
  2429. folio_put(folio);
  2430. ret = 0;
  2431. }
  2432. }
  2433. unlock_mutex:
  2434. mutex_unlock(&mf_mutex);
  2435. if (!ret) {
  2436. if (!huge)
  2437. num_poisoned_pages_sub(pfn, 1);
  2438. unpoison_pr_info("%#lx: software-unpoisoned page\n",
  2439. page_to_pfn(p), &unpoison_rs);
  2440. }
  2441. return ret;
  2442. }
  2443. EXPORT_SYMBOL(unpoison_memory);
  2444. #undef pr_fmt
  2445. #define pr_fmt(fmt) "Soft offline: " fmt
  2446. /*
  2447. * soft_offline_in_use_page handles hugetlb-pages and non-hugetlb pages.
  2448. * If the page is a non-dirty unmapped page-cache page, it simply invalidates.
  2449. * If the page is mapped, it migrates the contents over.
  2450. */
  2451. static int soft_offline_in_use_page(struct page *page)
  2452. {
  2453. long ret = 0;
  2454. unsigned long pfn = page_to_pfn(page);
  2455. struct folio *folio = page_folio(page);
  2456. char const *msg_page[] = {"page", "hugepage"};
  2457. bool huge = folio_test_hugetlb(folio);
  2458. bool isolated;
  2459. LIST_HEAD(pagelist);
  2460. struct migration_target_control mtc = {
  2461. .nid = NUMA_NO_NODE,
  2462. .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
  2463. .reason = MR_MEMORY_FAILURE,
  2464. };
  2465. if (!huge && folio_test_large(folio)) {
  2466. const int new_order = min_order_for_split(folio);
  2467. /*
  2468. * If new_order (target split order) is not 0, do not split the
  2469. * folio at all to retain the still accessible large folio.
  2470. * NOTE: if minimizing the number of soft offline pages is
  2471. * preferred, split it to non-zero new_order like it is done in
  2472. * memory_failure().
  2473. */
  2474. if (new_order || try_to_split_thp_page(page, /* new_order= */ 0,
  2475. /* release= */ true)) {
  2476. pr_info("%#lx: thp split failed\n", pfn);
  2477. return -EBUSY;
  2478. }
  2479. folio = page_folio(page);
  2480. }
  2481. folio_lock(folio);
  2482. if (!huge)
  2483. folio_wait_writeback(folio);
  2484. if (PageHWPoison(page)) {
  2485. folio_unlock(folio);
  2486. folio_put(folio);
  2487. pr_info("%#lx: page already poisoned\n", pfn);
  2488. return 0;
  2489. }
  2490. if (!huge && folio_test_lru(folio) && !folio_test_swapcache(folio))
  2491. /*
  2492. * Try to invalidate first. This should work for
  2493. * non dirty unmapped page cache pages.
  2494. */
  2495. ret = mapping_evict_folio(folio_mapping(folio), folio);
  2496. folio_unlock(folio);
  2497. if (ret) {
  2498. pr_info("%#lx: invalidated\n", pfn);
  2499. page_handle_poison(page, false, true);
  2500. return 0;
  2501. }
  2502. isolated = isolate_folio_to_list(folio, &pagelist);
  2503. /*
  2504. * If we succeed to isolate the folio, we grabbed another refcount on
  2505. * the folio, so we can safely drop the one we got from get_any_page().
  2506. * If we failed to isolate the folio, it means that we cannot go further
  2507. * and we will return an error, so drop the reference we got from
  2508. * get_any_page() as well.
  2509. */
  2510. folio_put(folio);
  2511. if (isolated) {
  2512. ret = migrate_pages(&pagelist, alloc_migration_target, NULL,
  2513. (unsigned long)&mtc, MIGRATE_SYNC, MR_MEMORY_FAILURE, NULL);
  2514. if (!ret) {
  2515. bool release = !huge;
  2516. if (!page_handle_poison(page, huge, release))
  2517. ret = -EBUSY;
  2518. } else {
  2519. if (!list_empty(&pagelist))
  2520. putback_movable_pages(&pagelist);
  2521. pr_info("%#lx: %s migration failed %ld, type %pGp\n",
  2522. pfn, msg_page[huge], ret, &page->flags.f);
  2523. if (ret > 0)
  2524. ret = -EBUSY;
  2525. }
  2526. } else {
  2527. pr_info("%#lx: %s isolation failed, page count %d, type %pGp\n",
  2528. pfn, msg_page[huge], page_count(page), &page->flags.f);
  2529. ret = -EBUSY;
  2530. }
  2531. return ret;
  2532. }
  2533. /**
  2534. * soft_offline_page - Soft offline a page.
  2535. * @pfn: pfn to soft-offline
  2536. * @flags: flags. Same as memory_failure().
  2537. *
  2538. * Returns 0 on success,
  2539. * -EOPNOTSUPP for hwpoison_filter() filtered the error event, or
  2540. * disabled by /proc/sys/vm/enable_soft_offline,
  2541. * < 0 otherwise negated errno.
  2542. *
  2543. * Soft offline a page, by migration or invalidation,
  2544. * without killing anything. This is for the case when
  2545. * a page is not corrupted yet (so it's still valid to access),
  2546. * but has had a number of corrected errors and is better taken
  2547. * out.
  2548. *
  2549. * The actual policy on when to do that is maintained by
  2550. * user space.
  2551. *
  2552. * This should never impact any application or cause data loss,
  2553. * however it might take some time.
  2554. *
  2555. * This is not a 100% solution for all memory, but tries to be
  2556. * ``good enough'' for the majority of memory.
  2557. */
  2558. int soft_offline_page(unsigned long pfn, int flags)
  2559. {
  2560. int ret;
  2561. bool try_again = true;
  2562. struct page *page;
  2563. if (!pfn_valid(pfn)) {
  2564. WARN_ON_ONCE(flags & MF_COUNT_INCREASED);
  2565. return -ENXIO;
  2566. }
  2567. /* Only online pages can be soft-offlined (esp., not ZONE_DEVICE). */
  2568. page = pfn_to_online_page(pfn);
  2569. if (!page) {
  2570. put_ref_page(pfn, flags);
  2571. return -EIO;
  2572. }
  2573. if (!sysctl_enable_soft_offline) {
  2574. pr_info_once("disabled by /proc/sys/vm/enable_soft_offline\n");
  2575. put_ref_page(pfn, flags);
  2576. return -EOPNOTSUPP;
  2577. }
  2578. mutex_lock(&mf_mutex);
  2579. if (PageHWPoison(page)) {
  2580. pr_info("%#lx: page already poisoned\n", pfn);
  2581. put_ref_page(pfn, flags);
  2582. mutex_unlock(&mf_mutex);
  2583. return 0;
  2584. }
  2585. retry:
  2586. get_online_mems();
  2587. ret = get_hwpoison_page(page, flags | MF_SOFT_OFFLINE);
  2588. put_online_mems();
  2589. if (hwpoison_filter(page)) {
  2590. if (ret > 0)
  2591. put_page(page);
  2592. mutex_unlock(&mf_mutex);
  2593. return -EOPNOTSUPP;
  2594. }
  2595. if (ret > 0) {
  2596. ret = soft_offline_in_use_page(page);
  2597. } else if (ret == 0) {
  2598. if (!page_handle_poison(page, true, false)) {
  2599. if (try_again) {
  2600. try_again = false;
  2601. flags &= ~MF_COUNT_INCREASED;
  2602. goto retry;
  2603. }
  2604. ret = -EBUSY;
  2605. }
  2606. }
  2607. mutex_unlock(&mf_mutex);
  2608. return ret;
  2609. }