swapfile.c 93 KB

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