zsmalloc.c 30 KB

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