swapfile.c 78 KB

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