zsmalloc.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  1. /*
  2. * zsmalloc memory allocator
  3. *
  4. * Copyright (C) 2011 Nitin Gupta
  5. * Copyright (C) 2012, 2013 Minchan Kim
  6. *
  7. * This code is released using a dual license strategy: BSD/GPL
  8. * You can choose the license 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. * This allocator is designed for use with zram. Thus, the allocator is
  15. * supposed to work well under low memory conditions. In particular, it
  16. * never attempts higher order page allocation which is very likely to
  17. * fail under memory pressure. On the other hand, if we just use single
  18. * (0-order) pages, it would suffer from very high fragmentation --
  19. * any object of size PAGE_SIZE/2 or larger would occupy an entire page.
  20. * This was one of the major issues with its predecessor (xvmalloc).
  21. *
  22. * To overcome these issues, zsmalloc allocates a bunch of 0-order pages
  23. * and links them together using various 'struct page' fields. These linked
  24. * pages act as a single higher-order page i.e. an object can span 0-order
  25. * page boundaries. The code refers to these linked pages as a single entity
  26. * called zspage.
  27. *
  28. * For simplicity, zsmalloc can only allocate objects of size up to PAGE_SIZE
  29. * since this satisfies the requirements of all its current users (in the
  30. * worst case, page is incompressible and is thus stored "as-is" i.e. in
  31. * uncompressed form). For allocation requests larger than this size, failure
  32. * is returned (see zs_malloc).
  33. *
  34. * Additionally, zs_malloc() does not return a dereferenceable pointer.
  35. * Instead, it returns an opaque handle (unsigned long) which encodes actual
  36. * location of the allocated object. The reason for this indirection is that
  37. * zsmalloc does not keep zspages permanently mapped since that would cause
  38. * issues on 32-bit systems where the VA region for kernel space mappings
  39. * is very small. So, before using the allocating memory, the object has to
  40. * be mapped using zs_map_object() to get a usable pointer and subsequently
  41. * unmapped using zs_unmap_object().
  42. *
  43. * Following is how we use various fields and flags of underlying
  44. * struct page(s) to form a zspage.
  45. *
  46. * Usage of struct page fields:
  47. * page->first_page: points to the first component (0-order) page
  48. * page->index (union with page->freelist): offset of the first object
  49. * starting in this page. For the first page, this is
  50. * always 0, so we use this field (aka freelist) to point
  51. * to the first free object in zspage.
  52. * page->lru: links together all component pages (except the first page)
  53. * of a zspage
  54. *
  55. * For _first_ page only:
  56. *
  57. * page->private (union with page->first_page): refers to the
  58. * component page after the first page
  59. * page->freelist: points to the first free object in zspage.
  60. * Free objects are linked together using in-place
  61. * metadata.
  62. * page->objects: maximum number of objects we can store in this
  63. * zspage (class->zspage_order * PAGE_SIZE / class->size)
  64. * page->lru: links together first pages of various zspages.
  65. * Basically forming list of zspages in a fullness group.
  66. * page->mapping: class index and fullness group of the zspage
  67. *
  68. * Usage of struct page flags:
  69. * PG_private: identifies the first component page
  70. * PG_private2: identifies the last component page
  71. *
  72. */
  73. #ifdef CONFIG_ZSMALLOC_DEBUG
  74. #define DEBUG
  75. #endif
  76. #include <linux/module.h>
  77. #include <linux/kernel.h>
  78. #include <linux/bitops.h>
  79. #include <linux/errno.h>
  80. #include <linux/highmem.h>
  81. #include <linux/string.h>
  82. #include <linux/slab.h>
  83. #include <asm/tlbflush.h>
  84. #include <asm/pgtable.h>
  85. #include <linux/cpumask.h>
  86. #include <linux/cpu.h>
  87. #include <linux/vmalloc.h>
  88. #include <linux/hardirq.h>
  89. #include <linux/spinlock.h>
  90. #include <linux/types.h>
  91. #include <linux/zsmalloc.h>
  92. #include <linux/zpool.h>
  93. /*
  94. * This must be power of 2 and greater than of equal to sizeof(link_free).
  95. * These two conditions ensure that any 'struct link_free' itself doesn't
  96. * span more than 1 page which avoids complex case of mapping 2 pages simply
  97. * to restore link_free pointer values.
  98. */
  99. #define ZS_ALIGN 8
  100. /*
  101. * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
  102. * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
  103. */
  104. #define ZS_MAX_ZSPAGE_ORDER 2
  105. #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
  106. /*
  107. * Object location (<PFN>, <obj_idx>) is encoded as
  108. * as single (unsigned long) handle value.
  109. *
  110. * Note that object index <obj_idx> is relative to system
  111. * page <PFN> it is stored in, so for each sub-page belonging
  112. * to a zspage, obj_idx starts with 0.
  113. *
  114. * This is made more complicated by various memory models and PAE.
  115. */
  116. #ifndef MAX_PHYSMEM_BITS
  117. #ifdef CONFIG_HIGHMEM64G
  118. #define MAX_PHYSMEM_BITS 36
  119. #else /* !CONFIG_HIGHMEM64G */
  120. /*
  121. * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
  122. * be PAGE_SHIFT
  123. */
  124. #define MAX_PHYSMEM_BITS BITS_PER_LONG
  125. #endif
  126. #endif
  127. #define _PFN_BITS (MAX_PHYSMEM_BITS - PAGE_SHIFT)
  128. #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS)
  129. #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
  130. #define MAX(a, b) ((a) >= (b) ? (a) : (b))
  131. /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
  132. #define ZS_MIN_ALLOC_SIZE \
  133. MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
  134. #define ZS_MAX_ALLOC_SIZE PAGE_SIZE
  135. /*
  136. * On systems with 4K page size, this gives 255 size classes! There is a
  137. * trader-off here:
  138. * - Large number of size classes is potentially wasteful as free page are
  139. * spread across these classes
  140. * - Small number of size classes causes large internal fragmentation
  141. * - Probably its better to use specific size classes (empirically
  142. * determined). NOTE: all those class sizes must be set as multiple of
  143. * ZS_ALIGN to make sure link_free itself never has to span 2 pages.
  144. *
  145. * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
  146. * (reason above)
  147. */
  148. #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> 8)
  149. /*
  150. * We do not maintain any list for completely empty or full pages
  151. */
  152. enum fullness_group {
  153. ZS_ALMOST_FULL,
  154. ZS_ALMOST_EMPTY,
  155. _ZS_NR_FULLNESS_GROUPS,
  156. ZS_EMPTY,
  157. ZS_FULL
  158. };
  159. /*
  160. * number of size_classes
  161. */
  162. static int zs_size_classes;
  163. /*
  164. * We assign a page to ZS_ALMOST_EMPTY fullness group when:
  165. * n <= N / f, where
  166. * n = number of allocated objects
  167. * N = total number of objects zspage can store
  168. * f = fullness_threshold_frac
  169. *
  170. * Similarly, we assign zspage to:
  171. * ZS_ALMOST_FULL when n > N / f
  172. * ZS_EMPTY when n == 0
  173. * ZS_FULL when n == N
  174. *
  175. * (see: fix_fullness_group())
  176. */
  177. static const int fullness_threshold_frac = 4;
  178. struct size_class {
  179. /*
  180. * Size of objects stored in this class. Must be multiple
  181. * of ZS_ALIGN.
  182. */
  183. int size;
  184. unsigned int index;
  185. /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
  186. int pages_per_zspage;
  187. spinlock_t lock;
  188. struct page *fullness_list[_ZS_NR_FULLNESS_GROUPS];
  189. };
  190. /*
  191. * Placed within free objects to form a singly linked list.
  192. * For every zspage, first_page->freelist gives head of this list.
  193. *
  194. * This must be power of 2 and less than or equal to ZS_ALIGN
  195. */
  196. struct link_free {
  197. /* Handle of next free chunk (encodes <PFN, obj_idx>) */
  198. void *next;
  199. };
  200. struct zs_pool {
  201. struct size_class **size_class;
  202. gfp_t flags; /* allocation flags used when growing pool */
  203. atomic_long_t pages_allocated;
  204. };
  205. /*
  206. * A zspage's class index and fullness group
  207. * are encoded in its (first)page->mapping
  208. */
  209. #define CLASS_IDX_BITS 28
  210. #define FULLNESS_BITS 4
  211. #define CLASS_IDX_MASK ((1 << CLASS_IDX_BITS) - 1)
  212. #define FULLNESS_MASK ((1 << FULLNESS_BITS) - 1)
  213. struct mapping_area {
  214. #ifdef CONFIG_PGTABLE_MAPPING
  215. struct vm_struct *vm; /* vm area for mapping object that span pages */
  216. #else
  217. char *vm_buf; /* copy buffer for objects that span pages */
  218. #endif
  219. char *vm_addr; /* address of kmap_atomic()'ed pages */
  220. enum zs_mapmode vm_mm; /* mapping mode */
  221. };
  222. /* zpool driver */
  223. #ifdef CONFIG_ZPOOL
  224. static void *zs_zpool_create(gfp_t gfp, struct zpool_ops *zpool_ops)
  225. {
  226. return zs_create_pool(gfp);
  227. }
  228. static void zs_zpool_destroy(void *pool)
  229. {
  230. zs_destroy_pool(pool);
  231. }
  232. static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
  233. unsigned long *handle)
  234. {
  235. *handle = zs_malloc(pool, size);
  236. return *handle ? 0 : -1;
  237. }
  238. static void zs_zpool_free(void *pool, unsigned long handle)
  239. {
  240. zs_free(pool, handle);
  241. }
  242. static int zs_zpool_shrink(void *pool, unsigned int pages,
  243. unsigned int *reclaimed)
  244. {
  245. return -EINVAL;
  246. }
  247. static void *zs_zpool_map(void *pool, unsigned long handle,
  248. enum zpool_mapmode mm)
  249. {
  250. enum zs_mapmode zs_mm;
  251. switch (mm) {
  252. case ZPOOL_MM_RO:
  253. zs_mm = ZS_MM_RO;
  254. break;
  255. case ZPOOL_MM_WO:
  256. zs_mm = ZS_MM_WO;
  257. break;
  258. case ZPOOL_MM_RW: /* fallthru */
  259. default:
  260. zs_mm = ZS_MM_RW;
  261. break;
  262. }
  263. return zs_map_object(pool, handle, zs_mm);
  264. }
  265. static void zs_zpool_unmap(void *pool, unsigned long handle)
  266. {
  267. zs_unmap_object(pool, handle);
  268. }
  269. static u64 zs_zpool_total_size(void *pool)
  270. {
  271. return zs_get_total_pages(pool) << PAGE_SHIFT;
  272. }
  273. static struct zpool_driver zs_zpool_driver = {
  274. .type = "zsmalloc",
  275. .owner = THIS_MODULE,
  276. .create = zs_zpool_create,
  277. .destroy = zs_zpool_destroy,
  278. .malloc = zs_zpool_malloc,
  279. .free = zs_zpool_free,
  280. .shrink = zs_zpool_shrink,
  281. .map = zs_zpool_map,
  282. .unmap = zs_zpool_unmap,
  283. .total_size = zs_zpool_total_size,
  284. };
  285. MODULE_ALIAS("zpool-zsmalloc");
  286. #endif /* CONFIG_ZPOOL */
  287. /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
  288. static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
  289. static int is_first_page(struct page *page)
  290. {
  291. return PagePrivate(page);
  292. }
  293. static int is_last_page(struct page *page)
  294. {
  295. return PagePrivate2(page);
  296. }
  297. static void get_zspage_mapping(struct page *page, unsigned int *class_idx,
  298. enum fullness_group *fullness)
  299. {
  300. unsigned long m;
  301. BUG_ON(!is_first_page(page));
  302. m = (unsigned long)page->mapping;
  303. *fullness = m & FULLNESS_MASK;
  304. *class_idx = (m >> FULLNESS_BITS) & CLASS_IDX_MASK;
  305. }
  306. static void set_zspage_mapping(struct page *page, unsigned int class_idx,
  307. enum fullness_group fullness)
  308. {
  309. unsigned long m;
  310. BUG_ON(!is_first_page(page));
  311. m = ((class_idx & CLASS_IDX_MASK) << FULLNESS_BITS) |
  312. (fullness & FULLNESS_MASK);
  313. page->mapping = (struct address_space *)m;
  314. }
  315. /*
  316. * zsmalloc divides the pool into various size classes where each
  317. * class maintains a list of zspages where each zspage is divided
  318. * into equal sized chunks. Each allocation falls into one of these
  319. * classes depending on its size. This function returns index of the
  320. * size class which has chunk size big enough to hold the give size.
  321. */
  322. static int get_size_class_index(int size)
  323. {
  324. int idx = 0;
  325. if (likely(size > ZS_MIN_ALLOC_SIZE))
  326. idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
  327. ZS_SIZE_CLASS_DELTA);
  328. return idx;
  329. }
  330. /*
  331. * For each size class, zspages are divided into different groups
  332. * depending on how "full" they are. This was done so that we could
  333. * easily find empty or nearly empty zspages when we try to shrink
  334. * the pool (not yet implemented). This function returns fullness
  335. * status of the given page.
  336. */
  337. static enum fullness_group get_fullness_group(struct page *page)
  338. {
  339. int inuse, max_objects;
  340. enum fullness_group fg;
  341. BUG_ON(!is_first_page(page));
  342. inuse = page->inuse;
  343. max_objects = page->objects;
  344. if (inuse == 0)
  345. fg = ZS_EMPTY;
  346. else if (inuse == max_objects)
  347. fg = ZS_FULL;
  348. else if (inuse <= max_objects / fullness_threshold_frac)
  349. fg = ZS_ALMOST_EMPTY;
  350. else
  351. fg = ZS_ALMOST_FULL;
  352. return fg;
  353. }
  354. /*
  355. * Each size class maintains various freelists and zspages are assigned
  356. * to one of these freelists based on the number of live objects they
  357. * have. This functions inserts the given zspage into the freelist
  358. * identified by <class, fullness_group>.
  359. */
  360. static void insert_zspage(struct page *page, struct size_class *class,
  361. enum fullness_group fullness)
  362. {
  363. struct page **head;
  364. BUG_ON(!is_first_page(page));
  365. if (fullness >= _ZS_NR_FULLNESS_GROUPS)
  366. return;
  367. head = &class->fullness_list[fullness];
  368. if (*head)
  369. list_add_tail(&page->lru, &(*head)->lru);
  370. *head = page;
  371. }
  372. /*
  373. * This function removes the given zspage from the freelist identified
  374. * by <class, fullness_group>.
  375. */
  376. static void remove_zspage(struct page *page, struct size_class *class,
  377. enum fullness_group fullness)
  378. {
  379. struct page **head;
  380. BUG_ON(!is_first_page(page));
  381. if (fullness >= _ZS_NR_FULLNESS_GROUPS)
  382. return;
  383. head = &class->fullness_list[fullness];
  384. BUG_ON(!*head);
  385. if (list_empty(&(*head)->lru))
  386. *head = NULL;
  387. else if (*head == page)
  388. *head = (struct page *)list_entry((*head)->lru.next,
  389. struct page, lru);
  390. list_del_init(&page->lru);
  391. }
  392. /*
  393. * Each size class maintains zspages in different fullness groups depending
  394. * on the number of live objects they contain. When allocating or freeing
  395. * objects, the fullness status of the page can change, say, from ALMOST_FULL
  396. * to ALMOST_EMPTY when freeing an object. This function checks if such
  397. * a status change has occurred for the given page and accordingly moves the
  398. * page from the freelist of the old fullness group to that of the new
  399. * fullness group.
  400. */
  401. static enum fullness_group fix_fullness_group(struct zs_pool *pool,
  402. struct page *page)
  403. {
  404. int class_idx;
  405. struct size_class *class;
  406. enum fullness_group currfg, newfg;
  407. BUG_ON(!is_first_page(page));
  408. get_zspage_mapping(page, &class_idx, &currfg);
  409. newfg = get_fullness_group(page);
  410. if (newfg == currfg)
  411. goto out;
  412. class = pool->size_class[class_idx];
  413. remove_zspage(page, class, currfg);
  414. insert_zspage(page, class, newfg);
  415. set_zspage_mapping(page, class_idx, newfg);
  416. out:
  417. return newfg;
  418. }
  419. /*
  420. * We have to decide on how many pages to link together
  421. * to form a zspage for each size class. This is important
  422. * to reduce wastage due to unusable space left at end of
  423. * each zspage which is given as:
  424. * wastage = Zp - Zp % size_class
  425. * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
  426. *
  427. * For example, for size class of 3/8 * PAGE_SIZE, we should
  428. * link together 3 PAGE_SIZE sized pages to form a zspage
  429. * since then we can perfectly fit in 8 such objects.
  430. */
  431. static int get_pages_per_zspage(int class_size)
  432. {
  433. int i, max_usedpc = 0;
  434. /* zspage order which gives maximum used size per KB */
  435. int max_usedpc_order = 1;
  436. for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
  437. int zspage_size;
  438. int waste, usedpc;
  439. zspage_size = i * PAGE_SIZE;
  440. waste = zspage_size % class_size;
  441. usedpc = (zspage_size - waste) * 100 / zspage_size;
  442. if (usedpc > max_usedpc) {
  443. max_usedpc = usedpc;
  444. max_usedpc_order = i;
  445. }
  446. }
  447. return max_usedpc_order;
  448. }
  449. /*
  450. * A single 'zspage' is composed of many system pages which are
  451. * linked together using fields in struct page. This function finds
  452. * the first/head page, given any component page of a zspage.
  453. */
  454. static struct page *get_first_page(struct page *page)
  455. {
  456. if (is_first_page(page))
  457. return page;
  458. else
  459. return page->first_page;
  460. }
  461. static struct page *get_next_page(struct page *page)
  462. {
  463. struct page *next;
  464. if (is_last_page(page))
  465. next = NULL;
  466. else if (is_first_page(page))
  467. next = (struct page *)page_private(page);
  468. else
  469. next = list_entry(page->lru.next, struct page, lru);
  470. return next;
  471. }
  472. /*
  473. * Encode <page, obj_idx> as a single handle value.
  474. * On hardware platforms with physical memory starting at 0x0 the pfn
  475. * could be 0 so we ensure that the handle will never be 0 by adjusting the
  476. * encoded obj_idx value before encoding.
  477. */
  478. static void *obj_location_to_handle(struct page *page, unsigned long obj_idx)
  479. {
  480. unsigned long handle;
  481. if (!page) {
  482. BUG_ON(obj_idx);
  483. return NULL;
  484. }
  485. handle = page_to_pfn(page) << OBJ_INDEX_BITS;
  486. handle |= ((obj_idx + 1) & OBJ_INDEX_MASK);
  487. return (void *)handle;
  488. }
  489. /*
  490. * Decode <page, obj_idx> pair from the given object handle. We adjust the
  491. * decoded obj_idx back to its original value since it was adjusted in
  492. * obj_location_to_handle().
  493. */
  494. static void obj_handle_to_location(unsigned long handle, struct page **page,
  495. unsigned long *obj_idx)
  496. {
  497. *page = pfn_to_page(handle >> OBJ_INDEX_BITS);
  498. *obj_idx = (handle & OBJ_INDEX_MASK) - 1;
  499. }
  500. static unsigned long obj_idx_to_offset(struct page *page,
  501. unsigned long obj_idx, int class_size)
  502. {
  503. unsigned long off = 0;
  504. if (!is_first_page(page))
  505. off = page->index;
  506. return off + obj_idx * class_size;
  507. }
  508. static void reset_page(struct page *page)
  509. {
  510. clear_bit(PG_private, &page->flags);
  511. clear_bit(PG_private_2, &page->flags);
  512. set_page_private(page, 0);
  513. page->mapping = NULL;
  514. page->freelist = NULL;
  515. page_mapcount_reset(page);
  516. }
  517. static void free_zspage(struct page *first_page)
  518. {
  519. struct page *nextp, *tmp, *head_extra;
  520. BUG_ON(!is_first_page(first_page));
  521. BUG_ON(first_page->inuse);
  522. head_extra = (struct page *)page_private(first_page);
  523. reset_page(first_page);
  524. __free_page(first_page);
  525. /* zspage with only 1 system page */
  526. if (!head_extra)
  527. return;
  528. list_for_each_entry_safe(nextp, tmp, &head_extra->lru, lru) {
  529. list_del(&nextp->lru);
  530. reset_page(nextp);
  531. __free_page(nextp);
  532. }
  533. reset_page(head_extra);
  534. __free_page(head_extra);
  535. }
  536. /* Initialize a newly allocated zspage */
  537. static void init_zspage(struct page *first_page, struct size_class *class)
  538. {
  539. unsigned long off = 0;
  540. struct page *page = first_page;
  541. BUG_ON(!is_first_page(first_page));
  542. while (page) {
  543. struct page *next_page;
  544. struct link_free *link;
  545. unsigned int i = 1;
  546. void *vaddr;
  547. /*
  548. * page->index stores offset of first object starting
  549. * in the page. For the first page, this is always 0,
  550. * so we use first_page->index (aka ->freelist) to store
  551. * head of corresponding zspage's freelist.
  552. */
  553. if (page != first_page)
  554. page->index = off;
  555. vaddr = kmap_atomic(page);
  556. link = (struct link_free *)vaddr + off / sizeof(*link);
  557. while ((off += class->size) < PAGE_SIZE) {
  558. link->next = obj_location_to_handle(page, i++);
  559. link += class->size / sizeof(*link);
  560. }
  561. /*
  562. * We now come to the last (full or partial) object on this
  563. * page, which must point to the first object on the next
  564. * page (if present)
  565. */
  566. next_page = get_next_page(page);
  567. link->next = obj_location_to_handle(next_page, 0);
  568. kunmap_atomic(vaddr);
  569. page = next_page;
  570. off %= PAGE_SIZE;
  571. }
  572. }
  573. /*
  574. * Allocate a zspage for the given size class
  575. */
  576. static struct page *alloc_zspage(struct size_class *class, gfp_t flags)
  577. {
  578. int i, error;
  579. struct page *first_page = NULL, *uninitialized_var(prev_page);
  580. /*
  581. * Allocate individual pages and link them together as:
  582. * 1. first page->private = first sub-page
  583. * 2. all sub-pages are linked together using page->lru
  584. * 3. each sub-page is linked to the first page using page->first_page
  585. *
  586. * For each size class, First/Head pages are linked together using
  587. * page->lru. Also, we set PG_private to identify the first page
  588. * (i.e. no other sub-page has this flag set) and PG_private_2 to
  589. * identify the last page.
  590. */
  591. error = -ENOMEM;
  592. for (i = 0; i < class->pages_per_zspage; i++) {
  593. struct page *page;
  594. page = alloc_page(flags);
  595. if (!page)
  596. goto cleanup;
  597. INIT_LIST_HEAD(&page->lru);
  598. if (i == 0) { /* first page */
  599. SetPagePrivate(page);
  600. set_page_private(page, 0);
  601. first_page = page;
  602. first_page->inuse = 0;
  603. }
  604. if (i == 1)
  605. set_page_private(first_page, (unsigned long)page);
  606. if (i >= 1)
  607. page->first_page = first_page;
  608. if (i >= 2)
  609. list_add(&page->lru, &prev_page->lru);
  610. if (i == class->pages_per_zspage - 1) /* last page */
  611. SetPagePrivate2(page);
  612. prev_page = page;
  613. }
  614. init_zspage(first_page, class);
  615. first_page->freelist = obj_location_to_handle(first_page, 0);
  616. /* Maximum number of objects we can store in this zspage */
  617. first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size;
  618. error = 0; /* Success */
  619. cleanup:
  620. if (unlikely(error) && first_page) {
  621. free_zspage(first_page);
  622. first_page = NULL;
  623. }
  624. return first_page;
  625. }
  626. static struct page *find_get_zspage(struct size_class *class)
  627. {
  628. int i;
  629. struct page *page;
  630. for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
  631. page = class->fullness_list[i];
  632. if (page)
  633. break;
  634. }
  635. return page;
  636. }
  637. #ifdef CONFIG_PGTABLE_MAPPING
  638. static inline int __zs_cpu_up(struct mapping_area *area)
  639. {
  640. /*
  641. * Make sure we don't leak memory if a cpu UP notification
  642. * and zs_init() race and both call zs_cpu_up() on the same cpu
  643. */
  644. if (area->vm)
  645. return 0;
  646. area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
  647. if (!area->vm)
  648. return -ENOMEM;
  649. return 0;
  650. }
  651. static inline void __zs_cpu_down(struct mapping_area *area)
  652. {
  653. if (area->vm)
  654. free_vm_area(area->vm);
  655. area->vm = NULL;
  656. }
  657. static inline void *__zs_map_object(struct mapping_area *area,
  658. struct page *pages[2], int off, int size)
  659. {
  660. BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
  661. area->vm_addr = area->vm->addr;
  662. return area->vm_addr + off;
  663. }
  664. static inline void __zs_unmap_object(struct mapping_area *area,
  665. struct page *pages[2], int off, int size)
  666. {
  667. unsigned long addr = (unsigned long)area->vm_addr;
  668. unmap_kernel_range(addr, PAGE_SIZE * 2);
  669. }
  670. #else /* CONFIG_PGTABLE_MAPPING */
  671. static inline int __zs_cpu_up(struct mapping_area *area)
  672. {
  673. /*
  674. * Make sure we don't leak memory if a cpu UP notification
  675. * and zs_init() race and both call zs_cpu_up() on the same cpu
  676. */
  677. if (area->vm_buf)
  678. return 0;
  679. area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
  680. if (!area->vm_buf)
  681. return -ENOMEM;
  682. return 0;
  683. }
  684. static inline void __zs_cpu_down(struct mapping_area *area)
  685. {
  686. kfree(area->vm_buf);
  687. area->vm_buf = NULL;
  688. }
  689. static void *__zs_map_object(struct mapping_area *area,
  690. struct page *pages[2], int off, int size)
  691. {
  692. int sizes[2];
  693. void *addr;
  694. char *buf = area->vm_buf;
  695. /* disable page faults to match kmap_atomic() return conditions */
  696. pagefault_disable();
  697. /* no read fastpath */
  698. if (area->vm_mm == ZS_MM_WO)
  699. goto out;
  700. sizes[0] = PAGE_SIZE - off;
  701. sizes[1] = size - sizes[0];
  702. /* copy object to per-cpu buffer */
  703. addr = kmap_atomic(pages[0]);
  704. memcpy(buf, addr + off, sizes[0]);
  705. kunmap_atomic(addr);
  706. addr = kmap_atomic(pages[1]);
  707. memcpy(buf + sizes[0], addr, sizes[1]);
  708. kunmap_atomic(addr);
  709. out:
  710. return area->vm_buf;
  711. }
  712. static void __zs_unmap_object(struct mapping_area *area,
  713. struct page *pages[2], int off, int size)
  714. {
  715. int sizes[2];
  716. void *addr;
  717. char *buf = area->vm_buf;
  718. /* no write fastpath */
  719. if (area->vm_mm == ZS_MM_RO)
  720. goto out;
  721. sizes[0] = PAGE_SIZE - off;
  722. sizes[1] = size - sizes[0];
  723. /* copy per-cpu buffer to object */
  724. addr = kmap_atomic(pages[0]);
  725. memcpy(addr + off, buf, sizes[0]);
  726. kunmap_atomic(addr);
  727. addr = kmap_atomic(pages[1]);
  728. memcpy(addr, buf + sizes[0], sizes[1]);
  729. kunmap_atomic(addr);
  730. out:
  731. /* enable page faults to match kunmap_atomic() return conditions */
  732. pagefault_enable();
  733. }
  734. #endif /* CONFIG_PGTABLE_MAPPING */
  735. static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
  736. void *pcpu)
  737. {
  738. int ret, cpu = (long)pcpu;
  739. struct mapping_area *area;
  740. switch (action) {
  741. case CPU_UP_PREPARE:
  742. area = &per_cpu(zs_map_area, cpu);
  743. ret = __zs_cpu_up(area);
  744. if (ret)
  745. return notifier_from_errno(ret);
  746. break;
  747. case CPU_DEAD:
  748. case CPU_UP_CANCELED:
  749. area = &per_cpu(zs_map_area, cpu);
  750. __zs_cpu_down(area);
  751. break;
  752. }
  753. return NOTIFY_OK;
  754. }
  755. static struct notifier_block zs_cpu_nb = {
  756. .notifier_call = zs_cpu_notifier
  757. };
  758. static int zs_register_cpu_notifier(void)
  759. {
  760. int cpu, uninitialized_var(ret);
  761. cpu_notifier_register_begin();
  762. __register_cpu_notifier(&zs_cpu_nb);
  763. for_each_online_cpu(cpu) {
  764. ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
  765. if (notifier_to_errno(ret))
  766. break;
  767. }
  768. cpu_notifier_register_done();
  769. return notifier_to_errno(ret);
  770. }
  771. static void zs_unregister_cpu_notifier(void)
  772. {
  773. int cpu;
  774. cpu_notifier_register_begin();
  775. for_each_online_cpu(cpu)
  776. zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
  777. __unregister_cpu_notifier(&zs_cpu_nb);
  778. cpu_notifier_register_done();
  779. }
  780. static void init_zs_size_classes(void)
  781. {
  782. int nr;
  783. nr = (ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / ZS_SIZE_CLASS_DELTA + 1;
  784. if ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) % ZS_SIZE_CLASS_DELTA)
  785. nr += 1;
  786. zs_size_classes = nr;
  787. }
  788. static unsigned int get_maxobj_per_zspage(int size, int pages_per_zspage)
  789. {
  790. return pages_per_zspage * PAGE_SIZE / size;
  791. }
  792. static bool can_merge(struct size_class *prev, int size, int pages_per_zspage)
  793. {
  794. if (prev->pages_per_zspage != pages_per_zspage)
  795. return false;
  796. if (get_maxobj_per_zspage(prev->size, prev->pages_per_zspage)
  797. != get_maxobj_per_zspage(size, pages_per_zspage))
  798. return false;
  799. return true;
  800. }
  801. unsigned long zs_get_total_pages(struct zs_pool *pool)
  802. {
  803. return atomic_long_read(&pool->pages_allocated);
  804. }
  805. EXPORT_SYMBOL_GPL(zs_get_total_pages);
  806. /**
  807. * zs_map_object - get address of allocated object from handle.
  808. * @pool: pool from which the object was allocated
  809. * @handle: handle returned from zs_malloc
  810. *
  811. * Before using an object allocated from zs_malloc, it must be mapped using
  812. * this function. When done with the object, it must be unmapped using
  813. * zs_unmap_object.
  814. *
  815. * Only one object can be mapped per cpu at a time. There is no protection
  816. * against nested mappings.
  817. *
  818. * This function returns with preemption and page faults disabled.
  819. */
  820. void *zs_map_object(struct zs_pool *pool, unsigned long handle,
  821. enum zs_mapmode mm)
  822. {
  823. struct page *page;
  824. unsigned long obj_idx, off;
  825. unsigned int class_idx;
  826. enum fullness_group fg;
  827. struct size_class *class;
  828. struct mapping_area *area;
  829. struct page *pages[2];
  830. BUG_ON(!handle);
  831. /*
  832. * Because we use per-cpu mapping areas shared among the
  833. * pools/users, we can't allow mapping in interrupt context
  834. * because it can corrupt another users mappings.
  835. */
  836. BUG_ON(in_interrupt());
  837. obj_handle_to_location(handle, &page, &obj_idx);
  838. get_zspage_mapping(get_first_page(page), &class_idx, &fg);
  839. class = pool->size_class[class_idx];
  840. off = obj_idx_to_offset(page, obj_idx, class->size);
  841. area = &get_cpu_var(zs_map_area);
  842. area->vm_mm = mm;
  843. if (off + class->size <= PAGE_SIZE) {
  844. /* this object is contained entirely within a page */
  845. area->vm_addr = kmap_atomic(page);
  846. return area->vm_addr + off;
  847. }
  848. /* this object spans two pages */
  849. pages[0] = page;
  850. pages[1] = get_next_page(page);
  851. BUG_ON(!pages[1]);
  852. return __zs_map_object(area, pages, off, class->size);
  853. }
  854. EXPORT_SYMBOL_GPL(zs_map_object);
  855. void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
  856. {
  857. struct page *page;
  858. unsigned long obj_idx, off;
  859. unsigned int class_idx;
  860. enum fullness_group fg;
  861. struct size_class *class;
  862. struct mapping_area *area;
  863. BUG_ON(!handle);
  864. obj_handle_to_location(handle, &page, &obj_idx);
  865. get_zspage_mapping(get_first_page(page), &class_idx, &fg);
  866. class = pool->size_class[class_idx];
  867. off = obj_idx_to_offset(page, obj_idx, class->size);
  868. area = this_cpu_ptr(&zs_map_area);
  869. if (off + class->size <= PAGE_SIZE)
  870. kunmap_atomic(area->vm_addr);
  871. else {
  872. struct page *pages[2];
  873. pages[0] = page;
  874. pages[1] = get_next_page(page);
  875. BUG_ON(!pages[1]);
  876. __zs_unmap_object(area, pages, off, class->size);
  877. }
  878. put_cpu_var(zs_map_area);
  879. }
  880. EXPORT_SYMBOL_GPL(zs_unmap_object);
  881. /**
  882. * zs_malloc - Allocate block of given size from pool.
  883. * @pool: pool to allocate from
  884. * @size: size of block to allocate
  885. *
  886. * On success, handle to the allocated object is returned,
  887. * otherwise 0.
  888. * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
  889. */
  890. unsigned long zs_malloc(struct zs_pool *pool, size_t size)
  891. {
  892. unsigned long obj;
  893. struct link_free *link;
  894. struct size_class *class;
  895. void *vaddr;
  896. struct page *first_page, *m_page;
  897. unsigned long m_objidx, m_offset;
  898. if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
  899. return 0;
  900. class = pool->size_class[get_size_class_index(size)];
  901. spin_lock(&class->lock);
  902. first_page = find_get_zspage(class);
  903. if (!first_page) {
  904. spin_unlock(&class->lock);
  905. first_page = alloc_zspage(class, pool->flags);
  906. if (unlikely(!first_page))
  907. return 0;
  908. set_zspage_mapping(first_page, class->index, ZS_EMPTY);
  909. atomic_long_add(class->pages_per_zspage,
  910. &pool->pages_allocated);
  911. spin_lock(&class->lock);
  912. }
  913. obj = (unsigned long)first_page->freelist;
  914. obj_handle_to_location(obj, &m_page, &m_objidx);
  915. m_offset = obj_idx_to_offset(m_page, m_objidx, class->size);
  916. vaddr = kmap_atomic(m_page);
  917. link = (struct link_free *)vaddr + m_offset / sizeof(*link);
  918. first_page->freelist = link->next;
  919. memset(link, POISON_INUSE, sizeof(*link));
  920. kunmap_atomic(vaddr);
  921. first_page->inuse++;
  922. /* Now move the zspage to another fullness group, if required */
  923. fix_fullness_group(pool, first_page);
  924. spin_unlock(&class->lock);
  925. return obj;
  926. }
  927. EXPORT_SYMBOL_GPL(zs_malloc);
  928. void zs_free(struct zs_pool *pool, unsigned long obj)
  929. {
  930. struct link_free *link;
  931. struct page *first_page, *f_page;
  932. unsigned long f_objidx, f_offset;
  933. void *vaddr;
  934. int class_idx;
  935. struct size_class *class;
  936. enum fullness_group fullness;
  937. if (unlikely(!obj))
  938. return;
  939. obj_handle_to_location(obj, &f_page, &f_objidx);
  940. first_page = get_first_page(f_page);
  941. get_zspage_mapping(first_page, &class_idx, &fullness);
  942. class = pool->size_class[class_idx];
  943. f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
  944. spin_lock(&class->lock);
  945. /* Insert this object in containing zspage's freelist */
  946. vaddr = kmap_atomic(f_page);
  947. link = (struct link_free *)(vaddr + f_offset);
  948. link->next = first_page->freelist;
  949. kunmap_atomic(vaddr);
  950. first_page->freelist = (void *)obj;
  951. first_page->inuse--;
  952. fullness = fix_fullness_group(pool, first_page);
  953. spin_unlock(&class->lock);
  954. if (fullness == ZS_EMPTY) {
  955. atomic_long_sub(class->pages_per_zspage,
  956. &pool->pages_allocated);
  957. free_zspage(first_page);
  958. }
  959. }
  960. EXPORT_SYMBOL_GPL(zs_free);
  961. /**
  962. * zs_create_pool - Creates an allocation pool to work from.
  963. * @flags: allocation flags used to allocate pool metadata
  964. *
  965. * This function must be called before anything when using
  966. * the zsmalloc allocator.
  967. *
  968. * On success, a pointer to the newly created pool is returned,
  969. * otherwise NULL.
  970. */
  971. struct zs_pool *zs_create_pool(gfp_t flags)
  972. {
  973. int i;
  974. struct zs_pool *pool;
  975. struct size_class *prev_class = NULL;
  976. pool = kzalloc(sizeof(*pool), GFP_KERNEL);
  977. if (!pool)
  978. return NULL;
  979. pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *),
  980. GFP_KERNEL);
  981. if (!pool->size_class) {
  982. kfree(pool);
  983. return NULL;
  984. }
  985. /*
  986. * Iterate reversly, because, size of size_class that we want to use
  987. * for merging should be larger or equal to current size.
  988. */
  989. for (i = zs_size_classes - 1; i >= 0; i--) {
  990. int size;
  991. int pages_per_zspage;
  992. struct size_class *class;
  993. size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
  994. if (size > ZS_MAX_ALLOC_SIZE)
  995. size = ZS_MAX_ALLOC_SIZE;
  996. pages_per_zspage = get_pages_per_zspage(size);
  997. /*
  998. * size_class is used for normal zsmalloc operation such
  999. * as alloc/free for that size. Although it is natural that we
  1000. * have one size_class for each size, there is a chance that we
  1001. * can get more memory utilization if we use one size_class for
  1002. * many different sizes whose size_class have same
  1003. * characteristics. So, we makes size_class point to
  1004. * previous size_class if possible.
  1005. */
  1006. if (prev_class) {
  1007. if (can_merge(prev_class, size, pages_per_zspage)) {
  1008. pool->size_class[i] = prev_class;
  1009. continue;
  1010. }
  1011. }
  1012. class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
  1013. if (!class)
  1014. goto err;
  1015. class->size = size;
  1016. class->index = i;
  1017. class->pages_per_zspage = pages_per_zspage;
  1018. spin_lock_init(&class->lock);
  1019. pool->size_class[i] = class;
  1020. prev_class = class;
  1021. }
  1022. pool->flags = flags;
  1023. return pool;
  1024. err:
  1025. zs_destroy_pool(pool);
  1026. return NULL;
  1027. }
  1028. EXPORT_SYMBOL_GPL(zs_create_pool);
  1029. void zs_destroy_pool(struct zs_pool *pool)
  1030. {
  1031. int i;
  1032. for (i = 0; i < zs_size_classes; i++) {
  1033. int fg;
  1034. struct size_class *class = pool->size_class[i];
  1035. if (!class)
  1036. continue;
  1037. if (class->index != i)
  1038. continue;
  1039. for (fg = 0; fg < _ZS_NR_FULLNESS_GROUPS; fg++) {
  1040. if (class->fullness_list[fg]) {
  1041. pr_info("Freeing non-empty class with size %db, fullness group %d\n",
  1042. class->size, fg);
  1043. }
  1044. }
  1045. kfree(class);
  1046. }
  1047. kfree(pool->size_class);
  1048. kfree(pool);
  1049. }
  1050. EXPORT_SYMBOL_GPL(zs_destroy_pool);
  1051. static int __init zs_init(void)
  1052. {
  1053. int ret = zs_register_cpu_notifier();
  1054. if (ret) {
  1055. zs_unregister_cpu_notifier();
  1056. return ret;
  1057. }
  1058. init_zs_size_classes();
  1059. #ifdef CONFIG_ZPOOL
  1060. zpool_register_driver(&zs_zpool_driver);
  1061. #endif
  1062. return 0;
  1063. }
  1064. static void __exit zs_exit(void)
  1065. {
  1066. #ifdef CONFIG_ZPOOL
  1067. zpool_unregister_driver(&zs_zpool_driver);
  1068. #endif
  1069. zs_unregister_cpu_notifier();
  1070. }
  1071. module_init(zs_init);
  1072. module_exit(zs_exit);
  1073. MODULE_LICENSE("Dual BSD/GPL");
  1074. MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");