zsmalloc.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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. /*
  93. * This must be power of 2 and greater than of equal to sizeof(link_free).
  94. * These two conditions ensure that any 'struct link_free' itself doesn't
  95. * span more than 1 page which avoids complex case of mapping 2 pages simply
  96. * to restore link_free pointer values.
  97. */
  98. #define ZS_ALIGN 8
  99. /*
  100. * A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
  101. * pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
  102. */
  103. #define ZS_MAX_ZSPAGE_ORDER 2
  104. #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
  105. /*
  106. * Object location (<PFN>, <obj_idx>) is encoded as
  107. * as single (unsigned long) handle value.
  108. *
  109. * Note that object index <obj_idx> is relative to system
  110. * page <PFN> it is stored in, so for each sub-page belonging
  111. * to a zspage, obj_idx starts with 0.
  112. *
  113. * This is made more complicated by various memory models and PAE.
  114. */
  115. #ifndef MAX_PHYSMEM_BITS
  116. #ifdef CONFIG_HIGHMEM64G
  117. #define MAX_PHYSMEM_BITS 36
  118. #else /* !CONFIG_HIGHMEM64G */
  119. /*
  120. * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
  121. * be PAGE_SHIFT
  122. */
  123. #define MAX_PHYSMEM_BITS BITS_PER_LONG
  124. #endif
  125. #endif
  126. #define _PFN_BITS (MAX_PHYSMEM_BITS - PAGE_SHIFT)
  127. #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS)
  128. #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
  129. #define MAX(a, b) ((a) >= (b) ? (a) : (b))
  130. /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
  131. #define ZS_MIN_ALLOC_SIZE \
  132. MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
  133. #define ZS_MAX_ALLOC_SIZE PAGE_SIZE
  134. /*
  135. * On systems with 4K page size, this gives 255 size classes! There is a
  136. * trader-off here:
  137. * - Large number of size classes is potentially wasteful as free page are
  138. * spread across these classes
  139. * - Small number of size classes causes large internal fragmentation
  140. * - Probably its better to use specific size classes (empirically
  141. * determined). NOTE: all those class sizes must be set as multiple of
  142. * ZS_ALIGN to make sure link_free itself never has to span 2 pages.
  143. *
  144. * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
  145. * (reason above)
  146. */
  147. #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> 8)
  148. #define ZS_SIZE_CLASSES ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / \
  149. ZS_SIZE_CLASS_DELTA + 1)
  150. /*
  151. * We do not maintain any list for completely empty or full pages
  152. */
  153. enum fullness_group {
  154. ZS_ALMOST_FULL,
  155. ZS_ALMOST_EMPTY,
  156. _ZS_NR_FULLNESS_GROUPS,
  157. ZS_EMPTY,
  158. ZS_FULL
  159. };
  160. /*
  161. * We assign a page to ZS_ALMOST_EMPTY fullness group when:
  162. * n <= N / f, where
  163. * n = number of allocated objects
  164. * N = total number of objects zspage can store
  165. * f = 1/fullness_threshold_frac
  166. *
  167. * Similarly, we assign zspage to:
  168. * ZS_ALMOST_FULL when n > N / f
  169. * ZS_EMPTY when n == 0
  170. * ZS_FULL when n == N
  171. *
  172. * (see: fix_fullness_group())
  173. */
  174. static const int fullness_threshold_frac = 4;
  175. struct size_class {
  176. /*
  177. * Size of objects stored in this class. Must be multiple
  178. * of ZS_ALIGN.
  179. */
  180. int size;
  181. unsigned int index;
  182. /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
  183. int pages_per_zspage;
  184. spinlock_t lock;
  185. /* stats */
  186. u64 pages_allocated;
  187. struct page *fullness_list[_ZS_NR_FULLNESS_GROUPS];
  188. };
  189. /*
  190. * Placed within free objects to form a singly linked list.
  191. * For every zspage, first_page->freelist gives head of this list.
  192. *
  193. * This must be power of 2 and less than or equal to ZS_ALIGN
  194. */
  195. struct link_free {
  196. /* Handle of next free chunk (encodes <PFN, obj_idx>) */
  197. void *next;
  198. };
  199. struct zs_pool {
  200. struct size_class size_class[ZS_SIZE_CLASSES];
  201. gfp_t flags; /* allocation flags used when growing pool */
  202. };
  203. /*
  204. * A zspage's class index and fullness group
  205. * are encoded in its (first)page->mapping
  206. */
  207. #define CLASS_IDX_BITS 28
  208. #define FULLNESS_BITS 4
  209. #define CLASS_IDX_MASK ((1 << CLASS_IDX_BITS) - 1)
  210. #define FULLNESS_MASK ((1 << FULLNESS_BITS) - 1)
  211. struct mapping_area {
  212. #ifdef CONFIG_PGTABLE_MAPPING
  213. struct vm_struct *vm; /* vm area for mapping object that span pages */
  214. #else
  215. char *vm_buf; /* copy buffer for objects that span pages */
  216. #endif
  217. char *vm_addr; /* address of kmap_atomic()'ed pages */
  218. enum zs_mapmode vm_mm; /* mapping mode */
  219. };
  220. /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
  221. static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
  222. static int is_first_page(struct page *page)
  223. {
  224. return PagePrivate(page);
  225. }
  226. static int is_last_page(struct page *page)
  227. {
  228. return PagePrivate2(page);
  229. }
  230. static void get_zspage_mapping(struct page *page, unsigned int *class_idx,
  231. enum fullness_group *fullness)
  232. {
  233. unsigned long m;
  234. BUG_ON(!is_first_page(page));
  235. m = (unsigned long)page->mapping;
  236. *fullness = m & FULLNESS_MASK;
  237. *class_idx = (m >> FULLNESS_BITS) & CLASS_IDX_MASK;
  238. }
  239. static void set_zspage_mapping(struct page *page, unsigned int class_idx,
  240. enum fullness_group fullness)
  241. {
  242. unsigned long m;
  243. BUG_ON(!is_first_page(page));
  244. m = ((class_idx & CLASS_IDX_MASK) << FULLNESS_BITS) |
  245. (fullness & FULLNESS_MASK);
  246. page->mapping = (struct address_space *)m;
  247. }
  248. /*
  249. * zsmalloc divides the pool into various size classes where each
  250. * class maintains a list of zspages where each zspage is divided
  251. * into equal sized chunks. Each allocation falls into one of these
  252. * classes depending on its size. This function returns index of the
  253. * size class which has chunk size big enough to hold the give size.
  254. */
  255. static int get_size_class_index(int size)
  256. {
  257. int idx = 0;
  258. if (likely(size > ZS_MIN_ALLOC_SIZE))
  259. idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
  260. ZS_SIZE_CLASS_DELTA);
  261. return idx;
  262. }
  263. /*
  264. * For each size class, zspages are divided into different groups
  265. * depending on how "full" they are. This was done so that we could
  266. * easily find empty or nearly empty zspages when we try to shrink
  267. * the pool (not yet implemented). This function returns fullness
  268. * status of the given page.
  269. */
  270. static enum fullness_group get_fullness_group(struct page *page)
  271. {
  272. int inuse, max_objects;
  273. enum fullness_group fg;
  274. BUG_ON(!is_first_page(page));
  275. inuse = page->inuse;
  276. max_objects = page->objects;
  277. if (inuse == 0)
  278. fg = ZS_EMPTY;
  279. else if (inuse == max_objects)
  280. fg = ZS_FULL;
  281. else if (inuse <= max_objects / fullness_threshold_frac)
  282. fg = ZS_ALMOST_EMPTY;
  283. else
  284. fg = ZS_ALMOST_FULL;
  285. return fg;
  286. }
  287. /*
  288. * Each size class maintains various freelists and zspages are assigned
  289. * to one of these freelists based on the number of live objects they
  290. * have. This functions inserts the given zspage into the freelist
  291. * identified by <class, fullness_group>.
  292. */
  293. static void insert_zspage(struct page *page, struct size_class *class,
  294. enum fullness_group fullness)
  295. {
  296. struct page **head;
  297. BUG_ON(!is_first_page(page));
  298. if (fullness >= _ZS_NR_FULLNESS_GROUPS)
  299. return;
  300. head = &class->fullness_list[fullness];
  301. if (*head)
  302. list_add_tail(&page->lru, &(*head)->lru);
  303. *head = page;
  304. }
  305. /*
  306. * This function removes the given zspage from the freelist identified
  307. * by <class, fullness_group>.
  308. */
  309. static void remove_zspage(struct page *page, struct size_class *class,
  310. enum fullness_group fullness)
  311. {
  312. struct page **head;
  313. BUG_ON(!is_first_page(page));
  314. if (fullness >= _ZS_NR_FULLNESS_GROUPS)
  315. return;
  316. head = &class->fullness_list[fullness];
  317. BUG_ON(!*head);
  318. if (list_empty(&(*head)->lru))
  319. *head = NULL;
  320. else if (*head == page)
  321. *head = (struct page *)list_entry((*head)->lru.next,
  322. struct page, lru);
  323. list_del_init(&page->lru);
  324. }
  325. /*
  326. * Each size class maintains zspages in different fullness groups depending
  327. * on the number of live objects they contain. When allocating or freeing
  328. * objects, the fullness status of the page can change, say, from ALMOST_FULL
  329. * to ALMOST_EMPTY when freeing an object. This function checks if such
  330. * a status change has occurred for the given page and accordingly moves the
  331. * page from the freelist of the old fullness group to that of the new
  332. * fullness group.
  333. */
  334. static enum fullness_group fix_fullness_group(struct zs_pool *pool,
  335. struct page *page)
  336. {
  337. int class_idx;
  338. struct size_class *class;
  339. enum fullness_group currfg, newfg;
  340. BUG_ON(!is_first_page(page));
  341. get_zspage_mapping(page, &class_idx, &currfg);
  342. newfg = get_fullness_group(page);
  343. if (newfg == currfg)
  344. goto out;
  345. class = &pool->size_class[class_idx];
  346. remove_zspage(page, class, currfg);
  347. insert_zspage(page, class, newfg);
  348. set_zspage_mapping(page, class_idx, newfg);
  349. out:
  350. return newfg;
  351. }
  352. /*
  353. * We have to decide on how many pages to link together
  354. * to form a zspage for each size class. This is important
  355. * to reduce wastage due to unusable space left at end of
  356. * each zspage which is given as:
  357. * wastage = Zp - Zp % size_class
  358. * where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
  359. *
  360. * For example, for size class of 3/8 * PAGE_SIZE, we should
  361. * link together 3 PAGE_SIZE sized pages to form a zspage
  362. * since then we can perfectly fit in 8 such objects.
  363. */
  364. static int get_pages_per_zspage(int class_size)
  365. {
  366. int i, max_usedpc = 0;
  367. /* zspage order which gives maximum used size per KB */
  368. int max_usedpc_order = 1;
  369. for (i = 1; i <= ZS_MAX_PAGES_PER_ZSPAGE; i++) {
  370. int zspage_size;
  371. int waste, usedpc;
  372. zspage_size = i * PAGE_SIZE;
  373. waste = zspage_size % class_size;
  374. usedpc = (zspage_size - waste) * 100 / zspage_size;
  375. if (usedpc > max_usedpc) {
  376. max_usedpc = usedpc;
  377. max_usedpc_order = i;
  378. }
  379. }
  380. return max_usedpc_order;
  381. }
  382. /*
  383. * A single 'zspage' is composed of many system pages which are
  384. * linked together using fields in struct page. This function finds
  385. * the first/head page, given any component page of a zspage.
  386. */
  387. static struct page *get_first_page(struct page *page)
  388. {
  389. if (is_first_page(page))
  390. return page;
  391. else
  392. return page->first_page;
  393. }
  394. static struct page *get_next_page(struct page *page)
  395. {
  396. struct page *next;
  397. if (is_last_page(page))
  398. next = NULL;
  399. else if (is_first_page(page))
  400. next = (struct page *)page_private(page);
  401. else
  402. next = list_entry(page->lru.next, struct page, lru);
  403. return next;
  404. }
  405. /*
  406. * Encode <page, obj_idx> as a single handle value.
  407. * On hardware platforms with physical memory starting at 0x0 the pfn
  408. * could be 0 so we ensure that the handle will never be 0 by adjusting the
  409. * encoded obj_idx value before encoding.
  410. */
  411. static void *obj_location_to_handle(struct page *page, unsigned long obj_idx)
  412. {
  413. unsigned long handle;
  414. if (!page) {
  415. BUG_ON(obj_idx);
  416. return NULL;
  417. }
  418. handle = page_to_pfn(page) << OBJ_INDEX_BITS;
  419. handle |= ((obj_idx + 1) & OBJ_INDEX_MASK);
  420. return (void *)handle;
  421. }
  422. /*
  423. * Decode <page, obj_idx> pair from the given object handle. We adjust the
  424. * decoded obj_idx back to its original value since it was adjusted in
  425. * obj_location_to_handle().
  426. */
  427. static void obj_handle_to_location(unsigned long handle, struct page **page,
  428. unsigned long *obj_idx)
  429. {
  430. *page = pfn_to_page(handle >> OBJ_INDEX_BITS);
  431. *obj_idx = (handle & OBJ_INDEX_MASK) - 1;
  432. }
  433. static unsigned long obj_idx_to_offset(struct page *page,
  434. unsigned long obj_idx, int class_size)
  435. {
  436. unsigned long off = 0;
  437. if (!is_first_page(page))
  438. off = page->index;
  439. return off + obj_idx * class_size;
  440. }
  441. static void reset_page(struct page *page)
  442. {
  443. clear_bit(PG_private, &page->flags);
  444. clear_bit(PG_private_2, &page->flags);
  445. set_page_private(page, 0);
  446. page->mapping = NULL;
  447. page->freelist = NULL;
  448. page_mapcount_reset(page);
  449. }
  450. static void free_zspage(struct page *first_page)
  451. {
  452. struct page *nextp, *tmp, *head_extra;
  453. BUG_ON(!is_first_page(first_page));
  454. BUG_ON(first_page->inuse);
  455. head_extra = (struct page *)page_private(first_page);
  456. reset_page(first_page);
  457. __free_page(first_page);
  458. /* zspage with only 1 system page */
  459. if (!head_extra)
  460. return;
  461. list_for_each_entry_safe(nextp, tmp, &head_extra->lru, lru) {
  462. list_del(&nextp->lru);
  463. reset_page(nextp);
  464. __free_page(nextp);
  465. }
  466. reset_page(head_extra);
  467. __free_page(head_extra);
  468. }
  469. /* Initialize a newly allocated zspage */
  470. static void init_zspage(struct page *first_page, struct size_class *class)
  471. {
  472. unsigned long off = 0;
  473. struct page *page = first_page;
  474. BUG_ON(!is_first_page(first_page));
  475. while (page) {
  476. struct page *next_page;
  477. struct link_free *link;
  478. unsigned int i, objs_on_page;
  479. /*
  480. * page->index stores offset of first object starting
  481. * in the page. For the first page, this is always 0,
  482. * so we use first_page->index (aka ->freelist) to store
  483. * head of corresponding zspage's freelist.
  484. */
  485. if (page != first_page)
  486. page->index = off;
  487. link = (struct link_free *)kmap_atomic(page) +
  488. off / sizeof(*link);
  489. objs_on_page = (PAGE_SIZE - off) / class->size;
  490. for (i = 1; i <= objs_on_page; i++) {
  491. off += class->size;
  492. if (off < PAGE_SIZE) {
  493. link->next = obj_location_to_handle(page, i);
  494. link += class->size / sizeof(*link);
  495. }
  496. }
  497. /*
  498. * We now come to the last (full or partial) object on this
  499. * page, which must point to the first object on the next
  500. * page (if present)
  501. */
  502. next_page = get_next_page(page);
  503. link->next = obj_location_to_handle(next_page, 0);
  504. kunmap_atomic(link);
  505. page = next_page;
  506. off = (off + class->size) % PAGE_SIZE;
  507. }
  508. }
  509. /*
  510. * Allocate a zspage for the given size class
  511. */
  512. static struct page *alloc_zspage(struct size_class *class, gfp_t flags)
  513. {
  514. int i, error;
  515. struct page *first_page = NULL, *uninitialized_var(prev_page);
  516. /*
  517. * Allocate individual pages and link them together as:
  518. * 1. first page->private = first sub-page
  519. * 2. all sub-pages are linked together using page->lru
  520. * 3. each sub-page is linked to the first page using page->first_page
  521. *
  522. * For each size class, First/Head pages are linked together using
  523. * page->lru. Also, we set PG_private to identify the first page
  524. * (i.e. no other sub-page has this flag set) and PG_private_2 to
  525. * identify the last page.
  526. */
  527. error = -ENOMEM;
  528. for (i = 0; i < class->pages_per_zspage; i++) {
  529. struct page *page;
  530. page = alloc_page(flags);
  531. if (!page)
  532. goto cleanup;
  533. INIT_LIST_HEAD(&page->lru);
  534. if (i == 0) { /* first page */
  535. SetPagePrivate(page);
  536. set_page_private(page, 0);
  537. first_page = page;
  538. first_page->inuse = 0;
  539. }
  540. if (i == 1)
  541. set_page_private(first_page, (unsigned long)page);
  542. if (i >= 1)
  543. page->first_page = first_page;
  544. if (i >= 2)
  545. list_add(&page->lru, &prev_page->lru);
  546. if (i == class->pages_per_zspage - 1) /* last page */
  547. SetPagePrivate2(page);
  548. prev_page = page;
  549. }
  550. init_zspage(first_page, class);
  551. first_page->freelist = obj_location_to_handle(first_page, 0);
  552. /* Maximum number of objects we can store in this zspage */
  553. first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size;
  554. error = 0; /* Success */
  555. cleanup:
  556. if (unlikely(error) && first_page) {
  557. free_zspage(first_page);
  558. first_page = NULL;
  559. }
  560. return first_page;
  561. }
  562. static struct page *find_get_zspage(struct size_class *class)
  563. {
  564. int i;
  565. struct page *page;
  566. for (i = 0; i < _ZS_NR_FULLNESS_GROUPS; i++) {
  567. page = class->fullness_list[i];
  568. if (page)
  569. break;
  570. }
  571. return page;
  572. }
  573. #ifdef CONFIG_PGTABLE_MAPPING
  574. static inline int __zs_cpu_up(struct mapping_area *area)
  575. {
  576. /*
  577. * Make sure we don't leak memory if a cpu UP notification
  578. * and zs_init() race and both call zs_cpu_up() on the same cpu
  579. */
  580. if (area->vm)
  581. return 0;
  582. area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
  583. if (!area->vm)
  584. return -ENOMEM;
  585. return 0;
  586. }
  587. static inline void __zs_cpu_down(struct mapping_area *area)
  588. {
  589. if (area->vm)
  590. free_vm_area(area->vm);
  591. area->vm = NULL;
  592. }
  593. static inline void *__zs_map_object(struct mapping_area *area,
  594. struct page *pages[2], int off, int size)
  595. {
  596. BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, &pages));
  597. area->vm_addr = area->vm->addr;
  598. return area->vm_addr + off;
  599. }
  600. static inline void __zs_unmap_object(struct mapping_area *area,
  601. struct page *pages[2], int off, int size)
  602. {
  603. unsigned long addr = (unsigned long)area->vm_addr;
  604. unmap_kernel_range(addr, PAGE_SIZE * 2);
  605. }
  606. #else /* CONFIG_PGTABLE_MAPPING */
  607. static inline int __zs_cpu_up(struct mapping_area *area)
  608. {
  609. /*
  610. * Make sure we don't leak memory if a cpu UP notification
  611. * and zs_init() race and both call zs_cpu_up() on the same cpu
  612. */
  613. if (area->vm_buf)
  614. return 0;
  615. area->vm_buf = (char *)__get_free_page(GFP_KERNEL);
  616. if (!area->vm_buf)
  617. return -ENOMEM;
  618. return 0;
  619. }
  620. static inline void __zs_cpu_down(struct mapping_area *area)
  621. {
  622. if (area->vm_buf)
  623. free_page((unsigned long)area->vm_buf);
  624. area->vm_buf = NULL;
  625. }
  626. static void *__zs_map_object(struct mapping_area *area,
  627. struct page *pages[2], int off, int size)
  628. {
  629. int sizes[2];
  630. void *addr;
  631. char *buf = area->vm_buf;
  632. /* disable page faults to match kmap_atomic() return conditions */
  633. pagefault_disable();
  634. /* no read fastpath */
  635. if (area->vm_mm == ZS_MM_WO)
  636. goto out;
  637. sizes[0] = PAGE_SIZE - off;
  638. sizes[1] = size - sizes[0];
  639. /* copy object to per-cpu buffer */
  640. addr = kmap_atomic(pages[0]);
  641. memcpy(buf, addr + off, sizes[0]);
  642. kunmap_atomic(addr);
  643. addr = kmap_atomic(pages[1]);
  644. memcpy(buf + sizes[0], addr, sizes[1]);
  645. kunmap_atomic(addr);
  646. out:
  647. return area->vm_buf;
  648. }
  649. static void __zs_unmap_object(struct mapping_area *area,
  650. struct page *pages[2], int off, int size)
  651. {
  652. int sizes[2];
  653. void *addr;
  654. char *buf = area->vm_buf;
  655. /* no write fastpath */
  656. if (area->vm_mm == ZS_MM_RO)
  657. goto out;
  658. sizes[0] = PAGE_SIZE - off;
  659. sizes[1] = size - sizes[0];
  660. /* copy per-cpu buffer to object */
  661. addr = kmap_atomic(pages[0]);
  662. memcpy(addr + off, buf, sizes[0]);
  663. kunmap_atomic(addr);
  664. addr = kmap_atomic(pages[1]);
  665. memcpy(addr, buf + sizes[0], sizes[1]);
  666. kunmap_atomic(addr);
  667. out:
  668. /* enable page faults to match kunmap_atomic() return conditions */
  669. pagefault_enable();
  670. }
  671. #endif /* CONFIG_PGTABLE_MAPPING */
  672. static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
  673. void *pcpu)
  674. {
  675. int ret, cpu = (long)pcpu;
  676. struct mapping_area *area;
  677. switch (action) {
  678. case CPU_UP_PREPARE:
  679. area = &per_cpu(zs_map_area, cpu);
  680. ret = __zs_cpu_up(area);
  681. if (ret)
  682. return notifier_from_errno(ret);
  683. break;
  684. case CPU_DEAD:
  685. case CPU_UP_CANCELED:
  686. area = &per_cpu(zs_map_area, cpu);
  687. __zs_cpu_down(area);
  688. break;
  689. }
  690. return NOTIFY_OK;
  691. }
  692. static struct notifier_block zs_cpu_nb = {
  693. .notifier_call = zs_cpu_notifier
  694. };
  695. static void zs_exit(void)
  696. {
  697. int cpu;
  698. cpu_notifier_register_begin();
  699. for_each_online_cpu(cpu)
  700. zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
  701. __unregister_cpu_notifier(&zs_cpu_nb);
  702. cpu_notifier_register_done();
  703. }
  704. static int zs_init(void)
  705. {
  706. int cpu, ret;
  707. cpu_notifier_register_begin();
  708. __register_cpu_notifier(&zs_cpu_nb);
  709. for_each_online_cpu(cpu) {
  710. ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
  711. if (notifier_to_errno(ret)) {
  712. cpu_notifier_register_done();
  713. goto fail;
  714. }
  715. }
  716. cpu_notifier_register_done();
  717. return 0;
  718. fail:
  719. zs_exit();
  720. return notifier_to_errno(ret);
  721. }
  722. /**
  723. * zs_create_pool - Creates an allocation pool to work from.
  724. * @flags: allocation flags used to allocate pool metadata
  725. *
  726. * This function must be called before anything when using
  727. * the zsmalloc allocator.
  728. *
  729. * On success, a pointer to the newly created pool is returned,
  730. * otherwise NULL.
  731. */
  732. struct zs_pool *zs_create_pool(gfp_t flags)
  733. {
  734. int i, ovhd_size;
  735. struct zs_pool *pool;
  736. ovhd_size = roundup(sizeof(*pool), PAGE_SIZE);
  737. pool = kzalloc(ovhd_size, GFP_KERNEL);
  738. if (!pool)
  739. return NULL;
  740. for (i = 0; i < ZS_SIZE_CLASSES; i++) {
  741. int size;
  742. struct size_class *class;
  743. size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
  744. if (size > ZS_MAX_ALLOC_SIZE)
  745. size = ZS_MAX_ALLOC_SIZE;
  746. class = &pool->size_class[i];
  747. class->size = size;
  748. class->index = i;
  749. spin_lock_init(&class->lock);
  750. class->pages_per_zspage = get_pages_per_zspage(size);
  751. }
  752. pool->flags = flags;
  753. return pool;
  754. }
  755. EXPORT_SYMBOL_GPL(zs_create_pool);
  756. void zs_destroy_pool(struct zs_pool *pool)
  757. {
  758. int i;
  759. for (i = 0; i < ZS_SIZE_CLASSES; i++) {
  760. int fg;
  761. struct size_class *class = &pool->size_class[i];
  762. for (fg = 0; fg < _ZS_NR_FULLNESS_GROUPS; fg++) {
  763. if (class->fullness_list[fg]) {
  764. pr_info("Freeing non-empty class with size %db, fullness group %d\n",
  765. class->size, fg);
  766. }
  767. }
  768. }
  769. kfree(pool);
  770. }
  771. EXPORT_SYMBOL_GPL(zs_destroy_pool);
  772. /**
  773. * zs_malloc - Allocate block of given size from pool.
  774. * @pool: pool to allocate from
  775. * @size: size of block to allocate
  776. *
  777. * On success, handle to the allocated object is returned,
  778. * otherwise 0.
  779. * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
  780. */
  781. unsigned long zs_malloc(struct zs_pool *pool, size_t size)
  782. {
  783. unsigned long obj;
  784. struct link_free *link;
  785. int class_idx;
  786. struct size_class *class;
  787. struct page *first_page, *m_page;
  788. unsigned long m_objidx, m_offset;
  789. if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
  790. return 0;
  791. class_idx = get_size_class_index(size);
  792. class = &pool->size_class[class_idx];
  793. BUG_ON(class_idx != class->index);
  794. spin_lock(&class->lock);
  795. first_page = find_get_zspage(class);
  796. if (!first_page) {
  797. spin_unlock(&class->lock);
  798. first_page = alloc_zspage(class, pool->flags);
  799. if (unlikely(!first_page))
  800. return 0;
  801. set_zspage_mapping(first_page, class->index, ZS_EMPTY);
  802. spin_lock(&class->lock);
  803. class->pages_allocated += class->pages_per_zspage;
  804. }
  805. obj = (unsigned long)first_page->freelist;
  806. obj_handle_to_location(obj, &m_page, &m_objidx);
  807. m_offset = obj_idx_to_offset(m_page, m_objidx, class->size);
  808. link = (struct link_free *)kmap_atomic(m_page) +
  809. m_offset / sizeof(*link);
  810. first_page->freelist = link->next;
  811. memset(link, POISON_INUSE, sizeof(*link));
  812. kunmap_atomic(link);
  813. first_page->inuse++;
  814. /* Now move the zspage to another fullness group, if required */
  815. fix_fullness_group(pool, first_page);
  816. spin_unlock(&class->lock);
  817. return obj;
  818. }
  819. EXPORT_SYMBOL_GPL(zs_malloc);
  820. void zs_free(struct zs_pool *pool, unsigned long obj)
  821. {
  822. struct link_free *link;
  823. struct page *first_page, *f_page;
  824. unsigned long f_objidx, f_offset;
  825. int class_idx;
  826. struct size_class *class;
  827. enum fullness_group fullness;
  828. if (unlikely(!obj))
  829. return;
  830. obj_handle_to_location(obj, &f_page, &f_objidx);
  831. first_page = get_first_page(f_page);
  832. get_zspage_mapping(first_page, &class_idx, &fullness);
  833. class = &pool->size_class[class_idx];
  834. f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
  835. spin_lock(&class->lock);
  836. /* Insert this object in containing zspage's freelist */
  837. link = (struct link_free *)((unsigned char *)kmap_atomic(f_page)
  838. + f_offset);
  839. link->next = first_page->freelist;
  840. kunmap_atomic(link);
  841. first_page->freelist = (void *)obj;
  842. first_page->inuse--;
  843. fullness = fix_fullness_group(pool, first_page);
  844. if (fullness == ZS_EMPTY)
  845. class->pages_allocated -= class->pages_per_zspage;
  846. spin_unlock(&class->lock);
  847. if (fullness == ZS_EMPTY)
  848. free_zspage(first_page);
  849. }
  850. EXPORT_SYMBOL_GPL(zs_free);
  851. /**
  852. * zs_map_object - get address of allocated object from handle.
  853. * @pool: pool from which the object was allocated
  854. * @handle: handle returned from zs_malloc
  855. *
  856. * Before using an object allocated from zs_malloc, it must be mapped using
  857. * this function. When done with the object, it must be unmapped using
  858. * zs_unmap_object.
  859. *
  860. * Only one object can be mapped per cpu at a time. There is no protection
  861. * against nested mappings.
  862. *
  863. * This function returns with preemption and page faults disabled.
  864. */
  865. void *zs_map_object(struct zs_pool *pool, unsigned long handle,
  866. enum zs_mapmode mm)
  867. {
  868. struct page *page;
  869. unsigned long obj_idx, off;
  870. unsigned int class_idx;
  871. enum fullness_group fg;
  872. struct size_class *class;
  873. struct mapping_area *area;
  874. struct page *pages[2];
  875. BUG_ON(!handle);
  876. /*
  877. * Because we use per-cpu mapping areas shared among the
  878. * pools/users, we can't allow mapping in interrupt context
  879. * because it can corrupt another users mappings.
  880. */
  881. BUG_ON(in_interrupt());
  882. obj_handle_to_location(handle, &page, &obj_idx);
  883. get_zspage_mapping(get_first_page(page), &class_idx, &fg);
  884. class = &pool->size_class[class_idx];
  885. off = obj_idx_to_offset(page, obj_idx, class->size);
  886. area = &get_cpu_var(zs_map_area);
  887. area->vm_mm = mm;
  888. if (off + class->size <= PAGE_SIZE) {
  889. /* this object is contained entirely within a page */
  890. area->vm_addr = kmap_atomic(page);
  891. return area->vm_addr + off;
  892. }
  893. /* this object spans two pages */
  894. pages[0] = page;
  895. pages[1] = get_next_page(page);
  896. BUG_ON(!pages[1]);
  897. return __zs_map_object(area, pages, off, class->size);
  898. }
  899. EXPORT_SYMBOL_GPL(zs_map_object);
  900. void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
  901. {
  902. struct page *page;
  903. unsigned long obj_idx, off;
  904. unsigned int class_idx;
  905. enum fullness_group fg;
  906. struct size_class *class;
  907. struct mapping_area *area;
  908. BUG_ON(!handle);
  909. obj_handle_to_location(handle, &page, &obj_idx);
  910. get_zspage_mapping(get_first_page(page), &class_idx, &fg);
  911. class = &pool->size_class[class_idx];
  912. off = obj_idx_to_offset(page, obj_idx, class->size);
  913. area = this_cpu_ptr(&zs_map_area);
  914. if (off + class->size <= PAGE_SIZE)
  915. kunmap_atomic(area->vm_addr);
  916. else {
  917. struct page *pages[2];
  918. pages[0] = page;
  919. pages[1] = get_next_page(page);
  920. BUG_ON(!pages[1]);
  921. __zs_unmap_object(area, pages, off, class->size);
  922. }
  923. put_cpu_var(zs_map_area);
  924. }
  925. EXPORT_SYMBOL_GPL(zs_unmap_object);
  926. u64 zs_get_total_size_bytes(struct zs_pool *pool)
  927. {
  928. int i;
  929. u64 npages = 0;
  930. for (i = 0; i < ZS_SIZE_CLASSES; i++)
  931. npages += pool->size_class[i].pages_allocated;
  932. return npages << PAGE_SHIFT;
  933. }
  934. EXPORT_SYMBOL_GPL(zs_get_total_size_bytes);
  935. module_init(zs_init);
  936. module_exit(zs_exit);
  937. MODULE_LICENSE("Dual BSD/GPL");
  938. MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");