zram_drv.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394
  1. /*
  2. * Compressed RAM block device
  3. *
  4. * Copyright (C) 2008, 2009, 2010 Nitin Gupta
  5. * 2012, 2013 Minchan Kim
  6. *
  7. * This code is released using a dual license strategy: BSD/GPL
  8. * You can choose the licence that better fits your requirements.
  9. *
  10. * Released under the terms of 3-clause BSD License
  11. * Released under the terms of GNU General Public License Version 2.0
  12. *
  13. */
  14. #define KMSG_COMPONENT "zram"
  15. #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
  16. #include <linux/module.h>
  17. #include <linux/kernel.h>
  18. #include <linux/bio.h>
  19. #include <linux/bitops.h>
  20. #include <linux/blkdev.h>
  21. #include <linux/buffer_head.h>
  22. #include <linux/device.h>
  23. #include <linux/genhd.h>
  24. #include <linux/highmem.h>
  25. #include <linux/slab.h>
  26. #include <linux/backing-dev.h>
  27. #include <linux/string.h>
  28. #include <linux/vmalloc.h>
  29. #include <linux/err.h>
  30. #include <linux/idr.h>
  31. #include <linux/sysfs.h>
  32. #include <linux/debugfs.h>
  33. #include <linux/cpuhotplug.h>
  34. #include <linux/fb.h>
  35. #include <linux/input.h>
  36. #include <linux/power_supply.h>
  37. #include "zram_drv.h"
  38. static DEFINE_IDR(zram_index_idr);
  39. /* idr index must be protected */
  40. static DEFINE_MUTEX(zram_index_mutex);
  41. static int zram_major;
  42. static struct zram *zram_devices;
  43. static const char *default_compressor = CONFIG_ZRAM_DEF_COMP;
  44. /* Module params (documentation at end) */
  45. static unsigned int num_devices = 1;
  46. /*
  47. * Pages that compress to sizes equals or greater than this are stored
  48. * uncompressed in memory.
  49. */
  50. static size_t huge_class_size;
  51. static bool screen_on = true;
  52. static unsigned long long total_touch_clock;
  53. module_param(total_touch_clock, ullong, 0644);
  54. static DEFINE_MUTEX(zram_wb_wakelock_mutex);
  55. static struct wakeup_source zram_wb_wakelock;
  56. /*
  57. * Blocks that hasn't been accessed in wb_start_mins
  58. * while the touch event is present will be writebacked.
  59. *
  60. * This is to prevent writebacking blocks that'll be used
  61. * right after the screen goes back on.
  62. * (e.g., using the phone after waking up in the morning)
  63. *
  64. * Note that total_touch_clock is increased only during
  65. * BTN_TOUCH events are received.
  66. * This means that wb_start_mins will work with BTN_TOUCH's
  67. * perspective, not system uptime.
  68. */
  69. static int wb_start_mins = 240;
  70. module_param(wb_start_mins, int, 0644);
  71. static struct work_struct zram_wb_fb_worker;
  72. static void zram_free_page(struct zram *zram, size_t index);
  73. static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
  74. u32 index, int offset, struct bio *bio);
  75. static int zram_slot_trylock(struct zram *zram, u32 index)
  76. {
  77. return bit_spin_trylock(ZRAM_LOCK, &zram->table[index].flags);
  78. }
  79. static void zram_slot_lock(struct zram *zram, u32 index)
  80. {
  81. bit_spin_lock(ZRAM_LOCK, &zram->table[index].flags);
  82. }
  83. static void zram_slot_unlock(struct zram *zram, u32 index)
  84. {
  85. bit_spin_unlock(ZRAM_LOCK, &zram->table[index].flags);
  86. }
  87. static inline bool init_done(struct zram *zram)
  88. {
  89. return zram ? zram->disksize : 0;
  90. }
  91. static inline struct zram *dev_to_zram(struct device *dev)
  92. {
  93. return (struct zram *)dev_to_disk(dev)->private_data;
  94. }
  95. static struct zram_entry *zram_get_entry(struct zram *zram, u32 index)
  96. {
  97. return zram->table[index].entry;
  98. }
  99. static void zram_set_entry(struct zram *zram, u32 index,
  100. struct zram_entry *entry)
  101. {
  102. zram->table[index].entry = entry;
  103. }
  104. /* flag operations require table entry bit_spin_lock() being held */
  105. static bool zram_test_flag(struct zram *zram, u32 index,
  106. enum zram_pageflags flag)
  107. {
  108. return zram->table[index].flags & BIT(flag);
  109. }
  110. static void zram_set_flag(struct zram *zram, u32 index,
  111. enum zram_pageflags flag)
  112. {
  113. zram->table[index].flags |= BIT(flag);
  114. }
  115. static void zram_clear_flag(struct zram *zram, u32 index,
  116. enum zram_pageflags flag)
  117. {
  118. zram->table[index].flags &= ~BIT(flag);
  119. }
  120. static inline void zram_set_element(struct zram *zram, u32 index,
  121. unsigned long element)
  122. {
  123. zram->table[index].element = element;
  124. }
  125. static unsigned long zram_get_element(struct zram *zram, u32 index)
  126. {
  127. return zram->table[index].element;
  128. }
  129. static size_t zram_get_obj_size(struct zram *zram, u32 index)
  130. {
  131. return zram->table[index].flags & (BIT(ZRAM_FLAG_SHIFT) - 1);
  132. }
  133. static void zram_set_obj_size(struct zram *zram,
  134. u32 index, size_t size)
  135. {
  136. unsigned long flags = zram->table[index].flags >> ZRAM_FLAG_SHIFT;
  137. zram->table[index].flags = (flags << ZRAM_FLAG_SHIFT) | size;
  138. }
  139. static inline bool zram_allocated(struct zram *zram, u32 index)
  140. {
  141. return zram_get_obj_size(zram, index) ||
  142. zram_test_flag(zram, index, ZRAM_SAME) ||
  143. zram_test_flag(zram, index, ZRAM_WB);
  144. }
  145. #if PAGE_SIZE != 4096
  146. static inline bool is_partial_io(struct bio_vec *bvec)
  147. {
  148. return bvec->bv_len != PAGE_SIZE;
  149. }
  150. #else
  151. static inline bool is_partial_io(struct bio_vec *bvec)
  152. {
  153. return false;
  154. }
  155. #endif
  156. /*
  157. * Check if request is within bounds and aligned on zram logical blocks.
  158. */
  159. static inline bool valid_io_request(struct zram *zram,
  160. sector_t start, unsigned int size)
  161. {
  162. u64 end, bound;
  163. /* unaligned request */
  164. if (unlikely(start & (ZRAM_SECTOR_PER_LOGICAL_BLOCK - 1)))
  165. return false;
  166. if (unlikely(size & (ZRAM_LOGICAL_BLOCK_SIZE - 1)))
  167. return false;
  168. end = start + (size >> SECTOR_SHIFT);
  169. bound = zram->disksize >> SECTOR_SHIFT;
  170. /* out of range range */
  171. if (unlikely(start >= bound || end > bound || start > end))
  172. return false;
  173. /* I/O request is valid */
  174. return true;
  175. }
  176. static void update_position(u32 *index, int *offset, struct bio_vec *bvec)
  177. {
  178. *index += (*offset + bvec->bv_len) / PAGE_SIZE;
  179. *offset = (*offset + bvec->bv_len) % PAGE_SIZE;
  180. }
  181. static inline void update_used_max(struct zram *zram,
  182. const unsigned long pages)
  183. {
  184. unsigned long old_max, cur_max;
  185. old_max = atomic_long_read(&zram->stats.max_used_pages);
  186. do {
  187. cur_max = old_max;
  188. if (pages > cur_max)
  189. old_max = atomic_long_cmpxchg(
  190. &zram->stats.max_used_pages, cur_max, pages);
  191. } while (old_max != cur_max);
  192. }
  193. static inline void zram_fill_page(void *ptr, unsigned long len,
  194. unsigned long value)
  195. {
  196. WARN_ON_ONCE(!IS_ALIGNED(len, sizeof(unsigned long)));
  197. memset_l(ptr, value, len / sizeof(unsigned long));
  198. }
  199. static bool page_same_filled(void *ptr, unsigned long *element)
  200. {
  201. unsigned long *page;
  202. unsigned long val;
  203. unsigned int pos, last_pos = PAGE_SIZE / sizeof(*page) - 1;
  204. page = (unsigned long *)ptr;
  205. val = page[0];
  206. if (val != page[last_pos])
  207. return false;
  208. for (pos = 1; pos < last_pos; pos++) {
  209. if (val != page[pos])
  210. return false;
  211. }
  212. *element = val;
  213. return true;
  214. }
  215. static ssize_t initstate_show(struct device *dev,
  216. struct device_attribute *attr, char *buf)
  217. {
  218. u32 val;
  219. struct zram *zram = dev_to_zram(dev);
  220. down_read(&zram->init_lock);
  221. val = init_done(zram);
  222. up_read(&zram->init_lock);
  223. return scnprintf(buf, PAGE_SIZE, "%u\n", val);
  224. }
  225. static ssize_t disksize_show(struct device *dev,
  226. struct device_attribute *attr, char *buf)
  227. {
  228. struct zram *zram = dev_to_zram(dev);
  229. return scnprintf(buf, PAGE_SIZE, "%llu\n", zram->disksize);
  230. }
  231. static ssize_t mem_limit_store(struct device *dev,
  232. struct device_attribute *attr, const char *buf, size_t len)
  233. {
  234. u64 limit;
  235. char *tmp;
  236. struct zram *zram = dev_to_zram(dev);
  237. limit = memparse(buf, &tmp);
  238. if (buf == tmp) /* no chars parsed, invalid input */
  239. return -EINVAL;
  240. down_write(&zram->init_lock);
  241. zram->limit_pages = PAGE_ALIGN(limit) >> PAGE_SHIFT;
  242. up_write(&zram->init_lock);
  243. return len;
  244. }
  245. static ssize_t mem_used_max_store(struct device *dev,
  246. struct device_attribute *attr, const char *buf, size_t len)
  247. {
  248. int err;
  249. unsigned long val;
  250. struct zram *zram = dev_to_zram(dev);
  251. err = kstrtoul(buf, 10, &val);
  252. if (err || val != 0)
  253. return -EINVAL;
  254. down_read(&zram->init_lock);
  255. if (init_done(zram)) {
  256. atomic_long_set(&zram->stats.max_used_pages,
  257. zs_get_total_pages(zram->mem_pool));
  258. }
  259. up_read(&zram->init_lock);
  260. return len;
  261. }
  262. // Returns the number of marked blocks
  263. static int mark_idle(struct zram *zram, unsigned long long threshold)
  264. {
  265. unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
  266. int index, ret = 0;
  267. down_read(&zram->init_lock);
  268. if (!init_done(zram)) {
  269. up_read(&zram->init_lock);
  270. return -EINVAL;
  271. }
  272. for (index = 0; index < nr_pages; index++) {
  273. /*
  274. * Do not mark ZRAM_UNDER_WB slot as ZRAM_IDLE to close race.
  275. * See the comment in writeback_store.
  276. */
  277. zram_slot_lock(zram, index);
  278. #ifdef CONFIG_ZRAM_MEMORY_TRACKING
  279. if (zram_allocated(zram, index) &&
  280. !zram_test_flag(zram, index, ZRAM_UNDER_WB) &&
  281. !zram_test_flag(zram, index, ZRAM_WB) &&
  282. !zram_test_flag(zram, index, ZRAM_IDLE) &&
  283. !zram_test_flag(zram, index, ZRAM_SAME) &&
  284. !zram_test_flag(zram, index, ZRAM_DEDUPED) &&
  285. threshold >= zram->table[index].ac_time) {
  286. zram_set_flag(zram, index, ZRAM_IDLE);
  287. ret++;
  288. }
  289. #endif
  290. zram_slot_unlock(zram, index);
  291. }
  292. up_read(&zram->init_lock);
  293. return ret;
  294. }
  295. #ifdef CONFIG_ZRAM_WRITEBACK
  296. static void reset_bdev(struct zram *zram)
  297. {
  298. struct block_device *bdev;
  299. if (!zram->backing_dev)
  300. return;
  301. bdev = zram->bdev;
  302. blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
  303. /* hope filp_close flush all of IO */
  304. filp_close(zram->backing_dev, NULL);
  305. zram->backing_dev = NULL;
  306. zram->bdev = NULL;
  307. zram->disk->queue->backing_dev_info->capabilities |=
  308. BDI_CAP_SYNCHRONOUS_IO;
  309. kvfree(zram->bitmap);
  310. zram->bitmap = NULL;
  311. }
  312. static ssize_t backing_dev_show(struct device *dev,
  313. struct device_attribute *attr, char *buf)
  314. {
  315. struct file *file;
  316. struct zram *zram = dev_to_zram(dev);
  317. char *p;
  318. ssize_t ret;
  319. down_read(&zram->init_lock);
  320. file = zram->backing_dev;
  321. if (!file) {
  322. memcpy(buf, "none\n", 5);
  323. up_read(&zram->init_lock);
  324. return 5;
  325. }
  326. p = file_path(file, buf, PAGE_SIZE - 1);
  327. if (IS_ERR(p)) {
  328. ret = PTR_ERR(p);
  329. goto out;
  330. }
  331. ret = strlen(p);
  332. memmove(buf, p, ret);
  333. buf[ret++] = '\n';
  334. out:
  335. up_read(&zram->init_lock);
  336. return ret;
  337. }
  338. static ssize_t backing_dev_store(struct device *dev,
  339. struct device_attribute *attr, const char *buf, size_t len)
  340. {
  341. char *file_name;
  342. size_t sz;
  343. struct file *backing_dev = NULL;
  344. struct inode *inode;
  345. struct address_space *mapping;
  346. unsigned int bitmap_sz;
  347. unsigned long nr_pages, nr_size, *bitmap = NULL;
  348. struct block_device *bdev = NULL;
  349. int err;
  350. struct zram *zram = dev_to_zram(dev);
  351. file_name = kmalloc(PATH_MAX, GFP_KERNEL);
  352. if (!file_name)
  353. return -ENOMEM;
  354. down_write(&zram->init_lock);
  355. if (init_done(zram)) {
  356. pr_info("Can't setup backing device for initialized device\n");
  357. err = -EBUSY;
  358. goto out;
  359. }
  360. strlcpy(file_name, buf, PATH_MAX);
  361. /* ignore trailing newline */
  362. sz = strlen(file_name);
  363. if (sz > 0 && file_name[sz - 1] == '\n')
  364. file_name[sz - 1] = 0x00;
  365. backing_dev = filp_open(file_name, O_RDWR|O_LARGEFILE, 0);
  366. if (IS_ERR(backing_dev)) {
  367. err = PTR_ERR(backing_dev);
  368. backing_dev = NULL;
  369. goto out;
  370. }
  371. mapping = backing_dev->f_mapping;
  372. inode = mapping->host;
  373. /* Support only block device in this moment */
  374. if (!S_ISBLK(inode->i_mode)) {
  375. err = -ENOTBLK;
  376. goto out;
  377. }
  378. bdev = blkdev_get_by_dev(inode->i_rdev,
  379. FMODE_READ | FMODE_WRITE | FMODE_EXCL, zram);
  380. if (IS_ERR(bdev)) {
  381. err = PTR_ERR(bdev);
  382. bdev = NULL;
  383. goto out;
  384. }
  385. nr_size = i_size_read(inode);
  386. nr_pages = nr_size >> PAGE_SHIFT;
  387. bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
  388. bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
  389. if (!bitmap) {
  390. err = -ENOMEM;
  391. goto out;
  392. }
  393. // Trim the device
  394. pr_info("discarding backing device\n");
  395. err = blkdev_issue_discard(bdev, 0, nr_size >> 9, GFP_KERNEL, 0);
  396. if (err)
  397. pr_warn("failed to discard device: %d\n", err);
  398. reset_bdev(zram);
  399. zram->bdev = bdev;
  400. zram->backing_dev = backing_dev;
  401. zram->bitmap = bitmap;
  402. zram->nr_pages = nr_pages;
  403. /*
  404. * With writeback feature, zram does asynchronous IO so it's no longer
  405. * synchronous device so let's remove synchronous io flag. Othewise,
  406. * upper layer(e.g., swap) could wait IO completion rather than
  407. * (submit and return), which will cause system sluggish.
  408. * Furthermore, when the IO function returns(e.g., swap_readpage),
  409. * upper layer expects IO was done so it could deallocate the page
  410. * freely but in fact, IO is going on so finally could cause
  411. * use-after-free when the IO is really done.
  412. */
  413. zram->disk->queue->backing_dev_info->capabilities &=
  414. ~BDI_CAP_SYNCHRONOUS_IO;
  415. up_write(&zram->init_lock);
  416. pr_info("setup backing device %s\n", file_name);
  417. kfree(file_name);
  418. return len;
  419. out:
  420. kvfree(bitmap);
  421. if (bdev)
  422. blkdev_put(bdev, FMODE_READ | FMODE_WRITE | FMODE_EXCL);
  423. if (backing_dev)
  424. filp_close(backing_dev, NULL);
  425. up_write(&zram->init_lock);
  426. kfree(file_name);
  427. return err;
  428. }
  429. static unsigned long alloc_block_bdev(struct zram *zram)
  430. {
  431. unsigned long blk_idx = 1;
  432. retry:
  433. /* skip 0 bit to confuse zram.handle = 0 */
  434. blk_idx = find_next_zero_bit(zram->bitmap, zram->nr_pages, blk_idx);
  435. if (blk_idx == zram->nr_pages)
  436. return 0;
  437. if (test_and_set_bit(blk_idx, zram->bitmap))
  438. goto retry;
  439. atomic64_inc(&zram->stats.bd_count);
  440. return blk_idx;
  441. }
  442. static void free_block_bdev(struct zram *zram, unsigned long blk_idx)
  443. {
  444. int was_set;
  445. was_set = test_and_clear_bit(blk_idx, zram->bitmap);
  446. WARN_ON_ONCE(!was_set);
  447. atomic64_dec(&zram->stats.bd_count);
  448. }
  449. static void zram_page_end_io(struct bio *bio)
  450. {
  451. struct page *page = bio->bi_io_vec[0].bv_page;
  452. page_endio(page, op_is_write(bio_op(bio)),
  453. blk_status_to_errno(bio->bi_status));
  454. bio_put(bio);
  455. }
  456. /*
  457. * Returns 1 if the submission is successful.
  458. */
  459. static int read_from_bdev_async(struct zram *zram, struct bio_vec *bvec,
  460. unsigned long entry, struct bio *parent)
  461. {
  462. struct bio *bio;
  463. bio = bio_alloc(GFP_ATOMIC, 1);
  464. if (!bio)
  465. return -ENOMEM;
  466. bio->bi_iter.bi_sector = entry * (PAGE_SIZE >> 9);
  467. bio_set_dev(bio, zram->bdev);
  468. if (!bio_add_page(bio, bvec->bv_page, bvec->bv_len, bvec->bv_offset)) {
  469. bio_put(bio);
  470. return -EIO;
  471. }
  472. if (!parent) {
  473. bio->bi_opf = REQ_OP_READ;
  474. bio->bi_end_io = zram_page_end_io;
  475. } else {
  476. bio->bi_opf = parent->bi_opf;
  477. bio_chain(bio, parent);
  478. }
  479. submit_bio(bio);
  480. return 1;
  481. }
  482. #define FOUR_K(x) ((x) * (1 << (PAGE_SHIFT - 12)))
  483. static int do_writeback(struct zram *zram)
  484. {
  485. unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
  486. unsigned long index = 0;
  487. struct bio bio;
  488. struct bio_vec bio_vec;
  489. struct page *page;
  490. int ret = 0;
  491. int err;
  492. unsigned long blk_idx = 0;
  493. down_read(&zram->init_lock);
  494. if (!init_done(zram)) {
  495. ret = -EINVAL;
  496. goto release_init_lock;
  497. }
  498. if (!zram->backing_dev) {
  499. ret = -ENODEV;
  500. goto release_init_lock;
  501. }
  502. page = alloc_page(GFP_KERNEL);
  503. if (!page) {
  504. ret = -ENOMEM;
  505. goto release_init_lock;
  506. }
  507. for (; nr_pages != 0; index++, nr_pages--) {
  508. struct bio_vec bvec;
  509. if (!blk_idx) {
  510. blk_idx = alloc_block_bdev(zram);
  511. if (!blk_idx) {
  512. ret = -ENOSPC;
  513. break;
  514. }
  515. }
  516. zram_slot_lock(zram, index);
  517. if (!zram_allocated(zram, index))
  518. goto next;
  519. if (zram_test_flag(zram, index, ZRAM_WB) ||
  520. zram_test_flag(zram, index, ZRAM_SAME) ||
  521. zram_test_flag(zram, index, ZRAM_DEDUPED) ||
  522. zram_test_flag(zram, index, ZRAM_UNDER_WB))
  523. goto next;
  524. if (!zram_test_flag(zram, index, ZRAM_IDLE))
  525. goto next;
  526. /*
  527. * Clearing ZRAM_UNDER_WB is duty of caller.
  528. * IOW, zram_free_page never clear it.
  529. */
  530. zram_set_flag(zram, index, ZRAM_UNDER_WB);
  531. /* Need for hugepage writeback racing */
  532. zram_set_flag(zram, index, ZRAM_IDLE);
  533. zram_slot_unlock(zram, index);
  534. bvec.bv_page = page;
  535. bvec.bv_len = PAGE_SIZE;
  536. bvec.bv_offset = 0;
  537. if (zram_bvec_read(zram, &bvec, index, 0, NULL)) {
  538. zram_slot_lock(zram, index);
  539. zram_clear_flag(zram, index, ZRAM_UNDER_WB);
  540. zram_clear_flag(zram, index, ZRAM_IDLE);
  541. zram_slot_unlock(zram, index);
  542. continue;
  543. }
  544. bio_init(&bio, &bio_vec, 1);
  545. bio_set_dev(&bio, zram->bdev);
  546. bio.bi_iter.bi_sector = blk_idx * (PAGE_SIZE >> 9);
  547. bio.bi_opf = REQ_OP_WRITE | REQ_SYNC;
  548. bio_add_page(&bio, bvec.bv_page, bvec.bv_len,
  549. bvec.bv_offset);
  550. /*
  551. * XXX: A single page IO would be inefficient for write
  552. * but it would be not bad as starter.
  553. */
  554. err = submit_bio_wait(&bio);
  555. if (err) {
  556. zram_slot_lock(zram, index);
  557. zram_clear_flag(zram, index, ZRAM_UNDER_WB);
  558. zram_clear_flag(zram, index, ZRAM_IDLE);
  559. zram_slot_unlock(zram, index);
  560. /*
  561. * Return last IO error unless every IO were
  562. * not suceeded.
  563. */
  564. ret = err;
  565. continue;
  566. }
  567. atomic64_inc(&zram->stats.bd_writes);
  568. /*
  569. * We released zram_slot_lock so need to check if the slot was
  570. * changed. If there is freeing for the slot, we can catch it
  571. * easily by zram_allocated.
  572. * A subtle case is the slot is freed/reallocated/marked as
  573. * ZRAM_IDLE again. To close the race, idle_store doesn't
  574. * mark ZRAM_IDLE once it found the slot was ZRAM_UNDER_WB.
  575. * Thus, we could close the race by checking ZRAM_IDLE bit.
  576. */
  577. zram_slot_lock(zram, index);
  578. if (!zram_allocated(zram, index) ||
  579. !zram_test_flag(zram, index, ZRAM_IDLE)) {
  580. zram_clear_flag(zram, index, ZRAM_UNDER_WB);
  581. zram_clear_flag(zram, index, ZRAM_IDLE);
  582. goto next;
  583. }
  584. zram_free_page(zram, index);
  585. zram_clear_flag(zram, index, ZRAM_UNDER_WB);
  586. zram_set_flag(zram, index, ZRAM_WB);
  587. zram_set_element(zram, index, blk_idx);
  588. blk_idx = 0;
  589. atomic64_inc(&zram->stats.pages_stored);
  590. next:
  591. zram_slot_unlock(zram, index);
  592. }
  593. if (blk_idx)
  594. free_block_bdev(zram, blk_idx);
  595. __free_page(page);
  596. release_init_lock:
  597. pr_info("writeback: C: %llu MiB, R: %llu MiB, W: %llu MiB\n",
  598. FOUR_K((u64)atomic64_read(&zram->stats.bd_count)) / 256,
  599. FOUR_K((u64)atomic64_read(&zram->stats.bd_reads)) / 256,
  600. FOUR_K((u64)atomic64_read(&zram->stats.bd_writes)) / 256);
  601. up_read(&zram->init_lock);
  602. return ret;
  603. }
  604. struct zram_work {
  605. struct work_struct work;
  606. struct zram *zram;
  607. unsigned long entry;
  608. struct bio *bio;
  609. struct bio_vec bvec;
  610. };
  611. #if PAGE_SIZE != 4096
  612. static void zram_sync_read(struct work_struct *work)
  613. {
  614. struct zram_work *zw = container_of(work, struct zram_work, work);
  615. struct zram *zram = zw->zram;
  616. unsigned long entry = zw->entry;
  617. struct bio *bio = zw->bio;
  618. read_from_bdev_async(zram, &zw->bvec, entry, bio);
  619. }
  620. /*
  621. * Block layer want one ->make_request_fn to be active at a time
  622. * so if we use chained IO with parent IO in same context,
  623. * it's a deadlock. To avoid, it, it uses worker thread context.
  624. */
  625. static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
  626. unsigned long entry, struct bio *bio)
  627. {
  628. struct zram_work work;
  629. work.bvec = *bvec;
  630. work.zram = zram;
  631. work.entry = entry;
  632. work.bio = bio;
  633. INIT_WORK_ONSTACK(&work.work, zram_sync_read);
  634. queue_work(system_unbound_wq, &work.work);
  635. flush_work(&work.work);
  636. destroy_work_on_stack(&work.work);
  637. return 1;
  638. }
  639. #else
  640. static int read_from_bdev_sync(struct zram *zram, struct bio_vec *bvec,
  641. unsigned long entry, struct bio *bio)
  642. {
  643. WARN_ON(1);
  644. return -EIO;
  645. }
  646. #endif
  647. static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
  648. unsigned long entry, struct bio *parent, bool sync)
  649. {
  650. atomic64_inc(&zram->stats.bd_reads);
  651. if (sync)
  652. return read_from_bdev_sync(zram, bvec, entry, parent);
  653. else
  654. return read_from_bdev_async(zram, bvec, entry, parent);
  655. }
  656. #else
  657. static inline void reset_bdev(struct zram *zram) {};
  658. static int read_from_bdev(struct zram *zram, struct bio_vec *bvec,
  659. unsigned long entry, struct bio *parent, bool sync)
  660. {
  661. return -EIO;
  662. }
  663. static void free_block_bdev(struct zram *zram, unsigned long blk_idx) {};
  664. #endif
  665. #ifdef CONFIG_ZRAM_MEMORY_TRACKING
  666. static struct dentry *zram_debugfs_root;
  667. static void zram_debugfs_create(void)
  668. {
  669. zram_debugfs_root = debugfs_create_dir("zram", NULL);
  670. }
  671. static void zram_debugfs_destroy(void)
  672. {
  673. debugfs_remove_recursive(zram_debugfs_root);
  674. }
  675. static void zram_accessed(struct zram *zram, u32 index)
  676. {
  677. zram_clear_flag(zram, index, ZRAM_IDLE);
  678. zram->table[index].ac_time = total_touch_clock;
  679. }
  680. static ssize_t read_block_state(struct file *file, char __user *buf,
  681. size_t count, loff_t *ppos)
  682. {
  683. char *kbuf;
  684. ssize_t index, written = 0;
  685. struct zram *zram = file->private_data;
  686. unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
  687. unsigned long long *clock;
  688. kbuf = kvmalloc(count, GFP_KERNEL);
  689. if (!kbuf)
  690. return -ENOMEM;
  691. down_read(&zram->init_lock);
  692. if (!init_done(zram)) {
  693. up_read(&zram->init_lock);
  694. kvfree(kbuf);
  695. return -EINVAL;
  696. }
  697. for (index = *ppos; index < nr_pages; index++) {
  698. int copied;
  699. zram_slot_lock(zram, index);
  700. if (!zram_allocated(zram, index))
  701. goto next;
  702. clock = &zram->table[index].ac_time;
  703. copied = snprintf(kbuf + written, count,
  704. "%12zd %12llu.%06llu %c%c%c%c\n",
  705. index,
  706. *clock / NSEC_PER_SEC,
  707. *clock / NSEC_PER_USEC % USEC_PER_SEC,
  708. zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
  709. zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
  710. zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.',
  711. zram_test_flag(zram, index, ZRAM_DEDUPED) ? 'd' : '.');
  712. if (count < copied) {
  713. zram_slot_unlock(zram, index);
  714. break;
  715. }
  716. written += copied;
  717. count -= copied;
  718. next:
  719. zram_slot_unlock(zram, index);
  720. *ppos += 1;
  721. }
  722. up_read(&zram->init_lock);
  723. if (copy_to_user(buf, kbuf, written))
  724. written = -EFAULT;
  725. kvfree(kbuf);
  726. return written;
  727. }
  728. static const struct file_operations proc_zram_block_state_op = {
  729. .open = simple_open,
  730. .read = read_block_state,
  731. .llseek = default_llseek,
  732. };
  733. static void zram_debugfs_register(struct zram *zram)
  734. {
  735. if (!zram_debugfs_root)
  736. return;
  737. zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
  738. zram_debugfs_root);
  739. debugfs_create_file("block_state", 0400, zram->debugfs_dir,
  740. zram, &proc_zram_block_state_op);
  741. }
  742. static void zram_debugfs_unregister(struct zram *zram)
  743. {
  744. debugfs_remove_recursive(zram->debugfs_dir);
  745. }
  746. #else
  747. static void zram_debugfs_create(void) {};
  748. static void zram_debugfs_destroy(void) {};
  749. static void zram_accessed(struct zram *zram, u32 index)
  750. {
  751. zram_clear_flag(zram, index, ZRAM_IDLE);
  752. };
  753. static void zram_debugfs_register(struct zram *zram) {};
  754. static void zram_debugfs_unregister(struct zram *zram) {};
  755. #endif
  756. /*
  757. * We switched to per-cpu streams and this attr is not needed anymore.
  758. * However, we will keep it around for some time, because:
  759. * a) we may revert per-cpu streams in the future
  760. * b) it's visible to user space and we need to follow our 2 years
  761. * retirement rule; but we already have a number of 'soon to be
  762. * altered' attrs, so max_comp_streams need to wait for the next
  763. * layoff cycle.
  764. */
  765. static ssize_t max_comp_streams_show(struct device *dev,
  766. struct device_attribute *attr, char *buf)
  767. {
  768. return scnprintf(buf, PAGE_SIZE, "%d\n", num_online_cpus());
  769. }
  770. static ssize_t max_comp_streams_store(struct device *dev,
  771. struct device_attribute *attr, const char *buf, size_t len)
  772. {
  773. return len;
  774. }
  775. static ssize_t comp_algorithm_show(struct device *dev,
  776. struct device_attribute *attr, char *buf)
  777. {
  778. size_t sz;
  779. struct zram *zram = dev_to_zram(dev);
  780. down_read(&zram->init_lock);
  781. sz = zcomp_available_show(zram->compressor, buf);
  782. up_read(&zram->init_lock);
  783. return sz;
  784. }
  785. static ssize_t comp_algorithm_store(struct device *dev,
  786. struct device_attribute *attr, const char *buf, size_t len)
  787. {
  788. struct zram *zram = dev_to_zram(dev);
  789. char compressor[ARRAY_SIZE(zram->compressor)];
  790. size_t sz;
  791. strlcpy(compressor, buf, sizeof(compressor));
  792. /* ignore trailing newline */
  793. sz = strlen(compressor);
  794. if (sz > 0 && compressor[sz - 1] == '\n')
  795. compressor[sz - 1] = 0x00;
  796. if (!zcomp_available_algorithm(compressor))
  797. return -EINVAL;
  798. down_write(&zram->init_lock);
  799. if (init_done(zram)) {
  800. up_write(&zram->init_lock);
  801. pr_info("Can't change algorithm for initialized device\n");
  802. return -EBUSY;
  803. }
  804. strcpy(zram->compressor, compressor);
  805. up_write(&zram->init_lock);
  806. return len;
  807. }
  808. static ssize_t use_dedup_show(struct device *dev,
  809. struct device_attribute *attr, char *buf)
  810. {
  811. bool val;
  812. struct zram *zram = dev_to_zram(dev);
  813. down_read(&zram->init_lock);
  814. val = zram->use_dedup;
  815. up_read(&zram->init_lock);
  816. return scnprintf(buf, PAGE_SIZE, "%d\n", (int)val);
  817. }
  818. #ifdef CONFIG_ZRAM_DEDUP
  819. static ssize_t use_dedup_store(struct device *dev,
  820. struct device_attribute *attr, const char *buf, size_t len)
  821. {
  822. int val;
  823. struct zram *zram = dev_to_zram(dev);
  824. if (kstrtoint(buf, 10, &val) || (val != 0 && val != 1))
  825. return -EINVAL;
  826. down_write(&zram->init_lock);
  827. if (init_done(zram)) {
  828. up_write(&zram->init_lock);
  829. pr_info("Can't change dedup usage for initialized device\n");
  830. return -EBUSY;
  831. }
  832. zram->use_dedup = val;
  833. up_write(&zram->init_lock);
  834. return len;
  835. }
  836. #endif
  837. static ssize_t compact_store(struct device *dev,
  838. struct device_attribute *attr, const char *buf, size_t len)
  839. {
  840. struct zram *zram = dev_to_zram(dev);
  841. down_read(&zram->init_lock);
  842. if (!init_done(zram)) {
  843. up_read(&zram->init_lock);
  844. return -EINVAL;
  845. }
  846. zs_compact(zram->mem_pool);
  847. up_read(&zram->init_lock);
  848. return len;
  849. }
  850. static ssize_t io_stat_show(struct device *dev,
  851. struct device_attribute *attr, char *buf)
  852. {
  853. struct zram *zram = dev_to_zram(dev);
  854. ssize_t ret;
  855. down_read(&zram->init_lock);
  856. ret = scnprintf(buf, PAGE_SIZE,
  857. "%8llu %8llu %8llu %8llu\n",
  858. (u64)atomic64_read(&zram->stats.failed_reads),
  859. (u64)atomic64_read(&zram->stats.failed_writes),
  860. (u64)atomic64_read(&zram->stats.invalid_io),
  861. (u64)atomic64_read(&zram->stats.notify_free));
  862. up_read(&zram->init_lock);
  863. return ret;
  864. }
  865. static ssize_t mm_stat_show(struct device *dev,
  866. struct device_attribute *attr, char *buf)
  867. {
  868. struct zram *zram = dev_to_zram(dev);
  869. struct zs_pool_stats pool_stats;
  870. u64 orig_size, mem_used = 0;
  871. long max_used;
  872. ssize_t ret;
  873. memset(&pool_stats, 0x00, sizeof(struct zs_pool_stats));
  874. down_read(&zram->init_lock);
  875. if (init_done(zram)) {
  876. mem_used = zs_get_total_pages(zram->mem_pool);
  877. zs_pool_stats(zram->mem_pool, &pool_stats);
  878. }
  879. orig_size = atomic64_read(&zram->stats.pages_stored);
  880. max_used = atomic_long_read(&zram->stats.max_used_pages);
  881. ret = scnprintf(buf, PAGE_SIZE,
  882. "%8llu %8llu %8llu %8lu %8ld %8llu %8lu %8llu %8llu\n",
  883. (orig_size << PAGE_SHIFT) / 1048576,
  884. ((u64)atomic64_read(&zram->stats.compr_data_size)) / 1048576,
  885. (mem_used << PAGE_SHIFT) / 1048576,
  886. (zram->limit_pages << PAGE_SHIFT) / 1048576,
  887. (max_used << PAGE_SHIFT) / 1048576,
  888. ((u64)atomic64_read(&zram->stats.same_pages)) / 256,
  889. (atomic_long_read(&pool_stats.pages_compacted)) / 256,
  890. (zram_dedup_dup_size(zram)) / 1048576,
  891. (zram_dedup_meta_size(zram)) / 1048576);
  892. up_read(&zram->init_lock);
  893. return ret;
  894. }
  895. #ifdef CONFIG_ZRAM_WRITEBACK
  896. static ssize_t bd_stat_show(struct device *dev,
  897. struct device_attribute *attr, char *buf)
  898. {
  899. struct zram *zram = dev_to_zram(dev);
  900. ssize_t ret;
  901. down_read(&zram->init_lock);
  902. ret = scnprintf(buf, PAGE_SIZE,
  903. "%8llu %8llu %8llu\n",
  904. FOUR_K((u64)atomic64_read(&zram->stats.bd_count)) / 256,
  905. FOUR_K((u64)atomic64_read(&zram->stats.bd_reads)) / 256,
  906. FOUR_K((u64)atomic64_read(&zram->stats.bd_writes)) / 256);
  907. up_read(&zram->init_lock);
  908. return ret;
  909. }
  910. #endif
  911. static ssize_t debug_stat_show(struct device *dev,
  912. struct device_attribute *attr, char *buf)
  913. {
  914. int version = 1;
  915. struct zram *zram = dev_to_zram(dev);
  916. ssize_t ret;
  917. down_read(&zram->init_lock);
  918. ret = scnprintf(buf, PAGE_SIZE,
  919. "version: %d\n%8llu %8llu\n",
  920. version,
  921. (u64)atomic64_read(&zram->stats.writestall),
  922. (u64)atomic64_read(&zram->stats.miss_free));
  923. up_read(&zram->init_lock);
  924. return ret;
  925. }
  926. static DEVICE_ATTR_RO(io_stat);
  927. static DEVICE_ATTR_RO(mm_stat);
  928. #ifdef CONFIG_ZRAM_WRITEBACK
  929. static DEVICE_ATTR_RO(bd_stat);
  930. #endif
  931. static DEVICE_ATTR_RO(debug_stat);
  932. static unsigned long zram_entry_handle(struct zram *zram,
  933. struct zram_entry *entry)
  934. {
  935. if (zram_dedup_enabled(zram))
  936. return entry->handle;
  937. else
  938. return (unsigned long)entry;
  939. }
  940. static struct zram_entry *zram_entry_alloc(struct zram *zram,
  941. unsigned int len, gfp_t flags)
  942. {
  943. struct zram_entry *entry;
  944. unsigned long handle;
  945. handle = zs_malloc(zram->mem_pool, len, flags);
  946. if (!handle)
  947. return NULL;
  948. if (!zram_dedup_enabled(zram))
  949. return (struct zram_entry *)handle;
  950. entry = kzalloc(sizeof(*entry),
  951. flags & ~(__GFP_HIGHMEM|__GFP_MOVABLE|__GFP_CMA));
  952. if (!entry) {
  953. zs_free(zram->mem_pool, handle);
  954. return NULL;
  955. }
  956. zram_dedup_init_entry(zram, entry, handle, len);
  957. atomic64_add(sizeof(*entry), &zram->stats.meta_data_size);
  958. return entry;
  959. }
  960. void zram_entry_free(struct zram *zram, struct zram_entry *entry)
  961. {
  962. if (!zram_dedup_put_entry(zram, entry))
  963. return;
  964. zs_free(zram->mem_pool, zram_entry_handle(zram, entry));
  965. if (!zram_dedup_enabled(zram))
  966. return;
  967. kfree(entry);
  968. atomic64_sub(sizeof(*entry), &zram->stats.meta_data_size);
  969. }
  970. static void zram_meta_free(struct zram *zram, u64 disksize)
  971. {
  972. size_t num_pages = disksize >> PAGE_SHIFT;
  973. size_t index;
  974. /* Free all pages that are still in this zram device */
  975. for (index = 0; index < num_pages; index++)
  976. zram_free_page(zram, index);
  977. zs_destroy_pool(zram->mem_pool);
  978. zram_dedup_fini(zram);
  979. vfree(zram->table);
  980. }
  981. static bool zram_meta_alloc(struct zram *zram, u64 disksize)
  982. {
  983. size_t num_pages;
  984. num_pages = disksize >> PAGE_SHIFT;
  985. zram->table = vzalloc(num_pages * sizeof(*zram->table));
  986. if (!zram->table)
  987. return false;
  988. zram->mem_pool = zs_create_pool(zram->disk->disk_name);
  989. if (!zram->mem_pool) {
  990. vfree(zram->table);
  991. return false;
  992. }
  993. if (!huge_class_size)
  994. huge_class_size = zs_huge_class_size(zram->mem_pool);
  995. if (zram_dedup_init(zram, num_pages)) {
  996. vfree(zram->table);
  997. zs_destroy_pool(zram->mem_pool);
  998. return false;
  999. }
  1000. return true;
  1001. }
  1002. /*
  1003. * To protect concurrent access to the same index entry,
  1004. * caller should hold this table index entry's bit_spinlock to
  1005. * indicate this index entry is accessing.
  1006. */
  1007. static void zram_free_page(struct zram *zram, size_t index)
  1008. {
  1009. struct zram_entry *entry;
  1010. #ifdef CONFIG_ZRAM_MEMORY_TRACKING
  1011. zram->table[index].ac_time = 0;
  1012. #endif
  1013. if (zram_test_flag(zram, index, ZRAM_IDLE))
  1014. zram_clear_flag(zram, index, ZRAM_IDLE);
  1015. if (zram_test_flag(zram, index, ZRAM_DEDUPED))
  1016. zram_clear_flag(zram, index, ZRAM_DEDUPED);
  1017. if (zram_test_flag(zram, index, ZRAM_WB)) {
  1018. zram_clear_flag(zram, index, ZRAM_WB);
  1019. free_block_bdev(zram, zram_get_element(zram, index));
  1020. goto out;
  1021. }
  1022. /*
  1023. * No memory is allocated for same element filled pages.
  1024. * Simply clear same page flag.
  1025. */
  1026. if (zram_test_flag(zram, index, ZRAM_SAME)) {
  1027. zram_clear_flag(zram, index, ZRAM_SAME);
  1028. atomic64_dec(&zram->stats.same_pages);
  1029. goto out;
  1030. }
  1031. entry = zram_get_entry(zram, index);
  1032. if (!entry)
  1033. return;
  1034. zram_entry_free(zram, entry);
  1035. atomic64_sub(zram_get_obj_size(zram, index),
  1036. &zram->stats.compr_data_size);
  1037. out:
  1038. atomic64_dec(&zram->stats.pages_stored);
  1039. zram_set_entry(zram, index, NULL);
  1040. zram_set_obj_size(zram, index, 0);
  1041. WARN_ON_ONCE(zram->table[index].flags &
  1042. ~(1UL << ZRAM_LOCK | 1UL << ZRAM_UNDER_WB));
  1043. }
  1044. static int __zram_bvec_read(struct zram *zram, struct page *page, u32 index,
  1045. struct bio *bio, bool partial_io)
  1046. {
  1047. struct zcomp_strm *zstrm;
  1048. struct zram_entry *entry;
  1049. unsigned int size;
  1050. void *src, *dst;
  1051. int ret;
  1052. zram_slot_lock(zram, index);
  1053. if (zram_test_flag(zram, index, ZRAM_WB)) {
  1054. struct bio_vec bvec;
  1055. zram_slot_unlock(zram, index);
  1056. bvec.bv_page = page;
  1057. bvec.bv_len = PAGE_SIZE;
  1058. bvec.bv_offset = 0;
  1059. return read_from_bdev(zram, &bvec,
  1060. zram_get_element(zram, index),
  1061. bio, partial_io);
  1062. }
  1063. entry = zram_get_entry(zram, index);
  1064. if (!entry || zram_test_flag(zram, index, ZRAM_SAME)) {
  1065. unsigned long value;
  1066. void *mem;
  1067. value = entry ? zram_get_element(zram, index) : 0;
  1068. mem = kmap_atomic(page);
  1069. zram_fill_page(mem, PAGE_SIZE, value);
  1070. kunmap_atomic(mem);
  1071. zram_slot_unlock(zram, index);
  1072. return 0;
  1073. }
  1074. size = zram_get_obj_size(zram, index);
  1075. if (size != PAGE_SIZE)
  1076. zstrm = zcomp_stream_get(zram->comp);
  1077. src = zs_map_object(zram->mem_pool,
  1078. zram_entry_handle(zram, entry), ZS_MM_RO);
  1079. if (size == PAGE_SIZE) {
  1080. dst = kmap_atomic(page);
  1081. memcpy(dst, src, PAGE_SIZE);
  1082. kunmap_atomic(dst);
  1083. ret = 0;
  1084. } else {
  1085. dst = kmap_atomic(page);
  1086. ret = zcomp_decompress(zstrm, src, size, dst);
  1087. kunmap_atomic(dst);
  1088. zcomp_stream_put(zram->comp);
  1089. }
  1090. zs_unmap_object(zram->mem_pool, zram_entry_handle(zram, entry));
  1091. zram_slot_unlock(zram, index);
  1092. /* Should NEVER happen. Return bio error if it does. */
  1093. if (WARN_ON(ret))
  1094. pr_err("Decompression failed! err=%d, page=%u\n", ret, index);
  1095. return ret;
  1096. }
  1097. static int zram_bvec_read(struct zram *zram, struct bio_vec *bvec,
  1098. u32 index, int offset, struct bio *bio)
  1099. {
  1100. int ret;
  1101. struct page *page;
  1102. page = bvec->bv_page;
  1103. if (is_partial_io(bvec)) {
  1104. /* Use a temporary buffer to decompress the page */
  1105. page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
  1106. if (!page)
  1107. return -ENOMEM;
  1108. }
  1109. ret = __zram_bvec_read(zram, page, index, bio, is_partial_io(bvec));
  1110. if (unlikely(ret))
  1111. goto out;
  1112. if (is_partial_io(bvec)) {
  1113. void *dst = kmap_atomic(bvec->bv_page);
  1114. void *src = kmap_atomic(page);
  1115. memcpy(dst + bvec->bv_offset, src + offset, bvec->bv_len);
  1116. kunmap_atomic(src);
  1117. kunmap_atomic(dst);
  1118. }
  1119. out:
  1120. if (is_partial_io(bvec))
  1121. __free_page(page);
  1122. return ret;
  1123. }
  1124. static int __zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
  1125. u32 index, struct bio *bio)
  1126. {
  1127. int ret = 0;
  1128. unsigned long alloced_pages;
  1129. struct zram_entry *entry = NULL;
  1130. unsigned int comp_len = 0;
  1131. void *src, *dst, *mem;
  1132. struct zcomp_strm *zstrm;
  1133. struct page *page = bvec->bv_page;
  1134. u32 checksum;
  1135. unsigned long element = 0;
  1136. enum zram_pageflags flags = 0;
  1137. mem = kmap_atomic(page);
  1138. if (page_same_filled(mem, &element)) {
  1139. kunmap_atomic(mem);
  1140. /* Free memory associated with this sector now. */
  1141. flags = ZRAM_SAME;
  1142. atomic64_inc(&zram->stats.same_pages);
  1143. goto out;
  1144. }
  1145. kunmap_atomic(mem);
  1146. entry = zram_dedup_find(zram, page, &checksum);
  1147. if (entry) {
  1148. flags = ZRAM_DEDUPED;
  1149. comp_len = entry->len;
  1150. goto out;
  1151. }
  1152. compress_again:
  1153. zstrm = zcomp_stream_get(zram->comp);
  1154. src = kmap_atomic(page);
  1155. ret = zcomp_compress(zstrm, src, &comp_len);
  1156. kunmap_atomic(src);
  1157. if (unlikely(ret)) {
  1158. zcomp_stream_put(zram->comp);
  1159. pr_err("Compression failed! err=%d\n", ret);
  1160. if (entry)
  1161. zram_entry_free(zram, entry);
  1162. return ret;
  1163. }
  1164. if (comp_len >= huge_class_size)
  1165. comp_len = PAGE_SIZE;
  1166. /*
  1167. * entry allocation has 2 paths:
  1168. * a) fast path is executed with preemption disabled (for
  1169. * per-cpu streams) and has __GFP_DIRECT_RECLAIM bit clear,
  1170. * since we can't sleep;
  1171. * b) slow path enables preemption and attempts to allocate
  1172. * the page with __GFP_DIRECT_RECLAIM bit set. we have to
  1173. * put per-cpu compression stream and, thus, to re-do
  1174. * the compression once entry is allocated.
  1175. *
  1176. * if we have a 'non-null' entry here then we are coming
  1177. * from the slow path and entry has already been allocated.
  1178. */
  1179. if (!entry)
  1180. entry = zram_entry_alloc(zram, comp_len,
  1181. __GFP_KSWAPD_RECLAIM |
  1182. __GFP_NOWARN |
  1183. __GFP_HIGHMEM |
  1184. __GFP_MOVABLE);
  1185. if (!entry) {
  1186. zcomp_stream_put(zram->comp);
  1187. atomic64_inc(&zram->stats.writestall);
  1188. entry = zram_entry_alloc(zram, comp_len,
  1189. GFP_NOIO | __GFP_HIGHMEM |
  1190. __GFP_MOVABLE);
  1191. if (entry)
  1192. goto compress_again;
  1193. return -ENOMEM;
  1194. }
  1195. alloced_pages = zs_get_total_pages(zram->mem_pool);
  1196. update_used_max(zram, alloced_pages);
  1197. if (zram->limit_pages && alloced_pages > zram->limit_pages) {
  1198. zcomp_stream_put(zram->comp);
  1199. zram_entry_free(zram, entry);
  1200. return -ENOMEM;
  1201. }
  1202. dst = zs_map_object(zram->mem_pool,
  1203. zram_entry_handle(zram, entry), ZS_MM_WO);
  1204. src = zstrm->buffer;
  1205. if (comp_len == PAGE_SIZE)
  1206. src = kmap_atomic(page);
  1207. memcpy(dst, src, comp_len);
  1208. if (comp_len == PAGE_SIZE)
  1209. kunmap_atomic(src);
  1210. zcomp_stream_put(zram->comp);
  1211. zs_unmap_object(zram->mem_pool, zram_entry_handle(zram, entry));
  1212. atomic64_add(comp_len, &zram->stats.compr_data_size);
  1213. zram_dedup_insert(zram, entry, checksum);
  1214. out:
  1215. /*
  1216. * Free memory associated with this sector
  1217. * before overwriting unused sectors.
  1218. */
  1219. zram_slot_lock(zram, index);
  1220. zram_free_page(zram, index);
  1221. switch (flags) {
  1222. case ZRAM_SAME:
  1223. zram_set_flag(zram, index, flags);
  1224. zram_set_element(zram, index, element);
  1225. break;
  1226. case ZRAM_DEDUPED:
  1227. zram_set_flag(zram, index, flags);
  1228. // Fallthrough
  1229. default:
  1230. zram_set_entry(zram, index, entry);
  1231. zram_set_obj_size(zram, index, comp_len);
  1232. }
  1233. zram_slot_unlock(zram, index);
  1234. /* Update stats */
  1235. atomic64_inc(&zram->stats.pages_stored);
  1236. return ret;
  1237. }
  1238. static int zram_bvec_write(struct zram *zram, struct bio_vec *bvec,
  1239. u32 index, int offset, struct bio *bio)
  1240. {
  1241. int ret;
  1242. struct page *page = NULL;
  1243. void *src;
  1244. struct bio_vec vec;
  1245. vec = *bvec;
  1246. if (is_partial_io(bvec)) {
  1247. void *dst;
  1248. /*
  1249. * This is a partial IO. We need to read the full page
  1250. * before to write the changes.
  1251. */
  1252. page = alloc_page(GFP_NOIO|__GFP_HIGHMEM);
  1253. if (!page)
  1254. return -ENOMEM;
  1255. ret = __zram_bvec_read(zram, page, index, bio, true);
  1256. if (ret)
  1257. goto out;
  1258. src = kmap_atomic(bvec->bv_page);
  1259. dst = kmap_atomic(page);
  1260. memcpy(dst + offset, src + bvec->bv_offset, bvec->bv_len);
  1261. kunmap_atomic(dst);
  1262. kunmap_atomic(src);
  1263. vec.bv_page = page;
  1264. vec.bv_len = PAGE_SIZE;
  1265. vec.bv_offset = 0;
  1266. }
  1267. ret = __zram_bvec_write(zram, &vec, index, bio);
  1268. out:
  1269. if (is_partial_io(bvec))
  1270. __free_page(page);
  1271. return ret;
  1272. }
  1273. /*
  1274. * zram_bio_discard - handler on discard request
  1275. * @index: physical block index in PAGE_SIZE units
  1276. * @offset: byte offset within physical block
  1277. */
  1278. static void zram_bio_discard(struct zram *zram, u32 index,
  1279. int offset, struct bio *bio)
  1280. {
  1281. size_t n = bio->bi_iter.bi_size;
  1282. /*
  1283. * zram manages data in physical block size units. Because logical block
  1284. * size isn't identical with physical block size on some arch, we
  1285. * could get a discard request pointing to a specific offset within a
  1286. * certain physical block. Although we can handle this request by
  1287. * reading that physiclal block and decompressing and partially zeroing
  1288. * and re-compressing and then re-storing it, this isn't reasonable
  1289. * because our intent with a discard request is to save memory. So
  1290. * skipping this logical block is appropriate here.
  1291. */
  1292. if (offset) {
  1293. if (n <= (PAGE_SIZE - offset))
  1294. return;
  1295. n -= (PAGE_SIZE - offset);
  1296. index++;
  1297. }
  1298. while (n >= PAGE_SIZE) {
  1299. zram_slot_lock(zram, index);
  1300. zram_free_page(zram, index);
  1301. zram_slot_unlock(zram, index);
  1302. atomic64_inc(&zram->stats.notify_free);
  1303. index++;
  1304. n -= PAGE_SIZE;
  1305. }
  1306. }
  1307. /*
  1308. * Returns errno if it has some problem. Otherwise return 0 or 1.
  1309. * Returns 0 if IO request was done synchronously
  1310. * Returns 1 if IO request was successfully submitted.
  1311. */
  1312. static int zram_bvec_rw(struct zram *zram, struct bio_vec *bvec, u32 index,
  1313. int offset, unsigned int op, struct bio *bio)
  1314. {
  1315. unsigned long start_time = jiffies;
  1316. struct request_queue *q = zram->disk->queue;
  1317. int ret;
  1318. generic_start_io_acct(q, op, bvec->bv_len >> SECTOR_SHIFT,
  1319. &zram->disk->part0);
  1320. if (!op_is_write(op)) {
  1321. atomic64_inc(&zram->stats.num_reads);
  1322. ret = zram_bvec_read(zram, bvec, index, offset, bio);
  1323. flush_dcache_page(bvec->bv_page);
  1324. } else {
  1325. atomic64_inc(&zram->stats.num_writes);
  1326. ret = zram_bvec_write(zram, bvec, index, offset, bio);
  1327. }
  1328. generic_end_io_acct(q, op, &zram->disk->part0, start_time);
  1329. zram_slot_lock(zram, index);
  1330. zram_accessed(zram, index);
  1331. zram_slot_unlock(zram, index);
  1332. if (unlikely(ret < 0)) {
  1333. if (!op_is_write(op))
  1334. atomic64_inc(&zram->stats.failed_reads);
  1335. else
  1336. atomic64_inc(&zram->stats.failed_writes);
  1337. }
  1338. return ret;
  1339. }
  1340. static void zram_wb_input_event(struct input_handle *handle,
  1341. unsigned int type, unsigned int code, int value)
  1342. {
  1343. static unsigned int prev_value = UINT_MAX;
  1344. static unsigned long long prev;
  1345. unsigned long long delta;
  1346. if (code != BTN_TOUCH)
  1347. return;
  1348. if (prev_value == value)
  1349. return;
  1350. if (!screen_on)
  1351. return;
  1352. if (value == 1) {
  1353. prev = sched_clock();
  1354. } else {
  1355. delta = sched_clock() - prev;
  1356. total_touch_clock += delta;
  1357. }
  1358. prev_value = value;
  1359. }
  1360. static int zram_wb_input_connect(struct input_handler *handler,
  1361. struct input_dev *dev, const struct input_device_id *id)
  1362. {
  1363. struct input_handle *handle;
  1364. int error;
  1365. handle = kzalloc(sizeof(struct input_handle), GFP_KERNEL);
  1366. if (!handle)
  1367. return -ENOMEM;
  1368. handle->dev = dev;
  1369. handle->handler = handler;
  1370. handle->name = "zram_wb";
  1371. // Initialize zram_wb_input_event()'s prev
  1372. zram_wb_input_event(NULL, 1, BTN_TOUCH, UINT_MAX);
  1373. error = input_register_handle(handle);
  1374. if (error)
  1375. goto err2;
  1376. error = input_open_device(handle);
  1377. if (error)
  1378. goto err1;
  1379. pr_info("%s found and connected!\n", dev->name);
  1380. return 0;
  1381. err1:
  1382. input_unregister_handle(handle);
  1383. err2:
  1384. kfree(handle);
  1385. return error;
  1386. }
  1387. static void zram_wb_input_disconnect(struct input_handle *handle)
  1388. {
  1389. input_close_device(handle);
  1390. input_unregister_handle(handle);
  1391. kfree(handle);
  1392. }
  1393. static const struct input_device_id zram_wb_input_ids[] = {
  1394. {
  1395. .flags = INPUT_DEVICE_ID_MATCH_KEYBIT,
  1396. .keybit = { [BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH) },
  1397. },
  1398. { },
  1399. };
  1400. static struct input_handler zram_wb_input_handler = {
  1401. .event = zram_wb_input_event,
  1402. .connect = zram_wb_input_connect,
  1403. .disconnect = zram_wb_input_disconnect,
  1404. .name = "zram_wb_input_handler",
  1405. .id_table = zram_wb_input_ids,
  1406. };
  1407. static void zram_wb_fb_work(struct work_struct *work)
  1408. {
  1409. struct blk_plug plug;
  1410. struct zram *zram;
  1411. int ret, id;
  1412. if (screen_on)
  1413. return;
  1414. // Force finger-up to zram_wb_input_event()
  1415. zram_wb_input_event(NULL, 1, BTN_TOUCH, 0);
  1416. // Work only if charger is connected
  1417. if (power_supply_is_system_supplied() <= 0)
  1418. return;
  1419. if (total_touch_clock <= (wb_start_mins * NSEC_PER_SEC * 60))
  1420. return;
  1421. mutex_lock(&zram_wb_wakelock_mutex);
  1422. __pm_stay_awake(&zram_wb_wakelock);
  1423. blk_start_plug(&plug);
  1424. idr_for_each_entry(&zram_index_idr, zram, id) {
  1425. // Start marking blocks if they are old enough
  1426. ret = mark_idle(zram, total_touch_clock - (wb_start_mins * NSEC_PER_SEC * 60));
  1427. pr_err("mark_idle() returned %d\n", ret);
  1428. if (ret <= 0)
  1429. continue;
  1430. // Start writeback
  1431. pr_info("do_writeback()++\n");
  1432. ret = do_writeback(zram);
  1433. pr_info("do_writeback()--\n");
  1434. }
  1435. blk_finish_plug(&plug);
  1436. __pm_relax(&zram_wb_wakelock);
  1437. mutex_unlock(&zram_wb_wakelock_mutex);
  1438. }
  1439. static int fb_notifier_callback(struct notifier_block *self,
  1440. unsigned long event, void *data)
  1441. {
  1442. struct fb_event *evdata = data;
  1443. int *blank;
  1444. if (event != FB_EVENT_BLANK && event != FB_EARLY_EVENT_BLANK)
  1445. goto out;
  1446. blank = evdata->data;
  1447. switch (*blank) {
  1448. case FB_BLANK_POWERDOWN:
  1449. case FB_BLANK_HSYNC_SUSPEND:
  1450. case FB_BLANK_VSYNC_SUSPEND:
  1451. case FB_BLANK_NORMAL:
  1452. if (!screen_on)
  1453. goto out;
  1454. screen_on = false;
  1455. queue_work(system_power_efficient_wq, &zram_wb_fb_worker);
  1456. break;
  1457. case FB_BLANK_UNBLANK:
  1458. if (screen_on)
  1459. goto out;
  1460. screen_on = true;
  1461. queue_work(system_power_efficient_wq, &zram_wb_fb_worker);
  1462. break;
  1463. }
  1464. out:
  1465. return NOTIFY_OK;
  1466. }
  1467. static struct notifier_block fb_notifier_block = {
  1468. .notifier_call = fb_notifier_callback,
  1469. };
  1470. static void __init init_zram_wb(void)
  1471. {
  1472. int i;
  1473. INIT_WORK(&zram_wb_fb_worker, zram_wb_fb_work);
  1474. wakeup_source_init(&zram_wb_wakelock, "zram_wb_wakelock");
  1475. fb_register_client(&fb_notifier_block);
  1476. i = input_register_handler(&zram_wb_input_handler);
  1477. }
  1478. static void __exit destroy_zram_wb(void)
  1479. {
  1480. input_unregister_handler(&zram_wb_input_handler);
  1481. fb_unregister_client(&fb_notifier_block);
  1482. wakeup_source_trash(&zram_wb_wakelock);
  1483. }
  1484. static void __zram_make_request(struct zram *zram, struct bio *bio)
  1485. {
  1486. int offset;
  1487. u32 index;
  1488. struct bio_vec bvec;
  1489. struct bvec_iter iter;
  1490. index = bio->bi_iter.bi_sector >> SECTORS_PER_PAGE_SHIFT;
  1491. offset = (bio->bi_iter.bi_sector &
  1492. (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
  1493. switch (bio_op(bio)) {
  1494. case REQ_OP_DISCARD:
  1495. case REQ_OP_WRITE_ZEROES:
  1496. zram_bio_discard(zram, index, offset, bio);
  1497. bio_endio(bio);
  1498. return;
  1499. default:
  1500. break;
  1501. }
  1502. bio_for_each_segment(bvec, bio, iter) {
  1503. struct bio_vec bv = bvec;
  1504. unsigned int unwritten = bvec.bv_len;
  1505. do {
  1506. bv.bv_len = min_t(unsigned int, PAGE_SIZE - offset,
  1507. unwritten);
  1508. if (zram_bvec_rw(zram, &bv, index, offset,
  1509. bio_op(bio), bio) < 0)
  1510. goto out;
  1511. bv.bv_offset += bv.bv_len;
  1512. unwritten -= bv.bv_len;
  1513. update_position(&index, &offset, &bv);
  1514. } while (unwritten);
  1515. }
  1516. bio_endio(bio);
  1517. return;
  1518. out:
  1519. bio_io_error(bio);
  1520. }
  1521. /*
  1522. * Handler function for all zram I/O requests.
  1523. */
  1524. static blk_qc_t zram_make_request(struct request_queue *queue, struct bio *bio)
  1525. {
  1526. struct zram *zram = queue->queuedata;
  1527. if (!valid_io_request(zram, bio->bi_iter.bi_sector,
  1528. bio->bi_iter.bi_size)) {
  1529. atomic64_inc(&zram->stats.invalid_io);
  1530. goto error;
  1531. }
  1532. __zram_make_request(zram, bio);
  1533. return BLK_QC_T_NONE;
  1534. error:
  1535. bio_io_error(bio);
  1536. return BLK_QC_T_NONE;
  1537. }
  1538. static void zram_slot_free_notify(struct block_device *bdev,
  1539. unsigned long index)
  1540. {
  1541. struct zram *zram;
  1542. zram = bdev->bd_disk->private_data;
  1543. atomic64_inc(&zram->stats.notify_free);
  1544. if (!zram_slot_trylock(zram, index)) {
  1545. atomic64_inc(&zram->stats.miss_free);
  1546. return;
  1547. }
  1548. zram_free_page(zram, index);
  1549. zram_slot_unlock(zram, index);
  1550. }
  1551. static int zram_rw_page(struct block_device *bdev, sector_t sector,
  1552. struct page *page, unsigned int op)
  1553. {
  1554. int offset, ret;
  1555. u32 index;
  1556. struct zram *zram;
  1557. struct bio_vec bv;
  1558. if (PageTransHuge(page))
  1559. return -ENOTSUPP;
  1560. zram = bdev->bd_disk->private_data;
  1561. if (!valid_io_request(zram, sector, PAGE_SIZE)) {
  1562. atomic64_inc(&zram->stats.invalid_io);
  1563. ret = -EINVAL;
  1564. goto out;
  1565. }
  1566. index = sector >> SECTORS_PER_PAGE_SHIFT;
  1567. offset = (sector & (SECTORS_PER_PAGE - 1)) << SECTOR_SHIFT;
  1568. bv.bv_page = page;
  1569. bv.bv_len = PAGE_SIZE;
  1570. bv.bv_offset = 0;
  1571. ret = zram_bvec_rw(zram, &bv, index, offset, op, NULL);
  1572. out:
  1573. /*
  1574. * If I/O fails, just return error(ie, non-zero) without
  1575. * calling page_endio.
  1576. * It causes resubmit the I/O with bio request by upper functions
  1577. * of rw_page(e.g., swap_readpage, __swap_writepage) and
  1578. * bio->bi_end_io does things to handle the error
  1579. * (e.g., SetPageError, set_page_dirty and extra works).
  1580. */
  1581. if (unlikely(ret < 0))
  1582. return ret;
  1583. switch (ret) {
  1584. case 0:
  1585. page_endio(page, op_is_write(op), 0);
  1586. break;
  1587. case 1:
  1588. ret = 0;
  1589. break;
  1590. default:
  1591. WARN_ON(1);
  1592. }
  1593. return ret;
  1594. }
  1595. static void zram_reset_device(struct zram *zram)
  1596. {
  1597. struct zcomp *comp;
  1598. u64 disksize;
  1599. down_write(&zram->init_lock);
  1600. zram->limit_pages = 0;
  1601. if (!init_done(zram)) {
  1602. up_write(&zram->init_lock);
  1603. return;
  1604. }
  1605. comp = zram->comp;
  1606. disksize = zram->disksize;
  1607. zram->disksize = 0;
  1608. set_capacity(zram->disk, 0);
  1609. part_stat_set_all(&zram->disk->part0, 0);
  1610. up_write(&zram->init_lock);
  1611. /* I/O operation under all of CPU are done so let's free */
  1612. zram_meta_free(zram, disksize);
  1613. memset(&zram->stats, 0, sizeof(zram->stats));
  1614. zcomp_destroy(comp);
  1615. reset_bdev(zram);
  1616. }
  1617. static ssize_t disksize_store(struct device *dev,
  1618. struct device_attribute *attr, const char *buf, size_t len)
  1619. {
  1620. u64 disksize;
  1621. struct zcomp *comp;
  1622. struct zram *zram = dev_to_zram(dev);
  1623. int err;
  1624. disksize = memparse(buf, NULL);
  1625. if (!disksize)
  1626. return -EINVAL;
  1627. down_write(&zram->init_lock);
  1628. if (init_done(zram)) {
  1629. pr_info("Cannot change disksize for initialized device\n");
  1630. err = -EBUSY;
  1631. goto out_unlock;
  1632. }
  1633. disksize = PAGE_ALIGN(disksize);
  1634. if (!zram_meta_alloc(zram, disksize)) {
  1635. err = -ENOMEM;
  1636. goto out_unlock;
  1637. }
  1638. comp = zcomp_create(zram->compressor);
  1639. if (IS_ERR(comp)) {
  1640. pr_err("Cannot initialise %s compressing backend\n",
  1641. zram->compressor);
  1642. err = PTR_ERR(comp);
  1643. goto out_free_meta;
  1644. }
  1645. zram->comp = comp;
  1646. zram->disksize = disksize;
  1647. barrier();
  1648. set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT);
  1649. revalidate_disk(zram->disk);
  1650. up_write(&zram->init_lock);
  1651. return len;
  1652. out_free_meta:
  1653. zram_meta_free(zram, disksize);
  1654. out_unlock:
  1655. up_write(&zram->init_lock);
  1656. return err;
  1657. }
  1658. static ssize_t reset_store(struct device *dev,
  1659. struct device_attribute *attr, const char *buf, size_t len)
  1660. {
  1661. int ret;
  1662. unsigned short do_reset;
  1663. struct zram *zram;
  1664. struct block_device *bdev;
  1665. ret = kstrtou16(buf, 10, &do_reset);
  1666. if (ret)
  1667. return ret;
  1668. if (!do_reset)
  1669. return -EINVAL;
  1670. zram = dev_to_zram(dev);
  1671. bdev = bdget_disk(zram->disk, 0);
  1672. if (!bdev)
  1673. return -ENOMEM;
  1674. mutex_lock(&bdev->bd_mutex);
  1675. /* Do not reset an active device or claimed device */
  1676. if (bdev->bd_openers || zram->claim) {
  1677. mutex_unlock(&bdev->bd_mutex);
  1678. bdput(bdev);
  1679. return -EBUSY;
  1680. }
  1681. /* From now on, anyone can't open /dev/zram[0-9] */
  1682. zram->claim = true;
  1683. mutex_unlock(&bdev->bd_mutex);
  1684. /* Make sure all the pending I/O are finished */
  1685. fsync_bdev(bdev);
  1686. zram_reset_device(zram);
  1687. revalidate_disk(zram->disk);
  1688. bdput(bdev);
  1689. mutex_lock(&bdev->bd_mutex);
  1690. zram->claim = false;
  1691. mutex_unlock(&bdev->bd_mutex);
  1692. return len;
  1693. }
  1694. static int zram_open(struct block_device *bdev, fmode_t mode)
  1695. {
  1696. int ret = 0;
  1697. struct zram *zram;
  1698. WARN_ON(!mutex_is_locked(&bdev->bd_mutex));
  1699. zram = bdev->bd_disk->private_data;
  1700. /* zram was claimed to reset so open request fails */
  1701. if (zram->claim)
  1702. ret = -EBUSY;
  1703. return ret;
  1704. }
  1705. static const struct block_device_operations zram_devops = {
  1706. .open = zram_open,
  1707. .swap_slot_free_notify = zram_slot_free_notify,
  1708. .rw_page = zram_rw_page,
  1709. .owner = THIS_MODULE
  1710. };
  1711. static DEVICE_ATTR_WO(compact);
  1712. static DEVICE_ATTR_RW(disksize);
  1713. static DEVICE_ATTR_RO(initstate);
  1714. static DEVICE_ATTR_WO(reset);
  1715. static DEVICE_ATTR_WO(mem_limit);
  1716. static DEVICE_ATTR_WO(mem_used_max);
  1717. static DEVICE_ATTR_RW(max_comp_streams);
  1718. static DEVICE_ATTR_RW(comp_algorithm);
  1719. #ifdef CONFIG_ZRAM_WRITEBACK
  1720. static DEVICE_ATTR_RW(backing_dev);
  1721. #endif
  1722. #ifdef CONFIG_ZRAM_DEDUP
  1723. static DEVICE_ATTR_RW(use_dedup);
  1724. #else
  1725. static DEVICE_ATTR_RO(use_dedup);
  1726. #endif
  1727. static struct attribute *zram_disk_attrs[] = {
  1728. &dev_attr_disksize.attr,
  1729. &dev_attr_initstate.attr,
  1730. &dev_attr_reset.attr,
  1731. &dev_attr_compact.attr,
  1732. &dev_attr_mem_limit.attr,
  1733. &dev_attr_mem_used_max.attr,
  1734. &dev_attr_max_comp_streams.attr,
  1735. &dev_attr_comp_algorithm.attr,
  1736. #ifdef CONFIG_ZRAM_WRITEBACK
  1737. &dev_attr_backing_dev.attr,
  1738. #endif
  1739. &dev_attr_use_dedup.attr,
  1740. &dev_attr_io_stat.attr,
  1741. &dev_attr_mm_stat.attr,
  1742. #ifdef CONFIG_ZRAM_WRITEBACK
  1743. &dev_attr_bd_stat.attr,
  1744. #endif
  1745. &dev_attr_debug_stat.attr,
  1746. NULL,
  1747. };
  1748. static const struct attribute_group zram_disk_attr_group = {
  1749. .attrs = zram_disk_attrs,
  1750. };
  1751. static const struct attribute_group *zram_disk_attr_groups[] = {
  1752. &zram_disk_attr_group,
  1753. NULL,
  1754. };
  1755. /*
  1756. * Allocate and initialize new zram device. the function returns
  1757. * '>= 0' device_id upon success, and negative value otherwise.
  1758. */
  1759. static int zram_add(void)
  1760. {
  1761. struct zram *zram;
  1762. struct request_queue *queue;
  1763. int ret, device_id;
  1764. zram = kzalloc(sizeof(struct zram), GFP_KERNEL);
  1765. if (!zram)
  1766. return -ENOMEM;
  1767. if (!zram_devices)
  1768. zram_devices = zram;
  1769. ret = idr_alloc(&zram_index_idr, zram, 0, 0, GFP_KERNEL);
  1770. if (ret < 0)
  1771. goto out_free_dev;
  1772. device_id = ret;
  1773. init_rwsem(&zram->init_lock);
  1774. #ifdef CONFIG_ZRAM_DEDUP
  1775. zram->use_dedup = true;
  1776. #endif
  1777. queue = blk_alloc_queue(GFP_KERNEL);
  1778. if (!queue) {
  1779. pr_err("Error allocating disk queue for device %d\n",
  1780. device_id);
  1781. ret = -ENOMEM;
  1782. goto out_free_idr;
  1783. }
  1784. blk_queue_make_request(queue, zram_make_request);
  1785. /* gendisk structure */
  1786. zram->disk = alloc_disk(1);
  1787. if (!zram->disk) {
  1788. pr_err("Error allocating disk structure for device %d\n",
  1789. device_id);
  1790. ret = -ENOMEM;
  1791. goto out_free_queue;
  1792. }
  1793. zram->disk->major = zram_major;
  1794. zram->disk->first_minor = device_id;
  1795. zram->disk->fops = &zram_devops;
  1796. zram->disk->queue = queue;
  1797. zram->disk->queue->queuedata = zram;
  1798. zram->disk->private_data = zram;
  1799. snprintf(zram->disk->disk_name, 16, "zram%d", device_id);
  1800. /* Actual capacity set using syfs (/sys/block/zram<id>/disksize */
  1801. set_capacity(zram->disk, 0);
  1802. /* zram devices sort of resembles non-rotational disks */
  1803. queue_flag_set_unlocked(QUEUE_FLAG_NONROT, zram->disk->queue);
  1804. queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, zram->disk->queue);
  1805. /*
  1806. * To ensure that we always get PAGE_SIZE aligned
  1807. * and n*PAGE_SIZED sized I/O requests.
  1808. */
  1809. blk_queue_physical_block_size(zram->disk->queue, PAGE_SIZE);
  1810. blk_queue_logical_block_size(zram->disk->queue,
  1811. ZRAM_LOGICAL_BLOCK_SIZE);
  1812. blk_queue_io_min(zram->disk->queue, PAGE_SIZE);
  1813. blk_queue_io_opt(zram->disk->queue, PAGE_SIZE);
  1814. zram->disk->queue->limits.discard_granularity = PAGE_SIZE;
  1815. blk_queue_max_discard_sectors(zram->disk->queue, UINT_MAX);
  1816. queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, zram->disk->queue);
  1817. /*
  1818. * zram_bio_discard() will clear all logical blocks if logical block
  1819. * size is identical with physical block size(PAGE_SIZE). But if it is
  1820. * different, we will skip discarding some parts of logical blocks in
  1821. * the part of the request range which isn't aligned to physical block
  1822. * size. So we can't ensure that all discarded logical blocks are
  1823. * zeroed.
  1824. */
  1825. if (ZRAM_LOGICAL_BLOCK_SIZE == PAGE_SIZE)
  1826. blk_queue_max_write_zeroes_sectors(zram->disk->queue, UINT_MAX);
  1827. zram->disk->queue->backing_dev_info->capabilities |=
  1828. (BDI_CAP_STABLE_WRITES | BDI_CAP_SYNCHRONOUS_IO);
  1829. disk_to_dev(zram->disk)->groups = zram_disk_attr_groups;
  1830. add_disk(zram->disk);
  1831. strlcpy(zram->compressor, default_compressor, sizeof(zram->compressor));
  1832. zram_debugfs_register(zram);
  1833. if (!zram_devices)
  1834. zram_devices = zram;
  1835. pr_info("Added device: %s\n", zram->disk->disk_name);
  1836. return device_id;
  1837. out_free_queue:
  1838. blk_cleanup_queue(queue);
  1839. out_free_idr:
  1840. idr_remove(&zram_index_idr, device_id);
  1841. out_free_dev:
  1842. kfree(zram);
  1843. return ret;
  1844. }
  1845. static int zram_remove(struct zram *zram)
  1846. {
  1847. struct block_device *bdev;
  1848. bdev = bdget_disk(zram->disk, 0);
  1849. if (!bdev)
  1850. return -ENOMEM;
  1851. mutex_lock(&bdev->bd_mutex);
  1852. if (bdev->bd_openers || zram->claim) {
  1853. mutex_unlock(&bdev->bd_mutex);
  1854. bdput(bdev);
  1855. return -EBUSY;
  1856. }
  1857. zram->claim = true;
  1858. mutex_unlock(&bdev->bd_mutex);
  1859. zram_debugfs_unregister(zram);
  1860. /* Make sure all the pending I/O are finished */
  1861. fsync_bdev(bdev);
  1862. zram_reset_device(zram);
  1863. bdput(bdev);
  1864. pr_info("Removed device: %s\n", zram->disk->disk_name);
  1865. del_gendisk(zram->disk);
  1866. blk_cleanup_queue(zram->disk->queue);
  1867. put_disk(zram->disk);
  1868. if (zram_devices == zram)
  1869. zram_devices = NULL;
  1870. kfree(zram);
  1871. return 0;
  1872. }
  1873. /* zram-control sysfs attributes */
  1874. /*
  1875. * NOTE: hot_add attribute is not the usual read-only sysfs attribute. In a
  1876. * sense that reading from this file does alter the state of your system -- it
  1877. * creates a new un-initialized zram device and returns back this device's
  1878. * device_id (or an error code if it fails to create a new device).
  1879. */
  1880. static ssize_t hot_add_show(struct class *class,
  1881. struct class_attribute *attr,
  1882. char *buf)
  1883. {
  1884. int ret;
  1885. mutex_lock(&zram_index_mutex);
  1886. ret = zram_add();
  1887. mutex_unlock(&zram_index_mutex);
  1888. if (ret < 0)
  1889. return ret;
  1890. return scnprintf(buf, PAGE_SIZE, "%d\n", ret);
  1891. }
  1892. static struct class_attribute class_attr_hot_add =
  1893. __ATTR(hot_add, 0400, hot_add_show, NULL);
  1894. static ssize_t hot_remove_store(struct class *class,
  1895. struct class_attribute *attr,
  1896. const char *buf,
  1897. size_t count)
  1898. {
  1899. struct zram *zram;
  1900. int ret, dev_id;
  1901. /* dev_id is gendisk->first_minor, which is `int' */
  1902. ret = kstrtoint(buf, 10, &dev_id);
  1903. if (ret)
  1904. return ret;
  1905. if (dev_id < 0)
  1906. return -EINVAL;
  1907. mutex_lock(&zram_index_mutex);
  1908. zram = idr_find(&zram_index_idr, dev_id);
  1909. if (zram) {
  1910. ret = zram_remove(zram);
  1911. if (!ret)
  1912. idr_remove(&zram_index_idr, dev_id);
  1913. } else {
  1914. ret = -ENODEV;
  1915. }
  1916. mutex_unlock(&zram_index_mutex);
  1917. return ret ? ret : count;
  1918. }
  1919. static CLASS_ATTR_WO(hot_remove);
  1920. static struct attribute *zram_control_class_attrs[] = {
  1921. &class_attr_hot_add.attr,
  1922. &class_attr_hot_remove.attr,
  1923. NULL,
  1924. };
  1925. ATTRIBUTE_GROUPS(zram_control_class);
  1926. static struct class zram_control_class = {
  1927. .name = "zram-control",
  1928. .owner = THIS_MODULE,
  1929. .class_groups = zram_control_class_groups,
  1930. };
  1931. static int zram_remove_cb(int id, void *ptr, void *data)
  1932. {
  1933. zram_remove(ptr);
  1934. return 0;
  1935. }
  1936. static void destroy_devices(void)
  1937. {
  1938. class_unregister(&zram_control_class);
  1939. idr_for_each(&zram_index_idr, &zram_remove_cb, NULL);
  1940. zram_debugfs_destroy();
  1941. idr_destroy(&zram_index_idr);
  1942. unregister_blkdev(zram_major, "zram");
  1943. cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
  1944. }
  1945. unsigned long zram_mlog(void)
  1946. {
  1947. #define P2K(x) (((unsigned long)x) << (PAGE_SHIFT - 10))
  1948. if (num_devices == 0 && init_done(zram_devices))
  1949. return P2K(zs_get_total_pages(zram_devices->mem_pool));
  1950. #undef P2K
  1951. return 0;
  1952. }
  1953. static int __init zram_init(void)
  1954. {
  1955. int ret;
  1956. ret = cpuhp_setup_state_multi(CPUHP_ZCOMP_PREPARE, "block/zram:prepare",
  1957. zcomp_cpu_up_prepare, zcomp_cpu_dead);
  1958. if (ret < 0)
  1959. return ret;
  1960. ret = class_register(&zram_control_class);
  1961. if (ret) {
  1962. pr_err("Unable to register zram-control class\n");
  1963. cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
  1964. return ret;
  1965. }
  1966. zram_debugfs_create();
  1967. zram_major = register_blkdev(0, "zram");
  1968. if (zram_major <= 0) {
  1969. pr_err("Unable to get major number\n");
  1970. class_unregister(&zram_control_class);
  1971. cpuhp_remove_multi_state(CPUHP_ZCOMP_PREPARE);
  1972. return -EBUSY;
  1973. }
  1974. while (num_devices != 0) {
  1975. mutex_lock(&zram_index_mutex);
  1976. ret = zram_add();
  1977. mutex_unlock(&zram_index_mutex);
  1978. if (ret < 0)
  1979. goto out_error;
  1980. num_devices--;
  1981. }
  1982. init_zram_wb();
  1983. return 0;
  1984. out_error:
  1985. destroy_devices();
  1986. return ret;
  1987. }
  1988. static void __exit zram_exit(void)
  1989. {
  1990. destroy_zram_wb();
  1991. destroy_devices();
  1992. }
  1993. module_init(zram_init);
  1994. module_exit(zram_exit);
  1995. module_param(num_devices, uint, 0);
  1996. MODULE_PARM_DESC(num_devices, "Number of pre-created zram devices");
  1997. MODULE_LICENSE("Dual BSD/GPL");
  1998. MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
  1999. MODULE_DESCRIPTION("Compressed RAM Block Device");