swapfile.c 63 KB

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