swapfile.c 78 KB

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