swapfile.c 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063
  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. for_each_vma(vmi, vma) {
  2030. if (vma->anon_vma && !is_vm_hugetlb_page(vma)) {
  2031. ret = unuse_vma(vma, type);
  2032. if (ret)
  2033. break;
  2034. }
  2035. cond_resched();
  2036. }
  2037. mmap_read_unlock(mm);
  2038. return ret;
  2039. }
  2040. /*
  2041. * Scan swap_map from current position to next entry still in use.
  2042. * Return 0 if there are no inuse entries after prev till end of
  2043. * the map.
  2044. */
  2045. static unsigned int find_next_to_unuse(struct swap_info_struct *si,
  2046. unsigned int prev)
  2047. {
  2048. unsigned int i;
  2049. unsigned char count;
  2050. /*
  2051. * No need for swap_lock here: we're just looking
  2052. * for whether an entry is in use, not modifying it; false
  2053. * hits are okay, and sys_swapoff() has already prevented new
  2054. * allocations from this area (while holding swap_lock).
  2055. */
  2056. for (i = prev + 1; i < si->max; i++) {
  2057. count = READ_ONCE(si->swap_map[i]);
  2058. if (count && swap_count(count) != SWAP_MAP_BAD)
  2059. break;
  2060. if ((i % LATENCY_LIMIT) == 0)
  2061. cond_resched();
  2062. }
  2063. if (i == si->max)
  2064. i = 0;
  2065. return i;
  2066. }
  2067. static int try_to_unuse(unsigned int type)
  2068. {
  2069. struct mm_struct *prev_mm;
  2070. struct mm_struct *mm;
  2071. struct list_head *p;
  2072. int retval = 0;
  2073. struct swap_info_struct *si = swap_info[type];
  2074. struct folio *folio;
  2075. swp_entry_t entry;
  2076. unsigned int i;
  2077. if (!READ_ONCE(si->inuse_pages))
  2078. goto success;
  2079. retry:
  2080. retval = shmem_unuse(type);
  2081. if (retval)
  2082. return retval;
  2083. prev_mm = &init_mm;
  2084. mmget(prev_mm);
  2085. spin_lock(&mmlist_lock);
  2086. p = &init_mm.mmlist;
  2087. while (READ_ONCE(si->inuse_pages) &&
  2088. !signal_pending(current) &&
  2089. (p = p->next) != &init_mm.mmlist) {
  2090. mm = list_entry(p, struct mm_struct, mmlist);
  2091. if (!mmget_not_zero(mm))
  2092. continue;
  2093. spin_unlock(&mmlist_lock);
  2094. mmput(prev_mm);
  2095. prev_mm = mm;
  2096. retval = unuse_mm(mm, type);
  2097. if (retval) {
  2098. mmput(prev_mm);
  2099. return retval;
  2100. }
  2101. /*
  2102. * Make sure that we aren't completely killing
  2103. * interactive performance.
  2104. */
  2105. cond_resched();
  2106. spin_lock(&mmlist_lock);
  2107. }
  2108. spin_unlock(&mmlist_lock);
  2109. mmput(prev_mm);
  2110. i = 0;
  2111. while (READ_ONCE(si->inuse_pages) &&
  2112. !signal_pending(current) &&
  2113. (i = find_next_to_unuse(si, i)) != 0) {
  2114. entry = swp_entry(type, i);
  2115. folio = filemap_get_folio(swap_address_space(entry), swap_cache_index(entry));
  2116. if (IS_ERR(folio))
  2117. continue;
  2118. /*
  2119. * It is conceivable that a racing task removed this folio from
  2120. * swap cache just before we acquired the page lock. The folio
  2121. * might even be back in swap cache on another swap area. But
  2122. * that is okay, folio_free_swap() only removes stale folios.
  2123. */
  2124. folio_lock(folio);
  2125. folio_wait_writeback(folio);
  2126. folio_free_swap(folio);
  2127. folio_unlock(folio);
  2128. folio_put(folio);
  2129. }
  2130. /*
  2131. * Lets check again to see if there are still swap entries in the map.
  2132. * If yes, we would need to do retry the unuse logic again.
  2133. * Under global memory pressure, swap entries can be reinserted back
  2134. * into process space after the mmlist loop above passes over them.
  2135. *
  2136. * Limit the number of retries? No: when mmget_not_zero()
  2137. * above fails, that mm is likely to be freeing swap from
  2138. * exit_mmap(), which proceeds at its own independent pace;
  2139. * and even shmem_writepage() could have been preempted after
  2140. * folio_alloc_swap(), temporarily hiding that swap. It's easy
  2141. * and robust (though cpu-intensive) just to keep retrying.
  2142. */
  2143. if (READ_ONCE(si->inuse_pages)) {
  2144. if (!signal_pending(current))
  2145. goto retry;
  2146. return -EINTR;
  2147. }
  2148. success:
  2149. /*
  2150. * Make sure that further cleanups after try_to_unuse() returns happen
  2151. * after swap_range_free() reduces si->inuse_pages to 0.
  2152. */
  2153. smp_mb();
  2154. return 0;
  2155. }
  2156. /*
  2157. * After a successful try_to_unuse, if no swap is now in use, we know
  2158. * we can empty the mmlist. swap_lock must be held on entry and exit.
  2159. * Note that mmlist_lock nests inside swap_lock, and an mm must be
  2160. * added to the mmlist just after page_duplicate - before would be racy.
  2161. */
  2162. static void drain_mmlist(void)
  2163. {
  2164. struct list_head *p, *next;
  2165. unsigned int type;
  2166. for (type = 0; type < nr_swapfiles; type++)
  2167. if (swap_info[type]->inuse_pages)
  2168. return;
  2169. spin_lock(&mmlist_lock);
  2170. list_for_each_safe(p, next, &init_mm.mmlist)
  2171. list_del_init(p);
  2172. spin_unlock(&mmlist_lock);
  2173. }
  2174. /*
  2175. * Free all of a swapdev's extent information
  2176. */
  2177. static void destroy_swap_extents(struct swap_info_struct *sis)
  2178. {
  2179. while (!RB_EMPTY_ROOT(&sis->swap_extent_root)) {
  2180. struct rb_node *rb = sis->swap_extent_root.rb_node;
  2181. struct swap_extent *se = rb_entry(rb, struct swap_extent, rb_node);
  2182. rb_erase(rb, &sis->swap_extent_root);
  2183. kfree(se);
  2184. }
  2185. if (sis->flags & SWP_ACTIVATED) {
  2186. struct file *swap_file = sis->swap_file;
  2187. struct address_space *mapping = swap_file->f_mapping;
  2188. sis->flags &= ~SWP_ACTIVATED;
  2189. if (mapping->a_ops->swap_deactivate)
  2190. mapping->a_ops->swap_deactivate(swap_file);
  2191. }
  2192. }
  2193. /*
  2194. * Add a block range (and the corresponding page range) into this swapdev's
  2195. * extent tree.
  2196. *
  2197. * This function rather assumes that it is called in ascending page order.
  2198. */
  2199. int
  2200. add_swap_extent(struct swap_info_struct *sis, unsigned long start_page,
  2201. unsigned long nr_pages, sector_t start_block)
  2202. {
  2203. struct rb_node **link = &sis->swap_extent_root.rb_node, *parent = NULL;
  2204. struct swap_extent *se;
  2205. struct swap_extent *new_se;
  2206. /*
  2207. * place the new node at the right most since the
  2208. * function is called in ascending page order.
  2209. */
  2210. while (*link) {
  2211. parent = *link;
  2212. link = &parent->rb_right;
  2213. }
  2214. if (parent) {
  2215. se = rb_entry(parent, struct swap_extent, rb_node);
  2216. BUG_ON(se->start_page + se->nr_pages != start_page);
  2217. if (se->start_block + se->nr_pages == start_block) {
  2218. /* Merge it */
  2219. se->nr_pages += nr_pages;
  2220. return 0;
  2221. }
  2222. }
  2223. /* No merge, insert a new extent. */
  2224. new_se = kmalloc(sizeof(*se), GFP_KERNEL);
  2225. if (new_se == NULL)
  2226. return -ENOMEM;
  2227. new_se->start_page = start_page;
  2228. new_se->nr_pages = nr_pages;
  2229. new_se->start_block = start_block;
  2230. rb_link_node(&new_se->rb_node, parent, link);
  2231. rb_insert_color(&new_se->rb_node, &sis->swap_extent_root);
  2232. return 1;
  2233. }
  2234. EXPORT_SYMBOL_GPL(add_swap_extent);
  2235. /*
  2236. * A `swap extent' is a simple thing which maps a contiguous range of pages
  2237. * onto a contiguous range of disk blocks. A rbtree of swap extents is
  2238. * built at swapon time and is then used at swap_writepage/swap_read_folio
  2239. * time for locating where on disk a page belongs.
  2240. *
  2241. * If the swapfile is an S_ISBLK block device, a single extent is installed.
  2242. * This is done so that the main operating code can treat S_ISBLK and S_ISREG
  2243. * swap files identically.
  2244. *
  2245. * Whether the swapdev is an S_ISREG file or an S_ISBLK blockdev, the swap
  2246. * extent rbtree operates in PAGE_SIZE disk blocks. Both S_ISREG and S_ISBLK
  2247. * swapfiles are handled *identically* after swapon time.
  2248. *
  2249. * For S_ISREG swapfiles, setup_swap_extents() will walk all the file's blocks
  2250. * and will parse them into a rbtree, in PAGE_SIZE chunks. If some stray
  2251. * blocks are found which do not fall within the PAGE_SIZE alignment
  2252. * requirements, they are simply tossed out - we will never use those blocks
  2253. * for swapping.
  2254. *
  2255. * For all swap devices we set S_SWAPFILE across the life of the swapon. This
  2256. * prevents users from writing to the swap device, which will corrupt memory.
  2257. *
  2258. * The amount of disk space which a single swap extent represents varies.
  2259. * Typically it is in the 1-4 megabyte range. So we can have hundreds of
  2260. * extents in the rbtree. - akpm.
  2261. */
  2262. static int setup_swap_extents(struct swap_info_struct *sis, sector_t *span)
  2263. {
  2264. struct file *swap_file = sis->swap_file;
  2265. struct address_space *mapping = swap_file->f_mapping;
  2266. struct inode *inode = mapping->host;
  2267. int ret;
  2268. if (S_ISBLK(inode->i_mode)) {
  2269. ret = add_swap_extent(sis, 0, sis->max, 0);
  2270. *span = sis->pages;
  2271. return ret;
  2272. }
  2273. if (mapping->a_ops->swap_activate) {
  2274. ret = mapping->a_ops->swap_activate(sis, swap_file, span);
  2275. if (ret < 0)
  2276. return ret;
  2277. sis->flags |= SWP_ACTIVATED;
  2278. if ((sis->flags & SWP_FS_OPS) &&
  2279. sio_pool_init() != 0) {
  2280. destroy_swap_extents(sis);
  2281. return -ENOMEM;
  2282. }
  2283. return ret;
  2284. }
  2285. return generic_swapfile_activate(sis, swap_file, span);
  2286. }
  2287. static int swap_node(struct swap_info_struct *si)
  2288. {
  2289. struct block_device *bdev;
  2290. if (si->bdev)
  2291. bdev = si->bdev;
  2292. else
  2293. bdev = si->swap_file->f_inode->i_sb->s_bdev;
  2294. return bdev ? bdev->bd_disk->node_id : NUMA_NO_NODE;
  2295. }
  2296. static void setup_swap_info(struct swap_info_struct *si, int prio,
  2297. unsigned char *swap_map,
  2298. struct swap_cluster_info *cluster_info,
  2299. unsigned long *zeromap)
  2300. {
  2301. int i;
  2302. if (prio >= 0)
  2303. si->prio = prio;
  2304. else
  2305. si->prio = --least_priority;
  2306. /*
  2307. * the plist prio is negated because plist ordering is
  2308. * low-to-high, while swap ordering is high-to-low
  2309. */
  2310. si->list.prio = -si->prio;
  2311. for_each_node(i) {
  2312. if (si->prio >= 0)
  2313. si->avail_lists[i].prio = -si->prio;
  2314. else {
  2315. if (swap_node(si) == i)
  2316. si->avail_lists[i].prio = 1;
  2317. else
  2318. si->avail_lists[i].prio = -si->prio;
  2319. }
  2320. }
  2321. si->swap_map = swap_map;
  2322. si->cluster_info = cluster_info;
  2323. si->zeromap = zeromap;
  2324. }
  2325. static void _enable_swap_info(struct swap_info_struct *si)
  2326. {
  2327. si->flags |= SWP_WRITEOK;
  2328. atomic_long_add(si->pages, &nr_swap_pages);
  2329. total_swap_pages += si->pages;
  2330. assert_spin_locked(&swap_lock);
  2331. /*
  2332. * both lists are plists, and thus priority ordered.
  2333. * swap_active_head needs to be priority ordered for swapoff(),
  2334. * which on removal of any swap_info_struct with an auto-assigned
  2335. * (i.e. negative) priority increments the auto-assigned priority
  2336. * of any lower-priority swap_info_structs.
  2337. * swap_avail_head needs to be priority ordered for folio_alloc_swap(),
  2338. * which allocates swap pages from the highest available priority
  2339. * swap_info_struct.
  2340. */
  2341. plist_add(&si->list, &swap_active_head);
  2342. /* add to available list iff swap device is not full */
  2343. if (si->highest_bit)
  2344. add_to_avail_list(si);
  2345. }
  2346. static void enable_swap_info(struct swap_info_struct *si, int prio,
  2347. unsigned char *swap_map,
  2348. struct swap_cluster_info *cluster_info,
  2349. unsigned long *zeromap)
  2350. {
  2351. spin_lock(&swap_lock);
  2352. spin_lock(&si->lock);
  2353. setup_swap_info(si, prio, swap_map, cluster_info, zeromap);
  2354. spin_unlock(&si->lock);
  2355. spin_unlock(&swap_lock);
  2356. /*
  2357. * Finished initializing swap device, now it's safe to reference it.
  2358. */
  2359. percpu_ref_resurrect(&si->users);
  2360. spin_lock(&swap_lock);
  2361. spin_lock(&si->lock);
  2362. _enable_swap_info(si);
  2363. spin_unlock(&si->lock);
  2364. spin_unlock(&swap_lock);
  2365. }
  2366. static void reinsert_swap_info(struct swap_info_struct *si)
  2367. {
  2368. spin_lock(&swap_lock);
  2369. spin_lock(&si->lock);
  2370. setup_swap_info(si, si->prio, si->swap_map, si->cluster_info, si->zeromap);
  2371. _enable_swap_info(si);
  2372. spin_unlock(&si->lock);
  2373. spin_unlock(&swap_lock);
  2374. }
  2375. static bool __has_usable_swap(void)
  2376. {
  2377. return !plist_head_empty(&swap_active_head);
  2378. }
  2379. bool has_usable_swap(void)
  2380. {
  2381. bool ret;
  2382. spin_lock(&swap_lock);
  2383. ret = __has_usable_swap();
  2384. spin_unlock(&swap_lock);
  2385. return ret;
  2386. }
  2387. SYSCALL_DEFINE1(swapoff, const char __user *, specialfile)
  2388. {
  2389. struct swap_info_struct *p = NULL;
  2390. unsigned char *swap_map;
  2391. unsigned long *zeromap;
  2392. struct swap_cluster_info *cluster_info;
  2393. struct file *swap_file, *victim;
  2394. struct address_space *mapping;
  2395. struct inode *inode;
  2396. struct filename *pathname;
  2397. int err, found = 0;
  2398. if (!capable(CAP_SYS_ADMIN))
  2399. return -EPERM;
  2400. BUG_ON(!current->mm);
  2401. pathname = getname(specialfile);
  2402. if (IS_ERR(pathname))
  2403. return PTR_ERR(pathname);
  2404. victim = file_open_name(pathname, O_RDWR|O_LARGEFILE, 0);
  2405. err = PTR_ERR(victim);
  2406. if (IS_ERR(victim))
  2407. goto out;
  2408. mapping = victim->f_mapping;
  2409. spin_lock(&swap_lock);
  2410. plist_for_each_entry(p, &swap_active_head, list) {
  2411. if (p->flags & SWP_WRITEOK) {
  2412. if (p->swap_file->f_mapping == mapping) {
  2413. found = 1;
  2414. break;
  2415. }
  2416. }
  2417. }
  2418. if (!found) {
  2419. err = -EINVAL;
  2420. spin_unlock(&swap_lock);
  2421. goto out_dput;
  2422. }
  2423. if (!security_vm_enough_memory_mm(current->mm, p->pages))
  2424. vm_unacct_memory(p->pages);
  2425. else {
  2426. err = -ENOMEM;
  2427. spin_unlock(&swap_lock);
  2428. goto out_dput;
  2429. }
  2430. spin_lock(&p->lock);
  2431. del_from_avail_list(p);
  2432. if (p->prio < 0) {
  2433. struct swap_info_struct *si = p;
  2434. int nid;
  2435. plist_for_each_entry_continue(si, &swap_active_head, list) {
  2436. si->prio++;
  2437. si->list.prio--;
  2438. for_each_node(nid) {
  2439. if (si->avail_lists[nid].prio != 1)
  2440. si->avail_lists[nid].prio--;
  2441. }
  2442. }
  2443. least_priority++;
  2444. }
  2445. plist_del(&p->list, &swap_active_head);
  2446. atomic_long_sub(p->pages, &nr_swap_pages);
  2447. total_swap_pages -= p->pages;
  2448. p->flags &= ~SWP_WRITEOK;
  2449. spin_unlock(&p->lock);
  2450. spin_unlock(&swap_lock);
  2451. disable_swap_slots_cache_lock();
  2452. set_current_oom_origin();
  2453. err = try_to_unuse(p->type);
  2454. clear_current_oom_origin();
  2455. if (err) {
  2456. /* re-insert swap space back into swap_list */
  2457. reinsert_swap_info(p);
  2458. reenable_swap_slots_cache_unlock();
  2459. goto out_dput;
  2460. }
  2461. reenable_swap_slots_cache_unlock();
  2462. /*
  2463. * Wait for swap operations protected by get/put_swap_device()
  2464. * to complete. Because of synchronize_rcu() here, all swap
  2465. * operations protected by RCU reader side lock (including any
  2466. * spinlock) will be waited too. This makes it easy to
  2467. * prevent folio_test_swapcache() and the following swap cache
  2468. * operations from racing with swapoff.
  2469. */
  2470. percpu_ref_kill(&p->users);
  2471. synchronize_rcu();
  2472. wait_for_completion(&p->comp);
  2473. flush_work(&p->discard_work);
  2474. flush_work(&p->reclaim_work);
  2475. destroy_swap_extents(p);
  2476. if (p->flags & SWP_CONTINUED)
  2477. free_swap_count_continuations(p);
  2478. if (!p->bdev || !bdev_nonrot(p->bdev))
  2479. atomic_dec(&nr_rotate_swap);
  2480. mutex_lock(&swapon_mutex);
  2481. spin_lock(&swap_lock);
  2482. spin_lock(&p->lock);
  2483. drain_mmlist();
  2484. /* wait for anyone still in scan_swap_map_slots */
  2485. p->highest_bit = 0; /* cuts scans short */
  2486. while (p->flags >= SWP_SCANNING) {
  2487. spin_unlock(&p->lock);
  2488. spin_unlock(&swap_lock);
  2489. schedule_timeout_uninterruptible(1);
  2490. spin_lock(&swap_lock);
  2491. spin_lock(&p->lock);
  2492. }
  2493. swap_file = p->swap_file;
  2494. p->swap_file = NULL;
  2495. p->max = 0;
  2496. swap_map = p->swap_map;
  2497. p->swap_map = NULL;
  2498. zeromap = p->zeromap;
  2499. p->zeromap = NULL;
  2500. cluster_info = p->cluster_info;
  2501. p->cluster_info = NULL;
  2502. spin_unlock(&p->lock);
  2503. spin_unlock(&swap_lock);
  2504. arch_swap_invalidate_area(p->type);
  2505. zswap_swapoff(p->type);
  2506. mutex_unlock(&swapon_mutex);
  2507. free_percpu(p->percpu_cluster);
  2508. p->percpu_cluster = NULL;
  2509. free_percpu(p->cluster_next_cpu);
  2510. p->cluster_next_cpu = NULL;
  2511. vfree(swap_map);
  2512. kvfree(zeromap);
  2513. kvfree(cluster_info);
  2514. /* Destroy swap account information */
  2515. swap_cgroup_swapoff(p->type);
  2516. exit_swap_address_space(p->type);
  2517. inode = mapping->host;
  2518. inode_lock(inode);
  2519. inode->i_flags &= ~S_SWAPFILE;
  2520. inode_unlock(inode);
  2521. filp_close(swap_file, NULL);
  2522. /*
  2523. * Clear the SWP_USED flag after all resources are freed so that swapon
  2524. * can reuse this swap_info in alloc_swap_info() safely. It is ok to
  2525. * not hold p->lock after we cleared its SWP_WRITEOK.
  2526. */
  2527. spin_lock(&swap_lock);
  2528. p->flags = 0;
  2529. spin_unlock(&swap_lock);
  2530. err = 0;
  2531. atomic_inc(&proc_poll_event);
  2532. wake_up_interruptible(&proc_poll_wait);
  2533. out_dput:
  2534. filp_close(victim, NULL);
  2535. out:
  2536. putname(pathname);
  2537. return err;
  2538. }
  2539. #ifdef CONFIG_PROC_FS
  2540. static __poll_t swaps_poll(struct file *file, poll_table *wait)
  2541. {
  2542. struct seq_file *seq = file->private_data;
  2543. poll_wait(file, &proc_poll_wait, wait);
  2544. if (seq->poll_event != atomic_read(&proc_poll_event)) {
  2545. seq->poll_event = atomic_read(&proc_poll_event);
  2546. return EPOLLIN | EPOLLRDNORM | EPOLLERR | EPOLLPRI;
  2547. }
  2548. return EPOLLIN | EPOLLRDNORM;
  2549. }
  2550. /* iterator */
  2551. static void *swap_start(struct seq_file *swap, loff_t *pos)
  2552. {
  2553. struct swap_info_struct *si;
  2554. int type;
  2555. loff_t l = *pos;
  2556. mutex_lock(&swapon_mutex);
  2557. if (!l)
  2558. return SEQ_START_TOKEN;
  2559. for (type = 0; (si = swap_type_to_swap_info(type)); type++) {
  2560. if (!(si->flags & SWP_USED) || !si->swap_map)
  2561. continue;
  2562. if (!--l)
  2563. return si;
  2564. }
  2565. return NULL;
  2566. }
  2567. static void *swap_next(struct seq_file *swap, void *v, loff_t *pos)
  2568. {
  2569. struct swap_info_struct *si = v;
  2570. int type;
  2571. if (v == SEQ_START_TOKEN)
  2572. type = 0;
  2573. else
  2574. type = si->type + 1;
  2575. ++(*pos);
  2576. for (; (si = swap_type_to_swap_info(type)); type++) {
  2577. if (!(si->flags & SWP_USED) || !si->swap_map)
  2578. continue;
  2579. return si;
  2580. }
  2581. return NULL;
  2582. }
  2583. static void swap_stop(struct seq_file *swap, void *v)
  2584. {
  2585. mutex_unlock(&swapon_mutex);
  2586. }
  2587. static int swap_show(struct seq_file *swap, void *v)
  2588. {
  2589. struct swap_info_struct *si = v;
  2590. struct file *file;
  2591. int len;
  2592. unsigned long bytes, inuse;
  2593. if (si == SEQ_START_TOKEN) {
  2594. seq_puts(swap, "Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n");
  2595. return 0;
  2596. }
  2597. bytes = K(si->pages);
  2598. inuse = K(READ_ONCE(si->inuse_pages));
  2599. file = si->swap_file;
  2600. len = seq_file_path(swap, file, " \t\n\\");
  2601. seq_printf(swap, "%*s%s\t%lu\t%s%lu\t%s%d\n",
  2602. len < 40 ? 40 - len : 1, " ",
  2603. S_ISBLK(file_inode(file)->i_mode) ?
  2604. "partition" : "file\t",
  2605. bytes, bytes < 10000000 ? "\t" : "",
  2606. inuse, inuse < 10000000 ? "\t" : "",
  2607. si->prio);
  2608. return 0;
  2609. }
  2610. static const struct seq_operations swaps_op = {
  2611. .start = swap_start,
  2612. .next = swap_next,
  2613. .stop = swap_stop,
  2614. .show = swap_show
  2615. };
  2616. static int swaps_open(struct inode *inode, struct file *file)
  2617. {
  2618. struct seq_file *seq;
  2619. int ret;
  2620. ret = seq_open(file, &swaps_op);
  2621. if (ret)
  2622. return ret;
  2623. seq = file->private_data;
  2624. seq->poll_event = atomic_read(&proc_poll_event);
  2625. return 0;
  2626. }
  2627. static const struct proc_ops swaps_proc_ops = {
  2628. .proc_flags = PROC_ENTRY_PERMANENT,
  2629. .proc_open = swaps_open,
  2630. .proc_read = seq_read,
  2631. .proc_lseek = seq_lseek,
  2632. .proc_release = seq_release,
  2633. .proc_poll = swaps_poll,
  2634. };
  2635. static int __init procswaps_init(void)
  2636. {
  2637. proc_create("swaps", 0, NULL, &swaps_proc_ops);
  2638. return 0;
  2639. }
  2640. __initcall(procswaps_init);
  2641. #endif /* CONFIG_PROC_FS */
  2642. #ifdef MAX_SWAPFILES_CHECK
  2643. static int __init max_swapfiles_check(void)
  2644. {
  2645. MAX_SWAPFILES_CHECK();
  2646. return 0;
  2647. }
  2648. late_initcall(max_swapfiles_check);
  2649. #endif
  2650. static struct swap_info_struct *alloc_swap_info(void)
  2651. {
  2652. struct swap_info_struct *p;
  2653. struct swap_info_struct *defer = NULL;
  2654. unsigned int type;
  2655. int i;
  2656. p = kvzalloc(struct_size(p, avail_lists, nr_node_ids), GFP_KERNEL);
  2657. if (!p)
  2658. return ERR_PTR(-ENOMEM);
  2659. if (percpu_ref_init(&p->users, swap_users_ref_free,
  2660. PERCPU_REF_INIT_DEAD, GFP_KERNEL)) {
  2661. kvfree(p);
  2662. return ERR_PTR(-ENOMEM);
  2663. }
  2664. spin_lock(&swap_lock);
  2665. for (type = 0; type < nr_swapfiles; type++) {
  2666. if (!(swap_info[type]->flags & SWP_USED))
  2667. break;
  2668. }
  2669. if (type >= MAX_SWAPFILES) {
  2670. spin_unlock(&swap_lock);
  2671. percpu_ref_exit(&p->users);
  2672. kvfree(p);
  2673. return ERR_PTR(-EPERM);
  2674. }
  2675. if (type >= nr_swapfiles) {
  2676. p->type = type;
  2677. /*
  2678. * Publish the swap_info_struct after initializing it.
  2679. * Note that kvzalloc() above zeroes all its fields.
  2680. */
  2681. smp_store_release(&swap_info[type], p); /* rcu_assign_pointer() */
  2682. nr_swapfiles++;
  2683. } else {
  2684. defer = p;
  2685. p = swap_info[type];
  2686. /*
  2687. * Do not memset this entry: a racing procfs swap_next()
  2688. * would be relying on p->type to remain valid.
  2689. */
  2690. }
  2691. p->swap_extent_root = RB_ROOT;
  2692. plist_node_init(&p->list, 0);
  2693. for_each_node(i)
  2694. plist_node_init(&p->avail_lists[i], 0);
  2695. p->flags = SWP_USED;
  2696. spin_unlock(&swap_lock);
  2697. if (defer) {
  2698. percpu_ref_exit(&defer->users);
  2699. kvfree(defer);
  2700. }
  2701. spin_lock_init(&p->lock);
  2702. spin_lock_init(&p->cont_lock);
  2703. init_completion(&p->comp);
  2704. return p;
  2705. }
  2706. static int claim_swapfile(struct swap_info_struct *si, struct inode *inode)
  2707. {
  2708. if (S_ISBLK(inode->i_mode)) {
  2709. si->bdev = I_BDEV(inode);
  2710. /*
  2711. * Zoned block devices contain zones that have a sequential
  2712. * write only restriction. Hence zoned block devices are not
  2713. * suitable for swapping. Disallow them here.
  2714. */
  2715. if (bdev_is_zoned(si->bdev))
  2716. return -EINVAL;
  2717. si->flags |= SWP_BLKDEV;
  2718. } else if (S_ISREG(inode->i_mode)) {
  2719. si->bdev = inode->i_sb->s_bdev;
  2720. }
  2721. return 0;
  2722. }
  2723. /*
  2724. * Find out how many pages are allowed for a single swap device. There
  2725. * are two limiting factors:
  2726. * 1) the number of bits for the swap offset in the swp_entry_t type, and
  2727. * 2) the number of bits in the swap pte, as defined by the different
  2728. * architectures.
  2729. *
  2730. * In order to find the largest possible bit mask, a swap entry with
  2731. * swap type 0 and swap offset ~0UL is created, encoded to a swap pte,
  2732. * decoded to a swp_entry_t again, and finally the swap offset is
  2733. * extracted.
  2734. *
  2735. * This will mask all the bits from the initial ~0UL mask that can't
  2736. * be encoded in either the swp_entry_t or the architecture definition
  2737. * of a swap pte.
  2738. */
  2739. unsigned long generic_max_swapfile_size(void)
  2740. {
  2741. return swp_offset(pte_to_swp_entry(
  2742. swp_entry_to_pte(swp_entry(0, ~0UL)))) + 1;
  2743. }
  2744. /* Can be overridden by an architecture for additional checks. */
  2745. __weak unsigned long arch_max_swapfile_size(void)
  2746. {
  2747. return generic_max_swapfile_size();
  2748. }
  2749. static unsigned long read_swap_header(struct swap_info_struct *si,
  2750. union swap_header *swap_header,
  2751. struct inode *inode)
  2752. {
  2753. int i;
  2754. unsigned long maxpages;
  2755. unsigned long swapfilepages;
  2756. unsigned long last_page;
  2757. if (memcmp("SWAPSPACE2", swap_header->magic.magic, 10)) {
  2758. pr_err("Unable to find swap-space signature\n");
  2759. return 0;
  2760. }
  2761. /* swap partition endianness hack... */
  2762. if (swab32(swap_header->info.version) == 1) {
  2763. swab32s(&swap_header->info.version);
  2764. swab32s(&swap_header->info.last_page);
  2765. swab32s(&swap_header->info.nr_badpages);
  2766. if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
  2767. return 0;
  2768. for (i = 0; i < swap_header->info.nr_badpages; i++)
  2769. swab32s(&swap_header->info.badpages[i]);
  2770. }
  2771. /* Check the swap header's sub-version */
  2772. if (swap_header->info.version != 1) {
  2773. pr_warn("Unable to handle swap header version %d\n",
  2774. swap_header->info.version);
  2775. return 0;
  2776. }
  2777. si->lowest_bit = 1;
  2778. si->cluster_next = 1;
  2779. si->cluster_nr = 0;
  2780. maxpages = swapfile_maximum_size;
  2781. last_page = swap_header->info.last_page;
  2782. if (!last_page) {
  2783. pr_warn("Empty swap-file\n");
  2784. return 0;
  2785. }
  2786. if (last_page > maxpages) {
  2787. pr_warn("Truncating oversized swap area, only using %luk out of %luk\n",
  2788. K(maxpages), K(last_page));
  2789. }
  2790. if (maxpages > last_page) {
  2791. maxpages = last_page + 1;
  2792. /* p->max is an unsigned int: don't overflow it */
  2793. if ((unsigned int)maxpages == 0)
  2794. maxpages = UINT_MAX;
  2795. }
  2796. si->highest_bit = maxpages - 1;
  2797. if (!maxpages)
  2798. return 0;
  2799. swapfilepages = i_size_read(inode) >> PAGE_SHIFT;
  2800. if (swapfilepages && maxpages > swapfilepages) {
  2801. pr_warn("Swap area shorter than signature indicates\n");
  2802. return 0;
  2803. }
  2804. if (swap_header->info.nr_badpages && S_ISREG(inode->i_mode))
  2805. return 0;
  2806. if (swap_header->info.nr_badpages > MAX_SWAP_BADPAGES)
  2807. return 0;
  2808. return maxpages;
  2809. }
  2810. #define SWAP_CLUSTER_INFO_COLS \
  2811. DIV_ROUND_UP(L1_CACHE_BYTES, sizeof(struct swap_cluster_info))
  2812. #define SWAP_CLUSTER_SPACE_COLS \
  2813. DIV_ROUND_UP(SWAP_ADDRESS_SPACE_PAGES, SWAPFILE_CLUSTER)
  2814. #define SWAP_CLUSTER_COLS \
  2815. max_t(unsigned int, SWAP_CLUSTER_INFO_COLS, SWAP_CLUSTER_SPACE_COLS)
  2816. static int setup_swap_map_and_extents(struct swap_info_struct *si,
  2817. union swap_header *swap_header,
  2818. unsigned char *swap_map,
  2819. unsigned long maxpages,
  2820. sector_t *span)
  2821. {
  2822. unsigned int nr_good_pages;
  2823. unsigned long i;
  2824. int nr_extents;
  2825. nr_good_pages = maxpages - 1; /* 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. nr_good_pages--;
  2833. }
  2834. }
  2835. if (nr_good_pages) {
  2836. swap_map[0] = SWAP_MAP_BAD;
  2837. si->max = maxpages;
  2838. si->pages = nr_good_pages;
  2839. nr_extents = setup_swap_extents(si, span);
  2840. if (nr_extents < 0)
  2841. return nr_extents;
  2842. nr_good_pages = si->pages;
  2843. }
  2844. if (!nr_good_pages) {
  2845. pr_warn("Empty swap-file\n");
  2846. return -EINVAL;
  2847. }
  2848. return nr_extents;
  2849. }
  2850. static struct swap_cluster_info *setup_clusters(struct swap_info_struct *si,
  2851. union swap_header *swap_header,
  2852. unsigned long maxpages)
  2853. {
  2854. unsigned long nr_clusters = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
  2855. unsigned long col = si->cluster_next / SWAPFILE_CLUSTER % SWAP_CLUSTER_COLS;
  2856. struct swap_cluster_info *cluster_info;
  2857. unsigned long i, j, k, idx;
  2858. int cpu, err = -ENOMEM;
  2859. cluster_info = kvcalloc(nr_clusters, sizeof(*cluster_info), GFP_KERNEL);
  2860. if (!cluster_info)
  2861. goto err;
  2862. for (i = 0; i < nr_clusters; i++)
  2863. spin_lock_init(&cluster_info[i].lock);
  2864. si->cluster_next_cpu = alloc_percpu(unsigned int);
  2865. if (!si->cluster_next_cpu)
  2866. goto err_free;
  2867. /* Random start position to help with wear leveling */
  2868. for_each_possible_cpu(cpu)
  2869. per_cpu(*si->cluster_next_cpu, cpu) =
  2870. get_random_u32_inclusive(1, si->highest_bit);
  2871. si->percpu_cluster = alloc_percpu(struct percpu_cluster);
  2872. if (!si->percpu_cluster)
  2873. goto err_free;
  2874. for_each_possible_cpu(cpu) {
  2875. struct percpu_cluster *cluster;
  2876. cluster = per_cpu_ptr(si->percpu_cluster, cpu);
  2877. for (i = 0; i < SWAP_NR_ORDERS; i++)
  2878. cluster->next[i] = SWAP_NEXT_INVALID;
  2879. }
  2880. /*
  2881. * Mark unusable pages as unavailable. The clusters aren't
  2882. * marked free yet, so no list operations are involved yet.
  2883. *
  2884. * See setup_swap_map_and_extents(): header page, bad pages,
  2885. * and the EOF part of the last cluster.
  2886. */
  2887. inc_cluster_info_page(si, cluster_info, 0);
  2888. for (i = 0; i < swap_header->info.nr_badpages; i++)
  2889. inc_cluster_info_page(si, cluster_info,
  2890. swap_header->info.badpages[i]);
  2891. for (i = maxpages; i < round_up(maxpages, SWAPFILE_CLUSTER); i++)
  2892. inc_cluster_info_page(si, cluster_info, i);
  2893. INIT_LIST_HEAD(&si->free_clusters);
  2894. INIT_LIST_HEAD(&si->full_clusters);
  2895. INIT_LIST_HEAD(&si->discard_clusters);
  2896. for (i = 0; i < SWAP_NR_ORDERS; i++) {
  2897. INIT_LIST_HEAD(&si->nonfull_clusters[i]);
  2898. INIT_LIST_HEAD(&si->frag_clusters[i]);
  2899. si->frag_cluster_nr[i] = 0;
  2900. }
  2901. /*
  2902. * Reduce false cache line sharing between cluster_info and
  2903. * sharing same address space.
  2904. */
  2905. for (k = 0; k < SWAP_CLUSTER_COLS; k++) {
  2906. j = (k + col) % SWAP_CLUSTER_COLS;
  2907. for (i = 0; i < DIV_ROUND_UP(nr_clusters, SWAP_CLUSTER_COLS); i++) {
  2908. struct swap_cluster_info *ci;
  2909. idx = i * SWAP_CLUSTER_COLS + j;
  2910. ci = cluster_info + idx;
  2911. if (idx >= nr_clusters)
  2912. continue;
  2913. if (ci->count) {
  2914. ci->flags = CLUSTER_FLAG_NONFULL;
  2915. list_add_tail(&ci->list, &si->nonfull_clusters[0]);
  2916. continue;
  2917. }
  2918. ci->flags = CLUSTER_FLAG_FREE;
  2919. list_add_tail(&ci->list, &si->free_clusters);
  2920. }
  2921. }
  2922. return cluster_info;
  2923. err_free:
  2924. kvfree(cluster_info);
  2925. err:
  2926. return ERR_PTR(err);
  2927. }
  2928. SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
  2929. {
  2930. struct swap_info_struct *si;
  2931. struct filename *name;
  2932. struct file *swap_file = NULL;
  2933. struct address_space *mapping;
  2934. struct dentry *dentry;
  2935. int prio;
  2936. int error;
  2937. union swap_header *swap_header;
  2938. int nr_extents;
  2939. sector_t span;
  2940. unsigned long maxpages;
  2941. unsigned char *swap_map = NULL;
  2942. unsigned long *zeromap = NULL;
  2943. struct swap_cluster_info *cluster_info = NULL;
  2944. struct folio *folio = NULL;
  2945. struct inode *inode = NULL;
  2946. bool inced_nr_rotate_swap = false;
  2947. if (swap_flags & ~SWAP_FLAGS_VALID)
  2948. return -EINVAL;
  2949. if (!capable(CAP_SYS_ADMIN))
  2950. return -EPERM;
  2951. if (!swap_avail_heads)
  2952. return -ENOMEM;
  2953. si = alloc_swap_info();
  2954. if (IS_ERR(si))
  2955. return PTR_ERR(si);
  2956. INIT_WORK(&si->discard_work, swap_discard_work);
  2957. INIT_WORK(&si->reclaim_work, swap_reclaim_work);
  2958. name = getname(specialfile);
  2959. if (IS_ERR(name)) {
  2960. error = PTR_ERR(name);
  2961. name = NULL;
  2962. goto bad_swap;
  2963. }
  2964. swap_file = file_open_name(name, O_RDWR | O_LARGEFILE | O_EXCL, 0);
  2965. if (IS_ERR(swap_file)) {
  2966. error = PTR_ERR(swap_file);
  2967. swap_file = NULL;
  2968. goto bad_swap;
  2969. }
  2970. si->swap_file = swap_file;
  2971. mapping = swap_file->f_mapping;
  2972. dentry = swap_file->f_path.dentry;
  2973. inode = mapping->host;
  2974. error = claim_swapfile(si, inode);
  2975. if (unlikely(error))
  2976. goto bad_swap;
  2977. inode_lock(inode);
  2978. if (d_unlinked(dentry) || cant_mount(dentry)) {
  2979. error = -ENOENT;
  2980. goto bad_swap_unlock_inode;
  2981. }
  2982. if (IS_SWAPFILE(inode)) {
  2983. error = -EBUSY;
  2984. goto bad_swap_unlock_inode;
  2985. }
  2986. /*
  2987. * Read the swap header.
  2988. */
  2989. if (!mapping->a_ops->read_folio) {
  2990. error = -EINVAL;
  2991. goto bad_swap_unlock_inode;
  2992. }
  2993. folio = read_mapping_folio(mapping, 0, swap_file);
  2994. if (IS_ERR(folio)) {
  2995. error = PTR_ERR(folio);
  2996. goto bad_swap_unlock_inode;
  2997. }
  2998. swap_header = kmap_local_folio(folio, 0);
  2999. maxpages = read_swap_header(si, swap_header, inode);
  3000. if (unlikely(!maxpages)) {
  3001. error = -EINVAL;
  3002. goto bad_swap_unlock_inode;
  3003. }
  3004. /* OK, set up the swap map and apply the bad block list */
  3005. swap_map = vzalloc(maxpages);
  3006. if (!swap_map) {
  3007. error = -ENOMEM;
  3008. goto bad_swap_unlock_inode;
  3009. }
  3010. error = swap_cgroup_swapon(si->type, maxpages);
  3011. if (error)
  3012. goto bad_swap_unlock_inode;
  3013. nr_extents = setup_swap_map_and_extents(si, swap_header, swap_map,
  3014. maxpages, &span);
  3015. if (unlikely(nr_extents < 0)) {
  3016. error = nr_extents;
  3017. goto bad_swap_unlock_inode;
  3018. }
  3019. /*
  3020. * Use kvmalloc_array instead of bitmap_zalloc as the allocation order might
  3021. * be above MAX_PAGE_ORDER incase of a large swap file.
  3022. */
  3023. zeromap = kvmalloc_array(BITS_TO_LONGS(maxpages), sizeof(long),
  3024. GFP_KERNEL | __GFP_ZERO);
  3025. if (!zeromap) {
  3026. error = -ENOMEM;
  3027. goto bad_swap_unlock_inode;
  3028. }
  3029. if (si->bdev && bdev_stable_writes(si->bdev))
  3030. si->flags |= SWP_STABLE_WRITES;
  3031. if (si->bdev && bdev_synchronous(si->bdev))
  3032. si->flags |= SWP_SYNCHRONOUS_IO;
  3033. if (si->bdev && bdev_nonrot(si->bdev)) {
  3034. si->flags |= SWP_SOLIDSTATE;
  3035. cluster_info = setup_clusters(si, swap_header, maxpages);
  3036. if (IS_ERR(cluster_info)) {
  3037. error = PTR_ERR(cluster_info);
  3038. cluster_info = NULL;
  3039. goto bad_swap_unlock_inode;
  3040. }
  3041. } else {
  3042. atomic_inc(&nr_rotate_swap);
  3043. inced_nr_rotate_swap = true;
  3044. }
  3045. if ((swap_flags & SWAP_FLAG_DISCARD) &&
  3046. si->bdev && bdev_max_discard_sectors(si->bdev)) {
  3047. /*
  3048. * When discard is enabled for swap with no particular
  3049. * policy flagged, we set all swap discard flags here in
  3050. * order to sustain backward compatibility with older
  3051. * swapon(8) releases.
  3052. */
  3053. si->flags |= (SWP_DISCARDABLE | SWP_AREA_DISCARD |
  3054. SWP_PAGE_DISCARD);
  3055. /*
  3056. * By flagging sys_swapon, a sysadmin can tell us to
  3057. * either do single-time area discards only, or to just
  3058. * perform discards for released swap page-clusters.
  3059. * Now it's time to adjust the p->flags accordingly.
  3060. */
  3061. if (swap_flags & SWAP_FLAG_DISCARD_ONCE)
  3062. si->flags &= ~SWP_PAGE_DISCARD;
  3063. else if (swap_flags & SWAP_FLAG_DISCARD_PAGES)
  3064. si->flags &= ~SWP_AREA_DISCARD;
  3065. /* issue a swapon-time discard if it's still required */
  3066. if (si->flags & SWP_AREA_DISCARD) {
  3067. int err = discard_swap(si);
  3068. if (unlikely(err))
  3069. pr_err("swapon: discard_swap(%p): %d\n",
  3070. si, err);
  3071. }
  3072. }
  3073. error = init_swap_address_space(si->type, maxpages);
  3074. if (error)
  3075. goto bad_swap_unlock_inode;
  3076. error = zswap_swapon(si->type, maxpages);
  3077. if (error)
  3078. goto free_swap_address_space;
  3079. /*
  3080. * Flush any pending IO and dirty mappings before we start using this
  3081. * swap device.
  3082. */
  3083. inode->i_flags |= S_SWAPFILE;
  3084. error = inode_drain_writes(inode);
  3085. if (error) {
  3086. inode->i_flags &= ~S_SWAPFILE;
  3087. goto free_swap_zswap;
  3088. }
  3089. mutex_lock(&swapon_mutex);
  3090. prio = -1;
  3091. if (swap_flags & SWAP_FLAG_PREFER)
  3092. prio =
  3093. (swap_flags & SWAP_FLAG_PRIO_MASK) >> SWAP_FLAG_PRIO_SHIFT;
  3094. enable_swap_info(si, prio, swap_map, cluster_info, zeromap);
  3095. pr_info("Adding %uk swap on %s. Priority:%d extents:%d across:%lluk %s%s%s%s\n",
  3096. K(si->pages), name->name, si->prio, nr_extents,
  3097. K((unsigned long long)span),
  3098. (si->flags & SWP_SOLIDSTATE) ? "SS" : "",
  3099. (si->flags & SWP_DISCARDABLE) ? "D" : "",
  3100. (si->flags & SWP_AREA_DISCARD) ? "s" : "",
  3101. (si->flags & SWP_PAGE_DISCARD) ? "c" : "");
  3102. mutex_unlock(&swapon_mutex);
  3103. atomic_inc(&proc_poll_event);
  3104. wake_up_interruptible(&proc_poll_wait);
  3105. error = 0;
  3106. goto out;
  3107. free_swap_zswap:
  3108. zswap_swapoff(si->type);
  3109. free_swap_address_space:
  3110. exit_swap_address_space(si->type);
  3111. bad_swap_unlock_inode:
  3112. inode_unlock(inode);
  3113. bad_swap:
  3114. free_percpu(si->percpu_cluster);
  3115. si->percpu_cluster = NULL;
  3116. free_percpu(si->cluster_next_cpu);
  3117. si->cluster_next_cpu = NULL;
  3118. inode = NULL;
  3119. destroy_swap_extents(si);
  3120. swap_cgroup_swapoff(si->type);
  3121. spin_lock(&swap_lock);
  3122. si->swap_file = NULL;
  3123. si->flags = 0;
  3124. spin_unlock(&swap_lock);
  3125. vfree(swap_map);
  3126. kvfree(zeromap);
  3127. kvfree(cluster_info);
  3128. if (inced_nr_rotate_swap)
  3129. atomic_dec(&nr_rotate_swap);
  3130. if (swap_file)
  3131. filp_close(swap_file, NULL);
  3132. out:
  3133. if (!IS_ERR_OR_NULL(folio))
  3134. folio_release_kmap(folio, swap_header);
  3135. if (name)
  3136. putname(name);
  3137. if (inode)
  3138. inode_unlock(inode);
  3139. if (!error)
  3140. enable_swap_slots_cache();
  3141. return error;
  3142. }
  3143. void si_swapinfo(struct sysinfo *val)
  3144. {
  3145. unsigned int type;
  3146. unsigned long nr_to_be_unused = 0;
  3147. spin_lock(&swap_lock);
  3148. for (type = 0; type < nr_swapfiles; type++) {
  3149. struct swap_info_struct *si = swap_info[type];
  3150. if ((si->flags & SWP_USED) && !(si->flags & SWP_WRITEOK))
  3151. nr_to_be_unused += READ_ONCE(si->inuse_pages);
  3152. }
  3153. val->freeswap = atomic_long_read(&nr_swap_pages) + nr_to_be_unused;
  3154. val->totalswap = total_swap_pages + nr_to_be_unused;
  3155. spin_unlock(&swap_lock);
  3156. }
  3157. /*
  3158. * Verify that nr swap entries are valid and increment their swap map counts.
  3159. *
  3160. * Returns error code in following case.
  3161. * - success -> 0
  3162. * - swp_entry is invalid -> EINVAL
  3163. * - swp_entry is migration entry -> EINVAL
  3164. * - swap-cache reference is requested but there is already one. -> EEXIST
  3165. * - swap-cache reference is requested but the entry is not used. -> ENOENT
  3166. * - swap-mapped reference requested but needs continued swap count. -> ENOMEM
  3167. */
  3168. static int __swap_duplicate(swp_entry_t entry, unsigned char usage, int nr)
  3169. {
  3170. struct swap_info_struct *si;
  3171. struct swap_cluster_info *ci;
  3172. unsigned long offset;
  3173. unsigned char count;
  3174. unsigned char has_cache;
  3175. int err, i;
  3176. si = swp_swap_info(entry);
  3177. offset = swp_offset(entry);
  3178. VM_WARN_ON(nr > SWAPFILE_CLUSTER - offset % SWAPFILE_CLUSTER);
  3179. VM_WARN_ON(usage == 1 && nr > 1);
  3180. ci = lock_cluster_or_swap_info(si, offset);
  3181. err = 0;
  3182. for (i = 0; i < nr; i++) {
  3183. count = si->swap_map[offset + i];
  3184. /*
  3185. * swapin_readahead() doesn't check if a swap entry is valid, so the
  3186. * swap entry could be SWAP_MAP_BAD. Check here with lock held.
  3187. */
  3188. if (unlikely(swap_count(count) == SWAP_MAP_BAD)) {
  3189. err = -ENOENT;
  3190. goto unlock_out;
  3191. }
  3192. has_cache = count & SWAP_HAS_CACHE;
  3193. count &= ~SWAP_HAS_CACHE;
  3194. if (!count && !has_cache) {
  3195. err = -ENOENT;
  3196. } else if (usage == SWAP_HAS_CACHE) {
  3197. if (has_cache)
  3198. err = -EEXIST;
  3199. } else if ((count & ~COUNT_CONTINUED) > SWAP_MAP_MAX) {
  3200. err = -EINVAL;
  3201. }
  3202. if (err)
  3203. goto unlock_out;
  3204. }
  3205. for (i = 0; i < nr; i++) {
  3206. count = si->swap_map[offset + i];
  3207. has_cache = count & SWAP_HAS_CACHE;
  3208. count &= ~SWAP_HAS_CACHE;
  3209. if (usage == SWAP_HAS_CACHE)
  3210. has_cache = SWAP_HAS_CACHE;
  3211. else if ((count & ~COUNT_CONTINUED) < SWAP_MAP_MAX)
  3212. count += usage;
  3213. else if (swap_count_continued(si, offset + i, count))
  3214. count = COUNT_CONTINUED;
  3215. else {
  3216. /*
  3217. * Don't need to rollback changes, because if
  3218. * usage == 1, there must be nr == 1.
  3219. */
  3220. err = -ENOMEM;
  3221. goto unlock_out;
  3222. }
  3223. WRITE_ONCE(si->swap_map[offset + i], count | has_cache);
  3224. }
  3225. unlock_out:
  3226. unlock_cluster_or_swap_info(si, ci);
  3227. return err;
  3228. }
  3229. /*
  3230. * Help swapoff by noting that swap entry belongs to shmem/tmpfs
  3231. * (in which case its reference count is never incremented).
  3232. */
  3233. void swap_shmem_alloc(swp_entry_t entry, int nr)
  3234. {
  3235. __swap_duplicate(entry, SWAP_MAP_SHMEM, nr);
  3236. }
  3237. /*
  3238. * Increase reference count of swap entry by 1.
  3239. * Returns 0 for success, or -ENOMEM if a swap_count_continuation is required
  3240. * but could not be atomically allocated. Returns 0, just as if it succeeded,
  3241. * if __swap_duplicate() fails for another reason (-EINVAL or -ENOENT), which
  3242. * might occur if a page table entry has got corrupted.
  3243. */
  3244. int swap_duplicate(swp_entry_t entry)
  3245. {
  3246. int err = 0;
  3247. while (!err && __swap_duplicate(entry, 1, 1) == -ENOMEM)
  3248. err = add_swap_count_continuation(entry, GFP_ATOMIC);
  3249. return err;
  3250. }
  3251. /*
  3252. * @entry: first swap entry from which we allocate nr swap cache.
  3253. *
  3254. * Called when allocating swap cache for existing swap entries,
  3255. * This can return error codes. Returns 0 at success.
  3256. * -EEXIST means there is a swap cache.
  3257. * Note: return code is different from swap_duplicate().
  3258. */
  3259. int swapcache_prepare(swp_entry_t entry, int nr)
  3260. {
  3261. return __swap_duplicate(entry, SWAP_HAS_CACHE, nr);
  3262. }
  3263. void swapcache_clear(struct swap_info_struct *si, swp_entry_t entry, int nr)
  3264. {
  3265. unsigned long offset = swp_offset(entry);
  3266. cluster_swap_free_nr(si, offset, nr, SWAP_HAS_CACHE);
  3267. }
  3268. struct swap_info_struct *swp_swap_info(swp_entry_t entry)
  3269. {
  3270. return swap_type_to_swap_info(swp_type(entry));
  3271. }
  3272. /*
  3273. * out-of-line methods to avoid include hell.
  3274. */
  3275. struct address_space *swapcache_mapping(struct folio *folio)
  3276. {
  3277. return swp_swap_info(folio->swap)->swap_file->f_mapping;
  3278. }
  3279. EXPORT_SYMBOL_GPL(swapcache_mapping);
  3280. pgoff_t __folio_swap_cache_index(struct folio *folio)
  3281. {
  3282. return swap_cache_index(folio->swap);
  3283. }
  3284. EXPORT_SYMBOL_GPL(__folio_swap_cache_index);
  3285. /*
  3286. * add_swap_count_continuation - called when a swap count is duplicated
  3287. * beyond SWAP_MAP_MAX, it allocates a new page and links that to the entry's
  3288. * page of the original vmalloc'ed swap_map, to hold the continuation count
  3289. * (for that entry and for its neighbouring PAGE_SIZE swap entries). Called
  3290. * again when count is duplicated beyond SWAP_MAP_MAX * SWAP_CONT_MAX, etc.
  3291. *
  3292. * These continuation pages are seldom referenced: the common paths all work
  3293. * on the original swap_map, only referring to a continuation page when the
  3294. * low "digit" of a count is incremented or decremented through SWAP_MAP_MAX.
  3295. *
  3296. * add_swap_count_continuation(, GFP_ATOMIC) can be called while holding
  3297. * page table locks; if it fails, add_swap_count_continuation(, GFP_KERNEL)
  3298. * can be called after dropping locks.
  3299. */
  3300. int add_swap_count_continuation(swp_entry_t entry, gfp_t gfp_mask)
  3301. {
  3302. struct swap_info_struct *si;
  3303. struct swap_cluster_info *ci;
  3304. struct page *head;
  3305. struct page *page;
  3306. struct page *list_page;
  3307. pgoff_t offset;
  3308. unsigned char count;
  3309. int ret = 0;
  3310. /*
  3311. * When debugging, it's easier to use __GFP_ZERO here; but it's better
  3312. * for latency not to zero a page while GFP_ATOMIC and holding locks.
  3313. */
  3314. page = alloc_page(gfp_mask | __GFP_HIGHMEM);
  3315. si = get_swap_device(entry);
  3316. if (!si) {
  3317. /*
  3318. * An acceptable race has occurred since the failing
  3319. * __swap_duplicate(): the swap device may be swapoff
  3320. */
  3321. goto outer;
  3322. }
  3323. spin_lock(&si->lock);
  3324. offset = swp_offset(entry);
  3325. ci = lock_cluster(si, offset);
  3326. count = swap_count(si->swap_map[offset]);
  3327. if ((count & ~COUNT_CONTINUED) != SWAP_MAP_MAX) {
  3328. /*
  3329. * The higher the swap count, the more likely it is that tasks
  3330. * will race to add swap count continuation: we need to avoid
  3331. * over-provisioning.
  3332. */
  3333. goto out;
  3334. }
  3335. if (!page) {
  3336. ret = -ENOMEM;
  3337. goto out;
  3338. }
  3339. head = vmalloc_to_page(si->swap_map + offset);
  3340. offset &= ~PAGE_MASK;
  3341. spin_lock(&si->cont_lock);
  3342. /*
  3343. * Page allocation does not initialize the page's lru field,
  3344. * but it does always reset its private field.
  3345. */
  3346. if (!page_private(head)) {
  3347. BUG_ON(count & COUNT_CONTINUED);
  3348. INIT_LIST_HEAD(&head->lru);
  3349. set_page_private(head, SWP_CONTINUED);
  3350. si->flags |= SWP_CONTINUED;
  3351. }
  3352. list_for_each_entry(list_page, &head->lru, lru) {
  3353. unsigned char *map;
  3354. /*
  3355. * If the previous map said no continuation, but we've found
  3356. * a continuation page, free our allocation and use this one.
  3357. */
  3358. if (!(count & COUNT_CONTINUED))
  3359. goto out_unlock_cont;
  3360. map = kmap_local_page(list_page) + offset;
  3361. count = *map;
  3362. kunmap_local(map);
  3363. /*
  3364. * If this continuation count now has some space in it,
  3365. * free our allocation and use this one.
  3366. */
  3367. if ((count & ~COUNT_CONTINUED) != SWAP_CONT_MAX)
  3368. goto out_unlock_cont;
  3369. }
  3370. list_add_tail(&page->lru, &head->lru);
  3371. page = NULL; /* now it's attached, don't free it */
  3372. out_unlock_cont:
  3373. spin_unlock(&si->cont_lock);
  3374. out:
  3375. unlock_cluster(ci);
  3376. spin_unlock(&si->lock);
  3377. put_swap_device(si);
  3378. outer:
  3379. if (page)
  3380. __free_page(page);
  3381. return ret;
  3382. }
  3383. /*
  3384. * swap_count_continued - when the original swap_map count is incremented
  3385. * from SWAP_MAP_MAX, check if there is already a continuation page to carry
  3386. * into, carry if so, or else fail until a new continuation page is allocated;
  3387. * when the original swap_map count is decremented from 0 with continuation,
  3388. * borrow from the continuation and report whether it still holds more.
  3389. * Called while __swap_duplicate() or swap_entry_free() holds swap or cluster
  3390. * lock.
  3391. */
  3392. static bool swap_count_continued(struct swap_info_struct *si,
  3393. pgoff_t offset, unsigned char count)
  3394. {
  3395. struct page *head;
  3396. struct page *page;
  3397. unsigned char *map;
  3398. bool ret;
  3399. head = vmalloc_to_page(si->swap_map + offset);
  3400. if (page_private(head) != SWP_CONTINUED) {
  3401. BUG_ON(count & COUNT_CONTINUED);
  3402. return false; /* need to add count continuation */
  3403. }
  3404. spin_lock(&si->cont_lock);
  3405. offset &= ~PAGE_MASK;
  3406. page = list_next_entry(head, lru);
  3407. map = kmap_local_page(page) + offset;
  3408. if (count == SWAP_MAP_MAX) /* initial increment from swap_map */
  3409. goto init_map; /* jump over SWAP_CONT_MAX checks */
  3410. if (count == (SWAP_MAP_MAX | COUNT_CONTINUED)) { /* incrementing */
  3411. /*
  3412. * Think of how you add 1 to 999
  3413. */
  3414. while (*map == (SWAP_CONT_MAX | COUNT_CONTINUED)) {
  3415. kunmap_local(map);
  3416. page = list_next_entry(page, lru);
  3417. BUG_ON(page == head);
  3418. map = kmap_local_page(page) + offset;
  3419. }
  3420. if (*map == SWAP_CONT_MAX) {
  3421. kunmap_local(map);
  3422. page = list_next_entry(page, lru);
  3423. if (page == head) {
  3424. ret = false; /* add count continuation */
  3425. goto out;
  3426. }
  3427. map = kmap_local_page(page) + offset;
  3428. init_map: *map = 0; /* we didn't zero the page */
  3429. }
  3430. *map += 1;
  3431. kunmap_local(map);
  3432. while ((page = list_prev_entry(page, lru)) != head) {
  3433. map = kmap_local_page(page) + offset;
  3434. *map = COUNT_CONTINUED;
  3435. kunmap_local(map);
  3436. }
  3437. ret = true; /* incremented */
  3438. } else { /* decrementing */
  3439. /*
  3440. * Think of how you subtract 1 from 1000
  3441. */
  3442. BUG_ON(count != COUNT_CONTINUED);
  3443. while (*map == COUNT_CONTINUED) {
  3444. kunmap_local(map);
  3445. page = list_next_entry(page, lru);
  3446. BUG_ON(page == head);
  3447. map = kmap_local_page(page) + offset;
  3448. }
  3449. BUG_ON(*map == 0);
  3450. *map -= 1;
  3451. if (*map == 0)
  3452. count = 0;
  3453. kunmap_local(map);
  3454. while ((page = list_prev_entry(page, lru)) != head) {
  3455. map = kmap_local_page(page) + offset;
  3456. *map = SWAP_CONT_MAX | count;
  3457. count = COUNT_CONTINUED;
  3458. kunmap_local(map);
  3459. }
  3460. ret = count == COUNT_CONTINUED;
  3461. }
  3462. out:
  3463. spin_unlock(&si->cont_lock);
  3464. return ret;
  3465. }
  3466. /*
  3467. * free_swap_count_continuations - swapoff free all the continuation pages
  3468. * appended to the swap_map, after swap_map is quiesced, before vfree'ing it.
  3469. */
  3470. static void free_swap_count_continuations(struct swap_info_struct *si)
  3471. {
  3472. pgoff_t offset;
  3473. for (offset = 0; offset < si->max; offset += PAGE_SIZE) {
  3474. struct page *head;
  3475. head = vmalloc_to_page(si->swap_map + offset);
  3476. if (page_private(head)) {
  3477. struct page *page, *next;
  3478. list_for_each_entry_safe(page, next, &head->lru, lru) {
  3479. list_del(&page->lru);
  3480. __free_page(page);
  3481. }
  3482. }
  3483. }
  3484. }
  3485. #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
  3486. void __folio_throttle_swaprate(struct folio *folio, gfp_t gfp)
  3487. {
  3488. struct swap_info_struct *si, *next;
  3489. int nid = folio_nid(folio);
  3490. if (!(gfp & __GFP_IO))
  3491. return;
  3492. if (!__has_usable_swap())
  3493. return;
  3494. if (!blk_cgroup_congested())
  3495. return;
  3496. /*
  3497. * We've already scheduled a throttle, avoid taking the global swap
  3498. * lock.
  3499. */
  3500. if (current->throttle_disk)
  3501. return;
  3502. spin_lock(&swap_avail_lock);
  3503. plist_for_each_entry_safe(si, next, &swap_avail_heads[nid],
  3504. avail_lists[nid]) {
  3505. if (si->bdev) {
  3506. blkcg_schedule_throttle(si->bdev->bd_disk, true);
  3507. break;
  3508. }
  3509. }
  3510. spin_unlock(&swap_avail_lock);
  3511. }
  3512. #endif
  3513. static int __init swapfile_init(void)
  3514. {
  3515. int nid;
  3516. swap_avail_heads = kmalloc_array(nr_node_ids, sizeof(struct plist_head),
  3517. GFP_KERNEL);
  3518. if (!swap_avail_heads) {
  3519. pr_emerg("Not enough memory for swap heads, swap is disabled\n");
  3520. return -ENOMEM;
  3521. }
  3522. for_each_node(nid)
  3523. plist_head_init(&swap_avail_heads[nid]);
  3524. swapfile_maximum_size = arch_max_swapfile_size();
  3525. #ifdef CONFIG_MIGRATION
  3526. if (swapfile_maximum_size >= (1UL << SWP_MIG_TOTAL_BITS))
  3527. swap_migration_ad_supported = true;
  3528. #endif /* CONFIG_MIGRATION */
  3529. return 0;
  3530. }
  3531. subsys_initcall(swapfile_init);