swapfile.c 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * linux/mm/swapfile.c
  4. *
  5. * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
  6. * Swap reorganised 29.12.95, Stephen Tweedie
  7. */
  8. #include <linux/blkdev.h>
  9. #include <linux/mm.h>
  10. #include <linux/sched/mm.h>
  11. #include <linux/sched/task.h>
  12. #include <linux/hugetlb.h>
  13. #include <linux/mman.h>
  14. #include <linux/slab.h>
  15. #include <linux/kernel_stat.h>
  16. #include <linux/swap.h>
  17. #include <linux/vmalloc.h>
  18. #include <linux/pagemap.h>
  19. #include <linux/namei.h>
  20. #include <linux/shmem_fs.h>
  21. #include <linux/blk-cgroup.h>
  22. #include <linux/random.h>
  23. #include <linux/writeback.h>
  24. #include <linux/proc_fs.h>
  25. #include <linux/seq_file.h>
  26. #include <linux/init.h>
  27. #include <linux/ksm.h>
  28. #include <linux/rmap.h>
  29. #include <linux/security.h>
  30. #include <linux/backing-dev.h>
  31. #include <linux/mutex.h>
  32. #include <linux/capability.h>
  33. #include <linux/syscalls.h>
  34. #include <linux/memcontrol.h>
  35. #include <linux/poll.h>
  36. #include <linux/oom.h>
  37. #include <linux/swapfile.h>
  38. #include <linux/export.h>
  39. #include <linux/swap_slots.h>
  40. #include <linux/sort.h>
  41. #include <linux/completion.h>
  42. #include <linux/suspend.h>
  43. #include <linux/zswap.h>
  44. #include <linux/plist.h>
  45. #include <asm/tlbflush.h>
  46. #include <linux/swapops.h>
  47. #include <linux/swap_cgroup.h>
  48. #include "internal.h"
  49. #include "swap.h"
  50. static bool swap_count_continued(struct swap_info_struct *, pgoff_t,
  51. unsigned char);
  52. static void free_swap_count_continuations(struct swap_info_struct *);
  53. static void swap_entry_range_free(struct swap_info_struct *si, swp_entry_t entry,
  54. unsigned int nr_pages);
  55. static void swap_range_alloc(struct swap_info_struct *si, unsigned long offset,
  56. unsigned int nr_entries);
  57. static bool folio_swapcache_freeable(struct folio *folio);
  58. static struct swap_cluster_info *lock_cluster_or_swap_info(
  59. struct swap_info_struct *si, unsigned long offset);
  60. static void unlock_cluster_or_swap_info(struct swap_info_struct *si,
  61. struct swap_cluster_info *ci);
  62. static DEFINE_SPINLOCK(swap_lock);
  63. static unsigned int nr_swapfiles;
  64. atomic_long_t nr_swap_pages;
  65. /*
  66. * Some modules use swappable objects and may try to swap them out under
  67. * memory pressure (via the shrinker). Before doing so, they may wish to
  68. * check to see if any swap space is available.
  69. */
  70. EXPORT_SYMBOL_GPL(nr_swap_pages);
  71. /* protected with swap_lock. reading in vm_swap_full() doesn't need lock */
  72. long total_swap_pages;
  73. static int least_priority = -1;
  74. unsigned long swapfile_maximum_size;
  75. #ifdef CONFIG_MIGRATION
  76. bool swap_migration_ad_supported;
  77. #endif /* CONFIG_MIGRATION */
  78. static const char Bad_file[] = "Bad swap file entry ";
  79. static const char Unused_file[] = "Unused swap file entry ";
  80. static const char Bad_offset[] = "Bad swap offset entry ";
  81. static const char Unused_offset[] = "Unused swap offset entry ";
  82. /*
  83. * all active swap_info_structs
  84. * protected with swap_lock, and ordered by priority.
  85. */
  86. static PLIST_HEAD(swap_active_head);
  87. /*
  88. * all available (active, not full) swap_info_structs
  89. * protected with swap_avail_lock, ordered by priority.
  90. * This is used by folio_alloc_swap() instead of swap_active_head
  91. * because swap_active_head includes all swap_info_structs,
  92. * but folio_alloc_swap() doesn't need to look at full ones.
  93. * This uses its own lock instead of swap_lock because when a
  94. * swap_info_struct changes between not-full/full, it needs to
  95. * add/remove itself to/from this list, but the swap_info_struct->lock
  96. * is held and the locking order requires swap_lock to be taken
  97. * before any swap_info_struct->lock.
  98. */
  99. static struct plist_head *swap_avail_heads;
  100. static DEFINE_SPINLOCK(swap_avail_lock);
  101. static struct swap_info_struct *swap_info[MAX_SWAPFILES];
  102. static DEFINE_MUTEX(swapon_mutex);
  103. static DECLARE_WAIT_QUEUE_HEAD(proc_poll_wait);
  104. /* Activity counter to indicate that a swapon or swapoff has occurred */
  105. static atomic_t proc_poll_event = ATOMIC_INIT(0);
  106. atomic_t nr_rotate_swap = ATOMIC_INIT(0);
  107. static struct swap_info_struct *swap_type_to_swap_info(int type)
  108. {
  109. if (type >= MAX_SWAPFILES)
  110. return NULL;
  111. return READ_ONCE(swap_info[type]); /* rcu_dereference() */
  112. }
  113. static inline unsigned char swap_count(unsigned char ent)
  114. {
  115. return ent & ~SWAP_HAS_CACHE; /* may include COUNT_CONTINUED flag */
  116. }
  117. /* Reclaim the swap entry anyway if possible */
  118. #define TTRS_ANYWAY 0x1
  119. /*
  120. * Reclaim the swap entry if there are no more mappings of the
  121. * corresponding page
  122. */
  123. #define TTRS_UNMAPPED 0x2
  124. /* Reclaim the swap entry if swap is getting full */
  125. #define TTRS_FULL 0x4
  126. /* Reclaim directly, bypass the slot cache and don't touch device lock */
  127. #define TTRS_DIRECT 0x8
  128. static bool swap_is_has_cache(struct swap_info_struct *si,
  129. unsigned long offset, int nr_pages)
  130. {
  131. unsigned char *map = si->swap_map + offset;
  132. unsigned char *map_end = map + nr_pages;
  133. do {
  134. VM_BUG_ON(!(*map & SWAP_HAS_CACHE));
  135. if (*map != SWAP_HAS_CACHE)
  136. return false;
  137. } while (++map < map_end);
  138. return true;
  139. }
  140. static bool swap_is_last_map(struct swap_info_struct *si,
  141. unsigned long offset, int nr_pages, bool *has_cache)
  142. {
  143. unsigned char *map = si->swap_map + offset;
  144. unsigned char *map_end = map + nr_pages;
  145. unsigned char count = *map;
  146. if (swap_count(count) != 1)
  147. return false;
  148. while (++map < map_end) {
  149. if (*map != count)
  150. return false;
  151. }
  152. *has_cache = !!(count & SWAP_HAS_CACHE);
  153. return true;
  154. }
  155. /*
  156. * returns number of pages in the folio that backs the swap entry. If positive,
  157. * the folio was reclaimed. If negative, the folio was not reclaimed. If 0, no
  158. * folio was associated with the swap entry.
  159. */
  160. static int __try_to_reclaim_swap(struct swap_info_struct *si,
  161. unsigned long offset, unsigned long flags)
  162. {
  163. swp_entry_t entry = swp_entry(si->type, offset);
  164. struct address_space *address_space = swap_address_space(entry);
  165. struct swap_cluster_info *ci;
  166. struct folio *folio;
  167. int ret, nr_pages;
  168. bool need_reclaim;
  169. folio = filemap_get_folio(address_space, swap_cache_index(entry));
  170. if (IS_ERR(folio))
  171. return 0;
  172. nr_pages = folio_nr_pages(folio);
  173. ret = -nr_pages;
  174. /*
  175. * When this function is called from scan_swap_map_slots() and it's
  176. * called by vmscan.c at reclaiming folios. So we hold a folio lock
  177. * here. We have to use trylock for avoiding deadlock. This is a special
  178. * case and you should use folio_free_swap() with explicit folio_lock()
  179. * in usual operations.
  180. */
  181. if (!folio_trylock(folio))
  182. goto out;
  183. /* offset could point to the middle of a large folio */
  184. entry = folio->swap;
  185. offset = swp_offset(entry);
  186. need_reclaim = ((flags & TTRS_ANYWAY) ||
  187. ((flags & TTRS_UNMAPPED) && !folio_mapped(folio)) ||
  188. ((flags & TTRS_FULL) && mem_cgroup_swap_full(folio)));
  189. if (!need_reclaim || !folio_swapcache_freeable(folio))
  190. goto out_unlock;
  191. /*
  192. * It's safe to delete the folio from swap cache only if the folio's
  193. * swap_map is HAS_CACHE only, which means the slots have no page table
  194. * reference or pending writeback, and can't be allocated to others.
  195. */
  196. ci = lock_cluster_or_swap_info(si, offset);
  197. need_reclaim = swap_is_has_cache(si, offset, nr_pages);
  198. unlock_cluster_or_swap_info(si, ci);
  199. if (!need_reclaim)
  200. goto out_unlock;
  201. if (!(flags & TTRS_DIRECT)) {
  202. /* Free through slot cache */
  203. delete_from_swap_cache(folio);
  204. folio_set_dirty(folio);
  205. ret = nr_pages;
  206. goto out_unlock;
  207. }
  208. xa_lock_irq(&address_space->i_pages);
  209. __delete_from_swap_cache(folio, entry, NULL);
  210. xa_unlock_irq(&address_space->i_pages);
  211. folio_ref_sub(folio, nr_pages);
  212. folio_set_dirty(folio);
  213. spin_lock(&si->lock);
  214. /* Only sinple page folio can be backed by zswap */
  215. if (nr_pages == 1)
  216. zswap_invalidate(entry);
  217. swap_entry_range_free(si, entry, nr_pages);
  218. spin_unlock(&si->lock);
  219. ret = nr_pages;
  220. out_unlock:
  221. folio_unlock(folio);
  222. out:
  223. folio_put(folio);
  224. return ret;
  225. }
  226. static inline struct swap_extent *first_se(struct swap_info_struct *sis)
  227. {
  228. struct rb_node *rb = rb_first(&sis->swap_extent_root);
  229. return rb_entry(rb, struct swap_extent, rb_node);
  230. }
  231. static inline struct swap_extent *next_se(struct swap_extent *se)
  232. {
  233. struct rb_node *rb = rb_next(&se->rb_node);
  234. return rb ? rb_entry(rb, struct swap_extent, rb_node) : NULL;
  235. }
  236. /*
  237. * swapon tell device that all the old swap contents can be discarded,
  238. * to allow the swap device to optimize its wear-levelling.
  239. */
  240. static int discard_swap(struct swap_info_struct *si)
  241. {
  242. struct swap_extent *se;
  243. sector_t start_block;
  244. sector_t nr_blocks;
  245. int err = 0;
  246. /* Do not discard the swap header page! */
  247. se = first_se(si);
  248. start_block = (se->start_block + 1) << (PAGE_SHIFT - 9);
  249. nr_blocks = ((sector_t)se->nr_pages - 1) << (PAGE_SHIFT - 9);
  250. if (nr_blocks) {
  251. err = blkdev_issue_discard(si->bdev, start_block,
  252. nr_blocks, GFP_KERNEL);
  253. if (err)
  254. return err;
  255. cond_resched();
  256. }
  257. for (se = next_se(se); se; se = next_se(se)) {
  258. start_block = se->start_block << (PAGE_SHIFT - 9);
  259. nr_blocks = (sector_t)se->nr_pages << (PAGE_SHIFT - 9);
  260. err = blkdev_issue_discard(si->bdev, start_block,
  261. nr_blocks, GFP_KERNEL);
  262. if (err)
  263. break;
  264. cond_resched();
  265. }
  266. return err; /* That will often be -EOPNOTSUPP */
  267. }
  268. static struct swap_extent *
  269. offset_to_swap_extent(struct swap_info_struct *sis, unsigned long offset)
  270. {
  271. struct swap_extent *se;
  272. struct rb_node *rb;
  273. rb = sis->swap_extent_root.rb_node;
  274. while (rb) {
  275. se = rb_entry(rb, struct swap_extent, rb_node);
  276. if (offset < se->start_page)
  277. rb = rb->rb_left;
  278. else if (offset >= se->start_page + se->nr_pages)
  279. rb = rb->rb_right;
  280. else
  281. return se;
  282. }
  283. /* It *must* be present */
  284. BUG();
  285. }
  286. sector_t swap_folio_sector(struct folio *folio)
  287. {
  288. struct swap_info_struct *sis = swp_swap_info(folio->swap);
  289. struct swap_extent *se;
  290. sector_t sector;
  291. pgoff_t offset;
  292. offset = swp_offset(folio->swap);
  293. se = offset_to_swap_extent(sis, offset);
  294. sector = se->start_block + (offset - se->start_page);
  295. return sector << (PAGE_SHIFT - 9);
  296. }
  297. /*
  298. * swap allocation tell device that a cluster of swap can now be discarded,
  299. * to allow the swap device to optimize its wear-levelling.
  300. */
  301. static void discard_swap_cluster(struct swap_info_struct *si,
  302. pgoff_t start_page, pgoff_t nr_pages)
  303. {
  304. struct swap_extent *se = offset_to_swap_extent(si, start_page);
  305. while (nr_pages) {
  306. pgoff_t offset = start_page - se->start_page;
  307. sector_t start_block = se->start_block + offset;
  308. sector_t nr_blocks = se->nr_pages - offset;
  309. if (nr_blocks > nr_pages)
  310. nr_blocks = nr_pages;
  311. start_page += nr_blocks;
  312. nr_pages -= nr_blocks;
  313. start_block <<= PAGE_SHIFT - 9;
  314. nr_blocks <<= PAGE_SHIFT - 9;
  315. if (blkdev_issue_discard(si->bdev, start_block,
  316. nr_blocks, GFP_NOIO))
  317. break;
  318. se = next_se(se);
  319. }
  320. }
  321. #ifdef CONFIG_THP_SWAP
  322. #define SWAPFILE_CLUSTER HPAGE_PMD_NR
  323. #define swap_entry_order(order) (order)
  324. #else
  325. #define SWAPFILE_CLUSTER 256
  326. /*
  327. * Define swap_entry_order() as constant to let compiler to optimize
  328. * out some code if !CONFIG_THP_SWAP
  329. */
  330. #define swap_entry_order(order) 0
  331. #endif
  332. #define LATENCY_LIMIT 256
  333. static inline bool cluster_is_free(struct swap_cluster_info *info)
  334. {
  335. return info->flags & CLUSTER_FLAG_FREE;
  336. }
  337. static inline unsigned int cluster_index(struct swap_info_struct *si,
  338. struct swap_cluster_info *ci)
  339. {
  340. return ci - si->cluster_info;
  341. }
  342. static inline unsigned int cluster_offset(struct swap_info_struct *si,
  343. struct swap_cluster_info *ci)
  344. {
  345. return cluster_index(si, ci) * SWAPFILE_CLUSTER;
  346. }
  347. static inline struct swap_cluster_info *lock_cluster(struct swap_info_struct *si,
  348. unsigned long offset)
  349. {
  350. struct swap_cluster_info *ci;
  351. ci = si->cluster_info;
  352. if (ci) {
  353. ci += offset / SWAPFILE_CLUSTER;
  354. spin_lock(&ci->lock);
  355. }
  356. return ci;
  357. }
  358. static inline void unlock_cluster(struct swap_cluster_info *ci)
  359. {
  360. if (ci)
  361. spin_unlock(&ci->lock);
  362. }
  363. /*
  364. * Determine the locking method in use for this device. Return
  365. * swap_cluster_info if SSD-style cluster-based locking is in place.
  366. */
  367. static inline struct swap_cluster_info *lock_cluster_or_swap_info(
  368. struct swap_info_struct *si, unsigned long offset)
  369. {
  370. struct swap_cluster_info *ci;
  371. /* Try to use fine-grained SSD-style locking if available: */
  372. ci = lock_cluster(si, offset);
  373. /* Otherwise, fall back to traditional, coarse locking: */
  374. if (!ci)
  375. spin_lock(&si->lock);
  376. return ci;
  377. }
  378. static inline void unlock_cluster_or_swap_info(struct swap_info_struct *si,
  379. struct swap_cluster_info *ci)
  380. {
  381. if (ci)
  382. unlock_cluster(ci);
  383. else
  384. spin_unlock(&si->lock);
  385. }
  386. /* Add a cluster to discard list and schedule it to do discard */
  387. static void swap_cluster_schedule_discard(struct swap_info_struct *si,
  388. struct swap_cluster_info *ci)
  389. {
  390. unsigned int idx = cluster_index(si, ci);
  391. /*
  392. * If scan_swap_map_slots() can't find a free cluster, it will check
  393. * si->swap_map directly. To make sure the discarding cluster isn't
  394. * taken by scan_swap_map_slots(), mark the swap entries bad (occupied).
  395. * It will be cleared after discard
  396. */
  397. memset(si->swap_map + idx * SWAPFILE_CLUSTER,
  398. SWAP_MAP_BAD, SWAPFILE_CLUSTER);
  399. VM_BUG_ON(ci->flags & CLUSTER_FLAG_FREE);
  400. list_move_tail(&ci->list, &si->discard_clusters);
  401. ci->flags = 0;
  402. schedule_work(&si->discard_work);
  403. }
  404. static void __free_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci)
  405. {
  406. lockdep_assert_held(&si->lock);
  407. lockdep_assert_held(&ci->lock);
  408. if (ci->flags)
  409. list_move_tail(&ci->list, &si->free_clusters);
  410. else
  411. list_add_tail(&ci->list, &si->free_clusters);
  412. ci->flags = CLUSTER_FLAG_FREE;
  413. ci->order = 0;
  414. }
  415. /*
  416. * Doing discard actually. After a cluster discard is finished, the cluster
  417. * will be added to free cluster list. caller should hold si->lock.
  418. */
  419. static void swap_do_scheduled_discard(struct swap_info_struct *si)
  420. {
  421. struct swap_cluster_info *ci;
  422. unsigned int idx;
  423. while (!list_empty(&si->discard_clusters)) {
  424. ci = list_first_entry(&si->discard_clusters, struct swap_cluster_info, list);
  425. list_del(&ci->list);
  426. idx = cluster_index(si, ci);
  427. spin_unlock(&si->lock);
  428. discard_swap_cluster(si, idx * SWAPFILE_CLUSTER,
  429. SWAPFILE_CLUSTER);
  430. spin_lock(&si->lock);
  431. spin_lock(&ci->lock);
  432. __free_cluster(si, ci);
  433. memset(si->swap_map + idx * SWAPFILE_CLUSTER,
  434. 0, SWAPFILE_CLUSTER);
  435. spin_unlock(&ci->lock);
  436. }
  437. }
  438. static void swap_discard_work(struct work_struct *work)
  439. {
  440. struct swap_info_struct *si;
  441. si = container_of(work, struct swap_info_struct, discard_work);
  442. spin_lock(&si->lock);
  443. swap_do_scheduled_discard(si);
  444. spin_unlock(&si->lock);
  445. }
  446. static void swap_users_ref_free(struct percpu_ref *ref)
  447. {
  448. struct swap_info_struct *si;
  449. si = container_of(ref, struct swap_info_struct, users);
  450. complete(&si->comp);
  451. }
  452. static void free_cluster(struct swap_info_struct *si, struct swap_cluster_info *ci)
  453. {
  454. VM_BUG_ON(ci->count != 0);
  455. lockdep_assert_held(&si->lock);
  456. lockdep_assert_held(&ci->lock);
  457. if (ci->flags & CLUSTER_FLAG_FRAG)
  458. si->frag_cluster_nr[ci->order]--;
  459. /*
  460. * If the swap is discardable, prepare discard the cluster
  461. * instead of free it immediately. The cluster will be freed
  462. * after discard.
  463. */
  464. if ((si->flags & (SWP_WRITEOK | SWP_PAGE_DISCARD)) ==
  465. (SWP_WRITEOK | SWP_PAGE_DISCARD)) {
  466. swap_cluster_schedule_discard(si, ci);
  467. return;
  468. }
  469. __free_cluster(si, ci);
  470. }
  471. /*
  472. * The cluster corresponding to page_nr will be used. The cluster will not be
  473. * added to free cluster list and its usage counter will be increased by 1.
  474. * Only used for initialization.
  475. */
  476. static void inc_cluster_info_page(struct swap_info_struct *si,
  477. struct swap_cluster_info *cluster_info, unsigned long page_nr)
  478. {
  479. unsigned long idx = page_nr / SWAPFILE_CLUSTER;
  480. struct swap_cluster_info *ci;
  481. if (!cluster_info)
  482. return;
  483. ci = cluster_info + idx;
  484. ci->count++;
  485. VM_BUG_ON(ci->count > SWAPFILE_CLUSTER);
  486. VM_BUG_ON(ci->flags);
  487. }
  488. /*
  489. * The cluster ci decreases @nr_pages usage. If the usage counter becomes 0,
  490. * which means no page in the cluster is in use, we can optionally discard
  491. * the cluster and add it to free cluster list.
  492. */
  493. static void dec_cluster_info_page(struct swap_info_struct *si,
  494. struct swap_cluster_info *ci, int nr_pages)
  495. {
  496. if (!si->cluster_info)
  497. return;
  498. VM_BUG_ON(ci->count < nr_pages);
  499. VM_BUG_ON(cluster_is_free(ci));
  500. lockdep_assert_held(&si->lock);
  501. lockdep_assert_held(&ci->lock);
  502. ci->count -= nr_pages;
  503. if (!ci->count) {
  504. free_cluster(si, ci);
  505. return;
  506. }
  507. if (!(ci->flags & CLUSTER_FLAG_NONFULL)) {
  508. VM_BUG_ON(ci->flags & CLUSTER_FLAG_FREE);
  509. if (ci->flags & CLUSTER_FLAG_FRAG)
  510. si->frag_cluster_nr[ci->order]--;
  511. list_move_tail(&ci->list, &si->nonfull_clusters[ci->order]);
  512. ci->flags = CLUSTER_FLAG_NONFULL;
  513. }
  514. }
  515. static bool cluster_reclaim_range(struct swap_info_struct *si,
  516. struct swap_cluster_info *ci,
  517. unsigned long start, unsigned long end)
  518. {
  519. unsigned char *map = si->swap_map;
  520. unsigned long offset;
  521. spin_unlock(&ci->lock);
  522. spin_unlock(&si->lock);
  523. for (offset = start; offset < end; offset++) {
  524. switch (READ_ONCE(map[offset])) {
  525. case 0:
  526. continue;
  527. case SWAP_HAS_CACHE:
  528. if (__try_to_reclaim_swap(si, offset, TTRS_ANYWAY | TTRS_DIRECT) > 0)
  529. continue;
  530. goto out;
  531. default:
  532. goto out;
  533. }
  534. }
  535. out:
  536. spin_lock(&si->lock);
  537. spin_lock(&ci->lock);
  538. /*
  539. * Recheck the range no matter reclaim succeeded or not, the slot
  540. * could have been be freed while we are not holding the lock.
  541. */
  542. for (offset = start; offset < end; offset++)
  543. if (READ_ONCE(map[offset]))
  544. return false;
  545. return true;
  546. }
  547. static bool cluster_scan_range(struct swap_info_struct *si,
  548. struct swap_cluster_info *ci,
  549. unsigned long start, unsigned int nr_pages)
  550. {
  551. unsigned long offset, end = start + nr_pages;
  552. unsigned char *map = si->swap_map;
  553. bool need_reclaim = false;
  554. for (offset = start; offset < end; offset++) {
  555. switch (READ_ONCE(map[offset])) {
  556. case 0:
  557. continue;
  558. case SWAP_HAS_CACHE:
  559. if (!vm_swap_full())
  560. return false;
  561. need_reclaim = true;
  562. continue;
  563. default:
  564. return false;
  565. }
  566. }
  567. if (need_reclaim)
  568. return cluster_reclaim_range(si, ci, start, end);
  569. return true;
  570. }
  571. static bool cluster_alloc_range(struct swap_info_struct *si, struct swap_cluster_info *ci,
  572. unsigned int start, unsigned char usage,
  573. unsigned int order)
  574. {
  575. unsigned int nr_pages = 1 << order;
  576. if (!(si->flags & SWP_WRITEOK))
  577. return false;
  578. if (cluster_is_free(ci)) {
  579. if (nr_pages < SWAPFILE_CLUSTER) {
  580. list_move_tail(&ci->list, &si->nonfull_clusters[order]);
  581. ci->flags = CLUSTER_FLAG_NONFULL;
  582. }
  583. ci->order = order;
  584. }
  585. memset(si->swap_map + start, usage, nr_pages);
  586. swap_range_alloc(si, start, nr_pages);
  587. ci->count += nr_pages;
  588. if (ci->count == SWAPFILE_CLUSTER) {
  589. VM_BUG_ON(!(ci->flags &
  590. (CLUSTER_FLAG_FREE | CLUSTER_FLAG_NONFULL | CLUSTER_FLAG_FRAG)));
  591. if (ci->flags & CLUSTER_FLAG_FRAG)
  592. si->frag_cluster_nr[ci->order]--;
  593. list_move_tail(&ci->list, &si->full_clusters);
  594. ci->flags = CLUSTER_FLAG_FULL;
  595. }
  596. return true;
  597. }
  598. static unsigned int alloc_swap_scan_cluster(struct swap_info_struct *si, unsigned long offset,
  599. unsigned int *foundp, unsigned int order,
  600. unsigned char usage)
  601. {
  602. unsigned long start = offset & ~(SWAPFILE_CLUSTER - 1);
  603. unsigned long end = min(start + SWAPFILE_CLUSTER, si->max);
  604. unsigned int nr_pages = 1 << order;
  605. struct swap_cluster_info *ci;
  606. if (end < nr_pages)
  607. return SWAP_NEXT_INVALID;
  608. end -= nr_pages;
  609. ci = lock_cluster(si, offset);
  610. if (ci->count + nr_pages > SWAPFILE_CLUSTER) {
  611. offset = SWAP_NEXT_INVALID;
  612. goto done;
  613. }
  614. while (offset <= end) {
  615. if (cluster_scan_range(si, ci, offset, nr_pages)) {
  616. if (!cluster_alloc_range(si, ci, offset, usage, order)) {
  617. offset = SWAP_NEXT_INVALID;
  618. goto done;
  619. }
  620. *foundp = offset;
  621. if (ci->count == SWAPFILE_CLUSTER) {
  622. offset = SWAP_NEXT_INVALID;
  623. goto done;
  624. }
  625. offset += nr_pages;
  626. break;
  627. }
  628. offset += nr_pages;
  629. }
  630. if (offset > end)
  631. offset = SWAP_NEXT_INVALID;
  632. done:
  633. unlock_cluster(ci);
  634. return offset;
  635. }
  636. /* Return true if reclaimed a whole cluster */
  637. static void swap_reclaim_full_clusters(struct swap_info_struct *si, bool force)
  638. {
  639. long to_scan = 1;
  640. unsigned long offset, end;
  641. struct swap_cluster_info *ci;
  642. unsigned char *map = si->swap_map;
  643. int nr_reclaim;
  644. if (force)
  645. to_scan = si->inuse_pages / SWAPFILE_CLUSTER;
  646. while (!list_empty(&si->full_clusters)) {
  647. ci = list_first_entry(&si->full_clusters, struct swap_cluster_info, list);
  648. list_move_tail(&ci->list, &si->full_clusters);
  649. offset = cluster_offset(si, ci);
  650. end = min(si->max, offset + SWAPFILE_CLUSTER);
  651. to_scan--;
  652. spin_unlock(&si->lock);
  653. while (offset < end) {
  654. if (READ_ONCE(map[offset]) == SWAP_HAS_CACHE) {
  655. nr_reclaim = __try_to_reclaim_swap(si, offset,
  656. TTRS_ANYWAY | TTRS_DIRECT);
  657. if (nr_reclaim) {
  658. offset += abs(nr_reclaim);
  659. continue;
  660. }
  661. }
  662. offset++;
  663. }
  664. spin_lock(&si->lock);
  665. if (to_scan <= 0)
  666. break;
  667. }
  668. }
  669. static void swap_reclaim_work(struct work_struct *work)
  670. {
  671. struct swap_info_struct *si;
  672. si = container_of(work, struct swap_info_struct, reclaim_work);
  673. spin_lock(&si->lock);
  674. swap_reclaim_full_clusters(si, true);
  675. spin_unlock(&si->lock);
  676. }
  677. /*
  678. * Try to get swap entries with specified order from current cpu's swap entry
  679. * pool (a cluster). This might involve allocating a new cluster for current CPU
  680. * too.
  681. */
  682. static unsigned long cluster_alloc_swap_entry(struct swap_info_struct *si, int order,
  683. unsigned char usage)
  684. {
  685. struct percpu_cluster *cluster;
  686. struct swap_cluster_info *ci;
  687. unsigned int offset, found = 0;
  688. new_cluster:
  689. lockdep_assert_held(&si->lock);
  690. cluster = this_cpu_ptr(si->percpu_cluster);
  691. offset = cluster->next[order];
  692. if (offset) {
  693. offset = alloc_swap_scan_cluster(si, offset, &found, order, usage);
  694. if (found)
  695. goto done;
  696. }
  697. if (!list_empty(&si->free_clusters)) {
  698. ci = list_first_entry(&si->free_clusters, struct swap_cluster_info, list);
  699. offset = alloc_swap_scan_cluster(si, cluster_offset(si, ci), &found, order, usage);
  700. /*
  701. * Either we didn't touch the cluster due to swapoff,
  702. * or the allocation must success.
  703. */
  704. VM_BUG_ON((si->flags & SWP_WRITEOK) && !found);
  705. goto done;
  706. }
  707. /* Try reclaim from full clusters if free clusters list is drained */
  708. if (vm_swap_full())
  709. swap_reclaim_full_clusters(si, false);
  710. if (order < PMD_ORDER) {
  711. unsigned int frags = 0;
  712. while (!list_empty(&si->nonfull_clusters[order])) {
  713. ci = list_first_entry(&si->nonfull_clusters[order],
  714. struct swap_cluster_info, list);
  715. list_move_tail(&ci->list, &si->frag_clusters[order]);
  716. ci->flags = CLUSTER_FLAG_FRAG;
  717. si->frag_cluster_nr[order]++;
  718. offset = alloc_swap_scan_cluster(si, cluster_offset(si, ci),
  719. &found, order, usage);
  720. frags++;
  721. if (found)
  722. break;
  723. }
  724. if (!found) {
  725. /*
  726. * Nonfull clusters are moved to frag tail if we reached
  727. * here, count them too, don't over scan the frag list.
  728. */
  729. while (frags < si->frag_cluster_nr[order]) {
  730. ci = list_first_entry(&si->frag_clusters[order],
  731. struct swap_cluster_info, list);
  732. /*
  733. * Rotate the frag list to iterate, they were all failing
  734. * high order allocation or moved here due to per-CPU usage,
  735. * this help keeping usable cluster ahead.
  736. */
  737. list_move_tail(&ci->list, &si->frag_clusters[order]);
  738. offset = alloc_swap_scan_cluster(si, cluster_offset(si, ci),
  739. &found, order, usage);
  740. frags++;
  741. if (found)
  742. break;
  743. }
  744. }
  745. }
  746. if (found)
  747. goto done;
  748. if (!list_empty(&si->discard_clusters)) {
  749. /*
  750. * we don't have free cluster but have some clusters in
  751. * discarding, do discard now and reclaim them, then
  752. * reread cluster_next_cpu since we dropped si->lock
  753. */
  754. swap_do_scheduled_discard(si);
  755. goto new_cluster;
  756. }
  757. if (order)
  758. goto done;
  759. /* Order 0 stealing from higher order */
  760. for (int o = 1; o < SWAP_NR_ORDERS; o++) {
  761. /*
  762. * Clusters here have at least one usable slots and can't fail order 0
  763. * allocation, but reclaim may drop si->lock and race with another user.
  764. */
  765. while (!list_empty(&si->frag_clusters[o])) {
  766. ci = list_first_entry(&si->frag_clusters[o],
  767. struct swap_cluster_info, list);
  768. offset = alloc_swap_scan_cluster(si, cluster_offset(si, ci),
  769. &found, 0, usage);
  770. if (found)
  771. goto done;
  772. }
  773. while (!list_empty(&si->nonfull_clusters[o])) {
  774. ci = list_first_entry(&si->nonfull_clusters[o],
  775. struct swap_cluster_info, list);
  776. offset = alloc_swap_scan_cluster(si, cluster_offset(si, ci),
  777. &found, 0, usage);
  778. if (found)
  779. goto done;
  780. }
  781. }
  782. done:
  783. cluster->next[order] = offset;
  784. return found;
  785. }
  786. static void __del_from_avail_list(struct swap_info_struct *si)
  787. {
  788. int nid;
  789. assert_spin_locked(&si->lock);
  790. for_each_node(nid)
  791. plist_del(&si->avail_lists[nid], &swap_avail_heads[nid]);
  792. }
  793. static void del_from_avail_list(struct swap_info_struct *si)
  794. {
  795. spin_lock(&swap_avail_lock);
  796. __del_from_avail_list(si);
  797. spin_unlock(&swap_avail_lock);
  798. }
  799. static void swap_range_alloc(struct swap_info_struct *si, unsigned long offset,
  800. unsigned int nr_entries)
  801. {
  802. unsigned int end = offset + nr_entries - 1;
  803. if (offset == si->lowest_bit)
  804. si->lowest_bit += nr_entries;
  805. if (end == si->highest_bit)
  806. WRITE_ONCE(si->highest_bit, si->highest_bit - nr_entries);
  807. WRITE_ONCE(si->inuse_pages, si->inuse_pages + nr_entries);
  808. if (si->inuse_pages == si->pages) {
  809. si->lowest_bit = si->max;
  810. si->highest_bit = 0;
  811. del_from_avail_list(si);
  812. if (si->cluster_info && vm_swap_full())
  813. schedule_work(&si->reclaim_work);
  814. }
  815. }
  816. static void add_to_avail_list(struct swap_info_struct *si)
  817. {
  818. int nid;
  819. spin_lock(&swap_avail_lock);
  820. for_each_node(nid)
  821. plist_add(&si->avail_lists[nid], &swap_avail_heads[nid]);
  822. spin_unlock(&swap_avail_lock);
  823. }
  824. static void swap_range_free(struct swap_info_struct *si, unsigned long offset,
  825. unsigned int nr_entries)
  826. {
  827. unsigned long begin = offset;
  828. unsigned long end = offset + nr_entries - 1;
  829. void (*swap_slot_free_notify)(struct block_device *, unsigned long);
  830. unsigned int i;
  831. /*
  832. * Use atomic clear_bit operations only on zeromap instead of non-atomic
  833. * bitmap_clear to prevent adjacent bits corruption due to simultaneous writes.
  834. */
  835. for (i = 0; i < nr_entries; i++)
  836. clear_bit(offset + i, si->zeromap);
  837. if (offset < si->lowest_bit)
  838. si->lowest_bit = offset;
  839. if (end > si->highest_bit) {
  840. bool was_full = !si->highest_bit;
  841. WRITE_ONCE(si->highest_bit, end);
  842. if (was_full && (si->flags & SWP_WRITEOK))
  843. add_to_avail_list(si);
  844. }
  845. if (si->flags & SWP_BLKDEV)
  846. swap_slot_free_notify =
  847. si->bdev->bd_disk->fops->swap_slot_free_notify;
  848. else
  849. swap_slot_free_notify = NULL;
  850. while (offset <= end) {
  851. arch_swap_invalidate_page(si->type, offset);
  852. if (swap_slot_free_notify)
  853. swap_slot_free_notify(si->bdev, offset);
  854. offset++;
  855. }
  856. clear_shadow_from_swap_cache(si->type, begin, end);
  857. /*
  858. * Make sure that try_to_unuse() observes si->inuse_pages reaching 0
  859. * only after the above cleanups are done.
  860. */
  861. smp_wmb();
  862. atomic_long_add(nr_entries, &nr_swap_pages);
  863. WRITE_ONCE(si->inuse_pages, si->inuse_pages - nr_entries);
  864. }
  865. static void set_cluster_next(struct swap_info_struct *si, unsigned long next)
  866. {
  867. unsigned long prev;
  868. if (!(si->flags & SWP_SOLIDSTATE)) {
  869. si->cluster_next = next;
  870. return;
  871. }
  872. prev = this_cpu_read(*si->cluster_next_cpu);
  873. /*
  874. * Cross the swap address space size aligned trunk, choose
  875. * another trunk randomly to avoid lock contention on swap
  876. * address space if possible.
  877. */
  878. if ((prev >> SWAP_ADDRESS_SPACE_SHIFT) !=
  879. (next >> SWAP_ADDRESS_SPACE_SHIFT)) {
  880. /* No free swap slots available */
  881. if (si->highest_bit <= si->lowest_bit)
  882. return;
  883. next = get_random_u32_inclusive(si->lowest_bit, si->highest_bit);
  884. next = ALIGN_DOWN(next, SWAP_ADDRESS_SPACE_PAGES);
  885. next = max_t(unsigned int, next, si->lowest_bit);
  886. }
  887. this_cpu_write(*si->cluster_next_cpu, next);
  888. }
  889. static bool swap_offset_available_and_locked(struct swap_info_struct *si,
  890. unsigned long offset)
  891. {
  892. if (data_race(!si->swap_map[offset])) {
  893. spin_lock(&si->lock);
  894. return true;
  895. }
  896. if (vm_swap_full() && READ_ONCE(si->swap_map[offset]) == SWAP_HAS_CACHE) {
  897. spin_lock(&si->lock);
  898. return true;
  899. }
  900. return false;
  901. }
  902. static int cluster_alloc_swap(struct swap_info_struct *si,
  903. unsigned char usage, int nr,
  904. swp_entry_t slots[], int order)
  905. {
  906. int n_ret = 0;
  907. VM_BUG_ON(!si->cluster_info);
  908. si->flags += SWP_SCANNING;
  909. while (n_ret < nr) {
  910. unsigned long offset = cluster_alloc_swap_entry(si, order, usage);
  911. if (!offset)
  912. break;
  913. slots[n_ret++] = swp_entry(si->type, offset);
  914. }
  915. si->flags -= SWP_SCANNING;
  916. return n_ret;
  917. }
  918. static int scan_swap_map_slots(struct swap_info_struct *si,
  919. unsigned char usage, int nr,
  920. swp_entry_t slots[], int order)
  921. {
  922. unsigned long offset;
  923. unsigned long scan_base;
  924. unsigned long last_in_cluster = 0;
  925. int latency_ration = LATENCY_LIMIT;
  926. unsigned int nr_pages = 1 << order;
  927. int n_ret = 0;
  928. bool scanned_many = false;
  929. /*
  930. * We try to cluster swap pages by allocating them sequentially
  931. * in swap. Once we've allocated SWAPFILE_CLUSTER pages this
  932. * way, however, we resort to first-free allocation, starting
  933. * a new cluster. This prevents us from scattering swap pages
  934. * all over the entire swap partition, so that we reduce
  935. * overall disk seek times between swap pages. -- sct
  936. * But we do now try to find an empty cluster. -Andrea
  937. * And we let swap pages go all over an SSD partition. Hugh
  938. */
  939. if (order > 0) {
  940. /*
  941. * Should not even be attempting large allocations when huge
  942. * page swap is disabled. Warn and fail the allocation.
  943. */
  944. if (!IS_ENABLED(CONFIG_THP_SWAP) ||
  945. nr_pages > SWAPFILE_CLUSTER) {
  946. VM_WARN_ON_ONCE(1);
  947. return 0;
  948. }
  949. /*
  950. * Swapfile is not block device or not using clusters so unable
  951. * to allocate large entries.
  952. */
  953. if (!(si->flags & SWP_BLKDEV) || !si->cluster_info)
  954. return 0;
  955. }
  956. if (si->cluster_info)
  957. return cluster_alloc_swap(si, usage, nr, slots, order);
  958. si->flags += SWP_SCANNING;
  959. /* For HDD, sequential access is more important. */
  960. scan_base = si->cluster_next;
  961. offset = scan_base;
  962. if (unlikely(!si->cluster_nr--)) {
  963. if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) {
  964. si->cluster_nr = SWAPFILE_CLUSTER - 1;
  965. goto checks;
  966. }
  967. spin_unlock(&si->lock);
  968. /*
  969. * If seek is expensive, start searching for new cluster from
  970. * start of partition, to minimize the span of allocated swap.
  971. */
  972. scan_base = offset = si->lowest_bit;
  973. last_in_cluster = offset + SWAPFILE_CLUSTER - 1;
  974. /* Locate the first empty (unaligned) cluster */
  975. for (; last_in_cluster <= READ_ONCE(si->highest_bit); offset++) {
  976. if (si->swap_map[offset])
  977. last_in_cluster = offset + SWAPFILE_CLUSTER;
  978. else if (offset == last_in_cluster) {
  979. spin_lock(&si->lock);
  980. offset -= SWAPFILE_CLUSTER - 1;
  981. si->cluster_next = offset;
  982. si->cluster_nr = SWAPFILE_CLUSTER - 1;
  983. goto checks;
  984. }
  985. if (unlikely(--latency_ration < 0)) {
  986. cond_resched();
  987. latency_ration = LATENCY_LIMIT;
  988. }
  989. }
  990. offset = scan_base;
  991. spin_lock(&si->lock);
  992. si->cluster_nr = SWAPFILE_CLUSTER - 1;
  993. }
  994. checks:
  995. if (!(si->flags & SWP_WRITEOK))
  996. goto no_page;
  997. if (!si->highest_bit)
  998. goto no_page;
  999. if (offset > si->highest_bit)
  1000. scan_base = offset = si->lowest_bit;
  1001. /* reuse swap entry of cache-only swap if not busy. */
  1002. if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) {
  1003. int swap_was_freed;
  1004. spin_unlock(&si->lock);
  1005. swap_was_freed = __try_to_reclaim_swap(si, offset, TTRS_ANYWAY | TTRS_DIRECT);
  1006. spin_lock(&si->lock);
  1007. /* entry was freed successfully, try to use this again */
  1008. if (swap_was_freed > 0)
  1009. goto checks;
  1010. goto scan; /* check next one */
  1011. }
  1012. if (si->swap_map[offset]) {
  1013. if (!n_ret)
  1014. goto scan;
  1015. else
  1016. goto done;
  1017. }
  1018. memset(si->swap_map + offset, usage, nr_pages);
  1019. swap_range_alloc(si, offset, nr_pages);
  1020. slots[n_ret++] = swp_entry(si->type, offset);
  1021. /* got enough slots or reach max slots? */
  1022. if ((n_ret == nr) || (offset >= si->highest_bit))
  1023. goto done;
  1024. /* search for next available slot */
  1025. /* time to take a break? */
  1026. if (unlikely(--latency_ration < 0)) {
  1027. if (n_ret)
  1028. goto done;
  1029. spin_unlock(&si->lock);
  1030. cond_resched();
  1031. spin_lock(&si->lock);
  1032. latency_ration = LATENCY_LIMIT;
  1033. }
  1034. if (si->cluster_nr && !si->swap_map[++offset]) {
  1035. /* non-ssd case, still more slots in cluster? */
  1036. --si->cluster_nr;
  1037. goto checks;
  1038. }
  1039. /*
  1040. * Even if there's no free clusters available (fragmented),
  1041. * try to scan a little more quickly with lock held unless we
  1042. * have scanned too many slots already.
  1043. */
  1044. if (!scanned_many) {
  1045. unsigned long scan_limit;
  1046. if (offset < scan_base)
  1047. scan_limit = scan_base;
  1048. else
  1049. scan_limit = si->highest_bit;
  1050. for (; offset <= scan_limit && --latency_ration > 0;
  1051. offset++) {
  1052. if (!si->swap_map[offset])
  1053. goto checks;
  1054. }
  1055. }
  1056. done:
  1057. if (order == 0)
  1058. set_cluster_next(si, offset + 1);
  1059. si->flags -= SWP_SCANNING;
  1060. return n_ret;
  1061. scan:
  1062. VM_WARN_ON(order > 0);
  1063. spin_unlock(&si->lock);
  1064. while (++offset <= READ_ONCE(si->highest_bit)) {
  1065. if (unlikely(--latency_ration < 0)) {
  1066. cond_resched();
  1067. latency_ration = LATENCY_LIMIT;
  1068. scanned_many = true;
  1069. }
  1070. if (swap_offset_available_and_locked(si, offset))
  1071. goto checks;
  1072. }
  1073. offset = si->lowest_bit;
  1074. while (offset < scan_base) {
  1075. if (unlikely(--latency_ration < 0)) {
  1076. cond_resched();
  1077. latency_ration = LATENCY_LIMIT;
  1078. scanned_many = true;
  1079. }
  1080. if (swap_offset_available_and_locked(si, offset))
  1081. goto checks;
  1082. offset++;
  1083. }
  1084. spin_lock(&si->lock);
  1085. no_page:
  1086. si->flags -= SWP_SCANNING;
  1087. return n_ret;
  1088. }
  1089. int get_swap_pages(int n_goal, swp_entry_t swp_entries[], int entry_order)
  1090. {
  1091. int order = swap_entry_order(entry_order);
  1092. unsigned long size = 1 << order;
  1093. struct swap_info_struct *si, *next;
  1094. long avail_pgs;
  1095. int n_ret = 0;
  1096. int node;
  1097. spin_lock(&swap_avail_lock);
  1098. avail_pgs = atomic_long_read(&nr_swap_pages) / size;
  1099. if (avail_pgs <= 0) {
  1100. spin_unlock(&swap_avail_lock);
  1101. goto noswap;
  1102. }
  1103. n_goal = min3((long)n_goal, (long)SWAP_BATCH, avail_pgs);
  1104. atomic_long_sub(n_goal * size, &nr_swap_pages);
  1105. start_over:
  1106. node = numa_node_id();
  1107. plist_for_each_entry_safe(si, next, &swap_avail_heads[node], avail_lists[node]) {
  1108. /* requeue si to after same-priority siblings */
  1109. plist_requeue(&si->avail_lists[node], &swap_avail_heads[node]);
  1110. spin_unlock(&swap_avail_lock);
  1111. spin_lock(&si->lock);
  1112. if (!si->highest_bit || !(si->flags & SWP_WRITEOK)) {
  1113. spin_lock(&swap_avail_lock);
  1114. if (plist_node_empty(&si->avail_lists[node])) {
  1115. spin_unlock(&si->lock);
  1116. goto nextsi;
  1117. }
  1118. WARN(!si->highest_bit,
  1119. "swap_info %d in list but !highest_bit\n",
  1120. si->type);
  1121. WARN(!(si->flags & SWP_WRITEOK),
  1122. "swap_info %d in list but !SWP_WRITEOK\n",
  1123. si->type);
  1124. __del_from_avail_list(si);
  1125. spin_unlock(&si->lock);
  1126. goto nextsi;
  1127. }
  1128. n_ret = scan_swap_map_slots(si, SWAP_HAS_CACHE,
  1129. n_goal, swp_entries, order);
  1130. spin_unlock(&si->lock);
  1131. if (n_ret || size > 1)
  1132. goto check_out;
  1133. cond_resched();
  1134. spin_lock(&swap_avail_lock);
  1135. nextsi:
  1136. /*
  1137. * if we got here, it's likely that si was almost full before,
  1138. * and since scan_swap_map_slots() can drop the si->lock,
  1139. * multiple callers probably all tried to get a page from the
  1140. * same si and it filled up before we could get one; or, the si
  1141. * filled up between us dropping swap_avail_lock and taking
  1142. * si->lock. Since we dropped the swap_avail_lock, the
  1143. * swap_avail_head list may have been modified; so if next is
  1144. * still in the swap_avail_head list then try it, otherwise
  1145. * start over if we have not gotten any slots.
  1146. */
  1147. if (plist_node_empty(&next->avail_lists[node]))
  1148. goto start_over;
  1149. }
  1150. spin_unlock(&swap_avail_lock);
  1151. check_out:
  1152. if (n_ret < n_goal)
  1153. atomic_long_add((long)(n_goal - n_ret) * size,
  1154. &nr_swap_pages);
  1155. noswap:
  1156. return n_ret;
  1157. }
  1158. static struct swap_info_struct *_swap_info_get(swp_entry_t entry)
  1159. {
  1160. struct swap_info_struct *si;
  1161. unsigned long offset;
  1162. if (!entry.val)
  1163. goto out;
  1164. si = swp_swap_info(entry);
  1165. if (!si)
  1166. goto bad_nofile;
  1167. if (data_race(!(si->flags & SWP_USED)))
  1168. goto bad_device;
  1169. offset = swp_offset(entry);
  1170. if (offset >= si->max)
  1171. goto bad_offset;
  1172. if (data_race(!si->swap_map[swp_offset(entry)]))
  1173. goto bad_free;
  1174. return si;
  1175. bad_free:
  1176. pr_err("%s: %s%08lx\n", __func__, Unused_offset, entry.val);
  1177. goto out;
  1178. bad_offset:
  1179. pr_err("%s: %s%08lx\n", __func__, Bad_offset, entry.val);
  1180. goto out;
  1181. bad_device:
  1182. pr_err("%s: %s%08lx\n", __func__, Unused_file, entry.val);
  1183. goto out;
  1184. bad_nofile:
  1185. pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val);
  1186. out:
  1187. return NULL;
  1188. }
  1189. static struct swap_info_struct *swap_info_get_cont(swp_entry_t entry,
  1190. struct swap_info_struct *q)
  1191. {
  1192. struct swap_info_struct *p;
  1193. p = _swap_info_get(entry);
  1194. if (p != q) {
  1195. if (q != NULL)
  1196. spin_unlock(&q->lock);
  1197. if (p != NULL)
  1198. spin_lock(&p->lock);
  1199. }
  1200. return p;
  1201. }
  1202. static unsigned char __swap_entry_free_locked(struct swap_info_struct *si,
  1203. unsigned long offset,
  1204. unsigned char usage)
  1205. {
  1206. unsigned char count;
  1207. unsigned char has_cache;
  1208. count = si->swap_map[offset];
  1209. has_cache = count & SWAP_HAS_CACHE;
  1210. count &= ~SWAP_HAS_CACHE;
  1211. if (usage == SWAP_HAS_CACHE) {
  1212. VM_BUG_ON(!has_cache);
  1213. has_cache = 0;
  1214. } else if (count == SWAP_MAP_SHMEM) {
  1215. /*
  1216. * Or we could insist on shmem.c using a special
  1217. * swap_shmem_free() and free_shmem_swap_and_cache()...
  1218. */
  1219. count = 0;
  1220. } else if ((count & ~COUNT_CONTINUED) <= SWAP_MAP_MAX) {
  1221. if (count == COUNT_CONTINUED) {
  1222. if (swap_count_continued(si, offset, count))
  1223. count = SWAP_MAP_MAX | COUNT_CONTINUED;
  1224. else
  1225. count = SWAP_MAP_MAX;
  1226. } else
  1227. count--;
  1228. }
  1229. usage = count | has_cache;
  1230. if (usage)
  1231. WRITE_ONCE(si->swap_map[offset], usage);
  1232. else
  1233. WRITE_ONCE(si->swap_map[offset], SWAP_HAS_CACHE);
  1234. return usage;
  1235. }
  1236. /*
  1237. * When we get a swap entry, if there aren't some other ways to
  1238. * prevent swapoff, such as the folio in swap cache is locked, RCU
  1239. * reader side is locked, etc., the swap entry may become invalid
  1240. * because of swapoff. Then, we need to enclose all swap related
  1241. * functions with get_swap_device() and put_swap_device(), unless the
  1242. * swap functions call get/put_swap_device() by themselves.
  1243. *
  1244. * RCU reader side lock (including any spinlock) is sufficient to
  1245. * prevent swapoff, because synchronize_rcu() is called in swapoff()
  1246. * before freeing data structures.
  1247. *
  1248. * Check whether swap entry is valid in the swap device. If so,
  1249. * return pointer to swap_info_struct, and keep the swap entry valid
  1250. * via preventing the swap device from being swapoff, until
  1251. * put_swap_device() is called. Otherwise return NULL.
  1252. *
  1253. * Notice that swapoff or swapoff+swapon can still happen before the
  1254. * percpu_ref_tryget_live() in get_swap_device() or after the
  1255. * percpu_ref_put() in put_swap_device() if there isn't any other way
  1256. * to prevent swapoff. The caller must be prepared for that. For
  1257. * example, the following situation is possible.
  1258. *
  1259. * CPU1 CPU2
  1260. * do_swap_page()
  1261. * ... swapoff+swapon
  1262. * __read_swap_cache_async()
  1263. * swapcache_prepare()
  1264. * __swap_duplicate()
  1265. * // check swap_map
  1266. * // verify PTE not changed
  1267. *
  1268. * In __swap_duplicate(), the swap_map need to be checked before
  1269. * changing partly because the specified swap entry may be for another
  1270. * swap device which has been swapoff. And in do_swap_page(), after
  1271. * the page is read from the swap device, the PTE is verified not
  1272. * changed with the page table locked to check whether the swap device
  1273. * has been swapoff or swapoff+swapon.
  1274. */
  1275. struct swap_info_struct *get_swap_device(swp_entry_t entry)
  1276. {
  1277. struct swap_info_struct *si;
  1278. unsigned long offset;
  1279. if (!entry.val)
  1280. goto out;
  1281. si = swp_swap_info(entry);
  1282. if (!si)
  1283. goto bad_nofile;
  1284. if (!percpu_ref_tryget_live(&si->users))
  1285. goto out;
  1286. /*
  1287. * Guarantee the si->users are checked before accessing other
  1288. * fields of swap_info_struct.
  1289. *
  1290. * Paired with the spin_unlock() after setup_swap_info() in
  1291. * enable_swap_info().
  1292. */
  1293. smp_rmb();
  1294. offset = swp_offset(entry);
  1295. if (offset >= si->max)
  1296. goto put_out;
  1297. return si;
  1298. bad_nofile:
  1299. pr_err("%s: %s%08lx\n", __func__, Bad_file, entry.val);
  1300. out:
  1301. return NULL;
  1302. put_out:
  1303. pr_err("%s: %s%08lx\n", __func__, Bad_offset, entry.val);
  1304. percpu_ref_put(&si->users);
  1305. return NULL;
  1306. }
  1307. static unsigned char __swap_entry_free(struct swap_info_struct *si,
  1308. swp_entry_t entry)
  1309. {
  1310. struct swap_cluster_info *ci;
  1311. unsigned long offset = swp_offset(entry);
  1312. unsigned char usage;
  1313. ci = lock_cluster_or_swap_info(si, offset);
  1314. usage = __swap_entry_free_locked(si, offset, 1);
  1315. unlock_cluster_or_swap_info(si, ci);
  1316. if (!usage)
  1317. free_swap_slot(entry);
  1318. return usage;
  1319. }
  1320. static bool __swap_entries_free(struct swap_info_struct *si,
  1321. swp_entry_t entry, int nr)
  1322. {
  1323. unsigned long offset = swp_offset(entry);
  1324. unsigned int type = swp_type(entry);
  1325. struct swap_cluster_info *ci;
  1326. bool has_cache = false;
  1327. unsigned char count;
  1328. int i;
  1329. if (nr <= 1 || swap_count(data_race(si->swap_map[offset])) != 1)
  1330. goto fallback;
  1331. /* cross into another cluster */
  1332. if (nr > SWAPFILE_CLUSTER - offset % SWAPFILE_CLUSTER)
  1333. goto fallback;
  1334. ci = lock_cluster_or_swap_info(si, offset);
  1335. if (!swap_is_last_map(si, offset, nr, &has_cache)) {
  1336. unlock_cluster_or_swap_info(si, ci);
  1337. goto fallback;
  1338. }
  1339. for (i = 0; i < nr; i++)
  1340. WRITE_ONCE(si->swap_map[offset + i], SWAP_HAS_CACHE);
  1341. unlock_cluster_or_swap_info(si, ci);
  1342. if (!has_cache) {
  1343. for (i = 0; i < nr; i++)
  1344. zswap_invalidate(swp_entry(si->type, offset + i));
  1345. spin_lock(&si->lock);
  1346. swap_entry_range_free(si, entry, nr);
  1347. spin_unlock(&si->lock);
  1348. }
  1349. return has_cache;
  1350. fallback:
  1351. for (i = 0; i < nr; i++) {
  1352. if (data_race(si->swap_map[offset + i])) {
  1353. count = __swap_entry_free(si, swp_entry(type, offset + i));
  1354. if (count == SWAP_HAS_CACHE)
  1355. has_cache = true;
  1356. } else {
  1357. WARN_ON_ONCE(1);
  1358. }
  1359. }
  1360. return has_cache;
  1361. }
  1362. /*
  1363. * Drop the last HAS_CACHE flag of swap entries, caller have to
  1364. * ensure all entries belong to the same cgroup.
  1365. */
  1366. static void swap_entry_range_free(struct swap_info_struct *si, swp_entry_t entry,
  1367. unsigned int nr_pages)
  1368. {
  1369. unsigned long offset = swp_offset(entry);
  1370. unsigned char *map = si->swap_map + offset;
  1371. unsigned char *map_end = map + nr_pages;
  1372. struct swap_cluster_info *ci;
  1373. ci = lock_cluster(si, offset);
  1374. do {
  1375. VM_BUG_ON(*map != SWAP_HAS_CACHE);
  1376. *map = 0;
  1377. } while (++map < map_end);
  1378. dec_cluster_info_page(si, ci, nr_pages);
  1379. unlock_cluster(ci);
  1380. mem_cgroup_uncharge_swap(entry, nr_pages);
  1381. swap_range_free(si, offset, nr_pages);
  1382. }
  1383. static void cluster_swap_free_nr(struct swap_info_struct *si,
  1384. unsigned long offset, int nr_pages,
  1385. unsigned char usage)
  1386. {
  1387. struct swap_cluster_info *ci;
  1388. DECLARE_BITMAP(to_free, BITS_PER_LONG) = { 0 };
  1389. int i, nr;
  1390. ci = lock_cluster_or_swap_info(si, offset);
  1391. while (nr_pages) {
  1392. nr = min(BITS_PER_LONG, nr_pages);
  1393. for (i = 0; i < nr; i++) {
  1394. if (!__swap_entry_free_locked(si, offset + i, usage))
  1395. bitmap_set(to_free, i, 1);
  1396. }
  1397. if (!bitmap_empty(to_free, BITS_PER_LONG)) {
  1398. unlock_cluster_or_swap_info(si, ci);
  1399. for_each_set_bit(i, to_free, BITS_PER_LONG)
  1400. free_swap_slot(swp_entry(si->type, offset + i));
  1401. if (nr == nr_pages)
  1402. return;
  1403. bitmap_clear(to_free, 0, BITS_PER_LONG);
  1404. ci = lock_cluster_or_swap_info(si, offset);
  1405. }
  1406. offset += nr;
  1407. nr_pages -= nr;
  1408. }
  1409. unlock_cluster_or_swap_info(si, ci);
  1410. }
  1411. /*
  1412. * Caller has made sure that the swap device corresponding to entry
  1413. * is still around or has not been recycled.
  1414. */
  1415. void swap_free_nr(swp_entry_t entry, int nr_pages)
  1416. {
  1417. int nr;
  1418. struct swap_info_struct *sis;
  1419. unsigned long offset = swp_offset(entry);
  1420. sis = _swap_info_get(entry);
  1421. if (!sis)
  1422. return;
  1423. while (nr_pages) {
  1424. nr = min_t(int, nr_pages, SWAPFILE_CLUSTER - offset % SWAPFILE_CLUSTER);
  1425. cluster_swap_free_nr(sis, offset, nr, 1);
  1426. offset += nr;
  1427. nr_pages -= nr;
  1428. }
  1429. }
  1430. /*
  1431. * Called after dropping swapcache to decrease refcnt to swap entries.
  1432. */
  1433. void put_swap_folio(struct folio *folio, swp_entry_t entry)
  1434. {
  1435. unsigned long offset = swp_offset(entry);
  1436. struct swap_cluster_info *ci;
  1437. struct swap_info_struct *si;
  1438. int size = 1 << swap_entry_order(folio_order(folio));
  1439. si = _swap_info_get(entry);
  1440. if (!si)
  1441. return;
  1442. ci = lock_cluster_or_swap_info(si, offset);
  1443. if (size > 1 && swap_is_has_cache(si, offset, size)) {
  1444. unlock_cluster_or_swap_info(si, ci);
  1445. spin_lock(&si->lock);
  1446. swap_entry_range_free(si, entry, size);
  1447. spin_unlock(&si->lock);
  1448. return;
  1449. }
  1450. for (int i = 0; i < size; i++, entry.val++) {
  1451. if (!__swap_entry_free_locked(si, offset + i, SWAP_HAS_CACHE)) {
  1452. unlock_cluster_or_swap_info(si, ci);
  1453. free_swap_slot(entry);
  1454. if (i == size - 1)
  1455. return;
  1456. lock_cluster_or_swap_info(si, offset);
  1457. }
  1458. }
  1459. unlock_cluster_or_swap_info(si, ci);
  1460. }
  1461. static int swp_entry_cmp(const void *ent1, const void *ent2)
  1462. {
  1463. const swp_entry_t *e1 = ent1, *e2 = ent2;
  1464. return (int)swp_type(*e1) - (int)swp_type(*e2);
  1465. }
  1466. void swapcache_free_entries(swp_entry_t *entries, int n)
  1467. {
  1468. struct swap_info_struct *p, *prev;
  1469. int i;
  1470. if (n <= 0)
  1471. return;
  1472. prev = NULL;
  1473. p = NULL;
  1474. /*
  1475. * Sort swap entries by swap device, so each lock is only taken once.
  1476. * nr_swapfiles isn't absolutely correct, but the overhead of sort() is
  1477. * so low that it isn't necessary to optimize further.
  1478. */
  1479. if (nr_swapfiles > 1)
  1480. sort(entries, n, sizeof(entries[0]), swp_entry_cmp, NULL);
  1481. for (i = 0; i < n; ++i) {
  1482. p = swap_info_get_cont(entries[i], prev);
  1483. if (p)
  1484. swap_entry_range_free(p, entries[i], 1);
  1485. prev = p;
  1486. }
  1487. if (p)
  1488. spin_unlock(&p->lock);
  1489. }
  1490. int __swap_count(swp_entry_t entry)
  1491. {
  1492. struct swap_info_struct *si = swp_swap_info(entry);
  1493. pgoff_t offset = swp_offset(entry);
  1494. return swap_count(si->swap_map[offset]);
  1495. }
  1496. /*
  1497. * How many references to @entry are currently swapped out?
  1498. * This does not give an exact answer when swap count is continued,
  1499. * but does include the high COUNT_CONTINUED flag to allow for that.
  1500. */
  1501. int swap_swapcount(struct swap_info_struct *si, swp_entry_t entry)
  1502. {
  1503. pgoff_t offset = swp_offset(entry);
  1504. struct swap_cluster_info *ci;
  1505. int count;
  1506. ci = lock_cluster_or_swap_info(si, offset);
  1507. count = swap_count(si->swap_map[offset]);
  1508. unlock_cluster_or_swap_info(si, ci);
  1509. return count;
  1510. }
  1511. /*
  1512. * How many references to @entry are currently swapped out?
  1513. * This considers COUNT_CONTINUED so it returns exact answer.
  1514. */
  1515. int swp_swapcount(swp_entry_t entry)
  1516. {
  1517. int count, tmp_count, n;
  1518. struct swap_info_struct *si;
  1519. struct swap_cluster_info *ci;
  1520. struct page *page;
  1521. pgoff_t offset;
  1522. unsigned char *map;
  1523. si = _swap_info_get(entry);
  1524. if (!si)
  1525. return 0;
  1526. offset = swp_offset(entry);
  1527. ci = lock_cluster_or_swap_info(si, offset);
  1528. count = swap_count(si->swap_map[offset]);
  1529. if (!(count & COUNT_CONTINUED))
  1530. goto out;
  1531. count &= ~COUNT_CONTINUED;
  1532. n = SWAP_MAP_MAX + 1;
  1533. page = vmalloc_to_page(si->swap_map + offset);
  1534. offset &= ~PAGE_MASK;
  1535. VM_BUG_ON(page_private(page) != SWP_CONTINUED);
  1536. do {
  1537. page = list_next_entry(page, lru);
  1538. map = kmap_local_page(page);
  1539. tmp_count = map[offset];
  1540. kunmap_local(map);
  1541. count += (tmp_count & ~COUNT_CONTINUED) * n;
  1542. n *= (SWAP_CONT_MAX + 1);
  1543. } while (tmp_count & COUNT_CONTINUED);
  1544. out:
  1545. unlock_cluster_or_swap_info(si, ci);
  1546. return count;
  1547. }
  1548. static bool swap_page_trans_huge_swapped(struct swap_info_struct *si,
  1549. swp_entry_t entry, int order)
  1550. {
  1551. struct swap_cluster_info *ci;
  1552. unsigned char *map = si->swap_map;
  1553. unsigned int nr_pages = 1 << order;
  1554. unsigned long roffset = swp_offset(entry);
  1555. unsigned long offset = round_down(roffset, nr_pages);
  1556. int i;
  1557. bool ret = false;
  1558. ci = lock_cluster_or_swap_info(si, offset);
  1559. if (!ci || nr_pages == 1) {
  1560. if (swap_count(map[roffset]))
  1561. ret = true;
  1562. goto unlock_out;
  1563. }
  1564. for (i = 0; i < nr_pages; i++) {
  1565. if (swap_count(map[offset + i])) {
  1566. ret = true;
  1567. break;
  1568. }
  1569. }
  1570. unlock_out:
  1571. unlock_cluster_or_swap_info(si, ci);
  1572. return ret;
  1573. }
  1574. static bool folio_swapped(struct folio *folio)
  1575. {
  1576. swp_entry_t entry = folio->swap;
  1577. struct swap_info_struct *si = _swap_info_get(entry);
  1578. if (!si)
  1579. return false;
  1580. if (!IS_ENABLED(CONFIG_THP_SWAP) || likely(!folio_test_large(folio)))
  1581. return swap_swapcount(si, entry) != 0;
  1582. return swap_page_trans_huge_swapped(si, entry, folio_order(folio));
  1583. }
  1584. static bool folio_swapcache_freeable(struct folio *folio)
  1585. {
  1586. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  1587. if (!folio_test_swapcache(folio))
  1588. return false;
  1589. if (folio_test_writeback(folio))
  1590. return false;
  1591. /*
  1592. * Once hibernation has begun to create its image of memory,
  1593. * there's a danger that one of the calls to folio_free_swap()
  1594. * - most probably a call from __try_to_reclaim_swap() while
  1595. * hibernation is allocating its own swap pages for the image,
  1596. * but conceivably even a call from memory reclaim - will free
  1597. * the swap from a folio which has already been recorded in the
  1598. * image as a clean swapcache folio, and then reuse its swap for
  1599. * another page of the image. On waking from hibernation, the
  1600. * original folio might be freed under memory pressure, then
  1601. * later read back in from swap, now with the wrong data.
  1602. *
  1603. * Hibernation suspends storage while it is writing the image
  1604. * to disk so check that here.
  1605. */
  1606. if (pm_suspended_storage())
  1607. return false;
  1608. return true;
  1609. }
  1610. /**
  1611. * folio_free_swap() - Free the swap space used for this folio.
  1612. * @folio: The folio to remove.
  1613. *
  1614. * If swap is getting full, or if there are no more mappings of this folio,
  1615. * then call folio_free_swap to free its swap space.
  1616. *
  1617. * Return: true if we were able to release the swap space.
  1618. */
  1619. bool folio_free_swap(struct folio *folio)
  1620. {
  1621. if (!folio_swapcache_freeable(folio))
  1622. return false;
  1623. if (folio_swapped(folio))
  1624. return false;
  1625. delete_from_swap_cache(folio);
  1626. folio_set_dirty(folio);
  1627. return true;
  1628. }
  1629. /**
  1630. * free_swap_and_cache_nr() - Release reference on range of swap entries and
  1631. * reclaim their cache if no more references remain.
  1632. * @entry: First entry of range.
  1633. * @nr: Number of entries in range.
  1634. *
  1635. * For each swap entry in the contiguous range, release a reference. If any swap
  1636. * entries become free, try to reclaim their underlying folios, if present. The
  1637. * offset range is defined by [entry.offset, entry.offset + nr).
  1638. */
  1639. void free_swap_and_cache_nr(swp_entry_t entry, int nr)
  1640. {
  1641. const unsigned long start_offset = swp_offset(entry);
  1642. const unsigned long end_offset = start_offset + nr;
  1643. struct swap_info_struct *si;
  1644. bool any_only_cache = false;
  1645. unsigned long offset;
  1646. if (non_swap_entry(entry))
  1647. return;
  1648. si = get_swap_device(entry);
  1649. if (!si)
  1650. return;
  1651. if (WARN_ON(end_offset > si->max))
  1652. goto out;
  1653. /*
  1654. * First free all entries in the range.
  1655. */
  1656. any_only_cache = __swap_entries_free(si, entry, nr);
  1657. /*
  1658. * Short-circuit the below loop if none of the entries had their
  1659. * reference drop to zero.
  1660. */
  1661. if (!any_only_cache)
  1662. goto out;
  1663. /*
  1664. * Now go back over the range trying to reclaim the swap cache. This is
  1665. * more efficient for large folios because we will only try to reclaim
  1666. * the swap once per folio in the common case. If we do
  1667. * __swap_entry_free() and __try_to_reclaim_swap() in the same loop, the
  1668. * latter will get a reference and lock the folio for every individual
  1669. * page but will only succeed once the swap slot for every subpage is
  1670. * zero.
  1671. */
  1672. for (offset = start_offset; offset < end_offset; offset += nr) {
  1673. nr = 1;
  1674. if (READ_ONCE(si->swap_map[offset]) == SWAP_HAS_CACHE) {
  1675. /*
  1676. * Folios are always naturally aligned in swap so
  1677. * advance forward to the next boundary. Zero means no
  1678. * folio was found for the swap entry, so advance by 1
  1679. * in this case. Negative value means folio was found
  1680. * but could not be reclaimed. Here we can still advance
  1681. * to the next boundary.
  1682. */
  1683. nr = __try_to_reclaim_swap(si, offset,
  1684. TTRS_UNMAPPED | TTRS_FULL);
  1685. if (nr == 0)
  1686. nr = 1;
  1687. else if (nr < 0)
  1688. nr = -nr;
  1689. nr = ALIGN(offset + 1, nr) - offset;
  1690. }
  1691. }
  1692. out:
  1693. put_swap_device(si);
  1694. }
  1695. #ifdef CONFIG_HIBERNATION
  1696. swp_entry_t get_swap_page_of_type(int type)
  1697. {
  1698. struct swap_info_struct *si = swap_type_to_swap_info(type);
  1699. swp_entry_t entry = {0};
  1700. if (!si)
  1701. goto fail;
  1702. /* This is called for allocating swap entry, not cache */
  1703. spin_lock(&si->lock);
  1704. if ((si->flags & SWP_WRITEOK) && scan_swap_map_slots(si, 1, 1, &entry, 0))
  1705. atomic_long_dec(&nr_swap_pages);
  1706. spin_unlock(&si->lock);
  1707. fail:
  1708. return entry;
  1709. }
  1710. /*
  1711. * Find the swap type that corresponds to given device (if any).
  1712. *
  1713. * @offset - number of the PAGE_SIZE-sized block of the device, starting
  1714. * from 0, in which the swap header is expected to be located.
  1715. *
  1716. * This is needed for the suspend to disk (aka swsusp).
  1717. */
  1718. int swap_type_of(dev_t device, sector_t offset)
  1719. {
  1720. int type;
  1721. if (!device)
  1722. return -1;
  1723. spin_lock(&swap_lock);
  1724. for (type = 0; type < nr_swapfiles; type++) {
  1725. struct swap_info_struct *sis = swap_info[type];
  1726. if (!(sis->flags & SWP_WRITEOK))
  1727. continue;
  1728. if (device == sis->bdev->bd_dev) {
  1729. struct swap_extent *se = first_se(sis);
  1730. if (se->start_block == offset) {
  1731. spin_unlock(&swap_lock);
  1732. return type;
  1733. }
  1734. }
  1735. }
  1736. spin_unlock(&swap_lock);
  1737. return -ENODEV;
  1738. }
  1739. int find_first_swap(dev_t *device)
  1740. {
  1741. int type;
  1742. spin_lock(&swap_lock);
  1743. for (type = 0; type < nr_swapfiles; type++) {
  1744. struct swap_info_struct *sis = swap_info[type];
  1745. if (!(sis->flags & SWP_WRITEOK))
  1746. continue;
  1747. *device = sis->bdev->bd_dev;
  1748. spin_unlock(&swap_lock);
  1749. return type;
  1750. }
  1751. spin_unlock(&swap_lock);
  1752. return -ENODEV;
  1753. }
  1754. /*
  1755. * Get the (PAGE_SIZE) block corresponding to given offset on the swapdev
  1756. * corresponding to given index in swap_info (swap type).
  1757. */
  1758. sector_t swapdev_block(int type, pgoff_t offset)
  1759. {
  1760. struct swap_info_struct *si = swap_type_to_swap_info(type);
  1761. struct swap_extent *se;
  1762. if (!si || !(si->flags & SWP_WRITEOK))
  1763. return 0;
  1764. se = offset_to_swap_extent(si, offset);
  1765. return se->start_block + (offset - se->start_page);
  1766. }
  1767. /*
  1768. * Return either the total number of swap pages of given type, or the number
  1769. * of free pages of that type (depending on @free)
  1770. *
  1771. * This is needed for software suspend
  1772. */
  1773. unsigned int count_swap_pages(int type, int free)
  1774. {
  1775. unsigned int n = 0;
  1776. spin_lock(&swap_lock);
  1777. if ((unsigned int)type < nr_swapfiles) {
  1778. struct swap_info_struct *sis = swap_info[type];
  1779. spin_lock(&sis->lock);
  1780. if (sis->flags & SWP_WRITEOK) {
  1781. n = sis->pages;
  1782. if (free)
  1783. n -= sis->inuse_pages;
  1784. }
  1785. spin_unlock(&sis->lock);
  1786. }
  1787. spin_unlock(&swap_lock);
  1788. return n;
  1789. }
  1790. #endif /* CONFIG_HIBERNATION */
  1791. static inline int pte_same_as_swp(pte_t pte, pte_t swp_pte)
  1792. {
  1793. return pte_same(pte_swp_clear_flags(pte), swp_pte);
  1794. }
  1795. /*
  1796. * No need to decide whether this PTE shares the swap entry with others,
  1797. * just let do_wp_page work it out if a write is requested later - to
  1798. * force COW, vm_page_prot omits write permission from any private vma.
  1799. */
  1800. static int unuse_pte(struct vm_area_struct *vma, pmd_t *pmd,
  1801. unsigned long addr, swp_entry_t entry, struct folio *folio)
  1802. {
  1803. struct page *page;
  1804. struct folio *swapcache;
  1805. spinlock_t *ptl;
  1806. pte_t *pte, new_pte, old_pte;
  1807. bool hwpoisoned = false;
  1808. int ret = 1;
  1809. swapcache = folio;
  1810. folio = ksm_might_need_to_copy(folio, vma, addr);
  1811. if (unlikely(!folio))
  1812. return -ENOMEM;
  1813. else if (unlikely(folio == ERR_PTR(-EHWPOISON))) {
  1814. hwpoisoned = true;
  1815. folio = swapcache;
  1816. }
  1817. page = folio_file_page(folio, swp_offset(entry));
  1818. if (PageHWPoison(page))
  1819. hwpoisoned = true;
  1820. pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
  1821. if (unlikely(!pte || !pte_same_as_swp(ptep_get(pte),
  1822. swp_entry_to_pte(entry)))) {
  1823. ret = 0;
  1824. goto out;
  1825. }
  1826. old_pte = ptep_get(pte);
  1827. if (unlikely(hwpoisoned || !folio_test_uptodate(folio))) {
  1828. swp_entry_t swp_entry;
  1829. dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
  1830. if (hwpoisoned) {
  1831. swp_entry = make_hwpoison_entry(page);
  1832. } else {
  1833. swp_entry = make_poisoned_swp_entry();
  1834. }
  1835. new_pte = swp_entry_to_pte(swp_entry);
  1836. ret = 0;
  1837. goto setpte;
  1838. }
  1839. /*
  1840. * Some architectures may have to restore extra metadata to the page
  1841. * when reading from swap. This metadata may be indexed by swap entry
  1842. * so this must be called before swap_free().
  1843. */
  1844. arch_swap_restore(folio_swap(entry, folio), folio);
  1845. dec_mm_counter(vma->vm_mm, MM_SWAPENTS);
  1846. inc_mm_counter(vma->vm_mm, MM_ANONPAGES);
  1847. folio_get(folio);
  1848. if (folio == swapcache) {
  1849. rmap_t rmap_flags = RMAP_NONE;
  1850. /*
  1851. * See do_swap_page(): writeback would be problematic.
  1852. * However, we do a folio_wait_writeback() just before this
  1853. * call and have the folio locked.
  1854. */
  1855. VM_BUG_ON_FOLIO(folio_test_writeback(folio), folio);
  1856. if (pte_swp_exclusive(old_pte))
  1857. rmap_flags |= RMAP_EXCLUSIVE;
  1858. /*
  1859. * We currently only expect small !anon folios, which are either
  1860. * fully exclusive or fully shared. If we ever get large folios
  1861. * here, we have to be careful.
  1862. */
  1863. if (!folio_test_anon(folio)) {
  1864. VM_WARN_ON_ONCE(folio_test_large(folio));
  1865. VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
  1866. folio_add_new_anon_rmap(folio, vma, addr, rmap_flags);
  1867. } else {
  1868. folio_add_anon_rmap_pte(folio, page, vma, addr, rmap_flags);
  1869. }
  1870. } else { /* ksm created a completely new copy */
  1871. folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
  1872. folio_add_lru_vma(folio, vma);
  1873. }
  1874. new_pte = pte_mkold(mk_pte(page, vma->vm_page_prot));
  1875. if (pte_swp_soft_dirty(old_pte))
  1876. new_pte = pte_mksoft_dirty(new_pte);
  1877. if (pte_swp_uffd_wp(old_pte))
  1878. new_pte = pte_mkuffd_wp(new_pte);
  1879. setpte:
  1880. set_pte_at(vma->vm_mm, addr, pte, new_pte);
  1881. swap_free(entry);
  1882. out:
  1883. if (pte)
  1884. pte_unmap_unlock(pte, ptl);
  1885. if (folio != swapcache) {
  1886. folio_unlock(folio);
  1887. folio_put(folio);
  1888. }
  1889. return ret;
  1890. }
  1891. static int unuse_pte_range(struct vm_area_struct *vma, pmd_t *pmd,
  1892. unsigned long addr, unsigned long end,
  1893. unsigned int type)
  1894. {
  1895. pte_t *pte = NULL;
  1896. struct swap_info_struct *si;
  1897. si = swap_info[type];
  1898. do {
  1899. struct folio *folio;
  1900. unsigned long offset;
  1901. unsigned char swp_count;
  1902. swp_entry_t entry;
  1903. int ret;
  1904. pte_t ptent;
  1905. if (!pte++) {
  1906. pte = pte_offset_map(pmd, addr);
  1907. if (!pte)
  1908. break;
  1909. }
  1910. ptent = ptep_get_lockless(pte);
  1911. if (!is_swap_pte(ptent))
  1912. continue;
  1913. entry = pte_to_swp_entry(ptent);
  1914. if (swp_type(entry) != type)
  1915. continue;
  1916. offset = swp_offset(entry);
  1917. pte_unmap(pte);
  1918. pte = NULL;
  1919. folio = swap_cache_get_folio(entry, vma, addr);
  1920. if (!folio) {
  1921. struct vm_fault vmf = {
  1922. .vma = vma,
  1923. .address = addr,
  1924. .real_address = addr,
  1925. .pmd = pmd,
  1926. };
  1927. folio = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
  1928. &vmf);
  1929. }
  1930. if (!folio) {
  1931. swp_count = READ_ONCE(si->swap_map[offset]);
  1932. if (swp_count == 0 || swp_count == SWAP_MAP_BAD)
  1933. continue;
  1934. return -ENOMEM;
  1935. }
  1936. folio_lock(folio);
  1937. folio_wait_writeback(folio);
  1938. ret = unuse_pte(vma, pmd, addr, entry, folio);
  1939. if (ret < 0) {
  1940. folio_unlock(folio);
  1941. folio_put(folio);
  1942. return ret;
  1943. }
  1944. folio_free_swap(folio);
  1945. folio_unlock(folio);
  1946. folio_put(folio);
  1947. } while (addr += PAGE_SIZE, addr != end);
  1948. if (pte)
  1949. pte_unmap(pte);
  1950. return 0;
  1951. }
  1952. static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
  1953. unsigned long addr, unsigned long end,
  1954. unsigned int type)
  1955. {
  1956. pmd_t *pmd;
  1957. unsigned long next;
  1958. int ret;
  1959. pmd = pmd_offset(pud, addr);
  1960. do {
  1961. cond_resched();
  1962. next = pmd_addr_end(addr, end);
  1963. ret = unuse_pte_range(vma, pmd, addr, next, type);
  1964. if (ret)
  1965. return ret;
  1966. } while (pmd++, addr = next, addr != end);
  1967. return 0;
  1968. }
  1969. static inline int unuse_pud_range(struct vm_area_struct *vma, p4d_t *p4d,
  1970. unsigned long addr, unsigned long end,
  1971. unsigned int type)
  1972. {
  1973. pud_t *pud;
  1974. unsigned long next;
  1975. int ret;
  1976. pud = pud_offset(p4d, addr);
  1977. do {
  1978. next = pud_addr_end(addr, end);
  1979. if (pud_none_or_clear_bad(pud))
  1980. continue;
  1981. ret = unuse_pmd_range(vma, pud, addr, next, type);
  1982. if (ret)
  1983. return ret;
  1984. } while (pud++, addr = next, addr != end);
  1985. return 0;
  1986. }
  1987. static inline int unuse_p4d_range(struct vm_area_struct *vma, pgd_t *pgd,
  1988. unsigned long addr, unsigned long end,
  1989. unsigned int type)
  1990. {
  1991. p4d_t *p4d;
  1992. unsigned long next;
  1993. int ret;
  1994. p4d = p4d_offset(pgd, addr);
  1995. do {
  1996. next = p4d_addr_end(addr, end);
  1997. if (p4d_none_or_clear_bad(p4d))
  1998. continue;
  1999. ret = unuse_pud_range(vma, p4d, addr, next, type);
  2000. if (ret)
  2001. return ret;
  2002. } while (p4d++, addr = next, addr != end);
  2003. return 0;
  2004. }
  2005. static int unuse_vma(struct vm_area_struct *vma, unsigned int type)
  2006. {
  2007. pgd_t *pgd;
  2008. unsigned long addr, end, next;
  2009. int ret;
  2010. addr = vma->vm_start;
  2011. end = vma->vm_end;
  2012. pgd = pgd_offset(vma->vm_mm, addr);
  2013. do {
  2014. next = pgd_addr_end(addr, end);
  2015. if (pgd_none_or_clear_bad(pgd))
  2016. continue;
  2017. ret = unuse_p4d_range(vma, pgd, addr, next, type);
  2018. if (ret)
  2019. return ret;
  2020. } while (pgd++, addr = next, addr != end);
  2021. return 0;
  2022. }
  2023. static int unuse_mm(struct mm_struct *mm, unsigned int type)
  2024. {
  2025. struct vm_area_struct *vma;
  2026. int ret = 0;
  2027. VMA_ITERATOR(vmi, mm, 0);
  2028. mmap_read_lock(mm);
  2029. if (check_stable_address_space(mm))
  2030. goto unlock;
  2031. for_each_vma(vmi, vma) {
  2032. if (vma->anon_vma && !is_vm_hugetlb_page(vma)) {
  2033. ret = unuse_vma(vma, type);
  2034. if (ret)
  2035. break;
  2036. }
  2037. cond_resched();
  2038. }
  2039. unlock:
  2040. mmap_read_unlock(mm);
  2041. return ret;
  2042. }
  2043. /*
  2044. * Scan swap_map from current position to next entry still in use.
  2045. * Return 0 if there are no inuse entries after prev till end of
  2046. * the map.
  2047. */
  2048. static unsigned int find_next_to_unuse(struct swap_info_struct *si,
  2049. unsigned int prev)
  2050. {
  2051. unsigned int i;
  2052. unsigned char count;
  2053. /*
  2054. * No need for swap_lock here: we're just looking
  2055. * for whether an entry is in use, not modifying it; false
  2056. * hits are okay, and sys_swapoff() has already prevented new
  2057. * allocations from this area (while holding swap_lock).
  2058. */
  2059. for (i = prev + 1; i < si->max; i++) {
  2060. count = READ_ONCE(si->swap_map[i]);
  2061. if (count && swap_count(count) != SWAP_MAP_BAD)
  2062. break;
  2063. if ((i % LATENCY_LIMIT) == 0)
  2064. cond_resched();
  2065. }
  2066. if (i == si->max)
  2067. i = 0;
  2068. return i;
  2069. }
  2070. static int try_to_unuse(unsigned int type)
  2071. {
  2072. struct mm_struct *prev_mm;
  2073. struct mm_struct *mm;
  2074. struct list_head *p;
  2075. int retval = 0;
  2076. struct swap_info_struct *si = swap_info[type];
  2077. struct folio *folio;
  2078. swp_entry_t entry;
  2079. unsigned int i;
  2080. if (!READ_ONCE(si->inuse_pages))
  2081. goto success;
  2082. retry:
  2083. retval = shmem_unuse(type);
  2084. if (retval)
  2085. return retval;
  2086. prev_mm = &init_mm;
  2087. mmget(prev_mm);
  2088. spin_lock(&mmlist_lock);
  2089. p = &init_mm.mmlist;
  2090. while (READ_ONCE(si->inuse_pages) &&
  2091. !signal_pending(current) &&
  2092. (p = p->next) != &init_mm.mmlist) {
  2093. mm = list_entry(p, struct mm_struct, mmlist);
  2094. if (!mmget_not_zero(mm))
  2095. continue;
  2096. spin_unlock(&mmlist_lock);
  2097. mmput(prev_mm);
  2098. prev_mm = mm;
  2099. retval = unuse_mm(mm, type);
  2100. if (retval) {
  2101. mmput(prev_mm);
  2102. return retval;
  2103. }
  2104. /*
  2105. * Make sure that we aren't completely killing
  2106. * interactive performance.
  2107. */
  2108. cond_resched();
  2109. spin_lock(&mmlist_lock);
  2110. }
  2111. spin_unlock(&mmlist_lock);
  2112. mmput(prev_mm);
  2113. i = 0;
  2114. while (READ_ONCE(si->inuse_pages) &&
  2115. !signal_pending(current) &&
  2116. (i = find_next_to_unuse(si, i)) != 0) {
  2117. entry = swp_entry(type, i);
  2118. folio = filemap_get_folio(swap_address_space(entry), swap_cache_index(entry));
  2119. if (IS_ERR(folio))
  2120. continue;
  2121. /*
  2122. * It is conceivable that a racing task removed this folio from
  2123. * swap cache just before we acquired the page lock. The folio
  2124. * might even be back in swap cache on another swap area. But
  2125. * that is okay, folio_free_swap() only removes stale folios.
  2126. */
  2127. folio_lock(folio);
  2128. folio_wait_writeback(folio);
  2129. folio_free_swap(folio);
  2130. folio_unlock(folio);
  2131. folio_put(folio);
  2132. }
  2133. /*
  2134. * Lets check again to see if there are still swap entries in the map.
  2135. * If yes, we would need to do retry the unuse logic again.
  2136. * Under global memory pressure, swap entries can be reinserted back
  2137. * into process space after the mmlist loop above passes over them.
  2138. *
  2139. * Limit the number of retries? No: when mmget_not_zero()
  2140. * above fails, that mm is likely to be freeing swap from
  2141. * exit_mmap(), which proceeds at its own independent pace;
  2142. * and even shmem_writepage() could have been preempted after
  2143. * folio_alloc_swap(), temporarily hiding that swap. It's easy
  2144. * and robust (though cpu-intensive) just to keep retrying.
  2145. */
  2146. if (READ_ONCE(si->inuse_pages)) {
  2147. if (!signal_pending(current))
  2148. goto retry;
  2149. return -EINTR;
  2150. }
  2151. success:
  2152. /*
  2153. * Make sure that further cleanups after try_to_unuse() returns happen
  2154. * after swap_range_free() reduces si->inuse_pages to 0.
  2155. */
  2156. smp_mb();
  2157. return 0;
  2158. }
  2159. /*
  2160. * After a successful try_to_unuse, if no swap is now in use, we know
  2161. * we can empty the mmlist. swap_lock must be held on entry and exit.
  2162. * Note that mmlist_lock nests inside swap_lock, and an mm must be
  2163. * added to the mmlist just after page_duplicate - before would be racy.
  2164. */
  2165. static void drain_mmlist(void)
  2166. {
  2167. struct list_head *p, *next;
  2168. unsigned int type;
  2169. for (type = 0; type < nr_swapfiles; type++)
  2170. if (swap_info[type]->inuse_pages)
  2171. return;
  2172. spin_lock(&mmlist_lock);
  2173. list_for_each_safe(p, next, &init_mm.mmlist)
  2174. list_del_init(p);
  2175. spin_unlock(&mmlist_lock);
  2176. }
  2177. /*
  2178. * Free all of a swapdev's extent information
  2179. */
  2180. static void destroy_swap_extents(struct swap_info_struct *sis)
  2181. {
  2182. while (!RB_EMPTY_ROOT(&sis->swap_extent_root)) {
  2183. struct rb_node *rb = sis->swap_extent_root.rb_node;
  2184. struct swap_extent *se = rb_entry(rb, struct swap_extent, rb_node);
  2185. rb_erase(rb, &sis->swap_extent_root);
  2186. kfree(se);
  2187. }
  2188. if (sis->flags & SWP_ACTIVATED) {
  2189. struct file *swap_file = sis->swap_file;
  2190. struct address_space *mapping = swap_file->f_mapping;
  2191. sis->flags &= ~SWP_ACTIVATED;
  2192. if (mapping->a_ops->swap_deactivate)
  2193. mapping->a_ops->swap_deactivate(swap_file);
  2194. }
  2195. }
  2196. /*
  2197. * Add a block range (and the corresponding page range) into this swapdev's
  2198. * extent tree.
  2199. *
  2200. * This function rather assumes that it is called in ascending page order.
  2201. */
  2202. int
  2203. add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
  2204. unsigned long nr_pages, sector_t start_block)
  2205. {
  2206. struct rb_node **link = &sis->swap_extent_root.rb_node, *parent = NULL;
  2207. struct swap_extent *se;
  2208. struct swap_extent *new_se;
  2209. /*
  2210. * place the new node at the right most since the
  2211. * function is called in ascending page order.
  2212. */
  2213. while (*link) {
  2214. parent = *link;
  2215. link = &parent->rb_right;
  2216. }
  2217. if (parent) {
  2218. se = rb_entry(parent, struct swap_extent, rb_node);
  2219. BUG_ON(se->start_page + se->nr_pages != start_page);
  2220. if (se->start_block + se->nr_pages == start_block) {
  2221. /* Merge it */
  2222. se->nr_pages += nr_pages;
  2223. return 0;
  2224. }
  2225. }
  2226. /* No merge, insert a new extent. */
  2227. new_se = kmalloc(sizeof(*se), GFP_KERNEL);
  2228. if (new_se == NULL)
  2229. return -ENOMEM;
  2230. new_se->start_page = start_page;
  2231. new_se->nr_pages = nr_pages;
  2232. new_se->start_block = start_block;
  2233. rb_link_node(&new_se->rb_node, parent, link);
  2234. rb_insert_color(&new_se->rb_node, &sis->swap_extent_root);
  2235. return 1;
  2236. }
  2237. EXPORT_SYMBOL_GPL(add_swap_extent);
  2238. /*
  2239. * A `swap extent' is a simple thing which maps a contiguous range of pages
  2240. * onto a contiguous range of disk blocks. A rbtree of swap extents is
  2241. * built at swapon time and is then used at swap_writepage/swap_read_folio
  2242. * time for locating where on disk a page belongs.
  2243. *
  2244. * If the swapfile is an S_ISBLK block device, a single extent is installed.
  2245. * This is done so that the main operating code can treat S_ISBLK and S_ISREG
  2246. * swap files identically.
  2247. *
  2248. * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
  2249. * extent rbtree operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
  2250. * swapfiles are handled *identically* after swapon time.
  2251. *
  2252. * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
  2253. * and will parse them into a rbtree, in PAGE_SIZE chunks. If some stray
  2254. * blocks are found which do not fall within the PAGE_SIZE alignment
  2255. * requirements, they are simply tossed out - we will never use those blocks
  2256. * for swapping.
  2257. *
  2258. * For all swap devices we set S_SWAPFILE across the life of the swapon. This
  2259. * prevents users from writing to the swap device, which will corrupt memory.
  2260. *
  2261. * The amount of disk space which a single swap extent represents varies.
  2262. * Typically it is in the 1-4 megabyte range. So we can have hundreds of
  2263. * extents in the rbtree. - akpm.
  2264. */
  2265. static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
  2266. {
  2267. struct file *swap_file = sis->swap_file;
  2268. struct address_space *mapping = swap_file->f_mapping;
  2269. struct inode *inode = mapping->host;
  2270. int ret;
  2271. if (S_ISBLK(inode->i_mode)) {
  2272. ret = add_swap_extent(sis, 0, sis->max, 0);
  2273. *span = sis->pages;
  2274. return ret;
  2275. }
  2276. if (mapping->a_ops->swap_activate) {
  2277. ret = mapping->a_ops->swap_activate(sis, swap_file, span);
  2278. if (ret < 0)
  2279. return ret;
  2280. sis->flags |= SWP_ACTIVATED;
  2281. if ((sis->flags & SWP_FS_OPS) &&
  2282. sio_pool_init() != 0) {
  2283. destroy_swap_extents(sis);
  2284. return -ENOMEM;
  2285. }
  2286. return ret;
  2287. }
  2288. return generic_swapfile_activate(sis, swap_file, span);
  2289. }
  2290. static int swap_node(struct swap_info_struct *si)
  2291. {
  2292. struct block_device *bdev;
  2293. if (si->bdev)
  2294. bdev = si->bdev;
  2295. else
  2296. bdev = si->swap_file->f_inode->i_sb->s_bdev;
  2297. return bdev ? bdev->bd_disk->node_id : NUMA_NO_NODE;
  2298. }
  2299. static void setup_swap_info(struct swap_info_struct *si, int prio,
  2300. unsigned char *swap_map,
  2301. struct swap_cluster_info *cluster_info,
  2302. unsigned long *zeromap)
  2303. {
  2304. int i;
  2305. if (prio >= 0)
  2306. si->prio = prio;
  2307. else
  2308. si->prio = --least_priority;
  2309. /*
  2310. * the plist prio is negated because plist ordering is
  2311. * low-to-high, while swap ordering is high-to-low
  2312. */
  2313. si->list.prio = -si->prio;
  2314. for_each_node(i) {
  2315. if (si->prio >= 0)
  2316. si->avail_lists[i].prio = -si->prio;
  2317. else {
  2318. if (swap_node(si) == i)
  2319. si->avail_lists[i].prio = 1;
  2320. else
  2321. si->avail_lists[i].prio = -si->prio;
  2322. }
  2323. }
  2324. si->swap_map = swap_map;
  2325. si->cluster_info = cluster_info;
  2326. si->zeromap = zeromap;
  2327. }
  2328. static void _enable_swap_info(struct swap_info_struct *si)
  2329. {
  2330. si->flags |= SWP_WRITEOK;
  2331. atomic_long_add(si->pages, &nr_swap_pages);
  2332. total_swap_pages += si->pages;
  2333. assert_spin_locked(&swap_lock);
  2334. /*
  2335. * both lists are plists, and thus priority ordered.
  2336. * swap_active_head needs to be priority ordered for swapoff(),
  2337. * which on removal of any swap_info_struct with an auto-assigned
  2338. * (i.e. negative) priority increments the auto-assigned priority
  2339. * of any lower-priority swap_info_structs.
  2340. * swap_avail_head needs to be priority ordered for folio_alloc_swap(),
  2341. * which allocates swap pages from the highest available priority
  2342. * swap_info_struct.
  2343. */
  2344. plist_add(&si->list, &swap_active_head);
  2345. /* add to available list iff swap device is not full */
  2346. if (si->highest_bit)
  2347. add_to_avail_list(si);
  2348. }
  2349. static void enable_swap_info(struct swap_info_struct *si, int prio,
  2350. unsigned char *swap_map,
  2351. struct swap_cluster_info *cluster_info,
  2352. unsigned long *zeromap)
  2353. {
  2354. spin_lock(&swap_lock);
  2355. spin_lock(&si->lock);
  2356. setup_swap_info(si, prio, swap_map, cluster_info, zeromap);
  2357. spin_unlock(&si->lock);
  2358. spin_unlock(&swap_lock);
  2359. /*
  2360. * Finished initializing swap device, now it's safe to reference it.
  2361. */
  2362. percpu_ref_resurrect(&si->users);
  2363. spin_lock(&swap_lock);
  2364. spin_lock(&si->lock);
  2365. _enable_swap_info(si);
  2366. spin_unlock(&si->lock);
  2367. spin_unlock(&swap_lock);
  2368. }
  2369. static void reinsert_swap_info(struct swap_info_struct *si)
  2370. {
  2371. spin_lock(&swap_lock);
  2372. spin_lock(&si->lock);
  2373. setup_swap_info(si, si->prio, si->swap_map, si->cluster_info, si->zeromap);
  2374. _enable_swap_info(si);
  2375. spin_unlock(&si->lock);
  2376. spin_unlock(&swap_lock);
  2377. }
  2378. static bool __has_usable_swap(void)
  2379. {
  2380. return !plist_head_empty(&swap_active_head);
  2381. }
  2382. bool has_usable_swap(void)
  2383. {
  2384. bool ret;
  2385. spin_lock(&swap_lock);
  2386. ret = __has_usable_swap();
  2387. spin_unlock(&swap_lock);
  2388. return ret;
  2389. }
  2390. SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
  2391. {
  2392. struct swap_info_struct *p = NULL;
  2393. unsigned char *swap_map;
  2394. unsigned long *zeromap;
  2395. struct swap_cluster_info *cluster_info;
  2396. struct file *swap_file, *victim;
  2397. struct address_space *mapping;
  2398. struct inode *inode;
  2399. struct filename *pathname;
  2400. int err, found = 0;
  2401. if (!capable(CAP_SYS_ADMIN))
  2402. return -EPERM;
  2403. BUG_ON(!current->mm);
  2404. pathname = getname(specialfile);
  2405. if (IS_ERR(pathname))
  2406. return PTR_ERR(pathname);
  2407. victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
  2408. err = PTR_ERR(victim);
  2409. if (IS_ERR(victim))
  2410. goto out;
  2411. mapping = victim->f_mapping;
  2412. spin_lock(&swap_lock);
  2413. plist_for_each_entry(p, &swap_active_head, list) {
  2414. if (p->flags & SWP_WRITEOK) {
  2415. if (p->swap_file->f_mapping == mapping) {
  2416. found = 1;
  2417. break;
  2418. }
  2419. }
  2420. }
  2421. if (!found) {
  2422. err = -EINVAL;
  2423. spin_unlock(&swap_lock);
  2424. goto out_dput;
  2425. }
  2426. if (!security_vm_enough_memory_mm(current->mm, p->pages))
  2427. vm_unacct_memory(p->pages);
  2428. else {
  2429. err = -ENOMEM;
  2430. spin_unlock(&swap_lock);
  2431. goto out_dput;
  2432. }
  2433. spin_lock(&p->lock);
  2434. del_from_avail_list(p);
  2435. if (p->prio < 0) {
  2436. struct swap_info_struct *si = p;
  2437. int nid;
  2438. plist_for_each_entry_continue(si, &swap_active_head, list) {
  2439. si->prio++;
  2440. si->list.prio--;
  2441. for_each_node(nid) {
  2442. if (si->avail_lists[nid].prio != 1)
  2443. si->avail_lists[nid].prio--;
  2444. }
  2445. }
  2446. least_priority++;
  2447. }
  2448. plist_del(&p->list, &swap_active_head);
  2449. atomic_long_sub(p->pages, &nr_swap_pages);
  2450. total_swap_pages -= p->pages;
  2451. p->flags &= ~SWP_WRITEOK;
  2452. spin_unlock(&p->lock);
  2453. spin_unlock(&swap_lock);
  2454. disable_swap_slots_cache_lock();
  2455. set_current_oom_origin();
  2456. err = try_to_unuse(p->type);
  2457. clear_current_oom_origin();
  2458. if (err) {
  2459. /* re-insert swap space back into swap_list */
  2460. reinsert_swap_info(p);
  2461. reenable_swap_slots_cache_unlock();
  2462. goto out_dput;
  2463. }
  2464. reenable_swap_slots_cache_unlock();
  2465. /*
  2466. * Wait for swap operations protected by get/put_swap_device()
  2467. * to complete. Because of synchronize_rcu() here, all swap
  2468. * operations protected by RCU reader side lock (including any
  2469. * spinlock) will be waited too. This makes it easy to
  2470. * prevent folio_test_swapcache() and the following swap cache
  2471. * operations from racing with swapoff.
  2472. */
  2473. percpu_ref_kill(&p->users);
  2474. synchronize_rcu();
  2475. wait_for_completion(&p->comp);
  2476. flush_work(&p->discard_work);
  2477. flush_work(&p->reclaim_work);
  2478. destroy_swap_extents(p);
  2479. if (p->flags & SWP_CONTINUED)
  2480. free_swap_count_continuations(p);
  2481. if (!p->bdev || !bdev_nonrot(p->bdev))
  2482. atomic_dec(&nr_rotate_swap);
  2483. mutex_lock(&swapon_mutex);
  2484. spin_lock(&swap_lock);
  2485. spin_lock(&p->lock);
  2486. drain_mmlist();
  2487. /* wait for anyone still in scan_swap_map_slots */
  2488. p->highest_bit = 0; /* cuts scans short */
  2489. while (p->flags >= SWP_SCANNING) {
  2490. spin_unlock(&p->lock);
  2491. spin_unlock(&swap_lock);
  2492. schedule_timeout_uninterruptible(1);
  2493. spin_lock(&swap_lock);
  2494. spin_lock(&p->lock);
  2495. }
  2496. swap_file = p->swap_file;
  2497. p->swap_file = NULL;
  2498. p->max = 0;
  2499. swap_map = p->swap_map;
  2500. p->swap_map = NULL;
  2501. zeromap = p->zeromap;
  2502. p->zeromap = NULL;
  2503. cluster_info = p->cluster_info;
  2504. p->cluster_info = NULL;
  2505. spin_unlock(&p->lock);
  2506. spin_unlock(&swap_lock);
  2507. arch_swap_invalidate_area(p->type);
  2508. zswap_swapoff(p->type);
  2509. mutex_unlock(&swapon_mutex);
  2510. free_percpu(p->percpu_cluster);
  2511. p->percpu_cluster = NULL;
  2512. free_percpu(p->cluster_next_cpu);
  2513. p->cluster_next_cpu = NULL;
  2514. vfree(swap_map);
  2515. kvfree(zeromap);
  2516. kvfree(cluster_info);
  2517. /* Destroy swap account information */
  2518. swap_cgroup_swapoff(p->type);
  2519. exit_swap_address_space(p->type);
  2520. inode = mapping->host;
  2521. inode_lock(inode);
  2522. inode->i_flags &= ~S_SWAPFILE;
  2523. inode_unlock(inode);
  2524. filp_close(swap_file, NULL);
  2525. /*
  2526. * Clear the SWP_USED flag after all resources are freed so that swapon
  2527. * can reuse this swap_info in alloc_swap_info() safely. It is ok to
  2528. * not hold p->lock after we cleared its SWP_WRITEOK.
  2529. */
  2530. spin_lock(&swap_lock);
  2531. p->flags = 0;
  2532. spin_unlock(&swap_lock);
  2533. err = 0;
  2534. atomic_inc(&proc_poll_event);
  2535. wake_up_interruptible(&proc_poll_wait);
  2536. out_dput:
  2537. filp_close(victim, NULL);
  2538. out:
  2539. putname(pathname);
  2540. return err;
  2541. }
  2542. #ifdef CONFIG_PROC_FS
  2543. static __poll_t swaps_poll(struct file *file, poll_table *wait)
  2544. {
  2545. struct seq_file *seq = file->private_data;
  2546. poll_wait(file, &proc_poll_wait, wait);
  2547. if (seq->poll_event != atomic_read(&proc_poll_event)) {
  2548. seq->poll_event = atomic_read(&proc_poll_event);
  2549. return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
  2550. }
  2551. return EPOLLIN | EPOLLRDNORM;
  2552. }
  2553. /* iterator */
  2554. static void *swap_start(struct seq_file *swap, loff_t *pos)
  2555. {
  2556. struct swap_info_struct *si;
  2557. int type;
  2558. loff_t l = *pos;
  2559. mutex_lock(&swapon_mutex);
  2560. if (!l)
  2561. return SEQ_START_TOKEN;
  2562. for (type = 0; (si = swap_type_to_swap_info(type)); type++) {
  2563. if (!(si->flags & SWP_USED) || !si->swap_map)
  2564. continue;
  2565. if (!--l)
  2566. return si;
  2567. }
  2568. return NULL;
  2569. }
  2570. static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
  2571. {
  2572. struct swap_info_struct *si = v;
  2573. int type;
  2574. if (v == SEQ_START_TOKEN)
  2575. type = 0;
  2576. else
  2577. type = si->type + 1;
  2578. ++(*pos);
  2579. for (; (si = swap_type_to_swap_info(type)); type++) {
  2580. if (!(si->flags & SWP_USED) || !si->swap_map)
  2581. continue;
  2582. return si;
  2583. }
  2584. return NULL;
  2585. }
  2586. static void swap_stop(struct seq_file *swap, void *v)
  2587. {
  2588. mutex_unlock(&swapon_mutex);
  2589. }
  2590. static int swap_show(struct seq_file *swap, void *v)
  2591. {
  2592. struct swap_info_struct *si = v;
  2593. struct file *file;
  2594. int len;
  2595. unsigned long bytes, inuse;
  2596. if (si == SEQ_START_TOKEN) {
  2597. seq_puts(swap, "Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n");
  2598. return 0;
  2599. }
  2600. bytes = K(si->pages);
  2601. inuse = K(READ_ONCE(si->inuse_pages));
  2602. file = si->swap_file;
  2603. len = seq_file_path(swap, file, " \t\n\\");
  2604. seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n",
  2605. len < 40 ? 40 - len : 1, " ",
  2606. S_ISBLK(file_inode(file)->i_mode) ?
  2607. "partition" : "file\t",
  2608. bytes, bytes < 10000000 ? "\t" : "",
  2609. inuse, inuse < 10000000 ? "\t" : "",
  2610. si->prio);
  2611. return 0;
  2612. }
  2613. static const struct seq_operations swaps_op = {
  2614. .start = swap_start,
  2615. .next = swap_next,
  2616. .stop = swap_stop,
  2617. .show = swap_show
  2618. };
  2619. static int swaps_open(struct inode *inode, struct file *file)
  2620. {
  2621. struct seq_file *seq;
  2622. int ret;
  2623. ret = seq_open(file, &swaps_op);
  2624. if (ret)
  2625. return ret;
  2626. seq = file->private_data;
  2627. seq->poll_event = atomic_read(&proc_poll_event);
  2628. return 0;
  2629. }
  2630. static const struct proc_ops swaps_proc_ops = {
  2631. .proc_flags = PROC_ENTRY_PERMANENT,
  2632. .proc_open = swaps_open,
  2633. .proc_read = seq_read,
  2634. .proc_lseek = seq_lseek,
  2635. .proc_release = seq_release,
  2636. .proc_poll = swaps_poll,
  2637. };
  2638. static int __init procswaps_init(void)
  2639. {
  2640. proc_create("swaps", 0, NULL, &swaps_proc_ops);
  2641. return 0;
  2642. }
  2643. __initcall(procswaps_init);
  2644. #endif /* CONFIG_PROC_FS */
  2645. #ifdef MAX_SWAPFILES_CHECK
  2646. static int __init max_swapfiles_check(void)
  2647. {
  2648. MAX_SWAPFILES_CHECK();
  2649. return 0;
  2650. }
  2651. late_initcall(max_swapfiles_check);
  2652. #endif
  2653. static struct swap_info_struct *alloc_swap_info(void)
  2654. {
  2655. struct swap_info_struct *p;
  2656. struct swap_info_struct *defer = NULL;
  2657. unsigned int type;
  2658. int i;
  2659. p = kvzalloc(struct_size(p, avail_lists, nr_node_ids), GFP_KERNEL);
  2660. if (!p)
  2661. return ERR_PTR(-ENOMEM);
  2662. if (percpu_ref_init(&p->users, swap_users_ref_free,
  2663. PERCPU_REF_INIT_DEAD, GFP_KERNEL)) {
  2664. kvfree(p);
  2665. return ERR_PTR(-ENOMEM);
  2666. }
  2667. spin_lock(&swap_lock);
  2668. for (type = 0; type < nr_swapfiles; type++) {
  2669. if (!(swap_info[type]->flags & SWP_USED))
  2670. break;
  2671. }
  2672. if (type >= MAX_SWAPFILES) {
  2673. spin_unlock(&swap_lock);
  2674. percpu_ref_exit(&p->users);
  2675. kvfree(p);
  2676. return ERR_PTR(-EPERM);
  2677. }
  2678. if (type >= nr_swapfiles) {
  2679. p->type = type;
  2680. /*
  2681. * Publish the swap_info_struct after initializing it.
  2682. * Note that kvzalloc() above zeroes all its fields.
  2683. */
  2684. smp_store_release(&swap_info[type], p); /* rcu_assign_pointer() */
  2685. nr_swapfiles++;
  2686. } else {
  2687. defer = p;
  2688. p = swap_info[type];
  2689. /*
  2690. * Do not memset this entry: a racing procfs swap_next()
  2691. * would be relying on p->type to remain valid.
  2692. */
  2693. }
  2694. p->swap_extent_root = RB_ROOT;
  2695. plist_node_init(&p->list, 0);
  2696. for_each_node(i)
  2697. plist_node_init(&p->avail_lists[i], 0);
  2698. p->flags = SWP_USED;
  2699. spin_unlock(&swap_lock);
  2700. if (defer) {
  2701. percpu_ref_exit(&defer->users);
  2702. kvfree(defer);
  2703. }
  2704. spin_lock_init(&p->lock);
  2705. spin_lock_init(&p->cont_lock);
  2706. init_completion(&p->comp);
  2707. return p;
  2708. }
  2709. static int claim_swapfile(struct swap_info_struct *si, struct inode *inode)
  2710. {
  2711. if (S_ISBLK(inode->i_mode)) {
  2712. si->bdev = I_BDEV(inode);
  2713. /*
  2714. * Zoned block devices contain zones that have a sequential
  2715. * write only restriction. Hence zoned block devices are not
  2716. * suitable for swapping. Disallow them here.
  2717. */
  2718. if (bdev_is_zoned(si->bdev))
  2719. return -EINVAL;
  2720. si->flags |= SWP_BLKDEV;
  2721. } else if (S_ISREG(inode->i_mode)) {
  2722. si->bdev = inode->i_sb->s_bdev;
  2723. }
  2724. return 0;
  2725. }
  2726. /*
  2727. * Find out how many pages are allowed for a single swap device. There
  2728. * are two limiting factors:
  2729. * 1) the number of bits for the swap offset in the swp_entry_t type, and
  2730. * 2) the number of bits in the swap pte, as defined by the different
  2731. * architectures.
  2732. *
  2733. * In order to find the largest possible bit mask, a swap entry with
  2734. * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
  2735. * decoded to a swp_entry_t again, and finally the swap offset is
  2736. * extracted.
  2737. *
  2738. * This will mask all the bits from the initial ~0UL mask that can't
  2739. * be encoded in either the swp_entry_t or the architecture definition
  2740. * of a swap pte.
  2741. */
  2742. unsigned long generic_max_swapfile_size(void)
  2743. {
  2744. return swp_offset(pte_to_swp_entry(
  2745. swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
  2746. }
  2747. /* Can be overridden by an architecture for additional checks. */
  2748. __weak unsigned long arch_max_swapfile_size(void)
  2749. {
  2750. return generic_max_swapfile_size();
  2751. }
  2752. static unsigned long read_swap_header(struct swap_info_struct *si,
  2753. union swap_header *swap_header,
  2754. struct inode *inode)
  2755. {
  2756. int i;
  2757. unsigned long maxpages;
  2758. unsigned long swapfilepages;
  2759. unsigned long last_page;
  2760. if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
  2761. pr_err("Unable to find swap-space signature\n");
  2762. return 0;
  2763. }
  2764. /* swap partition endianness hack... */
  2765. if (swab32(swap_header->info.version) == 1) {
  2766. swab32s(&swap_header->info.version);
  2767. swab32s(&swap_header->info.last_page);
  2768. swab32s(&swap_header->info.nr_badpages);
  2769. if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
  2770. return 0;
  2771. for (i = 0; i < swap_header->info.nr_badpages; i++)
  2772. swab32s(&swap_header->info.badpages[i]);
  2773. }
  2774. /* Check the swap header's sub-version */
  2775. if (swap_header->info.version != 1) {
  2776. pr_warn("Unable to handle swap header version %d\n",
  2777. swap_header->info.version);
  2778. return 0;
  2779. }
  2780. si->lowest_bit = 1;
  2781. si->cluster_next = 1;
  2782. si->cluster_nr = 0;
  2783. maxpages = swapfile_maximum_size;
  2784. last_page = swap_header->info.last_page;
  2785. if (!last_page) {
  2786. pr_warn("Empty swap-file\n");
  2787. return 0;
  2788. }
  2789. if (last_page > maxpages) {
  2790. pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
  2791. K(maxpages), K(last_page));
  2792. }
  2793. if (maxpages > last_page) {
  2794. maxpages = last_page + 1;
  2795. /* p->max is an unsigned int: don't overflow it */
  2796. if ((unsigned int)maxpages == 0)
  2797. maxpages = UINT_MAX;
  2798. }
  2799. si->highest_bit = maxpages - 1;
  2800. if (!maxpages)
  2801. return 0;
  2802. swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
  2803. if (swapfilepages && maxpages > swapfilepages) {
  2804. pr_warn("Swap area shorter than signature indicates\n");
  2805. return 0;
  2806. }
  2807. if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
  2808. return 0;
  2809. if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
  2810. return 0;
  2811. return maxpages;
  2812. }
  2813. #define SWAP_CLUSTER_INFO_COLS \
  2814. DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info))
  2815. #define SWAP_CLUSTER_SPACE_COLS \
  2816. DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER)
  2817. #define SWAP_CLUSTER_COLS \
  2818. max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS)
  2819. static int setup_swap_map(struct swap_info_struct *si,
  2820. union swap_header *swap_header,
  2821. unsigned char *swap_map,
  2822. unsigned long maxpages)
  2823. {
  2824. unsigned long i;
  2825. swap_map[0] = SWAP_MAP_BAD; /* omit header page */
  2826. for (i = 0; i < swap_header->info.nr_badpages; i++) {
  2827. unsigned int page_nr = swap_header->info.badpages[i];
  2828. if (page_nr == 0 || page_nr > swap_header->info.last_page)
  2829. return -EINVAL;
  2830. if (page_nr < maxpages) {
  2831. swap_map[page_nr] = SWAP_MAP_BAD;
  2832. si->pages--;
  2833. }
  2834. }
  2835. if (!si->pages) {
  2836. pr_warn("Empty swap-file\n");
  2837. return -EINVAL;
  2838. }
  2839. return 0;
  2840. }
  2841. static struct swap_cluster_info *setup_clusters(struct swap_info_struct *si,
  2842. union swap_header *swap_header,
  2843. unsigned long maxpages)
  2844. {
  2845. unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
  2846. unsigned long col = si->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_COLS;
  2847. struct swap_cluster_info *cluster_info;
  2848. unsigned long i, j, k, idx;
  2849. int cpu, err = -ENOMEM;
  2850. cluster_info = kvcalloc(nr_clusters, sizeof(*cluster_info), GFP_KERNEL);
  2851. if (!cluster_info)
  2852. goto err;
  2853. for (i = 0; i < nr_clusters; i++)
  2854. spin_lock_init(&cluster_info[i].lock);
  2855. si->cluster_next_cpu = alloc_percpu(unsigned int);
  2856. if (!si->cluster_next_cpu)
  2857. goto err_free;
  2858. /* Random start position to help with wear leveling */
  2859. for_each_possible_cpu(cpu)
  2860. per_cpu(*si->cluster_next_cpu, cpu) =
  2861. get_random_u32_inclusive(1, si->highest_bit);
  2862. si->percpu_cluster = alloc_percpu(struct percpu_cluster);
  2863. if (!si->percpu_cluster)
  2864. goto err_free;
  2865. for_each_possible_cpu(cpu) {
  2866. struct percpu_cluster *cluster;
  2867. cluster = per_cpu_ptr(si->percpu_cluster, cpu);
  2868. for (i = 0; i < SWAP_NR_ORDERS; i++)
  2869. cluster->next[i] = SWAP_NEXT_INVALID;
  2870. }
  2871. /*
  2872. * Mark unusable pages as unavailable. The clusters aren't
  2873. * marked free yet, so no list operations are involved yet.
  2874. *
  2875. * See setup_swap_map(): header page, bad pages,
  2876. * and the EOF part of the last cluster.
  2877. */
  2878. inc_cluster_info_page(si, cluster_info, 0);
  2879. for (i = 0; i < swap_header->info.nr_badpages; i++) {
  2880. unsigned int page_nr = swap_header->info.badpages[i];
  2881. if (page_nr >= maxpages)
  2882. continue;
  2883. inc_cluster_info_page(si, cluster_info, page_nr);
  2884. }
  2885. for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
  2886. inc_cluster_info_page(si, cluster_info, i);
  2887. INIT_LIST_HEAD(&si->free_clusters);
  2888. INIT_LIST_HEAD(&si->full_clusters);
  2889. INIT_LIST_HEAD(&si->discard_clusters);
  2890. for (i = 0; i < SWAP_NR_ORDERS; i++) {
  2891. INIT_LIST_HEAD(&si->nonfull_clusters[i]);
  2892. INIT_LIST_HEAD(&si->frag_clusters[i]);
  2893. si->frag_cluster_nr[i] = 0;
  2894. }
  2895. /*
  2896. * Reduce false cache line sharing between cluster_info and
  2897. * sharing same address space.
  2898. */
  2899. for (k = 0; k < SWAP_CLUSTER_COLS; k++) {
  2900. j = (k + col) % SWAP_CLUSTER_COLS;
  2901. for (i = 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) {
  2902. struct swap_cluster_info *ci;
  2903. idx = i * SWAP_CLUSTER_COLS + j;
  2904. ci = cluster_info + idx;
  2905. if (idx >= nr_clusters)
  2906. continue;
  2907. if (ci->count) {
  2908. ci->flags = CLUSTER_FLAG_NONFULL;
  2909. list_add_tail(&ci->list, &si->nonfull_clusters[0]);
  2910. continue;
  2911. }
  2912. ci->flags = CLUSTER_FLAG_FREE;
  2913. list_add_tail(&ci->list, &si->free_clusters);
  2914. }
  2915. }
  2916. return cluster_info;
  2917. err_free:
  2918. kvfree(cluster_info);
  2919. err:
  2920. return ERR_PTR(err);
  2921. }
  2922. SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
  2923. {
  2924. struct swap_info_struct *si;
  2925. struct filename *name;
  2926. struct file *swap_file = NULL;
  2927. struct address_space *mapping;
  2928. struct dentry *dentry;
  2929. int prio;
  2930. int error;
  2931. union swap_header *swap_header;
  2932. int nr_extents;
  2933. sector_t span;
  2934. unsigned long maxpages;
  2935. unsigned char *swap_map = NULL;
  2936. unsigned long *zeromap = NULL;
  2937. struct swap_cluster_info *cluster_info = NULL;
  2938. struct folio *folio = NULL;
  2939. struct inode *inode = NULL;
  2940. bool inced_nr_rotate_swap = false;
  2941. if (swap_flags & ~SWAP_FLAGS_VALID)
  2942. return -EINVAL;
  2943. if (!capable(CAP_SYS_ADMIN))
  2944. return -EPERM;
  2945. if (!swap_avail_heads)
  2946. return -ENOMEM;
  2947. si = alloc_swap_info();
  2948. if (IS_ERR(si))
  2949. return PTR_ERR(si);
  2950. INIT_WORK(&si->discard_work, swap_discard_work);
  2951. INIT_WORK(&si->reclaim_work, swap_reclaim_work);
  2952. name = getname(specialfile);
  2953. if (IS_ERR(name)) {
  2954. error = PTR_ERR(name);
  2955. name = NULL;
  2956. goto bad_swap;
  2957. }
  2958. swap_file = file_open_name(name, O_RDWR | O_LARGEFILE | O_EXCL, 0);
  2959. if (IS_ERR(swap_file)) {
  2960. error = PTR_ERR(swap_file);
  2961. swap_file = NULL;
  2962. goto bad_swap;
  2963. }
  2964. si->swap_file = swap_file;
  2965. mapping = swap_file->f_mapping;
  2966. dentry = swap_file->f_path.dentry;
  2967. inode = mapping->host;
  2968. error = claim_swapfile(si, inode);
  2969. if (unlikely(error))
  2970. goto bad_swap;
  2971. inode_lock(inode);
  2972. if (d_unlinked(dentry) || cant_mount(dentry)) {
  2973. error = -ENOENT;
  2974. goto bad_swap_unlock_inode;
  2975. }
  2976. if (IS_SWAPFILE(inode)) {
  2977. error = -EBUSY;
  2978. goto bad_swap_unlock_inode;
  2979. }
  2980. /*
  2981. * Read the swap header.
  2982. */
  2983. if (!mapping->a_ops->read_folio) {
  2984. error = -EINVAL;
  2985. goto bad_swap_unlock_inode;
  2986. }
  2987. folio = read_mapping_folio(mapping, 0, swap_file);
  2988. if (IS_ERR(folio)) {
  2989. error = PTR_ERR(folio);
  2990. goto bad_swap_unlock_inode;
  2991. }
  2992. swap_header = kmap_local_folio(folio, 0);
  2993. maxpages = read_swap_header(si, swap_header, inode);
  2994. if (unlikely(!maxpages)) {
  2995. error = -EINVAL;
  2996. goto bad_swap_unlock_inode;
  2997. }
  2998. si->max = maxpages;
  2999. si->pages = maxpages - 1;
  3000. nr_extents = setup_swap_extents(si, &span);
  3001. if (nr_extents < 0) {
  3002. error = nr_extents;
  3003. goto bad_swap_unlock_inode;
  3004. }
  3005. if (si->pages != si->max - 1) {
  3006. pr_err("swap:%u != (max:%u - 1)\n", si->pages, si->max);
  3007. error = -EINVAL;
  3008. goto bad_swap_unlock_inode;
  3009. }
  3010. maxpages = si->max;
  3011. /* OK, set up the swap map and apply the bad block list */
  3012. swap_map = vzalloc(maxpages);
  3013. if (!swap_map) {
  3014. error = -ENOMEM;
  3015. goto bad_swap_unlock_inode;
  3016. }
  3017. error = swap_cgroup_swapon(si->type, maxpages);
  3018. if (error)
  3019. goto bad_swap_unlock_inode;
  3020. error = setup_swap_map(si, swap_header, swap_map, maxpages);
  3021. if (error)
  3022. goto bad_swap_unlock_inode;
  3023. /*
  3024. * Use kvmalloc_array instead of bitmap_zalloc as the allocation order might
  3025. * be above MAX_PAGE_ORDER incase of a large swap file.
  3026. */
  3027. zeromap = kvmalloc_array(BITS_TO_LONGS(maxpages), sizeof(long),
  3028. GFP_KERNEL | __GFP_ZERO);
  3029. if (!zeromap) {
  3030. error = -ENOMEM;
  3031. goto bad_swap_unlock_inode;
  3032. }
  3033. if (si->bdev && bdev_stable_writes(si->bdev))
  3034. si->flags |= SWP_STABLE_WRITES;
  3035. if (si->bdev && bdev_synchronous(si->bdev))
  3036. si->flags |= SWP_SYNCHRONOUS_IO;
  3037. if (si->bdev && bdev_nonrot(si->bdev)) {
  3038. si->flags |= SWP_SOLIDSTATE;
  3039. cluster_info = setup_clusters(si, swap_header, maxpages);
  3040. if (IS_ERR(cluster_info)) {
  3041. error = PTR_ERR(cluster_info);
  3042. cluster_info = NULL;
  3043. goto bad_swap_unlock_inode;
  3044. }
  3045. } else {
  3046. atomic_inc(&nr_rotate_swap);
  3047. inced_nr_rotate_swap = true;
  3048. }
  3049. if ((swap_flags & SWAP_FLAG_DISCARD) &&
  3050. si->bdev && bdev_max_discard_sectors(si->bdev)) {
  3051. /*
  3052. * When discard is enabled for swap with no particular
  3053. * policy flagged, we set all swap discard flags here in
  3054. * order to sustain backward compatibility with older
  3055. * swapon(8) releases.
  3056. */
  3057. si->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
  3058. SWP_PAGE_DISCARD);
  3059. /*
  3060. * By flagging sys_swapon, a sysadmin can tell us to
  3061. * either do single-time area discards only, or to just
  3062. * perform discards for released swap page-clusters.
  3063. * Now it's time to adjust the p->flags accordingly.
  3064. */
  3065. if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
  3066. si->flags &= ~SWP_PAGE_DISCARD;
  3067. else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
  3068. si->flags &= ~SWP_AREA_DISCARD;
  3069. /* issue a swapon-time discard if it's still required */
  3070. if (si->flags & SWP_AREA_DISCARD) {
  3071. int err = discard_swap(si);
  3072. if (unlikely(err))
  3073. pr_err("swapon: discard_swap(%p): %d\n",
  3074. si, err);
  3075. }
  3076. }
  3077. error = init_swap_address_space(si->type, maxpages);
  3078. if (error)
  3079. goto bad_swap_unlock_inode;
  3080. error = zswap_swapon(si->type, maxpages);
  3081. if (error)
  3082. goto free_swap_address_space;
  3083. /*
  3084. * Flush any pending IO and dirty mappings before we start using this
  3085. * swap device.
  3086. */
  3087. inode->i_flags |= S_SWAPFILE;
  3088. error = inode_drain_writes(inode);
  3089. if (error) {
  3090. inode->i_flags &= ~S_SWAPFILE;
  3091. goto free_swap_zswap;
  3092. }
  3093. mutex_lock(&swapon_mutex);
  3094. prio = -1;
  3095. if (swap_flags & SWAP_FLAG_PREFER)
  3096. prio =
  3097. (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
  3098. enable_swap_info(si, prio, swap_map, cluster_info, zeromap);
  3099. pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s\n",
  3100. K(si->pages), name->name, si->prio, nr_extents,
  3101. K((unsigned long long)span),
  3102. (si->flags & SWP_SOLIDSTATE) ? "SS" : "",
  3103. (si->flags & SWP_DISCARDABLE) ? "D" : "",
  3104. (si->flags & SWP_AREA_DISCARD) ? "s" : "",
  3105. (si->flags & SWP_PAGE_DISCARD) ? "c" : "");
  3106. mutex_unlock(&swapon_mutex);
  3107. atomic_inc(&proc_poll_event);
  3108. wake_up_interruptible(&proc_poll_wait);
  3109. error = 0;
  3110. goto out;
  3111. free_swap_zswap:
  3112. zswap_swapoff(si->type);
  3113. free_swap_address_space:
  3114. exit_swap_address_space(si->type);
  3115. bad_swap_unlock_inode:
  3116. inode_unlock(inode);
  3117. bad_swap:
  3118. free_percpu(si->percpu_cluster);
  3119. si->percpu_cluster = NULL;
  3120. free_percpu(si->cluster_next_cpu);
  3121. si->cluster_next_cpu = NULL;
  3122. inode = NULL;
  3123. destroy_swap_extents(si);
  3124. swap_cgroup_swapoff(si->type);
  3125. spin_lock(&swap_lock);
  3126. si->swap_file = NULL;
  3127. si->flags = 0;
  3128. spin_unlock(&swap_lock);
  3129. vfree(swap_map);
  3130. kvfree(zeromap);
  3131. kvfree(cluster_info);
  3132. if (inced_nr_rotate_swap)
  3133. atomic_dec(&nr_rotate_swap);
  3134. if (swap_file)
  3135. filp_close(swap_file, NULL);
  3136. out:
  3137. if (!IS_ERR_OR_NULL(folio))
  3138. folio_release_kmap(folio, swap_header);
  3139. if (name)
  3140. putname(name);
  3141. if (inode)
  3142. inode_unlock(inode);
  3143. if (!error)
  3144. enable_swap_slots_cache();
  3145. return error;
  3146. }
  3147. void si_swapinfo(struct sysinfo *val)
  3148. {
  3149. unsigned int type;
  3150. unsigned long nr_to_be_unused = 0;
  3151. spin_lock(&swap_lock);
  3152. for (type = 0; type < nr_swapfiles; type++) {
  3153. struct swap_info_struct *si = swap_info[type];
  3154. if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
  3155. nr_to_be_unused += READ_ONCE(si->inuse_pages);
  3156. }
  3157. val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
  3158. val->totalswap = total_swap_pages + nr_to_be_unused;
  3159. spin_unlock(&swap_lock);
  3160. }
  3161. /*
  3162. * Verify that nr swap entries are valid and increment their swap map counts.
  3163. *
  3164. * Returns error code in following case.
  3165. * - success -> 0
  3166. * - swp_entry is invalid -> EINVAL
  3167. * - swp_entry is migration entry -> EINVAL
  3168. * - swap-cache reference is requested but there is already one. -> EEXIST
  3169. * - swap-cache reference is requested but the entry is not used. -> ENOENT
  3170. * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
  3171. */
  3172. static int __swap_duplicate(swp_entry_t entry, unsigned char usage, int nr)
  3173. {
  3174. struct swap_info_struct *si;
  3175. struct swap_cluster_info *ci;
  3176. unsigned long offset;
  3177. unsigned char count;
  3178. unsigned char has_cache;
  3179. int err, i;
  3180. si = swp_swap_info(entry);
  3181. offset = swp_offset(entry);
  3182. VM_WARN_ON(nr > SWAPFILE_CLUSTER - offset % SWAPFILE_CLUSTER);
  3183. VM_WARN_ON(usage == 1 && nr > 1);
  3184. ci = lock_cluster_or_swap_info(si, offset);
  3185. err = 0;
  3186. for (i = 0; i < nr; i++) {
  3187. count = si->swap_map[offset + i];
  3188. /*
  3189. * swapin_readahead() doesn't check if a swap entry is valid, so the
  3190. * swap entry could be SWAP_MAP_BAD. Check here with lock held.
  3191. */
  3192. if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
  3193. err = -ENOENT;
  3194. goto unlock_out;
  3195. }
  3196. has_cache = count & SWAP_HAS_CACHE;
  3197. count &= ~SWAP_HAS_CACHE;
  3198. if (!count && !has_cache) {
  3199. err = -ENOENT;
  3200. } else if (usage == SWAP_HAS_CACHE) {
  3201. if (has_cache)
  3202. err = -EEXIST;
  3203. } else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX) {
  3204. err = -EINVAL;
  3205. }
  3206. if (err)
  3207. goto unlock_out;
  3208. }
  3209. for (i = 0; i < nr; i++) {
  3210. count = si->swap_map[offset + i];
  3211. has_cache = count & SWAP_HAS_CACHE;
  3212. count &= ~SWAP_HAS_CACHE;
  3213. if (usage == SWAP_HAS_CACHE)
  3214. has_cache = SWAP_HAS_CACHE;
  3215. else if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
  3216. count += usage;
  3217. else if (swap_count_continued(si, offset + i, count))
  3218. count = COUNT_CONTINUED;
  3219. else {
  3220. /*
  3221. * Don't need to rollback changes, because if
  3222. * usage == 1, there must be nr == 1.
  3223. */
  3224. err = -ENOMEM;
  3225. goto unlock_out;
  3226. }
  3227. WRITE_ONCE(si->swap_map[offset + i], count | has_cache);
  3228. }
  3229. unlock_out:
  3230. unlock_cluster_or_swap_info(si, ci);
  3231. return err;
  3232. }
  3233. /*
  3234. * Help swapoff by noting that swap entry belongs to shmem/tmpfs
  3235. * (in which case its reference count is never incremented).
  3236. */
  3237. void swap_shmem_alloc(swp_entry_t entry, int nr)
  3238. {
  3239. __swap_duplicate(entry, SWAP_MAP_SHMEM, nr);
  3240. }
  3241. /*
  3242. * Increase reference count of swap entry by 1.
  3243. * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
  3244. * but could not be atomically allocated. Returns 0, just as if it succeeded,
  3245. * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
  3246. * might occur if a page table entry has got corrupted.
  3247. */
  3248. int swap_duplicate(swp_entry_t entry)
  3249. {
  3250. int err = 0;
  3251. while (!err && __swap_duplicate(entry, 1, 1) == -ENOMEM)
  3252. err = add_swap_count_continuation(entry, GFP_ATOMIC);
  3253. return err;
  3254. }
  3255. /*
  3256. * @entry: first swap entry from which we allocate nr swap cache.
  3257. *
  3258. * Called when allocating swap cache for existing swap entries,
  3259. * This can return error codes. Returns 0 at success.
  3260. * -EEXIST means there is a swap cache.
  3261. * Note: return code is different from swap_duplicate().
  3262. */
  3263. int swapcache_prepare(swp_entry_t entry, int nr)
  3264. {
  3265. return __swap_duplicate(entry, SWAP_HAS_CACHE, nr);
  3266. }
  3267. void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry, int nr)
  3268. {
  3269. unsigned long offset = swp_offset(entry);
  3270. cluster_swap_free_nr(si, offset, nr, SWAP_HAS_CACHE);
  3271. }
  3272. struct swap_info_struct *swp_swap_info(swp_entry_t entry)
  3273. {
  3274. return swap_type_to_swap_info(swp_type(entry));
  3275. }
  3276. /*
  3277. * out-of-line methods to avoid include hell.
  3278. */
  3279. struct address_space *swapcache_mapping(struct folio *folio)
  3280. {
  3281. return swp_swap_info(folio->swap)->swap_file->f_mapping;
  3282. }
  3283. EXPORT_SYMBOL_GPL(swapcache_mapping);
  3284. pgoff_t __folio_swap_cache_index(struct folio *folio)
  3285. {
  3286. return swap_cache_index(folio->swap);
  3287. }
  3288. EXPORT_SYMBOL_GPL(__folio_swap_cache_index);
  3289. /*
  3290. * add_swap_count_continuation - called when a swap count is duplicated
  3291. * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
  3292. * page of the original vmalloc'ed swap_map, to hold the continuation count
  3293. * (for that entry and for its neighbouring PAGE_SIZE swap entries). Called
  3294. * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
  3295. *
  3296. * These continuation pages are seldom referenced: the common paths all work
  3297. * on the original swap_map, only referring to a continuation page when the
  3298. * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
  3299. *
  3300. * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
  3301. * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
  3302. * can be called after dropping locks.
  3303. */
  3304. int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
  3305. {
  3306. struct swap_info_struct *si;
  3307. struct swap_cluster_info *ci;
  3308. struct page *head;
  3309. struct page *page;
  3310. struct page *list_page;
  3311. pgoff_t offset;
  3312. unsigned char count;
  3313. int ret = 0;
  3314. /*
  3315. * When debugging, it's easier to use __GFP_ZERO here; but it's better
  3316. * for latency not to zero a page while GFP_ATOMIC and holding locks.
  3317. */
  3318. page = alloc_page(gfp_mask | __GFP_HIGHMEM);
  3319. si = get_swap_device(entry);
  3320. if (!si) {
  3321. /*
  3322. * An acceptable race has occurred since the failing
  3323. * __swap_duplicate(): the swap device may be swapoff
  3324. */
  3325. goto outer;
  3326. }
  3327. spin_lock(&si->lock);
  3328. offset = swp_offset(entry);
  3329. ci = lock_cluster(si, offset);
  3330. count = swap_count(si->swap_map[offset]);
  3331. if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
  3332. /*
  3333. * The higher the swap count, the more likely it is that tasks
  3334. * will race to add swap count continuation: we need to avoid
  3335. * over-provisioning.
  3336. */
  3337. goto out;
  3338. }
  3339. if (!page) {
  3340. ret = -ENOMEM;
  3341. goto out;
  3342. }
  3343. head = vmalloc_to_page(si->swap_map + offset);
  3344. offset &= ~PAGE_MASK;
  3345. spin_lock(&si->cont_lock);
  3346. /*
  3347. * Page allocation does not initialize the page's lru field,
  3348. * but it does always reset its private field.
  3349. */
  3350. if (!page_private(head)) {
  3351. BUG_ON(count & COUNT_CONTINUED);
  3352. INIT_LIST_HEAD(&head->lru);
  3353. set_page_private(head, SWP_CONTINUED);
  3354. si->flags |= SWP_CONTINUED;
  3355. }
  3356. list_for_each_entry(list_page, &head->lru, lru) {
  3357. unsigned char *map;
  3358. /*
  3359. * If the previous map said no continuation, but we've found
  3360. * a continuation page, free our allocation and use this one.
  3361. */
  3362. if (!(count & COUNT_CONTINUED))
  3363. goto out_unlock_cont;
  3364. map = kmap_local_page(list_page) + offset;
  3365. count = *map;
  3366. kunmap_local(map);
  3367. /*
  3368. * If this continuation count now has some space in it,
  3369. * free our allocation and use this one.
  3370. */
  3371. if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
  3372. goto out_unlock_cont;
  3373. }
  3374. list_add_tail(&page->lru, &head->lru);
  3375. page = NULL; /* now it's attached, don't free it */
  3376. out_unlock_cont:
  3377. spin_unlock(&si->cont_lock);
  3378. out:
  3379. unlock_cluster(ci);
  3380. spin_unlock(&si->lock);
  3381. put_swap_device(si);
  3382. outer:
  3383. if (page)
  3384. __free_page(page);
  3385. return ret;
  3386. }
  3387. /*
  3388. * swap_count_continued - when the original swap_map count is incremented
  3389. * from SWAP_MAP_MAX, check if there is already a continuation page to carry
  3390. * into, carry if so, or else fail until a new continuation page is allocated;
  3391. * when the original swap_map count is decremented from 0 with continuation,
  3392. * borrow from the continuation and report whether it still holds more.
  3393. * Called while __swap_duplicate() or swap_entry_free() holds swap or cluster
  3394. * lock.
  3395. */
  3396. static bool swap_count_continued(struct swap_info_struct *si,
  3397. pgoff_t offset, unsigned char count)
  3398. {
  3399. struct page *head;
  3400. struct page *page;
  3401. unsigned char *map;
  3402. bool ret;
  3403. head = vmalloc_to_page(si->swap_map + offset);
  3404. if (page_private(head) != SWP_CONTINUED) {
  3405. BUG_ON(count & COUNT_CONTINUED);
  3406. return false; /* need to add count continuation */
  3407. }
  3408. spin_lock(&si->cont_lock);
  3409. offset &= ~PAGE_MASK;
  3410. page = list_next_entry(head, lru);
  3411. map = kmap_local_page(page) + offset;
  3412. if (count == SWAP_MAP_MAX) /* initial increment from swap_map */
  3413. goto init_map; /* jump over SWAP_CONT_MAX checks */
  3414. if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
  3415. /*
  3416. * Think of how you add 1 to 999
  3417. */
  3418. while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
  3419. kunmap_local(map);
  3420. page = list_next_entry(page, lru);
  3421. BUG_ON(page == head);
  3422. map = kmap_local_page(page) + offset;
  3423. }
  3424. if (*map == SWAP_CONT_MAX) {
  3425. kunmap_local(map);
  3426. page = list_next_entry(page, lru);
  3427. if (page == head) {
  3428. ret = false; /* add count continuation */
  3429. goto out;
  3430. }
  3431. map = kmap_local_page(page) + offset;
  3432. init_map: *map = 0; /* we didn't zero the page */
  3433. }
  3434. *map += 1;
  3435. kunmap_local(map);
  3436. while ((page = list_prev_entry(page, lru)) != head) {
  3437. map = kmap_local_page(page) + offset;
  3438. *map = COUNT_CONTINUED;
  3439. kunmap_local(map);
  3440. }
  3441. ret = true; /* incremented */
  3442. } else { /* decrementing */
  3443. /*
  3444. * Think of how you subtract 1 from 1000
  3445. */
  3446. BUG_ON(count != COUNT_CONTINUED);
  3447. while (*map == COUNT_CONTINUED) {
  3448. kunmap_local(map);
  3449. page = list_next_entry(page, lru);
  3450. BUG_ON(page == head);
  3451. map = kmap_local_page(page) + offset;
  3452. }
  3453. BUG_ON(*map == 0);
  3454. *map -= 1;
  3455. if (*map == 0)
  3456. count = 0;
  3457. kunmap_local(map);
  3458. while ((page = list_prev_entry(page, lru)) != head) {
  3459. map = kmap_local_page(page) + offset;
  3460. *map = SWAP_CONT_MAX | count;
  3461. count = COUNT_CONTINUED;
  3462. kunmap_local(map);
  3463. }
  3464. ret = count == COUNT_CONTINUED;
  3465. }
  3466. out:
  3467. spin_unlock(&si->cont_lock);
  3468. return ret;
  3469. }
  3470. /*
  3471. * free_swap_count_continuations - swapoff free all the continuation pages
  3472. * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
  3473. */
  3474. static void free_swap_count_continuations(struct swap_info_struct *si)
  3475. {
  3476. pgoff_t offset;
  3477. for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
  3478. struct page *head;
  3479. head = vmalloc_to_page(si->swap_map + offset);
  3480. if (page_private(head)) {
  3481. struct page *page, *next;
  3482. list_for_each_entry_safe(page, next, &head->lru, lru) {
  3483. list_del(&page->lru);
  3484. __free_page(page);
  3485. }
  3486. }
  3487. }
  3488. }
  3489. #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
  3490. void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
  3491. {
  3492. struct swap_info_struct *si, *next;
  3493. int nid = folio_nid(folio);
  3494. if (!(gfp & __GFP_IO))
  3495. return;
  3496. if (!__has_usable_swap())
  3497. return;
  3498. if (!blk_cgroup_congested())
  3499. return;
  3500. /*
  3501. * We've already scheduled a throttle, avoid taking the global swap
  3502. * lock.
  3503. */
  3504. if (current->throttle_disk)
  3505. return;
  3506. spin_lock(&swap_avail_lock);
  3507. plist_for_each_entry_safe(si, next, &swap_avail_heads[nid],
  3508. avail_lists[nid]) {
  3509. if (si->bdev) {
  3510. blkcg_schedule_throttle(si->bdev->bd_disk, true);
  3511. break;
  3512. }
  3513. }
  3514. spin_unlock(&swap_avail_lock);
  3515. }
  3516. #endif
  3517. static int __init swapfile_init(void)
  3518. {
  3519. int nid;
  3520. swap_avail_heads = kmalloc_array(nr_node_ids, sizeof(struct plist_head),
  3521. GFP_KERNEL);
  3522. if (!swap_avail_heads) {
  3523. pr_emerg("Not enough memory for swap heads, swap is disabled\n");
  3524. return -ENOMEM;
  3525. }
  3526. for_each_node(nid)
  3527. plist_head_init(&swap_avail_heads[nid]);
  3528. swapfile_maximum_size = arch_max_swapfile_size();
  3529. #ifdef CONFIG_MIGRATION
  3530. if (swapfile_maximum_size >= (1UL << SWP_MIG_TOTAL_BITS))
  3531. swap_migration_ad_supported = true;
  3532. #endif /* CONFIG_MIGRATION */
  3533. return 0;
  3534. }
  3535. subsys_initcall(swapfile_init);