zsmalloc.c 30 KB

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