dm-bufio.c 49.0 KB
Newer Older
M
Mikulas Patocka 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/*
 * Copyright (C) 2009-2011 Red Hat, Inc.
 *
 * Author: Mikulas Patocka <mpatocka@redhat.com>
 *
 * This file is released under the GPL.
 */

#include "dm-bufio.h"

#include <linux/device-mapper.h>
#include <linux/dm-io.h>
#include <linux/slab.h>
14
#include <linux/sched/mm.h>
15
#include <linux/jiffies.h>
M
Mikulas Patocka 已提交
16 17
#include <linux/vmalloc.h>
#include <linux/shrinker.h>
18
#include <linux/module.h>
19
#include <linux/rbtree.h>
20
#include <linux/stacktrace.h>
M
Mikulas Patocka 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

#define DM_MSG_PREFIX "bufio"

/*
 * Memory management policy:
 *	Limit the number of buffers to DM_BUFIO_MEMORY_PERCENT of main memory
 *	or DM_BUFIO_VMALLOC_PERCENT of vmalloc memory (whichever is lower).
 *	Always allocate at least DM_BUFIO_MIN_BUFFERS buffers.
 *	Start background writeback when there are DM_BUFIO_WRITEBACK_PERCENT
 *	dirty buffers.
 */
#define DM_BUFIO_MIN_BUFFERS		8

#define DM_BUFIO_MEMORY_PERCENT		2
#define DM_BUFIO_VMALLOC_PERCENT	25
#define DM_BUFIO_WRITEBACK_PERCENT	75

/*
 * Check buffer ages in this interval (seconds)
 */
41
#define DM_BUFIO_WORK_TIMER_SECS	30
M
Mikulas Patocka 已提交
42 43 44 45

/*
 * Free buffers when they are older than this (seconds)
 */
46
#define DM_BUFIO_DEFAULT_AGE_SECS	300
M
Mikulas Patocka 已提交
47 48

/*
49
 * The nr of bytes of cached data to keep around.
M
Mikulas Patocka 已提交
50
 */
51
#define DM_BUFIO_DEFAULT_RETAIN_BYTES   (256 * 1024)
M
Mikulas Patocka 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65

/*
 * The number of bvec entries that are embedded directly in the buffer.
 * If the chunk size is larger, dm-io is used to do the io.
 */
#define DM_BUFIO_INLINE_VECS		16

/*
 * Don't try to use kmem_cache_alloc for blocks larger than this.
 * For explanation, see alloc_buffer_data below.
 */
#define DM_BUFIO_BLOCK_SIZE_SLAB_LIMIT	(PAGE_SIZE >> 1)
#define DM_BUFIO_BLOCK_SIZE_GFP_LIMIT	(PAGE_SIZE << (MAX_ORDER - 1))

66 67 68 69 70 71
/*
 * Align buffer writes to this boundary.
 * Tests show that SSDs have the highest IOPS when using 4k writes.
 */
#define DM_BUFIO_WRITE_ALIGN		4096

M
Mikulas Patocka 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
/*
 * dm_buffer->list_mode
 */
#define LIST_CLEAN	0
#define LIST_DIRTY	1
#define LIST_SIZE	2

/*
 * Linking of buffers:
 *	All buffers are linked to cache_hash with their hash_list field.
 *
 *	Clean buffers that are not being written (B_WRITING not set)
 *	are linked to lru[LIST_CLEAN] with their lru_list field.
 *
 *	Dirty and clean buffers that are being written are linked to
 *	lru[LIST_DIRTY] with their lru_list field. When the write
 *	finishes, the buffer cannot be relinked immediately (because we
 *	are in an interrupt context and relinking requires process
 *	context), so some clean-not-writing buffers can be held on
 *	dirty_lru too.  They are later added to lru in the process
 *	context.
 */
struct dm_bufio_client {
	struct mutex lock;

	struct list_head lru[LIST_SIZE];
	unsigned long n_buffers[LIST_SIZE];

	struct block_device *bdev;
	unsigned block_size;
	unsigned char sectors_per_block_bits;
	unsigned char pages_per_block_bits;
	unsigned char blocks_per_page_bits;
	unsigned aux_size;
	void (*alloc_callback)(struct dm_buffer *);
	void (*write_callback)(struct dm_buffer *);

	struct dm_io_client *dm_io;

	struct list_head reserved_buffers;
	unsigned need_reserved_buffers;

114 115
	unsigned minimum_buffers;

116
	struct rb_root buffer_tree;
M
Mikulas Patocka 已提交
117 118
	wait_queue_head_t free_buffer_wait;

119 120
	sector_t start;

M
Mikulas Patocka 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
	int async_write_error;

	struct list_head client_list;
	struct shrinker shrinker;
};

/*
 * Buffer state bits.
 */
#define B_READING	0
#define B_WRITING	1
#define B_DIRTY		2

/*
 * Describes how the block was allocated:
 * kmem_cache_alloc(), __get_free_pages() or vmalloc().
 * See the comment at alloc_buffer_data.
 */
enum data_mode {
	DATA_MODE_SLAB = 0,
	DATA_MODE_GET_FREE_PAGES = 1,
	DATA_MODE_VMALLOC = 2,
	DATA_MODE_LIMIT = 3
};

struct dm_buffer {
147
	struct rb_node node;
M
Mikulas Patocka 已提交
148 149 150 151 152 153
	struct list_head lru_list;
	sector_t block;
	void *data;
	enum data_mode data_mode;
	unsigned char list_mode;		/* LIST_* */
	unsigned hold_count;
154 155
	blk_status_t read_error;
	blk_status_t write_error;
M
Mikulas Patocka 已提交
156 157
	unsigned long state;
	unsigned long last_accessed;
158 159 160 161
	unsigned dirty_start;
	unsigned dirty_end;
	unsigned write_start;
	unsigned write_end;
M
Mikulas Patocka 已提交
162
	struct dm_bufio_client *c;
163
	struct list_head write_list;
M
Mikulas Patocka 已提交
164 165
	struct bio bio;
	struct bio_vec bio_vec[DM_BUFIO_INLINE_VECS];
166 167 168 169 170
#ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
#define MAX_STACK 10
	struct stack_trace stack_trace;
	unsigned long stack_entries[MAX_STACK];
#endif
M
Mikulas Patocka 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
};

/*----------------------------------------------------------------*/

static struct kmem_cache *dm_bufio_caches[PAGE_SHIFT - SECTOR_SHIFT];
static char *dm_bufio_cache_names[PAGE_SHIFT - SECTOR_SHIFT];

static inline int dm_bufio_cache_index(struct dm_bufio_client *c)
{
	unsigned ret = c->blocks_per_page_bits - 1;

	BUG_ON(ret >= ARRAY_SIZE(dm_bufio_caches));

	return ret;
}

#define DM_BUFIO_CACHE(c)	(dm_bufio_caches[dm_bufio_cache_index(c)])
#define DM_BUFIO_CACHE_NAME(c)	(dm_bufio_cache_names[dm_bufio_cache_index(c)])

#define dm_bufio_in_request()	(!!current->bio_list)

static void dm_bufio_lock(struct dm_bufio_client *c)
{
	mutex_lock_nested(&c->lock, dm_bufio_in_request());
}

static int dm_bufio_trylock(struct dm_bufio_client *c)
{
	return mutex_trylock(&c->lock);
}

static void dm_bufio_unlock(struct dm_bufio_client *c)
{
	mutex_unlock(&c->lock);
}

/*----------------------------------------------------------------*/

/*
 * Default cache size: available memory divided by the ratio.
 */
static unsigned long dm_bufio_default_cache_size;

/*
 * Total cache size set by the user.
 */
static unsigned long dm_bufio_cache_size;

/*
 * A copy of dm_bufio_cache_size because dm_bufio_cache_size can change
 * at any time.  If it disagrees, the user has changed cache size.
 */
static unsigned long dm_bufio_cache_size_latch;

static DEFINE_SPINLOCK(param_spinlock);

/*
 * Buffers are freed after this timeout
 */
static unsigned dm_bufio_max_age = DM_BUFIO_DEFAULT_AGE_SECS;
231
static unsigned long dm_bufio_retain_bytes = DM_BUFIO_DEFAULT_RETAIN_BYTES;
M
Mikulas Patocka 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

static unsigned long dm_bufio_peak_allocated;
static unsigned long dm_bufio_allocated_kmem_cache;
static unsigned long dm_bufio_allocated_get_free_pages;
static unsigned long dm_bufio_allocated_vmalloc;
static unsigned long dm_bufio_current_allocated;

/*----------------------------------------------------------------*/

/*
 * Per-client cache: dm_bufio_cache_size / dm_bufio_client_count
 */
static unsigned long dm_bufio_cache_size_per_client;

/*
 * The current number of clients.
 */
static int dm_bufio_client_count;

/*
 * The list of all clients.
 */
static LIST_HEAD(dm_bufio_all_clients);

/*
 * This mutex protects dm_bufio_cache_size_latch,
 * dm_bufio_cache_size_per_client and dm_bufio_client_count
 */
static DEFINE_MUTEX(dm_bufio_clients_lock);

262 263 264 265 266 267 268 269 270 271 272
#ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
static void buffer_record_stack(struct dm_buffer *b)
{
	b->stack_trace.nr_entries = 0;
	b->stack_trace.max_entries = MAX_STACK;
	b->stack_trace.entries = b->stack_entries;
	b->stack_trace.skip = 2;
	save_stack_trace(&b->stack_trace);
}
#endif

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
/*----------------------------------------------------------------
 * A red/black tree acts as an index for all the buffers.
 *--------------------------------------------------------------*/
static struct dm_buffer *__find(struct dm_bufio_client *c, sector_t block)
{
	struct rb_node *n = c->buffer_tree.rb_node;
	struct dm_buffer *b;

	while (n) {
		b = container_of(n, struct dm_buffer, node);

		if (b->block == block)
			return b;

		n = (b->block < block) ? n->rb_left : n->rb_right;
	}

	return NULL;
}

static void __insert(struct dm_bufio_client *c, struct dm_buffer *b)
{
	struct rb_node **new = &c->buffer_tree.rb_node, *parent = NULL;
	struct dm_buffer *found;

	while (*new) {
		found = container_of(*new, struct dm_buffer, node);

		if (found->block == b->block) {
			BUG_ON(found != b);
			return;
		}

		parent = *new;
		new = (found->block < b->block) ?
			&((*new)->rb_left) : &((*new)->rb_right);
	}

	rb_link_node(&b->node, parent, new);
	rb_insert_color(&b->node, &c->buffer_tree);
}

static void __remove(struct dm_bufio_client *c, struct dm_buffer *b)
{
	rb_erase(&b->node, &c->buffer_tree);
}

M
Mikulas Patocka 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
/*----------------------------------------------------------------*/

static void adjust_total_allocated(enum data_mode data_mode, long diff)
{
	static unsigned long * const class_ptr[DATA_MODE_LIMIT] = {
		&dm_bufio_allocated_kmem_cache,
		&dm_bufio_allocated_get_free_pages,
		&dm_bufio_allocated_vmalloc,
	};

	spin_lock(&param_spinlock);

	*class_ptr[data_mode] += diff;

	dm_bufio_current_allocated += diff;

	if (dm_bufio_current_allocated > dm_bufio_peak_allocated)
		dm_bufio_peak_allocated = dm_bufio_current_allocated;

	spin_unlock(&param_spinlock);
}

/*
 * Change the number of clients and recalculate per-client limit.
 */
static void __cache_size_refresh(void)
{
	BUG_ON(!mutex_is_locked(&dm_bufio_clients_lock));
	BUG_ON(dm_bufio_client_count < 0);

350
	dm_bufio_cache_size_latch = READ_ONCE(dm_bufio_cache_size);
M
Mikulas Patocka 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

	/*
	 * Use default if set to 0 and report the actual cache size used.
	 */
	if (!dm_bufio_cache_size_latch) {
		(void)cmpxchg(&dm_bufio_cache_size, 0,
			      dm_bufio_default_cache_size);
		dm_bufio_cache_size_latch = dm_bufio_default_cache_size;
	}

	dm_bufio_cache_size_per_client = dm_bufio_cache_size_latch /
					 (dm_bufio_client_count ? : 1);
}

/*
 * Allocating buffer data.
 *
 * Small buffers are allocated with kmem_cache, to use space optimally.
 *
 * For large buffers, we choose between get_free_pages and vmalloc.
 * Each has advantages and disadvantages.
 *
 * __get_free_pages can randomly fail if the memory is fragmented.
 * __vmalloc won't randomly fail, but vmalloc space is limited (it may be
 * as low as 128M) so using it for caching is not appropriate.
 *
 * If the allocation may fail we use __get_free_pages. Memory fragmentation
 * won't have a fatal effect here, but it just causes flushes of some other
 * buffers and more I/O will be performed. Don't use __get_free_pages if it
 * always fails (i.e. order >= MAX_ORDER).
 *
 * If the allocation shouldn't fail we use __vmalloc. This is only for the
 * initial reserve allocation, so there's no risk of wasting all vmalloc
 * space.
 */
static void *alloc_buffer_data(struct dm_bufio_client *c, gfp_t gfp_mask,
			       enum data_mode *data_mode)
{
389 390 391
	unsigned noio_flag;
	void *ptr;

M
Mikulas Patocka 已提交
392 393 394 395 396 397 398 399 400 401 402 403 404
	if (c->block_size <= DM_BUFIO_BLOCK_SIZE_SLAB_LIMIT) {
		*data_mode = DATA_MODE_SLAB;
		return kmem_cache_alloc(DM_BUFIO_CACHE(c), gfp_mask);
	}

	if (c->block_size <= DM_BUFIO_BLOCK_SIZE_GFP_LIMIT &&
	    gfp_mask & __GFP_NORETRY) {
		*data_mode = DATA_MODE_GET_FREE_PAGES;
		return (void *)__get_free_pages(gfp_mask,
						c->pages_per_block_bits);
	}

	*data_mode = DATA_MODE_VMALLOC;
405 406 407 408 409 410 411 412 413 414 415 416 417 418

	/*
	 * __vmalloc allocates the data pages and auxiliary structures with
	 * gfp_flags that were specified, but pagetables are always allocated
	 * with GFP_KERNEL, no matter what was specified as gfp_mask.
	 *
	 * Consequently, we must set per-process flag PF_MEMALLOC_NOIO so that
	 * all allocations done by this process (including pagetables) are done
	 * as if GFP_NOIO was specified.
	 */

	if (gfp_mask & __GFP_NORETRY)
		noio_flag = memalloc_noio_save();

419
	ptr = __vmalloc(c->block_size, gfp_mask, PAGE_KERNEL);
420 421 422 423 424

	if (gfp_mask & __GFP_NORETRY)
		memalloc_noio_restore(noio_flag);

	return ptr;
M
Mikulas Patocka 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
}

/*
 * Free buffer's data.
 */
static void free_buffer_data(struct dm_bufio_client *c,
			     void *data, enum data_mode data_mode)
{
	switch (data_mode) {
	case DATA_MODE_SLAB:
		kmem_cache_free(DM_BUFIO_CACHE(c), data);
		break;

	case DATA_MODE_GET_FREE_PAGES:
		free_pages((unsigned long)data, c->pages_per_block_bits);
		break;

	case DATA_MODE_VMALLOC:
		vfree(data);
		break;

	default:
		DMCRIT("dm_bufio_free_buffer_data: bad data mode: %d",
		       data_mode);
		BUG();
	}
}

/*
 * Allocate buffer and its data.
 */
static struct dm_buffer *alloc_buffer(struct dm_bufio_client *c, gfp_t gfp_mask)
{
	struct dm_buffer *b = kmalloc(sizeof(struct dm_buffer) + c->aux_size,
				      gfp_mask);

	if (!b)
		return NULL;

	b->c = c;

	b->data = alloc_buffer_data(c, gfp_mask, &b->data_mode);
	if (!b->data) {
		kfree(b);
		return NULL;
	}

	adjust_total_allocated(b->data_mode, (long)c->block_size);

474 475 476
#ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
	memset(&b->stack_trace, 0, sizeof(b->stack_trace));
#endif
M
Mikulas Patocka 已提交
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
	return b;
}

/*
 * Free buffer and its data.
 */
static void free_buffer(struct dm_buffer *b)
{
	struct dm_bufio_client *c = b->c;

	adjust_total_allocated(b->data_mode, -(long)c->block_size);

	free_buffer_data(c, b->data, b->data_mode);
	kfree(b);
}

/*
 * Link buffer to the hash list and clean or dirty queue.
 */
static void __link_buffer(struct dm_buffer *b, sector_t block, int dirty)
{
	struct dm_bufio_client *c = b->c;

	c->n_buffers[dirty]++;
	b->block = block;
	b->list_mode = dirty;
	list_add(&b->lru_list, &c->lru[dirty]);
504
	__insert(b->c, b);
M
Mikulas Patocka 已提交
505 506 507 508 509 510 511 512 513 514 515 516 517
	b->last_accessed = jiffies;
}

/*
 * Unlink buffer from the hash list and dirty or clean queue.
 */
static void __unlink_buffer(struct dm_buffer *b)
{
	struct dm_bufio_client *c = b->c;

	BUG_ON(!c->n_buffers[b->list_mode]);

	c->n_buffers[b->list_mode]--;
518
	__remove(b->c, b);
M
Mikulas Patocka 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
	list_del(&b->lru_list);
}

/*
 * Place the buffer to the head of dirty or clean LRU queue.
 */
static void __relink_lru(struct dm_buffer *b, int dirty)
{
	struct dm_bufio_client *c = b->c;

	BUG_ON(!c->n_buffers[b->list_mode]);

	c->n_buffers[b->list_mode]--;
	c->n_buffers[dirty]++;
	b->list_mode = dirty;
W
Wei Yongjun 已提交
534
	list_move(&b->lru_list, &c->lru[dirty]);
535
	b->last_accessed = jiffies;
M
Mikulas Patocka 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
}

/*----------------------------------------------------------------
 * Submit I/O on the buffer.
 *
 * Bio interface is faster but it has some problems:
 *	the vector list is limited (increasing this limit increases
 *	memory-consumption per buffer, so it is not viable);
 *
 *	the memory must be direct-mapped, not vmalloced;
 *
 *	the I/O driver can reject requests spuriously if it thinks that
 *	the requests are too big for the device or if they cross a
 *	controller-defined memory boundary.
 *
 * If the buffer is small enough (up to DM_BUFIO_INLINE_VECS pages) and
 * it is not vmalloced, try using the bio interface.
 *
 * If the buffer is big, if it is vmalloced or if the underlying device
 * rejects the bio because it is too large, use dm-io layer to do the I/O.
 * The dm-io layer splits the I/O into multiple requests, avoiding the above
 * shortcomings.
 *--------------------------------------------------------------*/

/*
 * dm-io completion routine. It just calls b->bio.bi_end_io, pretending
 * that the request was handled directly with bio interface.
 */
static void dmio_complete(unsigned long error, void *context)
{
	struct dm_buffer *b = context;

568
	b->bio.bi_status = error ? BLK_STS_IOERR : 0;
569
	b->bio.bi_end_io(&b->bio);
M
Mikulas Patocka 已提交
570 571
}

572
static void use_dmio(struct dm_buffer *b, int rw, sector_t sector,
573
		     unsigned n_sectors, unsigned offset, bio_end_io_t *end_io)
M
Mikulas Patocka 已提交
574 575 576
{
	int r;
	struct dm_io_request io_req = {
M
Mike Christie 已提交
577 578
		.bi_op = rw,
		.bi_op_flags = 0,
M
Mikulas Patocka 已提交
579 580 581 582 583 584
		.notify.fn = dmio_complete,
		.notify.context = b,
		.client = b->c->dm_io,
	};
	struct dm_io_region region = {
		.bdev = b->c->bdev,
585 586
		.sector = sector,
		.count = n_sectors,
M
Mikulas Patocka 已提交
587 588 589 590
	};

	if (b->data_mode != DATA_MODE_VMALLOC) {
		io_req.mem.type = DM_IO_KMEM;
591
		io_req.mem.ptr.addr = (char *)b->data + offset;
M
Mikulas Patocka 已提交
592 593
	} else {
		io_req.mem.type = DM_IO_VMA;
594
		io_req.mem.ptr.vma = (char *)b->data + offset;
M
Mikulas Patocka 已提交
595 596 597 598 599
	}

	b->bio.bi_end_io = end_io;

	r = dm_io(&io_req, 1, &region, NULL);
600
	if (r) {
601
		b->bio.bi_status = errno_to_blk_status(r);
602 603
		end_io(&b->bio);
	}
M
Mikulas Patocka 已提交
604 605
}

606
static void inline_endio(struct bio *bio)
607 608
{
	bio_end_io_t *end_fn = bio->bi_private;
609
	blk_status_t status = bio->bi_status;
610 611 612 613 614 615 616

	/*
	 * Reset the bio to free any attached resources
	 * (e.g. bio integrity profiles).
	 */
	bio_reset(bio);

617
	bio->bi_status = status;
618
	end_fn(bio);
619 620
}

621
static void use_inline_bio(struct dm_buffer *b, int rw, sector_t sector,
622
			   unsigned n_sectors, unsigned offset, bio_end_io_t *end_io)
M
Mikulas Patocka 已提交
623 624
{
	char *ptr;
625
	unsigned len;
M
Mikulas Patocka 已提交
626

627
	bio_init(&b->bio, b->bio_vec, DM_BUFIO_INLINE_VECS);
628
	b->bio.bi_iter.bi_sector = sector;
629
	bio_set_dev(&b->bio, b->c->bdev);
630 631 632 633 634 635
	b->bio.bi_end_io = inline_endio;
	/*
	 * Use of .bi_private isn't a problem here because
	 * the dm_buffer's inline bio is local to bufio.
	 */
	b->bio.bi_private = end_io;
M
Mike Christie 已提交
636
	bio_set_op_attrs(&b->bio, rw, 0);
M
Mikulas Patocka 已提交
637

638
	ptr = (char *)b->data + offset;
639
	len = n_sectors << SECTOR_SHIFT;
M
Mikulas Patocka 已提交
640 641

	do {
642 643
		unsigned this_step = min((unsigned)(PAGE_SIZE - offset_in_page(ptr)), len);
		if (!bio_add_page(&b->bio, virt_to_page(ptr), this_step,
644
				  offset_in_page(ptr))) {
M
Mikulas Patocka 已提交
645
			BUG_ON(b->c->block_size <= PAGE_SIZE);
646
			use_dmio(b, rw, sector, n_sectors, offset, end_io);
M
Mikulas Patocka 已提交
647 648 649
			return;
		}

650 651
		len -= this_step;
		ptr += this_step;
M
Mikulas Patocka 已提交
652 653
	} while (len > 0);

654
	submit_bio(&b->bio);
M
Mikulas Patocka 已提交
655 656
}

657
static void submit_io(struct dm_buffer *b, int rw, bio_end_io_t *end_io)
M
Mikulas Patocka 已提交
658
{
659 660
	unsigned n_sectors;
	sector_t sector;
661
	unsigned offset, end;
M
Mikulas Patocka 已提交
662

663
	sector = (b->block << b->c->sectors_per_block_bits) + b->c->start;
664

665
	if (rw != REQ_OP_WRITE) {
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
		n_sectors = 1 << b->c->sectors_per_block_bits;
		offset = 0;
	} else {
		if (b->c->write_callback)
			b->c->write_callback(b);
		offset = b->write_start;
		end = b->write_end;
		offset &= -DM_BUFIO_WRITE_ALIGN;
		end += DM_BUFIO_WRITE_ALIGN - 1;
		end &= -DM_BUFIO_WRITE_ALIGN;
		if (unlikely(end > b->c->block_size))
			end = b->c->block_size;

		sector += offset >> SECTOR_SHIFT;
		n_sectors = (end - offset) >> SECTOR_SHIFT;
	}
682 683

	if (n_sectors <= ((DM_BUFIO_INLINE_VECS * PAGE_SIZE) >> SECTOR_SHIFT) &&
M
Mikulas Patocka 已提交
684
	    b->data_mode != DATA_MODE_VMALLOC)
685
		use_inline_bio(b, rw, sector, n_sectors, offset, end_io);
M
Mikulas Patocka 已提交
686
	else
687
		use_dmio(b, rw, sector, n_sectors, offset, end_io);
M
Mikulas Patocka 已提交
688 689 690 691 692 693 694 695 696 697 698 699
}

/*----------------------------------------------------------------
 * Writing dirty buffers
 *--------------------------------------------------------------*/

/*
 * The endio routine for write.
 *
 * Set the error, clear B_WRITING bit and wake anyone who was waiting on
 * it.
 */
700
static void write_endio(struct bio *bio)
M
Mikulas Patocka 已提交
701 702 703
{
	struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);

704 705
	b->write_error = bio->bi_status;
	if (unlikely(bio->bi_status)) {
M
Mikulas Patocka 已提交
706
		struct dm_bufio_client *c = b->c;
707 708 709

		(void)cmpxchg(&c->async_write_error, 0,
				blk_status_to_errno(bio->bi_status));
M
Mikulas Patocka 已提交
710 711 712 713
	}

	BUG_ON(!test_bit(B_WRITING, &b->state));

714
	smp_mb__before_atomic();
M
Mikulas Patocka 已提交
715
	clear_bit(B_WRITING, &b->state);
716
	smp_mb__after_atomic();
M
Mikulas Patocka 已提交
717 718 719 720 721 722 723 724 725 726 727 728 729

	wake_up_bit(&b->state, B_WRITING);
}

/*
 * Initiate a write on a dirty buffer, but don't wait for it.
 *
 * - If the buffer is not dirty, exit.
 * - If there some previous write going on, wait for it to finish (we can't
 *   have two writes on the same buffer simultaneously).
 * - Submit our write and don't wait on it. We set B_WRITING indicating
 *   that there is a write in progress.
 */
730 731
static void __write_dirty_buffer(struct dm_buffer *b,
				 struct list_head *write_list)
M
Mikulas Patocka 已提交
732 733 734 735 736
{
	if (!test_bit(B_DIRTY, &b->state))
		return;

	clear_bit(B_DIRTY, &b->state);
737
	wait_on_bit_lock_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
M
Mikulas Patocka 已提交
738

739 740 741
	b->write_start = b->dirty_start;
	b->write_end = b->dirty_end;

742
	if (!write_list)
743
		submit_io(b, REQ_OP_WRITE, write_endio);
744 745 746 747 748 749 750 751 752 753 754 755
	else
		list_add_tail(&b->write_list, write_list);
}

static void __flush_write_list(struct list_head *write_list)
{
	struct blk_plug plug;
	blk_start_plug(&plug);
	while (!list_empty(write_list)) {
		struct dm_buffer *b =
			list_entry(write_list->next, struct dm_buffer, write_list);
		list_del(&b->write_list);
756
		submit_io(b, REQ_OP_WRITE, write_endio);
757
		cond_resched();
758 759
	}
	blk_finish_plug(&plug);
M
Mikulas Patocka 已提交
760 761 762 763 764 765 766 767 768 769 770 771 772 773
}

/*
 * Wait until any activity on the buffer finishes.  Possibly write the
 * buffer if it is dirty.  When this function finishes, there is no I/O
 * running on the buffer and the buffer is not dirty.
 */
static void __make_buffer_clean(struct dm_buffer *b)
{
	BUG_ON(b->hold_count);

	if (!b->state)	/* fast case */
		return;

774
	wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
775
	__write_dirty_buffer(b, NULL);
776
	wait_on_bit_io(&b->state, B_WRITING, TASK_UNINTERRUPTIBLE);
M
Mikulas Patocka 已提交
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
}

/*
 * Find some buffer that is not held by anybody, clean it, unlink it and
 * return it.
 */
static struct dm_buffer *__get_unclaimed_buffer(struct dm_bufio_client *c)
{
	struct dm_buffer *b;

	list_for_each_entry_reverse(b, &c->lru[LIST_CLEAN], lru_list) {
		BUG_ON(test_bit(B_WRITING, &b->state));
		BUG_ON(test_bit(B_DIRTY, &b->state));

		if (!b->hold_count) {
			__make_buffer_clean(b);
			__unlink_buffer(b);
			return b;
		}
796
		cond_resched();
M
Mikulas Patocka 已提交
797 798 799 800 801 802 803 804 805 806
	}

	list_for_each_entry_reverse(b, &c->lru[LIST_DIRTY], lru_list) {
		BUG_ON(test_bit(B_READING, &b->state));

		if (!b->hold_count) {
			__make_buffer_clean(b);
			__unlink_buffer(b);
			return b;
		}
807
		cond_resched();
M
Mikulas Patocka 已提交
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
	}

	return NULL;
}

/*
 * Wait until some other threads free some buffer or release hold count on
 * some buffer.
 *
 * This function is entered with c->lock held, drops it and regains it
 * before exiting.
 */
static void __wait_for_free_buffer(struct dm_bufio_client *c)
{
	DECLARE_WAITQUEUE(wait, current);

	add_wait_queue(&c->free_buffer_wait, &wait);
825
	set_current_state(TASK_UNINTERRUPTIBLE);
M
Mikulas Patocka 已提交
826 827 828 829 830 831 832 833 834
	dm_bufio_unlock(c);

	io_schedule();

	remove_wait_queue(&c->free_buffer_wait, &wait);

	dm_bufio_lock(c);
}

M
Mikulas Patocka 已提交
835 836 837 838 839 840 841
enum new_flag {
	NF_FRESH = 0,
	NF_READ = 1,
	NF_GET = 2,
	NF_PREFETCH = 3
};

M
Mikulas Patocka 已提交
842 843 844 845 846 847
/*
 * Allocate a new buffer. If the allocation is not possible, wait until
 * some other thread frees a buffer.
 *
 * May drop the lock and regain it.
 */
M
Mikulas Patocka 已提交
848
static struct dm_buffer *__alloc_buffer_wait_no_callback(struct dm_bufio_client *c, enum new_flag nf)
M
Mikulas Patocka 已提交
849 850
{
	struct dm_buffer *b;
851
	bool tried_noio_alloc = false;
M
Mikulas Patocka 已提交
852 853 854 855 856

	/*
	 * dm-bufio is resistant to allocation failures (it just keeps
	 * one buffer reserved in cases all the allocations fail).
	 * So set flags to not try too hard:
857 858
	 *	GFP_NOWAIT: don't wait; if we need to sleep we'll release our
	 *		    mutex and wait ourselves.
M
Mikulas Patocka 已提交
859 860 861 862 863 864 865 866 867
	 *	__GFP_NORETRY: don't retry and rather return failure
	 *	__GFP_NOMEMALLOC: don't use emergency reserves
	 *	__GFP_NOWARN: don't print a warning in case of failure
	 *
	 * For debugging, if we set the cache size to 1, no new buffers will
	 * be allocated.
	 */
	while (1) {
		if (dm_bufio_cache_size_latch != 1) {
868
			b = alloc_buffer(c, GFP_NOWAIT | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
M
Mikulas Patocka 已提交
869 870 871 872
			if (b)
				return b;
		}

M
Mikulas Patocka 已提交
873 874 875
		if (nf == NF_PREFETCH)
			return NULL;

876 877 878 879 880 881 882 883 884
		if (dm_bufio_cache_size_latch != 1 && !tried_noio_alloc) {
			dm_bufio_unlock(c);
			b = alloc_buffer(c, GFP_NOIO | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN);
			dm_bufio_lock(c);
			if (b)
				return b;
			tried_noio_alloc = true;
		}

M
Mikulas Patocka 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
		if (!list_empty(&c->reserved_buffers)) {
			b = list_entry(c->reserved_buffers.next,
				       struct dm_buffer, lru_list);
			list_del(&b->lru_list);
			c->need_reserved_buffers++;

			return b;
		}

		b = __get_unclaimed_buffer(c);
		if (b)
			return b;

		__wait_for_free_buffer(c);
	}
}

M
Mikulas Patocka 已提交
902
static struct dm_buffer *__alloc_buffer_wait(struct dm_bufio_client *c, enum new_flag nf)
M
Mikulas Patocka 已提交
903
{
M
Mikulas Patocka 已提交
904 905 906 907
	struct dm_buffer *b = __alloc_buffer_wait_no_callback(c, nf);

	if (!b)
		return NULL;
M
Mikulas Patocka 已提交
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931

	if (c->alloc_callback)
		c->alloc_callback(b);

	return b;
}

/*
 * Free a buffer and wake other threads waiting for free buffers.
 */
static void __free_buffer_wake(struct dm_buffer *b)
{
	struct dm_bufio_client *c = b->c;

	if (!c->need_reserved_buffers)
		free_buffer(b);
	else {
		list_add(&b->lru_list, &c->reserved_buffers);
		c->need_reserved_buffers--;
	}

	wake_up(&c->free_buffer_wait);
}

932 933
static void __write_dirty_buffers_async(struct dm_bufio_client *c, int no_wait,
					struct list_head *write_list)
M
Mikulas Patocka 已提交
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
{
	struct dm_buffer *b, *tmp;

	list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
		BUG_ON(test_bit(B_READING, &b->state));

		if (!test_bit(B_DIRTY, &b->state) &&
		    !test_bit(B_WRITING, &b->state)) {
			__relink_lru(b, LIST_CLEAN);
			continue;
		}

		if (no_wait && test_bit(B_WRITING, &b->state))
			return;

949
		__write_dirty_buffer(b, write_list);
950
		cond_resched();
M
Mikulas Patocka 已提交
951 952 953 954 955 956 957 958 959 960 961 962
	}
}

/*
 * Get writeback threshold and buffer limit for a given client.
 */
static void __get_memory_limit(struct dm_bufio_client *c,
			       unsigned long *threshold_buffers,
			       unsigned long *limit_buffers)
{
	unsigned long buffers;

963
	if (unlikely(READ_ONCE(dm_bufio_cache_size) != dm_bufio_cache_size_latch)) {
964 965 966 967
		if (mutex_trylock(&dm_bufio_clients_lock)) {
			__cache_size_refresh();
			mutex_unlock(&dm_bufio_clients_lock);
		}
M
Mikulas Patocka 已提交
968 969 970 971 972
	}

	buffers = dm_bufio_cache_size_per_client >>
		  (c->sectors_per_block_bits + SECTOR_SHIFT);

973 974
	if (buffers < c->minimum_buffers)
		buffers = c->minimum_buffers;
M
Mikulas Patocka 已提交
975 976

	*limit_buffers = buffers;
977 978
	*threshold_buffers = mult_frac(buffers,
				       DM_BUFIO_WRITEBACK_PERCENT, 100);
M
Mikulas Patocka 已提交
979 980 981 982 983 984 985
}

/*
 * Check if we're over watermark.
 * If we are over threshold_buffers, start freeing buffers.
 * If we're over "limit_buffers", block until we get under the limit.
 */
986 987
static void __check_watermark(struct dm_bufio_client *c,
			      struct list_head *write_list)
M
Mikulas Patocka 已提交
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
{
	unsigned long threshold_buffers, limit_buffers;

	__get_memory_limit(c, &threshold_buffers, &limit_buffers);

	while (c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY] >
	       limit_buffers) {

		struct dm_buffer *b = __get_unclaimed_buffer(c);

		if (!b)
			return;

		__free_buffer_wake(b);
1002
		cond_resched();
M
Mikulas Patocka 已提交
1003 1004 1005
	}

	if (c->n_buffers[LIST_DIRTY] > threshold_buffers)
1006
		__write_dirty_buffers_async(c, 1, write_list);
M
Mikulas Patocka 已提交
1007 1008 1009 1010 1011 1012 1013
}

/*----------------------------------------------------------------
 * Getting a buffer
 *--------------------------------------------------------------*/

static struct dm_buffer *__bufio_new(struct dm_bufio_client *c, sector_t block,
1014 1015
				     enum new_flag nf, int *need_submit,
				     struct list_head *write_list)
M
Mikulas Patocka 已提交
1016 1017 1018 1019 1020 1021
{
	struct dm_buffer *b, *new_b = NULL;

	*need_submit = 0;

	b = __find(c, block);
M
Mikulas Patocka 已提交
1022 1023
	if (b)
		goto found_buffer;
M
Mikulas Patocka 已提交
1024 1025 1026 1027

	if (nf == NF_GET)
		return NULL;

M
Mikulas Patocka 已提交
1028 1029 1030
	new_b = __alloc_buffer_wait(c, nf);
	if (!new_b)
		return NULL;
M
Mikulas Patocka 已提交
1031 1032 1033 1034 1035 1036 1037 1038

	/*
	 * We've had a period where the mutex was unlocked, so need to
	 * recheck the hash table.
	 */
	b = __find(c, block);
	if (b) {
		__free_buffer_wake(new_b);
M
Mikulas Patocka 已提交
1039
		goto found_buffer;
M
Mikulas Patocka 已提交
1040 1041
	}

1042
	__check_watermark(c, write_list);
M
Mikulas Patocka 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058

	b = new_b;
	b->hold_count = 1;
	b->read_error = 0;
	b->write_error = 0;
	__link_buffer(b, block, LIST_CLEAN);

	if (nf == NF_FRESH) {
		b->state = 0;
		return b;
	}

	b->state = 1 << B_READING;
	*need_submit = 1;

	return b;
M
Mikulas Patocka 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076

found_buffer:
	if (nf == NF_PREFETCH)
		return NULL;
	/*
	 * Note: it is essential that we don't wait for the buffer to be
	 * read if dm_bufio_get function is used. Both dm_bufio_get and
	 * dm_bufio_prefetch can be used in the driver request routine.
	 * If the user called both dm_bufio_prefetch and dm_bufio_get on
	 * the same buffer, it would deadlock if we waited.
	 */
	if (nf == NF_GET && unlikely(test_bit(B_READING, &b->state)))
		return NULL;

	b->hold_count++;
	__relink_lru(b, test_bit(B_DIRTY, &b->state) ||
		     test_bit(B_WRITING, &b->state));
	return b;
M
Mikulas Patocka 已提交
1077 1078 1079 1080 1081 1082
}

/*
 * The endio routine for reading: set the error, clear the bit and wake up
 * anyone waiting on the buffer.
 */
1083
static void read_endio(struct bio *bio)
M
Mikulas Patocka 已提交
1084 1085 1086
{
	struct dm_buffer *b = container_of(bio, struct dm_buffer, bio);

1087
	b->read_error = bio->bi_status;
M
Mikulas Patocka 已提交
1088 1089 1090

	BUG_ON(!test_bit(B_READING, &b->state));

1091
	smp_mb__before_atomic();
M
Mikulas Patocka 已提交
1092
	clear_bit(B_READING, &b->state);
1093
	smp_mb__after_atomic();
M
Mikulas Patocka 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109

	wake_up_bit(&b->state, B_READING);
}

/*
 * A common routine for dm_bufio_new and dm_bufio_read.  Operation of these
 * functions is similar except that dm_bufio_new doesn't read the
 * buffer from the disk (assuming that the caller overwrites all the data
 * and uses dm_bufio_mark_buffer_dirty to write new data back).
 */
static void *new_read(struct dm_bufio_client *c, sector_t block,
		      enum new_flag nf, struct dm_buffer **bp)
{
	int need_submit;
	struct dm_buffer *b;

1110 1111
	LIST_HEAD(write_list);

M
Mikulas Patocka 已提交
1112
	dm_bufio_lock(c);
1113
	b = __bufio_new(c, block, nf, &need_submit, &write_list);
1114 1115 1116 1117
#ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
	if (b && b->hold_count == 1)
		buffer_record_stack(b);
#endif
M
Mikulas Patocka 已提交
1118 1119
	dm_bufio_unlock(c);

1120 1121
	__flush_write_list(&write_list);

M
Mikulas Patocka 已提交
1122
	if (!b)
1123
		return NULL;
M
Mikulas Patocka 已提交
1124 1125

	if (need_submit)
1126
		submit_io(b, REQ_OP_READ, read_endio);
M
Mikulas Patocka 已提交
1127

1128
	wait_on_bit_io(&b->state, B_READING, TASK_UNINTERRUPTIBLE);
M
Mikulas Patocka 已提交
1129 1130

	if (b->read_error) {
1131
		int error = blk_status_to_errno(b->read_error);
M
Mikulas Patocka 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

		dm_bufio_release(b);

		return ERR_PTR(error);
	}

	*bp = b;

	return b->data;
}

void *dm_bufio_get(struct dm_bufio_client *c, sector_t block,
		   struct dm_buffer **bp)
{
	return new_read(c, block, NF_GET, bp);
}
EXPORT_SYMBOL_GPL(dm_bufio_get);

void *dm_bufio_read(struct dm_bufio_client *c, sector_t block,
		    struct dm_buffer **bp)
{
	BUG_ON(dm_bufio_in_request());

	return new_read(c, block, NF_READ, bp);
}
EXPORT_SYMBOL_GPL(dm_bufio_read);

void *dm_bufio_new(struct dm_bufio_client *c, sector_t block,
		   struct dm_buffer **bp)
{
	BUG_ON(dm_bufio_in_request());

	return new_read(c, block, NF_FRESH, bp);
}
EXPORT_SYMBOL_GPL(dm_bufio_new);

M
Mikulas Patocka 已提交
1168 1169 1170 1171 1172
void dm_bufio_prefetch(struct dm_bufio_client *c,
		       sector_t block, unsigned n_blocks)
{
	struct blk_plug plug;

1173 1174
	LIST_HEAD(write_list);

M
Mikulas Patocka 已提交
1175 1176
	BUG_ON(dm_bufio_in_request());

M
Mikulas Patocka 已提交
1177 1178 1179 1180 1181 1182
	blk_start_plug(&plug);
	dm_bufio_lock(c);

	for (; n_blocks--; block++) {
		int need_submit;
		struct dm_buffer *b;
1183 1184 1185 1186 1187 1188 1189 1190 1191
		b = __bufio_new(c, block, NF_PREFETCH, &need_submit,
				&write_list);
		if (unlikely(!list_empty(&write_list))) {
			dm_bufio_unlock(c);
			blk_finish_plug(&plug);
			__flush_write_list(&write_list);
			blk_start_plug(&plug);
			dm_bufio_lock(c);
		}
M
Mikulas Patocka 已提交
1192 1193 1194 1195
		if (unlikely(b != NULL)) {
			dm_bufio_unlock(c);

			if (need_submit)
1196
				submit_io(b, REQ_OP_READ, read_endio);
M
Mikulas Patocka 已提交
1197 1198
			dm_bufio_release(b);

1199
			cond_resched();
M
Mikulas Patocka 已提交
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213

			if (!n_blocks)
				goto flush_plug;
			dm_bufio_lock(c);
		}
	}

	dm_bufio_unlock(c);

flush_plug:
	blk_finish_plug(&plug);
}
EXPORT_SYMBOL_GPL(dm_bufio_prefetch);

M
Mikulas Patocka 已提交
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
void dm_bufio_release(struct dm_buffer *b)
{
	struct dm_bufio_client *c = b->c;

	dm_bufio_lock(c);

	BUG_ON(!b->hold_count);

	b->hold_count--;
	if (!b->hold_count) {
		wake_up(&c->free_buffer_wait);

		/*
		 * If there were errors on the buffer, and the buffer is not
		 * to be written, free the buffer. There is no point in caching
		 * invalid buffer.
		 */
		if ((b->read_error || b->write_error) &&
M
Mikulas Patocka 已提交
1232
		    !test_bit(B_READING, &b->state) &&
M
Mikulas Patocka 已提交
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
		    !test_bit(B_WRITING, &b->state) &&
		    !test_bit(B_DIRTY, &b->state)) {
			__unlink_buffer(b);
			__free_buffer_wake(b);
		}
	}

	dm_bufio_unlock(c);
}
EXPORT_SYMBOL_GPL(dm_bufio_release);

1244 1245
void dm_bufio_mark_partial_buffer_dirty(struct dm_buffer *b,
					unsigned start, unsigned end)
M
Mikulas Patocka 已提交
1246 1247 1248
{
	struct dm_bufio_client *c = b->c;

1249 1250 1251
	BUG_ON(start >= end);
	BUG_ON(end > b->c->block_size);

M
Mikulas Patocka 已提交
1252 1253
	dm_bufio_lock(c);

M
Mikulas Patocka 已提交
1254 1255
	BUG_ON(test_bit(B_READING, &b->state));

1256 1257 1258
	if (!test_and_set_bit(B_DIRTY, &b->state)) {
		b->dirty_start = start;
		b->dirty_end = end;
M
Mikulas Patocka 已提交
1259
		__relink_lru(b, LIST_DIRTY);
1260 1261 1262 1263 1264 1265
	} else {
		if (start < b->dirty_start)
			b->dirty_start = start;
		if (end > b->dirty_end)
			b->dirty_end = end;
	}
M
Mikulas Patocka 已提交
1266 1267 1268

	dm_bufio_unlock(c);
}
1269 1270 1271 1272 1273 1274
EXPORT_SYMBOL_GPL(dm_bufio_mark_partial_buffer_dirty);

void dm_bufio_mark_buffer_dirty(struct dm_buffer *b)
{
	dm_bufio_mark_partial_buffer_dirty(b, 0, b->c->block_size);
}
M
Mikulas Patocka 已提交
1275 1276 1277 1278
EXPORT_SYMBOL_GPL(dm_bufio_mark_buffer_dirty);

void dm_bufio_write_dirty_buffers_async(struct dm_bufio_client *c)
{
1279 1280
	LIST_HEAD(write_list);

M
Mikulas Patocka 已提交
1281 1282 1283
	BUG_ON(dm_bufio_in_request());

	dm_bufio_lock(c);
1284
	__write_dirty_buffers_async(c, 0, &write_list);
M
Mikulas Patocka 已提交
1285
	dm_bufio_unlock(c);
1286
	__flush_write_list(&write_list);
M
Mikulas Patocka 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
}
EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers_async);

/*
 * For performance, it is essential that the buffers are written asynchronously
 * and simultaneously (so that the block layer can merge the writes) and then
 * waited upon.
 *
 * Finally, we flush hardware disk cache.
 */
int dm_bufio_write_dirty_buffers(struct dm_bufio_client *c)
{
1299
	int a, f;
M
Mikulas Patocka 已提交
1300 1301 1302
	unsigned long buffers_processed = 0;
	struct dm_buffer *b, *tmp;

1303 1304 1305 1306 1307 1308
	LIST_HEAD(write_list);

	dm_bufio_lock(c);
	__write_dirty_buffers_async(c, 0, &write_list);
	dm_bufio_unlock(c);
	__flush_write_list(&write_list);
M
Mikulas Patocka 已提交
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
	dm_bufio_lock(c);

again:
	list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_DIRTY], lru_list) {
		int dropped_lock = 0;

		if (buffers_processed < c->n_buffers[LIST_DIRTY])
			buffers_processed++;

		BUG_ON(test_bit(B_READING, &b->state));

		if (test_bit(B_WRITING, &b->state)) {
			if (buffers_processed < c->n_buffers[LIST_DIRTY]) {
				dropped_lock = 1;
				b->hold_count++;
				dm_bufio_unlock(c);
1325 1326
				wait_on_bit_io(&b->state, B_WRITING,
					       TASK_UNINTERRUPTIBLE);
M
Mikulas Patocka 已提交
1327 1328 1329
				dm_bufio_lock(c);
				b->hold_count--;
			} else
1330 1331
				wait_on_bit_io(&b->state, B_WRITING,
					       TASK_UNINTERRUPTIBLE);
M
Mikulas Patocka 已提交
1332 1333 1334 1335 1336 1337
		}

		if (!test_bit(B_DIRTY, &b->state) &&
		    !test_bit(B_WRITING, &b->state))
			__relink_lru(b, LIST_CLEAN);

1338
		cond_resched();
M
Mikulas Patocka 已提交
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374

		/*
		 * If we dropped the lock, the list is no longer consistent,
		 * so we must restart the search.
		 *
		 * In the most common case, the buffer just processed is
		 * relinked to the clean list, so we won't loop scanning the
		 * same buffer again and again.
		 *
		 * This may livelock if there is another thread simultaneously
		 * dirtying buffers, so we count the number of buffers walked
		 * and if it exceeds the total number of buffers, it means that
		 * someone is doing some writes simultaneously with us.  In
		 * this case, stop, dropping the lock.
		 */
		if (dropped_lock)
			goto again;
	}
	wake_up(&c->free_buffer_wait);
	dm_bufio_unlock(c);

	a = xchg(&c->async_write_error, 0);
	f = dm_bufio_issue_flush(c);
	if (a)
		return a;

	return f;
}
EXPORT_SYMBOL_GPL(dm_bufio_write_dirty_buffers);

/*
 * Use dm-io to send and empty barrier flush the device.
 */
int dm_bufio_issue_flush(struct dm_bufio_client *c)
{
	struct dm_io_request io_req = {
M
Mike Christie 已提交
1375
		.bi_op = REQ_OP_WRITE,
J
Jan Kara 已提交
1376
		.bi_op_flags = REQ_PREFLUSH | REQ_SYNC,
M
Mikulas Patocka 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
		.mem.type = DM_IO_KMEM,
		.mem.ptr.addr = NULL,
		.client = c->dm_io,
	};
	struct dm_io_region io_reg = {
		.bdev = c->bdev,
		.sector = 0,
		.count = 0,
	};

	BUG_ON(dm_bufio_in_request());

	return dm_io(&io_req, 1, &io_reg, NULL);
}
EXPORT_SYMBOL_GPL(dm_bufio_issue_flush);

/*
 * We first delete any other buffer that may be at that new location.
 *
 * Then, we write the buffer to the original location if it was dirty.
 *
 * Then, if we are the only one who is holding the buffer, relink the buffer
 * in the hash queue for the new location.
 *
 * If there was someone else holding the buffer, we write it to the new
 * location but not relink it, because that other user needs to have the buffer
 * at the same place.
 */
void dm_bufio_release_move(struct dm_buffer *b, sector_t new_block)
{
	struct dm_bufio_client *c = b->c;
	struct dm_buffer *new;

	BUG_ON(dm_bufio_in_request());

	dm_bufio_lock(c);

retry:
	new = __find(c, new_block);
	if (new) {
		if (new->hold_count) {
			__wait_for_free_buffer(c);
			goto retry;
		}

		/*
		 * FIXME: Is there any point waiting for a write that's going
		 * to be overwritten in a bit?
		 */
		__make_buffer_clean(new);
		__unlink_buffer(new);
		__free_buffer_wake(new);
	}

	BUG_ON(!b->hold_count);
	BUG_ON(test_bit(B_READING, &b->state));

1434
	__write_dirty_buffer(b, NULL);
M
Mikulas Patocka 已提交
1435
	if (b->hold_count == 1) {
1436 1437
		wait_on_bit_io(&b->state, B_WRITING,
			       TASK_UNINTERRUPTIBLE);
M
Mikulas Patocka 已提交
1438
		set_bit(B_DIRTY, &b->state);
1439 1440
		b->dirty_start = 0;
		b->dirty_end = c->block_size;
M
Mikulas Patocka 已提交
1441 1442 1443 1444
		__unlink_buffer(b);
		__link_buffer(b, new_block, LIST_DIRTY);
	} else {
		sector_t old_block;
1445 1446
		wait_on_bit_lock_io(&b->state, B_WRITING,
				    TASK_UNINTERRUPTIBLE);
M
Mikulas Patocka 已提交
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
		/*
		 * Relink buffer to "new_block" so that write_callback
		 * sees "new_block" as a block number.
		 * After the write, link the buffer back to old_block.
		 * All this must be done in bufio lock, so that block number
		 * change isn't visible to other threads.
		 */
		old_block = b->block;
		__unlink_buffer(b);
		__link_buffer(b, new_block, b->list_mode);
1457
		submit_io(b, REQ_OP_WRITE, write_endio);
1458 1459
		wait_on_bit_io(&b->state, B_WRITING,
			       TASK_UNINTERRUPTIBLE);
M
Mikulas Patocka 已提交
1460 1461 1462 1463 1464 1465 1466 1467 1468
		__unlink_buffer(b);
		__link_buffer(b, old_block, b->list_mode);
	}

	dm_bufio_unlock(c);
	dm_bufio_release(b);
}
EXPORT_SYMBOL_GPL(dm_bufio_release_move);

M
Mikulas Patocka 已提交
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
/*
 * Free the given buffer.
 *
 * This is just a hint, if the buffer is in use or dirty, this function
 * does nothing.
 */
void dm_bufio_forget(struct dm_bufio_client *c, sector_t block)
{
	struct dm_buffer *b;

	dm_bufio_lock(c);

	b = __find(c, block);
	if (b && likely(!b->hold_count) && likely(!b->state)) {
		__unlink_buffer(b);
		__free_buffer_wake(b);
	}

	dm_bufio_unlock(c);
}
EXPORT_SYMBOL(dm_bufio_forget);

1491 1492 1493 1494 1495 1496
void dm_bufio_set_minimum_buffers(struct dm_bufio_client *c, unsigned n)
{
	c->minimum_buffers = n;
}
EXPORT_SYMBOL(dm_bufio_set_minimum_buffers);

M
Mikulas Patocka 已提交
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
unsigned dm_bufio_get_block_size(struct dm_bufio_client *c)
{
	return c->block_size;
}
EXPORT_SYMBOL_GPL(dm_bufio_get_block_size);

sector_t dm_bufio_get_device_size(struct dm_bufio_client *c)
{
	return i_size_read(c->bdev->bd_inode) >>
			   (SECTOR_SHIFT + c->sectors_per_block_bits);
}
EXPORT_SYMBOL_GPL(dm_bufio_get_device_size);

sector_t dm_bufio_get_block_number(struct dm_buffer *b)
{
	return b->block;
}
EXPORT_SYMBOL_GPL(dm_bufio_get_block_number);

void *dm_bufio_get_block_data(struct dm_buffer *b)
{
	return b->data;
}
EXPORT_SYMBOL_GPL(dm_bufio_get_block_data);

void *dm_bufio_get_aux_data(struct dm_buffer *b)
{
	return b + 1;
}
EXPORT_SYMBOL_GPL(dm_bufio_get_aux_data);

struct dm_bufio_client *dm_bufio_get_client(struct dm_buffer *b)
{
	return b->c;
}
EXPORT_SYMBOL_GPL(dm_bufio_get_client);

static void drop_buffers(struct dm_bufio_client *c)
{
	struct dm_buffer *b;
	int i;
1538
	bool warned = false;
M
Mikulas Patocka 已提交
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552

	BUG_ON(dm_bufio_in_request());

	/*
	 * An optimization so that the buffers are not written one-by-one.
	 */
	dm_bufio_write_dirty_buffers_async(c);

	dm_bufio_lock(c);

	while ((b = __get_unclaimed_buffer(c)))
		__free_buffer_wake(b);

	for (i = 0; i < LIST_SIZE; i++)
1553 1554 1555
		list_for_each_entry(b, &c->lru[i], lru_list) {
			WARN_ON(!warned);
			warned = true;
M
Mikulas Patocka 已提交
1556 1557
			DMERR("leaked buffer %llx, hold count %u, list %d",
			      (unsigned long long)b->block, b->hold_count, i);
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
#ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
			print_stack_trace(&b->stack_trace, 1);
			b->hold_count = 0; /* mark unclaimed to avoid BUG_ON below */
#endif
		}

#ifdef CONFIG_DM_DEBUG_BLOCK_STACK_TRACING
	while ((b = __get_unclaimed_buffer(c)))
		__free_buffer_wake(b);
#endif
M
Mikulas Patocka 已提交
1568 1569 1570 1571 1572 1573 1574 1575

	for (i = 0; i < LIST_SIZE; i++)
		BUG_ON(!list_empty(&c->lru[i]));

	dm_bufio_unlock(c);
}

/*
1576 1577 1578
 * We may not be able to evict this buffer if IO pending or the client
 * is still using it.  Caller is expected to know buffer is too old.
 *
1579 1580 1581
 * And if GFP_NOFS is used, we must not do any I/O because we hold
 * dm_bufio_clients_lock and we would risk deadlock if the I/O gets
 * rerouted to different bufio client.
M
Mikulas Patocka 已提交
1582
 */
1583
static bool __try_evict_buffer(struct dm_buffer *b, gfp_t gfp)
M
Mikulas Patocka 已提交
1584
{
1585
	if (!(gfp & __GFP_FS)) {
M
Mikulas Patocka 已提交
1586 1587 1588
		if (test_bit(B_READING, &b->state) ||
		    test_bit(B_WRITING, &b->state) ||
		    test_bit(B_DIRTY, &b->state))
1589
			return false;
M
Mikulas Patocka 已提交
1590 1591 1592
	}

	if (b->hold_count)
1593
		return false;
M
Mikulas Patocka 已提交
1594 1595 1596 1597 1598

	__make_buffer_clean(b);
	__unlink_buffer(b);
	__free_buffer_wake(b);

1599
	return true;
M
Mikulas Patocka 已提交
1600 1601
}

1602
static unsigned long get_retain_buffers(struct dm_bufio_client *c)
1603
{
1604
        unsigned long retain_bytes = READ_ONCE(dm_bufio_retain_bytes);
1605
        return retain_bytes >> (c->sectors_per_block_bits + SECTOR_SHIFT);
1606 1607 1608 1609
}

static unsigned long __scan(struct dm_bufio_client *c, unsigned long nr_to_scan,
			    gfp_t gfp_mask)
M
Mikulas Patocka 已提交
1610 1611 1612
{
	int l;
	struct dm_buffer *b, *tmp;
1613
	unsigned long freed = 0;
1614 1615
	unsigned long count = c->n_buffers[LIST_CLEAN] +
			      c->n_buffers[LIST_DIRTY];
1616
	unsigned long retain_target = get_retain_buffers(c);
M
Mikulas Patocka 已提交
1617 1618

	for (l = 0; l < LIST_SIZE; l++) {
1619
		list_for_each_entry_safe_reverse(b, tmp, &c->lru[l], lru_list) {
1620 1621 1622
			if (__try_evict_buffer(b, gfp_mask))
				freed++;
			if (!--nr_to_scan || ((count - freed) <= retain_target))
1623
				return freed;
1624
			cond_resched();
1625
		}
M
Mikulas Patocka 已提交
1626
	}
1627
	return freed;
M
Mikulas Patocka 已提交
1628 1629
}

1630 1631
static unsigned long
dm_bufio_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
M
Mikulas Patocka 已提交
1632
{
1633 1634
	struct dm_bufio_client *c;
	unsigned long freed;
M
Mikulas Patocka 已提交
1635

1636
	c = container_of(shrink, struct dm_bufio_client, shrinker);
1637
	if (sc->gfp_mask & __GFP_FS)
M
Mikulas Patocka 已提交
1638 1639
		dm_bufio_lock(c);
	else if (!dm_bufio_trylock(c))
1640
		return SHRINK_STOP;
M
Mikulas Patocka 已提交
1641

1642 1643 1644 1645
	freed  = __scan(c, sc->nr_to_scan, sc->gfp_mask);
	dm_bufio_unlock(c);
	return freed;
}
M
Mikulas Patocka 已提交
1646

1647 1648 1649
static unsigned long
dm_bufio_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
{
1650
	struct dm_bufio_client *c = container_of(shrink, struct dm_bufio_client, shrinker);
1651 1652 1653
	unsigned long count = READ_ONCE(c->n_buffers[LIST_CLEAN]) +
			      READ_ONCE(c->n_buffers[LIST_DIRTY]);
	unsigned long retain_target = get_retain_buffers(c);
M
Mikulas Patocka 已提交
1654

1655
	return (count < retain_target) ? 0 : (count - retain_target);
M
Mikulas Patocka 已提交
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
}

/*
 * Create the buffering interface
 */
struct dm_bufio_client *dm_bufio_client_create(struct block_device *bdev, unsigned block_size,
					       unsigned reserved_buffers, unsigned aux_size,
					       void (*alloc_callback)(struct dm_buffer *),
					       void (*write_callback)(struct dm_buffer *))
{
	int r;
	struct dm_bufio_client *c;
	unsigned i;

	BUG_ON(block_size < 1 << SECTOR_SHIFT ||
	       (block_size & (block_size - 1)));

1673
	c = kzalloc(sizeof(*c), GFP_KERNEL);
M
Mikulas Patocka 已提交
1674 1675 1676 1677
	if (!c) {
		r = -ENOMEM;
		goto bad_client;
	}
1678
	c->buffer_tree = RB_ROOT;
M
Mikulas Patocka 已提交
1679 1680 1681

	c->bdev = bdev;
	c->block_size = block_size;
M
Mikulas Patocka 已提交
1682 1683 1684 1685 1686
	c->sectors_per_block_bits = __ffs(block_size) - SECTOR_SHIFT;
	c->pages_per_block_bits = (__ffs(block_size) >= PAGE_SHIFT) ?
				  __ffs(block_size) - PAGE_SHIFT : 0;
	c->blocks_per_page_bits = (__ffs(block_size) < PAGE_SHIFT ?
				  PAGE_SHIFT - __ffs(block_size) : 0);
M
Mikulas Patocka 已提交
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700

	c->aux_size = aux_size;
	c->alloc_callback = alloc_callback;
	c->write_callback = write_callback;

	for (i = 0; i < LIST_SIZE; i++) {
		INIT_LIST_HEAD(&c->lru[i]);
		c->n_buffers[i] = 0;
	}

	mutex_init(&c->lock);
	INIT_LIST_HEAD(&c->reserved_buffers);
	c->need_reserved_buffers = reserved_buffers;

1701 1702
	c->minimum_buffers = DM_BUFIO_MIN_BUFFERS;

M
Mikulas Patocka 已提交
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
	init_waitqueue_head(&c->free_buffer_wait);
	c->async_write_error = 0;

	c->dm_io = dm_io_client_create();
	if (IS_ERR(c->dm_io)) {
		r = PTR_ERR(c->dm_io);
		goto bad_dm_io;
	}

	mutex_lock(&dm_bufio_clients_lock);
	if (c->blocks_per_page_bits) {
		if (!DM_BUFIO_CACHE_NAME(c)) {
			DM_BUFIO_CACHE_NAME(c) = kasprintf(GFP_KERNEL, "dm_bufio_cache-%u", c->block_size);
			if (!DM_BUFIO_CACHE_NAME(c)) {
				r = -ENOMEM;
				mutex_unlock(&dm_bufio_clients_lock);
				goto bad_cache;
			}
		}

		if (!DM_BUFIO_CACHE(c)) {
			DM_BUFIO_CACHE(c) = kmem_cache_create(DM_BUFIO_CACHE_NAME(c),
							      c->block_size,
							      c->block_size, 0, NULL);
			if (!DM_BUFIO_CACHE(c)) {
				r = -ENOMEM;
				mutex_unlock(&dm_bufio_clients_lock);
				goto bad_cache;
			}
		}
	}
	mutex_unlock(&dm_bufio_clients_lock);

	while (c->need_reserved_buffers) {
		struct dm_buffer *b = alloc_buffer(c, GFP_KERNEL);

		if (!b) {
			r = -ENOMEM;
			goto bad_buffer;
		}
		__free_buffer_wake(b);
	}

1746 1747 1748 1749 1750 1751 1752 1753
	c->shrinker.count_objects = dm_bufio_shrink_count;
	c->shrinker.scan_objects = dm_bufio_shrink_scan;
	c->shrinker.seeks = 1;
	c->shrinker.batch = 0;
	r = register_shrinker(&c->shrinker);
	if (r)
		goto bad_shrinker;

M
Mikulas Patocka 已提交
1754 1755 1756 1757 1758 1759 1760 1761
	mutex_lock(&dm_bufio_clients_lock);
	dm_bufio_client_count++;
	list_add(&c->client_list, &dm_bufio_all_clients);
	__cache_size_refresh();
	mutex_unlock(&dm_bufio_clients_lock);

	return c;

1762
bad_shrinker:
M
Mikulas Patocka 已提交
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
bad_buffer:
bad_cache:
	while (!list_empty(&c->reserved_buffers)) {
		struct dm_buffer *b = list_entry(c->reserved_buffers.next,
						 struct dm_buffer, lru_list);
		list_del(&b->lru_list);
		free_buffer(b);
	}
	dm_io_client_destroy(c->dm_io);
bad_dm_io:
1773
	mutex_destroy(&c->lock);
M
Mikulas Patocka 已提交
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
	kfree(c);
bad_client:
	return ERR_PTR(r);
}
EXPORT_SYMBOL_GPL(dm_bufio_client_create);

/*
 * Free the buffering interface.
 * It is required that there are no references on any buffers.
 */
void dm_bufio_client_destroy(struct dm_bufio_client *c)
{
	unsigned i;

	drop_buffers(c);

	unregister_shrinker(&c->shrinker);

	mutex_lock(&dm_bufio_clients_lock);

	list_del(&c->client_list);
	dm_bufio_client_count--;
	__cache_size_refresh();

	mutex_unlock(&dm_bufio_clients_lock);

1800
	BUG_ON(!RB_EMPTY_ROOT(&c->buffer_tree));
M
Mikulas Patocka 已提交
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
	BUG_ON(c->need_reserved_buffers);

	while (!list_empty(&c->reserved_buffers)) {
		struct dm_buffer *b = list_entry(c->reserved_buffers.next,
						 struct dm_buffer, lru_list);
		list_del(&b->lru_list);
		free_buffer(b);
	}

	for (i = 0; i < LIST_SIZE; i++)
		if (c->n_buffers[i])
			DMERR("leaked buffer count %d: %ld", i, c->n_buffers[i]);

	for (i = 0; i < LIST_SIZE; i++)
		BUG_ON(c->n_buffers[i]);

	dm_io_client_destroy(c->dm_io);
1818
	mutex_destroy(&c->lock);
M
Mikulas Patocka 已提交
1819 1820 1821 1822
	kfree(c);
}
EXPORT_SYMBOL_GPL(dm_bufio_client_destroy);

1823 1824 1825 1826 1827 1828
void dm_bufio_set_sector_offset(struct dm_bufio_client *c, sector_t start)
{
	c->start = start;
}
EXPORT_SYMBOL_GPL(dm_bufio_set_sector_offset);

1829
static unsigned get_max_age_hz(void)
M
Mikulas Patocka 已提交
1830
{
1831
	unsigned max_age = READ_ONCE(dm_bufio_max_age);
M
Mikulas Patocka 已提交
1832

1833 1834
	if (max_age > UINT_MAX / HZ)
		max_age = UINT_MAX / HZ;
M
Mikulas Patocka 已提交
1835

1836 1837
	return max_age * HZ;
}
M
Mikulas Patocka 已提交
1838

1839 1840
static bool older_than(struct dm_buffer *b, unsigned long age_hz)
{
1841
	return time_after_eq(jiffies, b->last_accessed + age_hz);
1842 1843 1844 1845 1846
}

static void __evict_old_buffers(struct dm_bufio_client *c, unsigned long age_hz)
{
	struct dm_buffer *b, *tmp;
1847 1848
	unsigned long retain_target = get_retain_buffers(c);
	unsigned long count;
1849
	LIST_HEAD(write_list);
1850 1851 1852

	dm_bufio_lock(c);

1853 1854 1855 1856 1857 1858 1859
	__check_watermark(c, &write_list);
	if (unlikely(!list_empty(&write_list))) {
		dm_bufio_unlock(c);
		__flush_write_list(&write_list);
		dm_bufio_lock(c);
	}

1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
	count = c->n_buffers[LIST_CLEAN] + c->n_buffers[LIST_DIRTY];
	list_for_each_entry_safe_reverse(b, tmp, &c->lru[LIST_CLEAN], lru_list) {
		if (count <= retain_target)
			break;

		if (!older_than(b, age_hz))
			break;

		if (__try_evict_buffer(b, 0))
			count--;
M
Mikulas Patocka 已提交
1870

1871
		cond_resched();
M
Mikulas Patocka 已提交
1872
	}
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883

	dm_bufio_unlock(c);
}

static void cleanup_old_buffers(void)
{
	unsigned long max_age_hz = get_max_age_hz();
	struct dm_bufio_client *c;

	mutex_lock(&dm_bufio_clients_lock);

1884 1885
	__cache_size_refresh();

1886 1887 1888
	list_for_each_entry(c, &dm_bufio_all_clients, client_list)
		__evict_old_buffers(c, max_age_hz);

M
Mikulas Patocka 已提交
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
	mutex_unlock(&dm_bufio_clients_lock);
}

static struct workqueue_struct *dm_bufio_wq;
static struct delayed_work dm_bufio_work;

static void work_fn(struct work_struct *w)
{
	cleanup_old_buffers();

	queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
			   DM_BUFIO_WORK_TIMER_SECS * HZ);
}

/*----------------------------------------------------------------
 * Module setup
 *--------------------------------------------------------------*/

/*
 * This is called only once for the whole dm_bufio module.
 * It initializes memory limit.
 */
static int __init dm_bufio_init(void)
{
	__u64 mem;

1915 1916 1917 1918 1919
	dm_bufio_allocated_kmem_cache = 0;
	dm_bufio_allocated_get_free_pages = 0;
	dm_bufio_allocated_vmalloc = 0;
	dm_bufio_current_allocated = 0;

M
Mikulas Patocka 已提交
1920 1921 1922
	memset(&dm_bufio_caches, 0, sizeof dm_bufio_caches);
	memset(&dm_bufio_cache_names, 0, sizeof dm_bufio_cache_names);

1923 1924
	mem = (__u64)mult_frac(totalram_pages - totalhigh_pages,
			       DM_BUFIO_MEMORY_PERCENT, 100) << PAGE_SHIFT;
M
Mikulas Patocka 已提交
1925 1926 1927 1928 1929

	if (mem > ULONG_MAX)
		mem = ULONG_MAX;

#ifdef CONFIG_MMU
1930 1931
	if (mem > mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100))
		mem = mult_frac(VMALLOC_TOTAL, DM_BUFIO_VMALLOC_PERCENT, 100);
M
Mikulas Patocka 已提交
1932 1933 1934 1935 1936 1937 1938 1939
#endif

	dm_bufio_default_cache_size = mem;

	mutex_lock(&dm_bufio_clients_lock);
	__cache_size_refresh();
	mutex_unlock(&dm_bufio_clients_lock);

1940
	dm_bufio_wq = alloc_workqueue("dm_bufio_cache", WQ_MEM_RECLAIM, 0);
M
Mikulas Patocka 已提交
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
	if (!dm_bufio_wq)
		return -ENOMEM;

	INIT_DELAYED_WORK(&dm_bufio_work, work_fn);
	queue_delayed_work(dm_bufio_wq, &dm_bufio_work,
			   DM_BUFIO_WORK_TIMER_SECS * HZ);

	return 0;
}

/*
 * This is called once when unloading the dm_bufio module.
 */
static void __exit dm_bufio_exit(void)
{
	int bug = 0;
	int i;

	cancel_delayed_work_sync(&dm_bufio_work);
	destroy_workqueue(dm_bufio_wq);

1962 1963
	for (i = 0; i < ARRAY_SIZE(dm_bufio_caches); i++)
		kmem_cache_destroy(dm_bufio_caches[i]);
M
Mikulas Patocka 已提交
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991

	for (i = 0; i < ARRAY_SIZE(dm_bufio_cache_names); i++)
		kfree(dm_bufio_cache_names[i]);

	if (dm_bufio_client_count) {
		DMCRIT("%s: dm_bufio_client_count leaked: %d",
			__func__, dm_bufio_client_count);
		bug = 1;
	}

	if (dm_bufio_current_allocated) {
		DMCRIT("%s: dm_bufio_current_allocated leaked: %lu",
			__func__, dm_bufio_current_allocated);
		bug = 1;
	}

	if (dm_bufio_allocated_get_free_pages) {
		DMCRIT("%s: dm_bufio_allocated_get_free_pages leaked: %lu",
		       __func__, dm_bufio_allocated_get_free_pages);
		bug = 1;
	}

	if (dm_bufio_allocated_vmalloc) {
		DMCRIT("%s: dm_bufio_vmalloc leaked: %lu",
		       __func__, dm_bufio_allocated_vmalloc);
		bug = 1;
	}

1992
	BUG_ON(bug);
M
Mikulas Patocka 已提交
1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
}

module_init(dm_bufio_init)
module_exit(dm_bufio_exit)

module_param_named(max_cache_size_bytes, dm_bufio_cache_size, ulong, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(max_cache_size_bytes, "Size of metadata cache");

module_param_named(max_age_seconds, dm_bufio_max_age, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(max_age_seconds, "Max age of a buffer in seconds");
2003

2004
module_param_named(retain_bytes, dm_bufio_retain_bytes, ulong, S_IRUGO | S_IWUSR);
2005
MODULE_PARM_DESC(retain_bytes, "Try to keep at least this many bytes cached in memory");
M
Mikulas Patocka 已提交
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024

module_param_named(peak_allocated_bytes, dm_bufio_peak_allocated, ulong, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(peak_allocated_bytes, "Tracks the maximum allocated memory");

module_param_named(allocated_kmem_cache_bytes, dm_bufio_allocated_kmem_cache, ulong, S_IRUGO);
MODULE_PARM_DESC(allocated_kmem_cache_bytes, "Memory allocated with kmem_cache_alloc");

module_param_named(allocated_get_free_pages_bytes, dm_bufio_allocated_get_free_pages, ulong, S_IRUGO);
MODULE_PARM_DESC(allocated_get_free_pages_bytes, "Memory allocated with get_free_pages");

module_param_named(allocated_vmalloc_bytes, dm_bufio_allocated_vmalloc, ulong, S_IRUGO);
MODULE_PARM_DESC(allocated_vmalloc_bytes, "Memory allocated with vmalloc");

module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, S_IRUGO);
MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");

MODULE_AUTHOR("Mikulas Patocka <dm-devel@redhat.com>");
MODULE_DESCRIPTION(DM_NAME " buffered I/O library");
MODULE_LICENSE("GPL");