swapfile.c 64 KB

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