swapfile.c 97 KB

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