1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * zbud.c 4 * 5 * Copyright (C) 2013, Seth Jennings, IBM 6 * 7 * Concepts based on zcache internal zbud allocator by Dan Magenheimer. 8 * 9 * zbud is an special purpose allocator for storing compressed pages. Contrary 10 * to what its name may suggest, zbud is not a buddy allocator, but rather an 11 * allocator that "buddies" two compressed pages together in a single memory 12 * page. 13 * 14 * While this design limits storage density, it has simple and deterministic 15 * reclaim properties that make it preferable to a higher density approach when 16 * reclaim will be used. 17 * 18 * zbud works by storing compressed pages, or "zpages", together in pairs in a 19 * single memory page called a "zbud page". The first buddy is "left 20 * justified" at the beginning of the zbud page, and the last buddy is "right 21 * justified" at the end of the zbud page. The benefit is that if either 22 * buddy is freed, the freed buddy space, coalesced with whatever slack space 23 * that existed between the buddies, results in the largest possible free region 24 * within the zbud page. 25 * 26 * zbud also provides an attractive lower bound on density. The ratio of zpages 27 * to zbud pages can not be less than 1. This ensures that zbud can never "do 28 * harm" by using more pages to store zpages than the uncompressed zpages would 29 * have used on their own. 30 * 31 * zbud pages are divided into "chunks". The size of the chunks is fixed at 32 * compile time and determined by NCHUNKS_ORDER below. Dividing zbud pages 33 * into chunks allows organizing unbuddied zbud pages into a manageable number 34 * of unbuddied lists according to the number of free chunks available in the 35 * zbud page. 36 * 37 * The zbud API differs from that of conventional allocators in that the 38 * allocation function, zbud_alloc(), returns an opaque handle to the user, 39 * not a dereferenceable pointer. The user must map the handle using 40 * zbud_map() in order to get a usable pointer by which to access the 41 * allocation data and unmap the handle with zbud_unmap() when operations 42 * on the allocation data are complete. 43 */ 44 45 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 46 47 #include <linux/atomic.h> 48 #include <linux/list.h> 49 #include <linux/mm.h> 50 #include <linux/module.h> 51 #include <linux/preempt.h> 52 #include <linux/slab.h> 53 #include <linux/spinlock.h> 54 #include <linux/zpool.h> 55 56 /***************** 57 * Structures 58 *****************/ 59 /* 60 * NCHUNKS_ORDER determines the internal allocation granularity, effectively 61 * adjusting internal fragmentation. It also determines the number of 62 * freelists maintained in each pool. NCHUNKS_ORDER of 6 means that the 63 * allocation granularity will be in chunks of size PAGE_SIZE/64. As one chunk 64 * in allocated page is occupied by zbud header, NCHUNKS will be calculated to 65 * 63 which shows the max number of free chunks in zbud page, also there will be 66 * 63 freelists per pool. 67 */ 68 #define NCHUNKS_ORDER 6 69 70 #define CHUNK_SHIFT (PAGE_SHIFT - NCHUNKS_ORDER) 71 #define CHUNK_SIZE (1 << CHUNK_SHIFT) 72 #define ZHDR_SIZE_ALIGNED CHUNK_SIZE 73 #define NCHUNKS ((PAGE_SIZE - ZHDR_SIZE_ALIGNED) >> CHUNK_SHIFT) 74 75 struct zbud_pool; 76 77 struct zbud_ops { 78 int (*evict)(struct zbud_pool *pool, unsigned long handle); 79 }; 80 81 /** 82 * struct zbud_pool - stores metadata for each zbud pool 83 * @lock: protects all pool fields and first|last_chunk fields of any 84 * zbud page in the pool 85 * @unbuddied: array of lists tracking zbud pages that only contain one buddy; 86 * the lists each zbud page is added to depends on the size of 87 * its free region. 88 * @buddied: list tracking the zbud pages that contain two buddies; 89 * these zbud pages are full 90 * @lru: list tracking the zbud pages in LRU order by most recently 91 * added buddy. 92 * @pages_nr: number of zbud pages in the pool. 93 * @ops: pointer to a structure of user defined operations specified at 94 * pool creation time. 95 * @zpool: zpool driver 96 * @zpool_ops: zpool operations structure with an evict callback 97 * 98 * This structure is allocated at pool creation time and maintains metadata 99 * pertaining to a particular zbud pool. 100 */ 101 struct zbud_pool { 102 spinlock_t lock; 103 union { 104 /* 105 * Reuse unbuddied[0] as buddied on the ground that 106 * unbuddied[0] is unused. 107 */ 108 struct list_head buddied; 109 struct list_head unbuddied[NCHUNKS]; 110 }; 111 struct list_head lru; 112 u64 pages_nr; 113 const struct zbud_ops *ops; 114 struct zpool *zpool; 115 const struct zpool_ops *zpool_ops; 116 }; 117 118 /* 119 * struct zbud_header - zbud page metadata occupying the first chunk of each 120 * zbud page. 121 * @buddy: links the zbud page into the unbuddied/buddied lists in the pool 122 * @lru: links the zbud page into the lru list in the pool 123 * @first_chunks: the size of the first buddy in chunks, 0 if free 124 * @last_chunks: the size of the last buddy in chunks, 0 if free 125 */ 126 struct zbud_header { 127 struct list_head buddy; 128 struct list_head lru; 129 unsigned int first_chunks; 130 unsigned int last_chunks; 131 bool under_reclaim; 132 }; 133 134 /***************** 135 * Helpers 136 *****************/ 137 /* Just to make the code easier to read */ 138 enum buddy { 139 FIRST, 140 LAST 141 }; 142 143 /* Converts an allocation size in bytes to size in zbud chunks */ 144 static int size_to_chunks(size_t size) 145 { 146 return (size + CHUNK_SIZE - 1) >> CHUNK_SHIFT; 147 } 148 149 #define for_each_unbuddied_list(_iter, _begin) \ 150 for ((_iter) = (_begin); (_iter) < NCHUNKS; (_iter)++) 151 152 /* Initializes the zbud header of a newly allocated zbud page */ 153 static struct zbud_header *init_zbud_page(struct page *page) 154 { 155 struct zbud_header *zhdr = page_address(page); 156 zhdr->first_chunks = 0; 157 zhdr->last_chunks = 0; 158 INIT_LIST_HEAD(&zhdr->buddy); 159 INIT_LIST_HEAD(&zhdr->lru); 160 zhdr->under_reclaim = false; 161 return zhdr; 162 } 163 164 /* Resets the struct page fields and frees the page */ 165 static void free_zbud_page(struct zbud_header *zhdr) 166 { 167 __free_page(virt_to_page(zhdr)); 168 } 169 170 /* 171 * Encodes the handle of a particular buddy within a zbud page 172 * Pool lock should be held as this function accesses first|last_chunks 173 */ 174 static unsigned long encode_handle(struct zbud_header *zhdr, enum buddy bud) 175 { 176 unsigned long handle; 177 178 /* 179 * For now, the encoded handle is actually just the pointer to the data 180 * but this might not always be the case. A little information hiding. 181 * Add CHUNK_SIZE to the handle if it is the first allocation to jump 182 * over the zbud header in the first chunk. 183 */ 184 handle = (unsigned long)zhdr; 185 if (bud == FIRST) 186 /* skip over zbud header */ 187 handle += ZHDR_SIZE_ALIGNED; 188 else /* bud == LAST */ 189 handle += PAGE_SIZE - (zhdr->last_chunks << CHUNK_SHIFT); 190 return handle; 191 } 192 193 /* Returns the zbud page where a given handle is stored */ 194 static struct zbud_header *handle_to_zbud_header(unsigned long handle) 195 { 196 return (struct zbud_header *)(handle & PAGE_MASK); 197 } 198 199 /* Returns the number of free chunks in a zbud page */ 200 static int num_free_chunks(struct zbud_header *zhdr) 201 { 202 /* 203 * Rather than branch for different situations, just use the fact that 204 * free buddies have a length of zero to simplify everything. 205 */ 206 return NCHUNKS - zhdr->first_chunks - zhdr->last_chunks; 207 } 208 209 /***************** 210 * API Functions 211 *****************/ 212 /** 213 * zbud_create_pool() - create a new zbud pool 214 * @gfp: gfp flags when allocating the zbud pool structure 215 * @ops: user-defined operations for the zbud pool 216 * 217 * Return: pointer to the new zbud pool or NULL if the metadata allocation 218 * failed. 219 */ 220 static struct zbud_pool *zbud_create_pool(gfp_t gfp, const struct zbud_ops *ops) 221 { 222 struct zbud_pool *pool; 223 int i; 224 225 pool = kzalloc(sizeof(struct zbud_pool), gfp); 226 if (!pool) 227 return NULL; 228 spin_lock_init(&pool->lock); 229 for_each_unbuddied_list(i, 0) 230 INIT_LIST_HEAD(&pool->unbuddied[i]); 231 INIT_LIST_HEAD(&pool->buddied); 232 INIT_LIST_HEAD(&pool->lru); 233 pool->pages_nr = 0; 234 pool->ops = ops; 235 return pool; 236 } 237 238 /** 239 * zbud_destroy_pool() - destroys an existing zbud pool 240 * @pool: the zbud pool to be destroyed 241 * 242 * The pool should be emptied before this function is called. 243 */ 244 static void zbud_destroy_pool(struct zbud_pool *pool) 245 { 246 kfree(pool); 247 } 248 249 /** 250 * zbud_alloc() - allocates a region of a given size 251 * @pool: zbud pool from which to allocate 252 * @size: size in bytes of the desired allocation 253 * @gfp: gfp flags used if the pool needs to grow 254 * @handle: handle of the new allocation 255 * 256 * This function will attempt to find a free region in the pool large enough to 257 * satisfy the allocation request. A search of the unbuddied lists is 258 * performed first. If no suitable free region is found, then a new page is 259 * allocated and added to the pool to satisfy the request. 260 * 261 * gfp should not set __GFP_HIGHMEM as highmem pages cannot be used 262 * as zbud pool pages. 263 * 264 * Return: 0 if success and handle is set, otherwise -EINVAL if the size or 265 * gfp arguments are invalid or -ENOMEM if the pool was unable to allocate 266 * a new page. 267 */ 268 static int zbud_alloc(struct zbud_pool *pool, size_t size, gfp_t gfp, 269 unsigned long *handle) 270 { 271 int chunks, i, freechunks; 272 struct zbud_header *zhdr = NULL; 273 enum buddy bud; 274 struct page *page; 275 276 if (!size || (gfp & __GFP_HIGHMEM)) 277 return -EINVAL; 278 if (size > PAGE_SIZE - ZHDR_SIZE_ALIGNED - CHUNK_SIZE) 279 return -ENOSPC; 280 chunks = size_to_chunks(size); 281 spin_lock(&pool->lock); 282 283 /* First, try to find an unbuddied zbud page. */ 284 for_each_unbuddied_list(i, chunks) { 285 if (!list_empty(&pool->unbuddied[i])) { 286 zhdr = list_first_entry(&pool->unbuddied[i], 287 struct zbud_header, buddy); 288 list_del(&zhdr->buddy); 289 if (zhdr->first_chunks == 0) 290 bud = FIRST; 291 else 292 bud = LAST; 293 goto found; 294 } 295 } 296 297 /* Couldn't find unbuddied zbud page, create new one */ 298 spin_unlock(&pool->lock); 299 page = alloc_page(gfp); 300 if (!page) 301 return -ENOMEM; 302 spin_lock(&pool->lock); 303 pool->pages_nr++; 304 zhdr = init_zbud_page(page); 305 bud = FIRST; 306 307 found: 308 if (bud == FIRST) 309 zhdr->first_chunks = chunks; 310 else 311 zhdr->last_chunks = chunks; 312 313 if (zhdr->first_chunks == 0 || zhdr->last_chunks == 0) { 314 /* Add to unbuddied list */ 315 freechunks = num_free_chunks(zhdr); 316 list_add(&zhdr->buddy, &pool->unbuddied[freechunks]); 317 } else { 318 /* Add to buddied list */ 319 list_add(&zhdr->buddy, &pool->buddied); 320 } 321 322 /* Add/move zbud page to beginning of LRU */ 323 if (!list_empty(&zhdr->lru)) 324 list_del(&zhdr->lru); 325 list_add(&zhdr->lru, &pool->lru); 326 327 *handle = encode_handle(zhdr, bud); 328 spin_unlock(&pool->lock); 329 330 return 0; 331 } 332 333 /** 334 * zbud_free() - frees the allocation associated with the given handle 335 * @pool: pool in which the allocation resided 336 * @handle: handle associated with the allocation returned by zbud_alloc() 337 * 338 * In the case that the zbud page in which the allocation resides is under 339 * reclaim, as indicated by the PG_reclaim flag being set, this function 340 * only sets the first|last_chunks to 0. The page is actually freed 341 * once both buddies are evicted (see zbud_reclaim_page() below). 342 */ 343 static void zbud_free(struct zbud_pool *pool, unsigned long handle) 344 { 345 struct zbud_header *zhdr; 346 int freechunks; 347 348 spin_lock(&pool->lock); 349 zhdr = handle_to_zbud_header(handle); 350 351 /* If first buddy, handle will be page aligned */ 352 if ((handle - ZHDR_SIZE_ALIGNED) & ~PAGE_MASK) 353 zhdr->last_chunks = 0; 354 else 355 zhdr->first_chunks = 0; 356 357 if (zhdr->under_reclaim) { 358 /* zbud page is under reclaim, reclaim will free */ 359 spin_unlock(&pool->lock); 360 return; 361 } 362 363 /* Remove from existing buddy list */ 364 list_del(&zhdr->buddy); 365 366 if (zhdr->first_chunks == 0 && zhdr->last_chunks == 0) { 367 /* zbud page is empty, free */ 368 list_del(&zhdr->lru); 369 free_zbud_page(zhdr); 370 pool->pages_nr--; 371 } else { 372 /* Add to unbuddied list */ 373 freechunks = num_free_chunks(zhdr); 374 list_add(&zhdr->buddy, &pool->unbuddied[freechunks]); 375 } 376 377 spin_unlock(&pool->lock); 378 } 379 380 /** 381 * zbud_reclaim_page() - evicts allocations from a pool page and frees it 382 * @pool: pool from which a page will attempt to be evicted 383 * @retries: number of pages on the LRU list for which eviction will 384 * be attempted before failing 385 * 386 * zbud reclaim is different from normal system reclaim in that the reclaim is 387 * done from the bottom, up. This is because only the bottom layer, zbud, has 388 * information on how the allocations are organized within each zbud page. This 389 * has the potential to create interesting locking situations between zbud and 390 * the user, however. 391 * 392 * To avoid these, this is how zbud_reclaim_page() should be called: 393 * 394 * The user detects a page should be reclaimed and calls zbud_reclaim_page(). 395 * zbud_reclaim_page() will remove a zbud page from the pool LRU list and call 396 * the user-defined eviction handler with the pool and handle as arguments. 397 * 398 * If the handle can not be evicted, the eviction handler should return 399 * non-zero. zbud_reclaim_page() will add the zbud page back to the 400 * appropriate list and try the next zbud page on the LRU up to 401 * a user defined number of retries. 402 * 403 * If the handle is successfully evicted, the eviction handler should 404 * return 0 _and_ should have called zbud_free() on the handle. zbud_free() 405 * contains logic to delay freeing the page if the page is under reclaim, 406 * as indicated by the setting of the PG_reclaim flag on the underlying page. 407 * 408 * If all buddies in the zbud page are successfully evicted, then the 409 * zbud page can be freed. 410 * 411 * Returns: 0 if page is successfully freed, otherwise -EINVAL if there are 412 * no pages to evict or an eviction handler is not registered, -EAGAIN if 413 * the retry limit was hit. 414 */ 415 static int zbud_reclaim_page(struct zbud_pool *pool, unsigned int retries) 416 { 417 int i, ret, freechunks; 418 struct zbud_header *zhdr; 419 unsigned long first_handle = 0, last_handle = 0; 420 421 spin_lock(&pool->lock); 422 if (!pool->ops || !pool->ops->evict || list_empty(&pool->lru) || 423 retries == 0) { 424 spin_unlock(&pool->lock); 425 return -EINVAL; 426 } 427 for (i = 0; i < retries; i++) { 428 zhdr = list_last_entry(&pool->lru, struct zbud_header, lru); 429 list_del(&zhdr->lru); 430 list_del(&zhdr->buddy); 431 /* Protect zbud page against free */ 432 zhdr->under_reclaim = true; 433 /* 434 * We need encode the handles before unlocking, since we can 435 * race with free that will set (first|last)_chunks to 0 436 */ 437 first_handle = 0; 438 last_handle = 0; 439 if (zhdr->first_chunks) 440 first_handle = encode_handle(zhdr, FIRST); 441 if (zhdr->last_chunks) 442 last_handle = encode_handle(zhdr, LAST); 443 spin_unlock(&pool->lock); 444 445 /* Issue the eviction callback(s) */ 446 if (first_handle) { 447 ret = pool->ops->evict(pool, first_handle); 448 if (ret) 449 goto next; 450 } 451 if (last_handle) { 452 ret = pool->ops->evict(pool, last_handle); 453 if (ret) 454 goto next; 455 } 456 next: 457 spin_lock(&pool->lock); 458 zhdr->under_reclaim = false; 459 if (zhdr->first_chunks == 0 && zhdr->last_chunks == 0) { 460 /* 461 * Both buddies are now free, free the zbud page and 462 * return success. 463 */ 464 free_zbud_page(zhdr); 465 pool->pages_nr--; 466 spin_unlock(&pool->lock); 467 return 0; 468 } else if (zhdr->first_chunks == 0 || 469 zhdr->last_chunks == 0) { 470 /* add to unbuddied list */ 471 freechunks = num_free_chunks(zhdr); 472 list_add(&zhdr->buddy, &pool->unbuddied[freechunks]); 473 } else { 474 /* add to buddied list */ 475 list_add(&zhdr->buddy, &pool->buddied); 476 } 477 478 /* add to beginning of LRU */ 479 list_add(&zhdr->lru, &pool->lru); 480 } 481 spin_unlock(&pool->lock); 482 return -EAGAIN; 483 } 484 485 /** 486 * zbud_map() - maps the allocation associated with the given handle 487 * @pool: pool in which the allocation resides 488 * @handle: handle associated with the allocation to be mapped 489 * 490 * While trivial for zbud, the mapping functions for others allocators 491 * implementing this allocation API could have more complex information encoded 492 * in the handle and could create temporary mappings to make the data 493 * accessible to the user. 494 * 495 * Returns: a pointer to the mapped allocation 496 */ 497 static void *zbud_map(struct zbud_pool *pool, unsigned long handle) 498 { 499 return (void *)(handle); 500 } 501 502 /** 503 * zbud_unmap() - maps the allocation associated with the given handle 504 * @pool: pool in which the allocation resides 505 * @handle: handle associated with the allocation to be unmapped 506 */ 507 static void zbud_unmap(struct zbud_pool *pool, unsigned long handle) 508 { 509 } 510 511 /** 512 * zbud_get_pool_size() - gets the zbud pool size in pages 513 * @pool: pool whose size is being queried 514 * 515 * Returns: size in pages of the given pool. The pool lock need not be 516 * taken to access pages_nr. 517 */ 518 static u64 zbud_get_pool_size(struct zbud_pool *pool) 519 { 520 return pool->pages_nr; 521 } 522 523 /***************** 524 * zpool 525 ****************/ 526 527 static int zbud_zpool_evict(struct zbud_pool *pool, unsigned long handle) 528 { 529 if (pool->zpool && pool->zpool_ops && pool->zpool_ops->evict) 530 return pool->zpool_ops->evict(pool->zpool, handle); 531 else 532 return -ENOENT; 533 } 534 535 static const struct zbud_ops zbud_zpool_ops = { 536 .evict = zbud_zpool_evict 537 }; 538 539 static void *zbud_zpool_create(const char *name, gfp_t gfp, 540 const struct zpool_ops *zpool_ops, 541 struct zpool *zpool) 542 { 543 struct zbud_pool *pool; 544 545 pool = zbud_create_pool(gfp, zpool_ops ? &zbud_zpool_ops : NULL); 546 if (pool) { 547 pool->zpool = zpool; 548 pool->zpool_ops = zpool_ops; 549 } 550 return pool; 551 } 552 553 static void zbud_zpool_destroy(void *pool) 554 { 555 zbud_destroy_pool(pool); 556 } 557 558 static int zbud_zpool_malloc(void *pool, size_t size, gfp_t gfp, 559 unsigned long *handle) 560 { 561 return zbud_alloc(pool, size, gfp, handle); 562 } 563 static void zbud_zpool_free(void *pool, unsigned long handle) 564 { 565 zbud_free(pool, handle); 566 } 567 568 static int zbud_zpool_shrink(void *pool, unsigned int pages, 569 unsigned int *reclaimed) 570 { 571 unsigned int total = 0; 572 int ret = -EINVAL; 573 574 while (total < pages) { 575 ret = zbud_reclaim_page(pool, 8); 576 if (ret < 0) 577 break; 578 total++; 579 } 580 581 if (reclaimed) 582 *reclaimed = total; 583 584 return ret; 585 } 586 587 static void *zbud_zpool_map(void *pool, unsigned long handle, 588 enum zpool_mapmode mm) 589 { 590 return zbud_map(pool, handle); 591 } 592 static void zbud_zpool_unmap(void *pool, unsigned long handle) 593 { 594 zbud_unmap(pool, handle); 595 } 596 597 static u64 zbud_zpool_total_size(void *pool) 598 { 599 return zbud_get_pool_size(pool) * PAGE_SIZE; 600 } 601 602 static struct zpool_driver zbud_zpool_driver = { 603 .type = "zbud", 604 .sleep_mapped = true, 605 .owner = THIS_MODULE, 606 .create = zbud_zpool_create, 607 .destroy = zbud_zpool_destroy, 608 .malloc = zbud_zpool_malloc, 609 .free = zbud_zpool_free, 610 .shrink = zbud_zpool_shrink, 611 .map = zbud_zpool_map, 612 .unmap = zbud_zpool_unmap, 613 .total_size = zbud_zpool_total_size, 614 }; 615 616 MODULE_ALIAS("zpool-zbud"); 617 618 static int __init init_zbud(void) 619 { 620 /* Make sure the zbud header will fit in one chunk */ 621 BUILD_BUG_ON(sizeof(struct zbud_header) > ZHDR_SIZE_ALIGNED); 622 pr_info("loaded\n"); 623 624 zpool_register_driver(&zbud_zpool_driver); 625 626 return 0; 627 } 628 629 static void __exit exit_zbud(void) 630 { 631 zpool_unregister_driver(&zbud_zpool_driver); 632 pr_info("unloaded\n"); 633 } 634 635 module_init(init_zbud); 636 module_exit(exit_zbud); 637 638 MODULE_LICENSE("GPL"); 639 MODULE_AUTHOR("Seth Jennings <sjennings@variantweb.net>"); 640 MODULE_DESCRIPTION("Buddy Allocator for Compressed Pages"); 641