swapfile.c 78 KB

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