swapfile.c 88 KB

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