fs-io.c 79.4 KB
Newer Older
1 2 3 4
// SPDX-License-Identifier: GPL-2.0
#ifndef NO_BCACHEFS_FS

#include "bcachefs.h"
5
#include "alloc_foreground.h"
6
#include "bkey_buf.h"
7 8 9 10
#include "btree_update.h"
#include "buckets.h"
#include "clock.h"
#include "error.h"
11
#include "extents.h"
12
#include "extent_update.h"
13 14 15 16 17 18 19 20
#include "fs.h"
#include "fs-io.h"
#include "fsck.h"
#include "inode.h"
#include "journal.h"
#include "io.h"
#include "keylist.h"
#include "quota.h"
Kent Overstreet's avatar
Kent Overstreet committed
21
#include "reflink.h"
22 23 24 25 26 27 28 29
#include "trace.h"

#include <linux/aio.h>
#include <linux/backing-dev.h>
#include <linux/falloc.h>
#include <linux/migrate.h>
#include <linux/mmu_context.h>
#include <linux/pagevec.h>
30
#include <linux/rmap.h>
31 32 33 34 35 36 37
#include <linux/sched/signal.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/uio.h>
#include <linux/writeback.h>

#include <trace/events/writeback.h>

38 39 40 41 42 43 44 45 46
static inline bool bio_full(struct bio *bio, unsigned len)
{
	if (bio->bi_vcnt >= bio->bi_max_vecs)
		return true;
	if (bio->bi_iter.bi_size > UINT_MAX - len)
		return true;
	return false;
}

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
static inline struct address_space *faults_disabled_mapping(void)
{
	return (void *) (((unsigned long) current->faults_disabled_mapping) & ~1UL);
}

static inline void set_fdm_dropped_locks(void)
{
	current->faults_disabled_mapping =
		(void *) (((unsigned long) current->faults_disabled_mapping)|1);
}

static inline bool fdm_dropped_locks(void)
{
	return ((unsigned long) current->faults_disabled_mapping) & 1;
}

63 64 65 66 67
struct quota_res {
	u64				sectors;
};

struct bch_writepage_io {
68
	struct bch_inode_info		*inode;
69 70

	/* must be last: */
71
	struct bch_write_op		op;
72 73 74
};

struct dio_write {
75
	struct completion		done;
76
	struct kiocb			*req;
Kent Overstreet's avatar
Kent Overstreet committed
77
	struct mm_struct		*mm;
78 79 80 81
	unsigned			loop:1,
					sync:1,
					free_iov:1;
	struct quota_res		quota_res;
82
	u64				written;
83 84 85 86 87

	struct iov_iter			iter;
	struct iovec			inline_vecs[2];

	/* must be last: */
88
	struct bch_write_op		op;
89 90 91 92 93 94
};

struct dio_read {
	struct closure			cl;
	struct kiocb			*req;
	long				ret;
95
	bool				should_dirty;
96 97 98 99
	struct bch_read_bio		rbio;
};

/* pagecache_block must be held */
100
static noinline int write_invalidate_inode_pages_range(struct address_space *mapping,
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
					      loff_t start, loff_t end)
{
	int ret;

	/*
	 * XXX: the way this is currently implemented, we can spin if a process
	 * is continually redirtying a specific page
	 */
	do {
		if (!mapping->nrpages)
			return 0;

		ret = filemap_write_and_wait_range(mapping, start, end);
		if (ret)
			break;

		if (!mapping->nrpages)
			return 0;

		ret = invalidate_inode_pages2_range(mapping,
				start >> PAGE_SHIFT,
				end >> PAGE_SHIFT);
	} while (ret == -EBUSY);

	return ret;
}

/* quotas */

#ifdef CONFIG_BCACHEFS_QUOTA

static void bch2_quota_reservation_put(struct bch_fs *c,
				       struct bch_inode_info *inode,
				       struct quota_res *res)
{
	if (!res->sectors)
		return;

	mutex_lock(&inode->ei_quota_lock);
	BUG_ON(res->sectors > inode->ei_quota_reserved);

	bch2_quota_acct(c, inode->ei_qid, Q_SPC,
143
			-((s64) res->sectors), KEY_TYPE_QUOTA_PREALLOC);
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
	inode->ei_quota_reserved -= res->sectors;
	mutex_unlock(&inode->ei_quota_lock);

	res->sectors = 0;
}

static int bch2_quota_reservation_add(struct bch_fs *c,
				      struct bch_inode_info *inode,
				      struct quota_res *res,
				      unsigned sectors,
				      bool check_enospc)
{
	int ret;

	mutex_lock(&inode->ei_quota_lock);
	ret = bch2_quota_acct(c, inode->ei_qid, Q_SPC, sectors,
160
			      check_enospc ? KEY_TYPE_QUOTA_PREALLOC : KEY_TYPE_QUOTA_NOCHECK);
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
	if (likely(!ret)) {
		inode->ei_quota_reserved += sectors;
		res->sectors += sectors;
	}
	mutex_unlock(&inode->ei_quota_lock);

	return ret;
}

#else

static void bch2_quota_reservation_put(struct bch_fs *c,
				       struct bch_inode_info *inode,
				       struct quota_res *res)
{
}

static int bch2_quota_reservation_add(struct bch_fs *c,
				      struct bch_inode_info *inode,
				      struct quota_res *res,
				      unsigned sectors,
				      bool check_enospc)
{
	return 0;
}

#endif

/* i_size updates: */

191 192 193 194 195 196
struct inode_new_size {
	loff_t		new_size;
	u64		now;
	unsigned	fields;
};

197 198 199 200
static int inode_set_size(struct bch_inode_info *inode,
			  struct bch_inode_unpacked *bi,
			  void *p)
{
201
	struct inode_new_size *s = p;
202

203 204 205 206 207 208 209
	bi->bi_size = s->new_size;
	if (s->fields & ATTR_ATIME)
		bi->bi_atime = s->now;
	if (s->fields & ATTR_MTIME)
		bi->bi_mtime = s->now;
	if (s->fields & ATTR_CTIME)
		bi->bi_ctime = s->now;
210 211 212 213

	return 0;
}

Kent Overstreet's avatar
Kent Overstreet committed
214 215 216
int __must_check bch2_write_inode_size(struct bch_fs *c,
				       struct bch_inode_info *inode,
				       loff_t new_size, unsigned fields)
217
{
218 219 220 221 222 223 224
	struct inode_new_size s = {
		.new_size	= new_size,
		.now		= bch2_current_time(c),
		.fields		= fields,
	};

	return bch2_write_inode(c, inode, inode_set_size, &s, fields);
225 226 227
}

static void i_sectors_acct(struct bch_fs *c, struct bch_inode_info *inode,
228
			   struct quota_res *quota_res, s64 sectors)
229
{
230 231 232
	if (!sectors)
		return;

233
	mutex_lock(&inode->ei_quota_lock);
234 235 236
	BUG_ON((s64) inode->v.i_blocks + sectors < 0);
	inode->v.i_blocks += sectors;

237 238 239 240 241 242 243 244
#ifdef CONFIG_BCACHEFS_QUOTA
	if (quota_res && sectors > 0) {
		BUG_ON(sectors > quota_res->sectors);
		BUG_ON(sectors > inode->ei_quota_reserved);

		quota_res->sectors -= sectors;
		inode->ei_quota_reserved -= sectors;
	} else {
245
		bch2_quota_acct(c, inode->ei_qid, Q_SPC, sectors, KEY_TYPE_QUOTA_WARN);
246 247 248 249 250 251 252 253 254
	}
#endif
	mutex_unlock(&inode->ei_quota_lock);
}

/* page state: */

/* stored in page->private: */

255
struct bch_page_sector {
256 257
	/* Uncompressed, fully allocated replicas (or on disk reservation): */
	unsigned		nr_replicas:4;
258

259 260
	/* Owns PAGE_SECTORS * replicas_reserved sized in memory reservation: */
	unsigned		replicas_reserved:4;
261 262 263 264

	/* i_sectors: */
	enum {
		SECTOR_UNALLOCATED,
265
		SECTOR_RESERVED,
266
		SECTOR_DIRTY,
267
		SECTOR_DIRTY_RESERVED,
268
		SECTOR_ALLOCATED,
269
	}			state:8;
270
};
271

272
struct bch_page_state {
273
	spinlock_t		lock;
274
	atomic_t		write_count;
275
	struct bch_page_sector	s[PAGE_SECTORS];
276 277
};

278
static inline struct bch_page_state *__bch2_page_state(struct page *page)
279
{
280 281 282 283
	return page_has_private(page)
		? (struct bch_page_state *) page_private(page)
		: NULL;
}
284

285 286
static inline struct bch_page_state *bch2_page_state(struct page *page)
{
287
	EBUG_ON(!PageLocked(page));
288

289 290 291 292 293 294
	return __bch2_page_state(page);
}

/* for newly allocated pages: */
static void __bch2_page_state_release(struct page *page)
{
295
	kfree(detach_page_private(page));
296 297 298 299
}

static void bch2_page_state_release(struct page *page)
{
300 301
	EBUG_ON(!PageLocked(page));
	__bch2_page_state_release(page);
302 303 304 305 306 307 308 309 310 311 312
}

/* for newly allocated pages: */
static struct bch_page_state *__bch2_page_state_create(struct page *page,
						       gfp_t gfp)
{
	struct bch_page_state *s;

	s = kzalloc(sizeof(*s), GFP_NOFS|gfp);
	if (!s)
		return NULL;
313

314
	spin_lock_init(&s->lock);
315
	attach_page_private(page, s);
316 317 318
	return s;
}

319 320 321 322 323 324
static struct bch_page_state *bch2_page_state_create(struct page *page,
						     gfp_t gfp)
{
	return bch2_page_state(page) ?: __bch2_page_state_create(page, gfp);
}

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 350 351 352 353 354
static unsigned bkey_to_sector_state(const struct bkey *k)
{
	if (k->type == KEY_TYPE_reservation)
		return SECTOR_RESERVED;
	if (bkey_extent_is_allocation(k))
		return SECTOR_ALLOCATED;
	return SECTOR_UNALLOCATED;
}

static void bch2_bio_page_state_set(struct bio *bio, struct bkey_s_c k)
{
	struct bvec_iter iter;
	struct bio_vec bv;
	unsigned nr_ptrs = k.k->type == KEY_TYPE_reflink_v
		? 0 : bch2_bkey_nr_ptrs_fully_allocated(k);
	unsigned state = bkey_to_sector_state(k.k);

	bio_for_each_segment(bv, bio, iter) {
		struct bch_page_state *s = bch2_page_state(bv.bv_page);
		unsigned i;

		for (i = bv.bv_offset >> 9;
		     i < (bv.bv_offset + bv.bv_len) >> 9;
		     i++) {
			s->s[i].nr_replicas = nr_ptrs;
			s->s[i].state = state;
		}
	}
}

355 356 357 358 359 360 361 362
static inline unsigned inode_nr_replicas(struct bch_fs *c, struct bch_inode_info *inode)
{
	/* XXX: this should not be open coded */
	return inode->ei_inode.bi_data_replicas
		? inode->ei_inode.bi_data_replicas - 1
		: c->opts.data_replicas;
}

363 364
static inline unsigned sectors_to_reserve(struct bch_page_sector *s,
						  unsigned nr_replicas)
365
{
366 367 368 369 370 371 372 373 374 375
	return max(0, (int) nr_replicas -
		   s->nr_replicas -
		   s->replicas_reserved);
}

static int bch2_get_page_disk_reservation(struct bch_fs *c,
				struct bch_inode_info *inode,
				struct page *page, bool check_enospc)
{
	struct bch_page_state *s = bch2_page_state_create(page, 0);
376
	unsigned nr_replicas = inode_nr_replicas(c, inode);
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
	struct disk_reservation disk_res = { 0 };
	unsigned i, disk_res_sectors = 0;
	int ret;

	if (!s)
		return -ENOMEM;

	for (i = 0; i < ARRAY_SIZE(s->s); i++)
		disk_res_sectors += sectors_to_reserve(&s->s[i], nr_replicas);

	if (!disk_res_sectors)
		return 0;

	ret = bch2_disk_reservation_get(c, &disk_res,
					disk_res_sectors, 1,
					!check_enospc
					? BCH_DISK_RESERVATION_NOFAIL
					: 0);
	if (unlikely(ret))
		return ret;

	for (i = 0; i < ARRAY_SIZE(s->s); i++)
		s->s[i].replicas_reserved +=
			sectors_to_reserve(&s->s[i], nr_replicas);

	return 0;
}

405 406 407 408 409 410
struct bch2_page_reservation {
	struct disk_reservation	disk;
	struct quota_res	quota;
};

static void bch2_page_reservation_init(struct bch_fs *c,
411
			struct bch_inode_info *inode,
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
			struct bch2_page_reservation *res)
{
	memset(res, 0, sizeof(*res));

	res->disk.nr_replicas = inode_nr_replicas(c, inode);
}

static void bch2_page_reservation_put(struct bch_fs *c,
			struct bch_inode_info *inode,
			struct bch2_page_reservation *res)
{
	bch2_disk_reservation_put(c, &res->disk);
	bch2_quota_reservation_put(c, inode, &res->quota);
}

static int bch2_page_reservation_get(struct bch_fs *c,
			struct bch_inode_info *inode, struct page *page,
			struct bch2_page_reservation *res,
			unsigned offset, unsigned len, bool check_enospc)
431 432
{
	struct bch_page_state *s = bch2_page_state_create(page, 0);
433
	unsigned i, disk_sectors = 0, quota_sectors = 0;
434
	int ret;
435

436 437
	if (!s)
		return -ENOMEM;
438

439 440
	for (i = round_down(offset, block_bytes(c)) >> 9;
	     i < round_up(offset + len, block_bytes(c)) >> 9;
441 442 443 444 445
	     i++) {
		disk_sectors += sectors_to_reserve(&s->s[i],
						res->disk.nr_replicas);
		quota_sectors += s->s[i].state == SECTOR_UNALLOCATED;
	}
446

447 448 449 450 451 452 453 454 455
	if (disk_sectors) {
		ret = bch2_disk_reservation_add(c, &res->disk,
						disk_sectors,
						!check_enospc
						? BCH_DISK_RESERVATION_NOFAIL
						: 0);
		if (unlikely(ret))
			return ret;
	}
456

457 458 459 460 461 462 463 464 465 466 467 468 469 470
	if (quota_sectors) {
		ret = bch2_quota_reservation_add(c, inode, &res->quota,
						 quota_sectors,
						 check_enospc);
		if (unlikely(ret)) {
			struct disk_reservation tmp = {
				.sectors = disk_sectors
			};

			bch2_disk_reservation_put(c, &tmp);
			res->disk.sectors -= disk_sectors;
			return ret;
		}
	}
471

472
	return 0;
473 474 475 476 477 478
}

static void bch2_clear_page_bits(struct page *page)
{
	struct bch_inode_info *inode = to_bch_ei(page->mapping->host);
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
479
	struct bch_page_state *s = bch2_page_state(page);
480
	struct disk_reservation disk_res = { 0 };
481
	int i, dirty_sectors = 0;
482

483
	if (!s)
484 485
		return;

486 487 488
	EBUG_ON(!PageLocked(page));
	EBUG_ON(PageWriteback(page));

489
	for (i = 0; i < ARRAY_SIZE(s->s); i++) {
490 491 492
		disk_res.sectors += s->s[i].replicas_reserved;
		s->s[i].replicas_reserved = 0;

493 494
		switch (s->s[i].state) {
		case SECTOR_DIRTY:
495
			s->s[i].state = SECTOR_UNALLOCATED;
496 497 498 499 500 501 502
			--dirty_sectors;
			break;
		case SECTOR_DIRTY_RESERVED:
			s->s[i].state = SECTOR_RESERVED;
			break;
		default:
			break;
503 504
		}
	}
505

506 507
	bch2_disk_reservation_put(c, &disk_res);

508
	if (dirty_sectors)
509
		i_sectors_acct(c, inode, NULL, dirty_sectors);
510

511
	bch2_page_state_release(page);
512 513
}

514 515 516 517
static void bch2_set_page_dirty(struct bch_fs *c,
			struct bch_inode_info *inode, struct page *page,
			struct bch2_page_reservation *res,
			unsigned offset, unsigned len)
518
{
519
	struct bch_page_state *s = bch2_page_state(page);
520
	unsigned i, dirty_sectors = 0;
521

522 523
	WARN_ON((u64) page_offset(page) + offset + len >
		round_up((u64) i_size_read(&inode->v), block_bytes(c)));
524

525 526
	spin_lock(&s->lock);

527 528
	for (i = round_down(offset, block_bytes(c)) >> 9;
	     i < round_up(offset + len, block_bytes(c)) >> 9;
529 530 531
	     i++) {
		unsigned sectors = sectors_to_reserve(&s->s[i],
						res->disk.nr_replicas);
532

533 534 535 536 537 538
		/*
		 * This can happen if we race with the error path in
		 * bch2_writepage_io_done():
		 */
		sectors = min_t(unsigned, sectors, res->disk.sectors);

539 540
		s->s[i].replicas_reserved += sectors;
		res->disk.sectors -= sectors;
541

542 543 544
		switch (s->s[i].state) {
		case SECTOR_UNALLOCATED:
			s->s[i].state = SECTOR_DIRTY;
545
			dirty_sectors++;
546 547 548 549 550 551 552
			break;
		case SECTOR_RESERVED:
			s->s[i].state = SECTOR_DIRTY_RESERVED;
			break;
		default:
			break;
		}
553 554
	}

555 556
	spin_unlock(&s->lock);

557
	if (dirty_sectors)
558
		i_sectors_acct(c, inode, &res->quota, dirty_sectors);
559

560 561
	if (!PageDirty(page))
		filemap_dirty_folio(inode->v.i_mapping, page_folio(page));
562 563 564 565 566
}

vm_fault_t bch2_page_fault(struct vm_fault *vmf)
{
	struct file *file = vmf->vma->vm_file;
567 568
	struct address_space *mapping = file->f_mapping;
	struct address_space *fdm = faults_disabled_mapping();
569 570 571
	struct bch_inode_info *inode = file_bch_inode(file);
	int ret;

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
	if (fdm == mapping)
		return VM_FAULT_SIGBUS;

	/* Lock ordering: */
	if (fdm > mapping) {
		struct bch_inode_info *fdm_host = to_bch_ei(fdm->host);

		if (bch2_pagecache_add_tryget(&inode->ei_pagecache_lock))
			goto got_lock;

		bch2_pagecache_block_put(&fdm_host->ei_pagecache_lock);

		bch2_pagecache_add_get(&inode->ei_pagecache_lock);
		bch2_pagecache_add_put(&inode->ei_pagecache_lock);

		bch2_pagecache_block_get(&fdm_host->ei_pagecache_lock);

		/* Signal that lock has been dropped: */
		set_fdm_dropped_locks();
		return VM_FAULT_SIGBUS;
	}

594
	bch2_pagecache_add_get(&inode->ei_pagecache_lock);
595
got_lock:
596 597 598 599 600 601 602 603 604 605 606 607 608
	ret = filemap_fault(vmf);
	bch2_pagecache_add_put(&inode->ei_pagecache_lock);

	return ret;
}

vm_fault_t bch2_page_mkwrite(struct vm_fault *vmf)
{
	struct page *page = vmf->page;
	struct file *file = vmf->vma->vm_file;
	struct bch_inode_info *inode = file_bch_inode(file);
	struct address_space *mapping = file->f_mapping;
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
609
	struct bch2_page_reservation res;
610 611
	unsigned len;
	loff_t isize;
612 613
	int ret = VM_FAULT_LOCKED;

614 615
	bch2_page_reservation_init(c, inode, &res);

616 617 618 619 620 621 622 623 624 625 626 627
	sb_start_pagefault(inode->v.i_sb);
	file_update_time(file);

	/*
	 * Not strictly necessary, but helps avoid dio writes livelocking in
	 * write_invalidate_inode_pages_range() - can drop this if/when we get
	 * a write_invalidate_inode_pages_range() that works without dropping
	 * page lock before invalidating page
	 */
	bch2_pagecache_add_get(&inode->ei_pagecache_lock);

	lock_page(page);
628 629 630
	isize = i_size_read(&inode->v);

	if (page->mapping != mapping || page_offset(page) >= isize) {
631 632 633 634 635
		unlock_page(page);
		ret = VM_FAULT_NOPAGE;
		goto out;
	}

636
	len = min_t(loff_t, PAGE_SIZE, isize - page_offset(page));
637 638

	if (bch2_page_reservation_get(c, inode, page, &res, 0, len, true)) {
639 640 641 642 643
		unlock_page(page);
		ret = VM_FAULT_SIGBUS;
		goto out;
	}

644
	bch2_set_page_dirty(c, inode, page, &res, 0, len);
645 646
	bch2_page_reservation_put(c, inode, &res);

647 648 649 650
	wait_for_stable_page(page);
out:
	bch2_pagecache_add_put(&inode->ei_pagecache_lock);
	sb_end_pagefault(inode->v.i_sb);
651

652 653 654 655 656 657 658 659 660 661 662 663 664
	return ret;
}

void bch2_invalidate_folio(struct folio *folio, size_t offset, size_t length)
{
	if (offset || length < folio_size(folio))
		return;

	bch2_clear_page_bits(&folio->page);
}

bool bch2_release_folio(struct folio *folio, gfp_t gfp_mask)
{
665
	if (folio_test_dirty(folio) || folio_test_writeback(folio))
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
		return false;

	bch2_clear_page_bits(&folio->page);
	return true;
}

/* readpage(s): */

static void bch2_readpages_end_io(struct bio *bio)
{
	struct bvec_iter_all iter;
	struct bio_vec *bv;

	bio_for_each_segment_all(bv, bio, iter) {
		struct page *page = bv->bv_page;

		if (!bio->bi_status) {
			SetPageUptodate(page);
		} else {
			ClearPageUptodate(page);
			SetPageError(page);
		}
		unlock_page(page);
	}

	bio_put(bio);
}

struct readpages_iter {
	struct address_space	*mapping;
	struct page		**pages;
	unsigned		nr_pages;
	unsigned		idx;
	pgoff_t			offset;
};

static int readpages_iter_init(struct readpages_iter *iter,
			       struct readahead_control *ractl)
{
	unsigned i, nr_pages = readahead_count(ractl);

	memset(iter, 0, sizeof(*iter));

	iter->mapping	= ractl->mapping;
	iter->offset	= readahead_index(ractl);
	iter->nr_pages	= nr_pages;

	iter->pages = kmalloc_array(nr_pages, sizeof(struct page *), GFP_NOFS);
	if (!iter->pages)
		return -ENOMEM;

717
	nr_pages = __readahead_batch(ractl, iter->pages, nr_pages);
718
	for (i = 0; i < nr_pages; i++) {
719
		__bch2_page_state_create(iter->pages[i], __GFP_NOFAIL);
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
		put_page(iter->pages[i]);
	}

	return 0;
}

static inline struct page *readpage_iter_next(struct readpages_iter *iter)
{
	if (iter->idx >= iter->nr_pages)
		return NULL;

	EBUG_ON(iter->pages[iter->idx]->index != iter->offset + iter->idx);

	return iter->pages[iter->idx];
}

Kent Overstreet's avatar
Kent Overstreet committed
736 737 738 739 740 741 742 743 744 745 746 747
static bool extent_partial_reads_expensive(struct bkey_s_c k)
{
	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
	struct bch_extent_crc_unpacked crc;
	const union bch_extent_entry *i;

	bkey_for_each_crc(k.k, ptrs, crc, i)
		if (crc.csum_type || crc.compression_type)
			return true;
	return false;
}

748
static void readpage_bio_extend(struct readpages_iter *iter,
Kent Overstreet's avatar
Kent Overstreet committed
749 750
				struct bio *bio,
				unsigned sectors_this_extent,
751 752
				bool get_more)
{
Kent Overstreet's avatar
Kent Overstreet committed
753
	while (bio_sectors(bio) < sectors_this_extent &&
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
	       bio->bi_vcnt < bio->bi_max_vecs) {
		pgoff_t page_offset = bio_end_sector(bio) >> PAGE_SECTOR_SHIFT;
		struct page *page = readpage_iter_next(iter);
		int ret;

		if (page) {
			if (iter->offset + iter->idx != page_offset)
				break;

			iter->idx++;
		} else {
			if (!get_more)
				break;

			page = xa_load(&iter->mapping->i_pages, page_offset);
			if (page && !xa_is_value(page))
				break;

			page = __page_cache_alloc(readahead_gfp_mask(iter->mapping));
			if (!page)
				break;

776 777 778 779
			if (!__bch2_page_state_create(page, 0)) {
				put_page(page);
				break;
			}
780 781 782 783

			ret = add_to_page_cache_lru(page, iter->mapping,
						    page_offset, GFP_NOFS);
			if (ret) {
784
				__bch2_page_state_release(page);
785 786 787 788 789 790 791
				put_page(page);
				break;
			}

			put_page(page);
		}

792
		BUG_ON(!bio_add_page(bio, page, PAGE_SIZE, 0));
793 794 795
	}
}

796 797 798
static void bchfs_read(struct btree_trans *trans,
		       struct bch_read_bio *rbio,
		       subvol_inum inum,
799 800
		       struct readpages_iter *readpages_iter)
{
801
	struct bch_fs *c = trans->c;
802
	struct btree_iter iter;
803
	struct bkey_buf sk;
804 805
	int flags = BCH_READ_RETRY_IF_STALE|
		BCH_READ_MAY_PROMOTE;
806
	u32 snapshot;
Kent Overstreet's avatar
Kent Overstreet committed
807
	int ret = 0;
808 809 810

	rbio->c = c;
	rbio->start_time = local_clock();
811
	rbio->subvol = inum.subvol;
Kent Overstreet's avatar
Kent Overstreet committed
812

813
	bch2_bkey_buf_init(&sk);
Kent Overstreet's avatar
Kent Overstreet committed
814
retry:
815
	bch2_trans_begin(trans);
816
	iter = (struct btree_iter) { NULL };
817

818 819 820 821 822 823 824
	ret = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
	if (ret)
		goto err;

	bch2_trans_iter_init(trans, &iter, BTREE_ID_extents,
			     SPOS(inum.inum, rbio->bio.bi_iter.bi_sector, snapshot),
			     BTREE_ITER_SLOTS|BTREE_ITER_FILTER_SNAPSHOTS);
825 826
	while (1) {
		struct bkey_s_c k;
Kent Overstreet's avatar
Kent Overstreet committed
827
		unsigned bytes, sectors, offset_into_extent;
828
		enum btree_id data_btree = BTREE_ID_extents;
829

830 831 832 833 834 835 836 837 838
		/*
		 * read_extent -> io_time_reset may cause a transaction restart
		 * without returning an error, we need to check for that here:
		 */
		if (!bch2_trans_relock(trans)) {
			ret = -EINTR;
			break;
		}

839 840
		bch2_btree_iter_set_pos(&iter,
				POS(inum.inum, rbio->bio.bi_iter.bi_sector));
841

842
		k = bch2_btree_iter_peek_slot(&iter);
Kent Overstreet's avatar
Kent Overstreet committed
843 844 845
		ret = bkey_err(k);
		if (ret)
			break;
846

847
		offset_into_extent = iter.pos.offset -
848
			bkey_start_offset(k.k);
Kent Overstreet's avatar
Kent Overstreet committed
849 850
		sectors = k.k->size - offset_into_extent;

851
		bch2_bkey_buf_reassemble(&sk, c, k);
852

853
		ret = bch2_read_indirect_extent(trans, &data_btree,
854
					&offset_into_extent, &sk);
Kent Overstreet's avatar
Kent Overstreet committed
855 856 857
		if (ret)
			break;

858 859
		k = bkey_i_to_s_c(sk.k);

Kent Overstreet's avatar
Kent Overstreet committed
860 861 862
		sectors = min(sectors, k.k->size - offset_into_extent);

		bch2_trans_unlock(trans);
863

Kent Overstreet's avatar
Kent Overstreet committed
864 865 866
		if (readpages_iter)
			readpage_bio_extend(readpages_iter, &rbio->bio, sectors,
					    extent_partial_reads_expensive(k));
867

Kent Overstreet's avatar
Kent Overstreet committed
868
		bytes = min(sectors, bio_sectors(&rbio->bio)) << 9;
869
		swap(rbio->bio.bi_iter.bi_size, bytes);
870

871
		if (rbio->bio.bi_iter.bi_size == bytes)
872 873
			flags |= BCH_READ_LAST_FRAGMENT;

874
		bch2_bio_page_state_set(&rbio->bio, k);
875

876
		bch2_read_extent(trans, rbio, iter.pos,
877
				 data_btree, k, offset_into_extent, flags);
878 879

		if (flags & BCH_READ_LAST_FRAGMENT)
Kent Overstreet's avatar
Kent Overstreet committed
880
			break;
881

882 883
		swap(rbio->bio.bi_iter.bi_size, bytes);
		bio_advance(&rbio->bio, bytes);
884 885 886 887

		ret = btree_trans_too_many_iters(trans);
		if (ret)
			break;
888
	}
889 890
err:
	bch2_trans_iter_exit(trans, &iter);
Kent Overstreet's avatar
Kent Overstreet committed
891 892 893 894

	if (ret == -EINTR)
		goto retry;

Kent Overstreet's avatar
Kent Overstreet committed
895
	if (ret) {
896
		bch_err_inum_ratelimited(c, inum.inum,
897 898
				"read error %i from btree lookup", ret);
		rbio->bio.bi_status = BLK_STS_IOERR;
Kent Overstreet's avatar
Kent Overstreet committed
899 900 901
		bio_endio(&rbio->bio);
	}

902
	bch2_bkey_buf_exit(&sk, c);
903 904 905 906 907 908
}

void bch2_readahead(struct readahead_control *ractl)
{
	struct bch_inode_info *inode = to_bch_ei(ractl->mapping->host);
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
909
	struct bch_io_opts opts = io_opts(c, &inode->ei_inode);
910
	struct btree_trans trans;
911 912 913 914 915 916 917
	struct page *page;
	struct readpages_iter readpages_iter;
	int ret;

	ret = readpages_iter_init(&readpages_iter, ractl);
	BUG_ON(ret);

918
	bch2_trans_init(&trans, c, 0, 0);
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936

	bch2_pagecache_add_get(&inode->ei_pagecache_lock);

	while ((page = readpage_iter_next(&readpages_iter))) {
		pgoff_t index = readpages_iter.offset + readpages_iter.idx;
		unsigned n = min_t(unsigned,
				   readpages_iter.nr_pages -
				   readpages_iter.idx,
				   BIO_MAX_VECS);
		struct bch_read_bio *rbio =
			rbio_init(bio_alloc_bioset(NULL, n, REQ_OP_READ,
						   GFP_NOFS, &c->bio_read),
				  opts);

		readpages_iter.idx++;

		rbio->bio.bi_iter.bi_sector = (sector_t) index << PAGE_SECTOR_SHIFT;
		rbio->bio.bi_end_io = bch2_readpages_end_io;
937
		BUG_ON(!bio_add_page(&rbio->bio, page, PAGE_SIZE, 0));
938

939
		bchfs_read(&trans, rbio, inode_inum(inode),
940
			   &readpages_iter);
941 942 943
	}

	bch2_pagecache_add_put(&inode->ei_pagecache_lock);
944 945

	bch2_trans_exit(&trans);
946 947 948 949
	kfree(readpages_iter.pages);
}

static void __bchfs_readpage(struct bch_fs *c, struct bch_read_bio *rbio,
950
			     subvol_inum inum, struct page *page)
951
{
952
	struct btree_trans trans;
953

954
	bch2_page_state_create(page, __GFP_NOFAIL);
955 956

	rbio->bio.bi_opf = REQ_OP_READ|REQ_SYNC;
957 958 959
	rbio->bio.bi_iter.bi_sector =
		(sector_t) page->index << PAGE_SECTOR_SHIFT;
	BUG_ON(!bio_add_page(&rbio->bio, page, PAGE_SIZE, 0));
960

961
	bch2_trans_init(&trans, c, 0, 0);
962
	bchfs_read(&trans, rbio, inum, NULL);
963
	bch2_trans_exit(&trans);
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
}

static void bch2_read_single_page_end_io(struct bio *bio)
{
	complete(bio->bi_private);
}

static int bch2_read_single_page(struct page *page,
				 struct address_space *mapping)
{
	struct bch_inode_info *inode = to_bch_ei(mapping->host);
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
	struct bch_read_bio *rbio;
	int ret;
	DECLARE_COMPLETION_ONSTACK(done);

	rbio = rbio_init(bio_alloc_bioset(NULL, 1, REQ_OP_READ, GFP_NOFS, &c->bio_read),
981
			 io_opts(c, &inode->ei_inode));
982 983 984
	rbio->bio.bi_private = &done;
	rbio->bio.bi_end_io = bch2_read_single_page_end_io;

985
	__bchfs_readpage(c, rbio, inode_inum(inode), page);
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
	wait_for_completion(&done);

	ret = blk_status_to_errno(rbio->bio.bi_status);
	bio_put(&rbio->bio);

	if (ret < 0)
		return ret;

	SetPageUptodate(page);
	return 0;
}

int bch2_read_folio(struct file *file, struct folio *folio)
{
	struct page *page = &folio->page;
	int ret;

	ret = bch2_read_single_page(page, page->mapping);
	folio_unlock(folio);
	return ret;
}

/* writepages: */

struct bch_writepage_state {
	struct bch_writepage_io	*io;
	struct bch_io_opts	opts;
};

static inline struct bch_writepage_state bch_writepage_state_init(struct bch_fs *c,
								  struct bch_inode_info *inode)
{
1018 1019 1020
	return (struct bch_writepage_state) {
		.opts = io_opts(c, &inode->ei_inode)
	};
1021 1022
}

1023
static void bch2_writepage_io_done(struct bch_write_op *op)
1024
{
1025 1026
	struct bch_writepage_io *io =
		container_of(op, struct bch_writepage_io, op);
1027 1028
	struct bch_fs *c = io->op.c;
	struct bio *bio = &io->op.wbio.bio;
1029 1030
	struct bvec_iter_all iter;
	struct bio_vec *bvec;
1031
	unsigned i;
1032

1033 1034
	up(&io->op.c->io_in_flight);

1035
	if (io->op.error) {
1036 1037
		set_bit(EI_INODE_ERROR, &io->inode->ei_flags);

1038
		bio_for_each_segment_all(bvec, bio, iter) {
1039 1040
			struct bch_page_state *s;

1041
			SetPageError(bvec->bv_page);
1042
			mapping_set_error(bvec->bv_page->mapping, -EIO);
1043

1044 1045
			s = __bch2_page_state(bvec->bv_page);
			spin_lock(&s->lock);
1046 1047
			for (i = 0; i < PAGE_SECTORS; i++)
				s->s[i].nr_replicas = 0;
1048
			spin_unlock(&s->lock);
1049
		}
1050 1051
	}

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
	if (io->op.flags & BCH_WRITE_WROTE_DATA_INLINE) {
		bio_for_each_segment_all(bvec, bio, iter) {
			struct bch_page_state *s;

			s = __bch2_page_state(bvec->bv_page);
			spin_lock(&s->lock);
			for (i = 0; i < PAGE_SECTORS; i++)
				s->s[i].nr_replicas = 0;
			spin_unlock(&s->lock);
		}
	}

1064 1065 1066 1067
	/*
	 * racing with fallocate can cause us to add fewer sectors than
	 * expected - but we shouldn't add more sectors than expected:
	 */
1068
	BUG_ON(io->op.i_sectors_delta > 0);
1069 1070 1071 1072 1073

	/*
	 * (error (due to going RO) halfway through a page can screw that up
	 * slightly)
	 * XXX wtf?
1074
	   BUG_ON(io->op.op.i_sectors_delta >= PAGE_SECTORS);
1075 1076 1077 1078 1079 1080
	 */

	/*
	 * PageWriteback is effectively our ref on the inode - fixup i_blocks
	 * before calling end_page_writeback:
	 */
1081
	i_sectors_acct(c, io->inode, NULL, io->op.i_sectors_delta);
1082

1083 1084 1085 1086 1087 1088
	bio_for_each_segment_all(bvec, bio, iter) {
		struct bch_page_state *s = __bch2_page_state(bvec->bv_page);

		if (atomic_dec_and_test(&s->write_count))
			end_page_writeback(bvec->bv_page);
	}
1089

1090
	bio_put(&io->op.wbio.bio);
1091 1092 1093 1094 1095 1096
}

static void bch2_writepage_do_io(struct bch_writepage_state *w)
{
	struct bch_writepage_io *io = w->io;

1097 1098
	down(&io->op.c->io_in_flight);

1099
	w->io = NULL;
1100
	closure_call(&io->op.cl, bch2_write, NULL, NULL);
1101 1102 1103 1104 1105 1106 1107
}

/*
 * Get a bch_writepage_io and add @page to it - appending to an existing one if
 * possible, else allocating a new one:
 */
static void bch2_writepage_io_alloc(struct bch_fs *c,
1108
				    struct writeback_control *wbc,
1109 1110
				    struct bch_writepage_state *w,
				    struct bch_inode_info *inode,
1111
				    u64 sector,
1112 1113 1114 1115 1116 1117 1118 1119
				    unsigned nr_replicas)
{
	struct bch_write_op *op;

	w->io = container_of(bio_alloc_bioset(NULL, BIO_MAX_VECS,
					      REQ_OP_WRITE,
					      GFP_NOFS,
					      &c->writepage_bioset),
1120
			     struct bch_writepage_io, op.wbio.bio);
1121

1122 1123 1124 1125
	w->io->inode		= inode;
	op			= &w->io->op;
	bch2_write_op_init(op, c, w->opts);
	op->target		= w->opts.foreground_target;
1126 1127 1128
	op->nr_replicas		= nr_replicas;
	op->res.nr_replicas	= nr_replicas;
	op->write_point		= writepoint_hashed(inode->ei_last_dirtied);
1129
	op->subvol		= inode->ei_subvol;
1130
	op->pos			= POS(inode->v.i_ino, sector);
1131
	op->end_io		= bch2_writepage_io_done;
1132
	op->wbio.bio.bi_iter.bi_sector = sector;
1133
	op->wbio.bio.bi_opf	= wbc_to_write_flags(wbc);
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
}

static int __bch2_writepage(struct folio *folio,
			    struct writeback_control *wbc,
			    void *data)
{
	struct page *page = &folio->page;
	struct bch_inode_info *inode = to_bch_ei(page->mapping->host);
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
	struct bch_writepage_state *w = data;
1144 1145
	struct bch_page_state *s, orig;
	unsigned i, offset, nr_replicas_this_write = U32_MAX;
1146 1147
	loff_t i_size = i_size_read(&inode->v);
	pgoff_t end_index = i_size >> PAGE_SHIFT;
1148
	int ret;
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171

	EBUG_ON(!PageUptodate(page));

	/* Is the page fully inside i_size? */
	if (page->index < end_index)
		goto do_io;

	/* Is the page fully outside i_size? (truncate in progress) */
	offset = i_size & (PAGE_SIZE - 1);
	if (page->index > end_index || !offset) {
		unlock_page(page);
		return 0;
	}

	/*
	 * The page straddles i_size.  It must be zeroed out on each and every
	 * writepage invocation because it may be mmapped.  "A file is mapped
	 * in multiples of the page size.  For a file that is not a multiple of
	 * the  page size, the remaining memory is zeroed when mapped, and
	 * writes to that region are not written out to the file."
	 */
	zero_user_segment(page, offset, PAGE_SIZE);
do_io:
1172
	s = bch2_page_state_create(page, __GFP_NOFAIL);
1173

1174 1175 1176 1177 1178
	/*
	 * Things get really hairy with errors during writeback:
	 */
	ret = bch2_get_page_disk_reservation(c, inode, page, false);
	BUG_ON(ret);
1179

1180
	/* Before unlocking the page, get copy of reservations: */
1181
	spin_lock(&s->lock);
1182
	orig = *s;
1183
	spin_unlock(&s->lock);
1184 1185

	for (i = 0; i < PAGE_SECTORS; i++) {
1186
		if (s->s[i].state < SECTOR_DIRTY)
1187 1188
			continue;

1189 1190 1191 1192
		nr_replicas_this_write =
			min_t(unsigned, nr_replicas_this_write,
			      s->s[i].nr_replicas +
			      s->s[i].replicas_reserved);
1193
	}
1194

1195
	for (i = 0; i < PAGE_SECTORS; i++) {
1196
		if (s->s[i].state < SECTOR_DIRTY)
1197 1198
			continue;

1199 1200
		s->s[i].nr_replicas = w->opts.compression
			? 0 : nr_replicas_this_write;
1201

1202 1203 1204
		s->s[i].replicas_reserved = 0;
		s->s[i].state = SECTOR_ALLOCATED;
	}
1205

1206 1207 1208
	BUG_ON(atomic_read(&s->write_count));
	atomic_set(&s->write_count, 1);

1209 1210
	BUG_ON(PageWriteback(page));
	set_page_writeback(page);
1211

1212 1213
	unlock_page(page);

1214 1215
	offset = 0;
	while (1) {
1216
		unsigned sectors = 0, dirty_sectors = 0, reserved_sectors = 0;
1217 1218 1219
		u64 sector;

		while (offset < PAGE_SECTORS &&
1220
		       orig.s[offset].state < SECTOR_DIRTY)
1221
			offset++;
1222

1223 1224 1225 1226
		if (offset == PAGE_SECTORS)
			break;

		while (offset + sectors < PAGE_SECTORS &&
1227 1228 1229
		       orig.s[offset + sectors].state >= SECTOR_DIRTY) {
			reserved_sectors += orig.s[offset + sectors].replicas_reserved;
			dirty_sectors += orig.s[offset + sectors].state == SECTOR_DIRTY;
1230 1231
			sectors++;
		}
1232 1233 1234
		BUG_ON(!sectors);

		sector = ((u64) page->index << PAGE_SECTOR_SHIFT) + offset;
1235 1236

		if (w->io &&
1237 1238
		    (w->io->op.res.nr_replicas != nr_replicas_this_write ||
		     bio_full(&w->io->op.wbio.bio, PAGE_SIZE) ||
1239 1240
		     w->io->op.wbio.bio.bi_iter.bi_size + (sectors << 9) >=
		     (BIO_MAX_VECS * PAGE_SIZE) ||
1241
		     bio_end_sector(&w->io->op.wbio.bio) != sector))
1242
			bch2_writepage_do_io(w);
1243

1244
		if (!w->io)
1245
			bch2_writepage_io_alloc(c, wbc, w, inode, sector,
1246
						nr_replicas_this_write);
1247

1248 1249
		atomic_inc(&s->write_count);

1250 1251
		BUG_ON(inode != w->io->inode);
		BUG_ON(!bio_add_page(&w->io->op.wbio.bio, page,
1252 1253
				     sectors << 9, offset << 9));

1254
		/* Check for writing past i_size: */
1255
		WARN_ON((bio_end_sector(&w->io->op.wbio.bio) << 9) >
1256
			round_up(i_size, block_bytes(c)));
1257

1258 1259
		w->io->op.res.sectors += reserved_sectors;
		w->io->op.i_sectors_delta -= dirty_sectors;
1260 1261 1262 1263
		w->io->op.new_i_size = i_size;

		offset += sectors;
	}
1264

1265 1266
	if (atomic_dec_and_test(&s->write_count))
		end_page_writeback(page);
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308

	return 0;
}

int bch2_writepages(struct address_space *mapping, struct writeback_control *wbc)
{
	struct bch_fs *c = mapping->host->i_sb->s_fs_info;
	struct bch_writepage_state w =
		bch_writepage_state_init(c, to_bch_ei(mapping->host));
	struct blk_plug plug;
	int ret;

	blk_start_plug(&plug);
	ret = write_cache_pages(mapping, wbc, __bch2_writepage, &w);
	if (w.io)
		bch2_writepage_do_io(&w);
	blk_finish_plug(&plug);
	return ret;
}

int bch2_writepage(struct page *page, struct writeback_control *wbc)
{
	struct bch_fs *c = page->mapping->host->i_sb->s_fs_info;
	struct bch_writepage_state w =
		bch_writepage_state_init(c, to_bch_ei(page->mapping->host));
	int ret;

	ret = __bch2_writepage(page_folio(page), wbc, &w);
	if (w.io)
		bch2_writepage_do_io(&w);

	return ret;
}

/* buffered writes: */

int bch2_write_begin(struct file *file, struct address_space *mapping,
		     loff_t pos, unsigned len,
		     struct page **pagep, void **fsdata)
{
	struct bch_inode_info *inode = to_bch_ei(mapping->host);
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
1309
	struct bch2_page_reservation *res;
1310 1311 1312 1313 1314
	pgoff_t index = pos >> PAGE_SHIFT;
	unsigned offset = pos & (PAGE_SIZE - 1);
	struct page *page;
	int ret = -ENOMEM;

1315 1316 1317 1318 1319 1320
	res = kmalloc(sizeof(*res), GFP_KERNEL);
	if (!res)
		return -ENOMEM;

	bch2_page_reservation_init(c, inode, res);
	*fsdata = res;
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350

	bch2_pagecache_add_get(&inode->ei_pagecache_lock);

	page = grab_cache_page_write_begin(mapping, index);
	if (!page)
		goto err_unlock;

	if (PageUptodate(page))
		goto out;

	/* If we're writing entire page, don't need to read it in first: */
	if (len == PAGE_SIZE)
		goto out;

	if (!offset && pos + len >= inode->v.i_size) {
		zero_user_segment(page, len, PAGE_SIZE);
		flush_dcache_page(page);
		goto out;
	}

	if (index > inode->v.i_size >> PAGE_SHIFT) {
		zero_user_segments(page, 0, offset, offset + len, PAGE_SIZE);
		flush_dcache_page(page);
		goto out;
	}
readpage:
	ret = bch2_read_single_page(page, mapping);
	if (ret)
		goto err;
out:
1351 1352
	ret = bch2_page_reservation_get(c, inode, page, res,
					offset, len, true);
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
	if (ret) {
		if (!PageUptodate(page)) {
			/*
			 * If the page hasn't been read in, we won't know if we
			 * actually need a reservation - we don't actually need
			 * to read here, we just need to check if the page is
			 * fully backed by uncompressed data:
			 */
			goto readpage;
		}

		goto err;
	}

	*pagep = page;
	return 0;
err:
	unlock_page(page);
	put_page(page);
	*pagep = NULL;
err_unlock:
	bch2_pagecache_add_put(&inode->ei_pagecache_lock);
1375 1376
	kfree(res);
	*fsdata = NULL;
1377 1378 1379 1380 1381 1382 1383 1384 1385
	return ret;
}

int bch2_write_end(struct file *file, struct address_space *mapping,
		   loff_t pos, unsigned len, unsigned copied,
		   struct page *page, void *fsdata)
{
	struct bch_inode_info *inode = to_bch_ei(mapping->host);
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
1386 1387
	struct bch2_page_reservation *res = fsdata;
	unsigned offset = pos & (PAGE_SIZE - 1);
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409

	lockdep_assert_held(&inode->v.i_rwsem);

	if (unlikely(copied < len && !PageUptodate(page))) {
		/*
		 * The page needs to be read in, but that would destroy
		 * our partial write - simplest thing is to just force
		 * userspace to redo the write:
		 */
		zero_user(page, 0, PAGE_SIZE);
		flush_dcache_page(page);
		copied = 0;
	}

	spin_lock(&inode->v.i_lock);
	if (pos + copied > inode->v.i_size)
		i_size_write(&inode->v, pos + copied);
	spin_unlock(&inode->v.i_lock);

	if (copied) {
		if (!PageUptodate(page))
			SetPageUptodate(page);
1410 1411

		bch2_set_page_dirty(c, inode, page, res, offset, copied);
1412 1413 1414 1415 1416 1417 1418 1419

		inode->ei_last_dirtied = (unsigned long) current;
	}

	unlock_page(page);
	put_page(page);
	bch2_pagecache_add_put(&inode->ei_pagecache_lock);

1420 1421 1422
	bch2_page_reservation_put(c, inode, res);
	kfree(res);

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
	return copied;
}

#define WRITE_BATCH_PAGES	32

static int __bch2_buffered_write(struct bch_inode_info *inode,
				 struct address_space *mapping,
				 struct iov_iter *iter,
				 loff_t pos, unsigned len)
{
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
	struct page *pages[WRITE_BATCH_PAGES];
1435
	struct bch2_page_reservation res;
1436 1437 1438
	unsigned long index = pos >> PAGE_SHIFT;
	unsigned offset = pos & (PAGE_SIZE - 1);
	unsigned nr_pages = DIV_ROUND_UP(offset + len, PAGE_SIZE);
1439 1440
	unsigned i, reserved = 0, set_dirty = 0;
	unsigned copied = 0, nr_pages_copied = 0;
1441 1442 1443 1444 1445
	int ret = 0;

	BUG_ON(!len);
	BUG_ON(nr_pages > ARRAY_SIZE(pages));

1446 1447
	bch2_page_reservation_init(c, inode, &res);

1448 1449 1450 1451
	for (i = 0; i < nr_pages; i++) {
		pages[i] = grab_cache_page_write_begin(mapping, index + i);
		if (!pages[i]) {
			nr_pages = i;
1452 1453 1454 1455 1456 1457 1458
			if (!i) {
				ret = -ENOMEM;
				goto out;
			}
			len = min_t(unsigned, len,
				    nr_pages * PAGE_SIZE - offset);
			break;
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
		}
	}

	if (offset && !PageUptodate(pages[0])) {
		ret = bch2_read_single_page(pages[0], mapping);
		if (ret)
			goto out;
	}

	if ((pos + len) & (PAGE_SIZE - 1) &&
	    !PageUptodate(pages[nr_pages - 1])) {
		if ((index + nr_pages - 1) << PAGE_SHIFT >= inode->v.i_size) {
			zero_user(pages[nr_pages - 1], 0, PAGE_SIZE);
		} else {
			ret = bch2_read_single_page(pages[nr_pages - 1], mapping);
			if (ret)
				goto out;
		}
	}

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
	while (reserved < len) {
		struct page *page = pages[(offset + reserved) >> PAGE_SHIFT];
		unsigned pg_offset = (offset + reserved) & (PAGE_SIZE - 1);
		unsigned pg_len = min_t(unsigned, len - reserved,
					PAGE_SIZE - pg_offset);
retry_reservation:
		ret = bch2_page_reservation_get(c, inode, page, &res,
						pg_offset, pg_len, true);

		if (ret && !PageUptodate(page)) {
			ret = bch2_read_single_page(page, mapping);
			if (!ret)
				goto retry_reservation;
1492 1493 1494 1495
		}

		if (ret)
			goto out;
1496 1497

		reserved += pg_len;
1498 1499 1500 1501 1502 1503 1504 1505 1506
	}

	if (mapping_writably_mapped(mapping))
		for (i = 0; i < nr_pages; i++)
			flush_dcache_page(pages[i]);

	while (copied < len) {
		struct page *page = pages[(offset + copied) >> PAGE_SHIFT];
		unsigned pg_offset = (offset + copied) & (PAGE_SIZE - 1);
1507 1508
		unsigned pg_len = min_t(unsigned, len - copied,
					PAGE_SIZE - pg_offset);
1509
		unsigned pg_copied = copy_page_from_iter_atomic(page,
1510 1511 1512 1513
						pg_offset, pg_len, iter);

		if (!pg_copied)
			break;
1514

1515 1516 1517 1518 1519 1520 1521
		if (!PageUptodate(page) &&
		    pg_copied != PAGE_SIZE &&
		    pos + copied + pg_copied < inode->v.i_size) {
			zero_user(page, 0, PAGE_SIZE);
			break;
		}

1522 1523
		flush_dcache_page(page);
		copied += pg_copied;
1524 1525 1526

		if (pg_copied != pg_len)
			break;
1527 1528 1529 1530 1531
	}

	if (!copied)
		goto out;

1532 1533 1534 1535 1536
	spin_lock(&inode->v.i_lock);
	if (pos + copied > inode->v.i_size)
		i_size_write(&inode->v, pos + copied);
	spin_unlock(&inode->v.i_lock);

1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
	while (set_dirty < copied) {
		struct page *page = pages[(offset + set_dirty) >> PAGE_SHIFT];
		unsigned pg_offset = (offset + set_dirty) & (PAGE_SIZE - 1);
		unsigned pg_len = min_t(unsigned, copied - set_dirty,
					PAGE_SIZE - pg_offset);

		if (!PageUptodate(page))
			SetPageUptodate(page);

		bch2_set_page_dirty(c, inode, page, &res, pg_offset, pg_len);
		unlock_page(page);
		put_page(page);

		set_dirty += pg_len;
	}
1552 1553 1554

	nr_pages_copied = DIV_ROUND_UP(offset + copied, PAGE_SIZE);
	inode->ei_last_dirtied = (unsigned long) current;
1555
out:
1556 1557 1558 1559 1560
	for (i = nr_pages_copied; i < nr_pages; i++) {
		unlock_page(pages[i]);
		put_page(pages[i]);
	}

1561 1562
	bch2_page_reservation_put(c, inode, &res);

1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
	return copied ?: ret;
}

static ssize_t bch2_buffered_write(struct kiocb *iocb, struct iov_iter *iter)
{
	struct file *file = iocb->ki_filp;
	struct address_space *mapping = file->f_mapping;
	struct bch_inode_info *inode = file_bch_inode(file);
	loff_t pos = iocb->ki_pos;
	ssize_t written = 0;
	int ret = 0;

	bch2_pagecache_add_get(&inode->ei_pagecache_lock);

	do {
		unsigned offset = pos & (PAGE_SIZE - 1);
		unsigned bytes = min_t(unsigned long, iov_iter_count(iter),
			      PAGE_SIZE * WRITE_BATCH_PAGES - offset);
again:
		/*
		 * Bring in the user page that we will copy from _first_.
		 * Otherwise there's a nasty deadlock on copying from the
		 * same page as we're writing to, without it being marked
		 * up-to-date.
		 *
		 * Not only is this an optimisation, but it is also required
		 * to check that the address is actually valid, when atomic
		 * usercopies are used, below.
		 */
		if (unlikely(fault_in_iov_iter_readable(iter, bytes))) {
			bytes = min_t(unsigned long, iov_iter_count(iter),
				      PAGE_SIZE - offset);

			if (unlikely(fault_in_iov_iter_readable(iter, bytes))) {
				ret = -EFAULT;
				break;
			}
		}

		if (unlikely(fatal_signal_pending(current))) {
			ret = -EINTR;
			break;
		}

		ret = __bch2_buffered_write(inode, mapping, iter, pos, bytes);
		if (unlikely(ret < 0))
			break;

		cond_resched();

		if (unlikely(ret == 0)) {
			/*
			 * If we were unable to copy any data at all, we must
			 * fall back to a single segment length write.
			 *
			 * If we didn't fallback here, we could livelock
			 * because not all segments in the iov can be copied at
			 * once without a pagefault.
			 */
			bytes = min_t(unsigned long, PAGE_SIZE - offset,
				      iov_iter_single_seg_count(iter));
			goto again;
		}
		pos += ret;
		written += ret;
1628
		ret = 0;
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639

		balance_dirty_pages_ratelimited(mapping);
	} while (iov_iter_count(iter));

	bch2_pagecache_add_put(&inode->ei_pagecache_lock);

	return written ? written : ret;
}

/* O_DIRECT reads */

1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
static void bio_check_or_release(struct bio *bio, bool check_dirty)
{
	if (check_dirty) {
		bio_check_pages_dirty(bio);
	} else {
		bio_release_pages(bio, false);
		bio_put(bio);
	}
}

1650 1651 1652 1653 1654
static void bch2_dio_read_complete(struct closure *cl)
{
	struct dio_read *dio = container_of(cl, struct dio_read, cl);

	dio->req->ki_complete(dio->req, dio->ret);
1655
	bio_check_or_release(&dio->rbio.bio, dio->should_dirty);
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
}

static void bch2_direct_IO_read_endio(struct bio *bio)
{
	struct dio_read *dio = bio->bi_private;

	if (bio->bi_status)
		dio->ret = blk_status_to_errno(bio->bi_status);

	closure_put(&dio->cl);
}

static void bch2_direct_IO_read_split_endio(struct bio *bio)
{
1670 1671 1672
	struct dio_read *dio = bio->bi_private;
	bool should_dirty = dio->should_dirty;

1673
	bch2_direct_IO_read_endio(bio);
1674
	bio_check_or_release(bio, should_dirty);
1675 1676 1677 1678 1679 1680 1681
}

static int bch2_direct_IO_read(struct kiocb *req, struct iov_iter *iter)
{
	struct file *file = req->ki_filp;
	struct bch_inode_info *inode = file_bch_inode(file);
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
1682
	struct bch_io_opts opts = io_opts(c, &inode->ei_inode);
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 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
	struct dio_read *dio;
	struct bio *bio;
	loff_t offset = req->ki_pos;
	bool sync = is_sync_kiocb(req);
	size_t shorten;
	ssize_t ret;

	if ((offset|iter->count) & (block_bytes(c) - 1))
		return -EINVAL;

	ret = min_t(loff_t, iter->count,
		    max_t(loff_t, 0, i_size_read(&inode->v) - offset));

	if (!ret)
		return ret;

	shorten = iov_iter_count(iter) - round_up(ret, block_bytes(c));
	iter->count -= shorten;

	bio = bio_alloc_bioset(NULL,
			       iov_iter_npages(iter, BIO_MAX_VECS),
			       REQ_OP_READ,
			       GFP_KERNEL,
			       &c->dio_read_bioset);

	bio->bi_end_io = bch2_direct_IO_read_endio;

	dio = container_of(bio, struct dio_read, rbio.bio);
	closure_init(&dio->cl, NULL);

	/*
	 * this is a _really_ horrible hack just to avoid an atomic sub at the
	 * end:
	 */
	if (!sync) {
		set_closure_fn(&dio->cl, bch2_dio_read_complete, NULL);
		atomic_set(&dio->cl.remaining,
			   CLOSURE_REMAINING_INITIALIZER -
			   CLOSURE_RUNNING +
			   CLOSURE_DESTRUCTOR);
	} else {
		atomic_set(&dio->cl.remaining,
			   CLOSURE_REMAINING_INITIALIZER + 1);
	}

	dio->req	= req;
	dio->ret	= ret;
1730 1731 1732 1733 1734 1735
	/*
	 * This is one of the sketchier things I've encountered: we have to skip
	 * the dirtying of requests that are internal from the kernel (i.e. from
	 * loopback), because we'll deadlock on page_lock.
	 */
	dio->should_dirty = iter_is_iovec(iter);
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758

	goto start;
	while (iter->count) {
		bio = bio_alloc_bioset(NULL,
				       iov_iter_npages(iter, BIO_MAX_VECS),
				       REQ_OP_READ,
				       GFP_KERNEL,
				       &c->bio_read);
		bio->bi_end_io		= bch2_direct_IO_read_split_endio;
start:
		bio->bi_opf		= REQ_OP_READ|REQ_SYNC;
		bio->bi_iter.bi_sector	= offset >> 9;
		bio->bi_private		= dio;

		ret = bio_iov_iter_get_pages(bio, iter);
		if (ret < 0) {
			/* XXX: fault inject this path */
			bio->bi_status = BLK_STS_RESOURCE;
			bio_endio(bio);
			break;
		}

		offset += bio->bi_iter.bi_size;
1759 1760 1761

		if (dio->should_dirty)
			bio_set_pages_dirty(bio);
1762 1763 1764 1765

		if (iter->count)
			closure_get(&dio->cl);

1766
		bch2_read(c, rbio_init(bio, opts), inode_inum(inode));
1767 1768 1769 1770 1771 1772 1773 1774
	}

	iter->count += shorten;

	if (sync) {
		closure_sync(&dio->cl);
		closure_debug_destroy(&dio->cl);
		ret = dio->ret;
1775
		bio_check_or_release(&dio->rbio.bio, dio->should_dirty);
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
		return ret;
	} else {
		return -EIOCBQUEUED;
	}
}

ssize_t bch2_read_iter(struct kiocb *iocb, struct iov_iter *iter)
{
	struct file *file = iocb->ki_filp;
	struct bch_inode_info *inode = file_bch_inode(file);
	struct address_space *mapping = file->f_mapping;
	size_t count = iov_iter_count(iter);
	ssize_t ret;

	if (!count)
		return 0; /* skip atime */

	if (iocb->ki_flags & IOCB_DIRECT) {
		struct blk_plug plug;

1796 1797 1798 1799 1800 1801 1802
		if (unlikely(mapping->nrpages)) {
			ret = filemap_write_and_wait_range(mapping,
						iocb->ki_pos,
						iocb->ki_pos + count - 1);
			if (ret < 0)
				return ret;
		}
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822

		file_accessed(file);

		blk_start_plug(&plug);
		ret = bch2_direct_IO_read(iocb, iter);
		blk_finish_plug(&plug);

		if (ret >= 0)
			iocb->ki_pos += ret;
	} else {
		bch2_pagecache_add_get(&inode->ei_pagecache_lock);
		ret = generic_file_read_iter(iocb, iter);
		bch2_pagecache_add_put(&inode->ei_pagecache_lock);
	}

	return ret;
}

/* O_DIRECT writes */

1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
static bool bch2_check_range_allocated(struct bch_fs *c, subvol_inum inum,
				       u64 offset, u64 size,
				       unsigned nr_replicas, bool compressed)
{
	struct btree_trans trans;
	struct btree_iter iter;
	struct bkey_s_c k;
	u64 end = offset + size;
	u32 snapshot;
	bool ret = true;
	int err;

	bch2_trans_init(&trans, c, 0, 0);
retry:
	bch2_trans_begin(&trans);

	err = bch2_subvolume_get_snapshot(&trans, inum.subvol, &snapshot);
	if (err)
		goto err;

1843
	for_each_btree_key_norestart(&trans, iter, BTREE_ID_extents,
1844 1845 1846 1847 1848
			   SPOS(inum.inum, offset, snapshot),
			   BTREE_ITER_SLOTS, k, err) {
		if (bkey_cmp(bkey_start_pos(k.k), POS(inum.inum, end)) >= 0)
			break;

1849 1850
		if (k.k->p.snapshot != snapshot ||
		    nr_replicas > bch2_bkey_replicas(c, k) ||
1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
		    (!compressed && bch2_bkey_sectors_compressed(k))) {
			ret = false;
			break;
		}
	}

	offset = iter.pos.offset;
	bch2_trans_iter_exit(&trans, &iter);
err:
	if (err == -EINTR)
		goto retry;
	bch2_trans_exit(&trans);

	return err ? false : ret;
}

1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
/*
 * We're going to return -EIOCBQUEUED, but we haven't finished consuming the
 * iov_iter yet, so we need to stash a copy of the iovec: it might be on the
 * caller's stack, we're not guaranteed that it will live for the duration of
 * the IO:
 */
static noinline int bch2_dio_write_copy_iov(struct dio_write *dio)
{
	struct iovec *iov = dio->inline_vecs;

	/*
	 * iov_iter has a single embedded iovec - nothing to do:
	 */
	if (iter_is_ubuf(&dio->iter))
		return 0;

	/*
	 * We don't currently handle non-iovec iov_iters here - return an error,
	 * and we'll fall back to doing the IO synchronously:
	 */
	if (!iter_is_iovec(&dio->iter))
		return -1;

	if (dio->iter.nr_segs > ARRAY_SIZE(dio->inline_vecs)) {
		iov = kmalloc_array(dio->iter.nr_segs, sizeof(*iov),
				    GFP_KERNEL);
		if (unlikely(!iov))
			return -ENOMEM;

		dio->free_iov = true;
	}

	memcpy(iov, dio->iter.__iov, dio->iter.nr_segs * sizeof(*iov));
	dio->iter.__iov = iov;
	return 0;
}

1904 1905
static void bch2_dio_write_loop_async(struct bch_write_op *);

1906 1907
static long bch2_dio_write_loop(struct dio_write *dio)
{
Kent Overstreet's avatar
Kent Overstreet committed
1908
	bool kthread = (current->flags & PF_KTHREAD) != 0;
1909 1910
	struct kiocb *req = dio->req;
	struct address_space *mapping = req->ki_filp->f_mapping;
1911
	struct bch_inode_info *inode = file_bch_inode(req->ki_filp);
1912
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
1913
	struct bio *bio = &dio->op.wbio.bio;
1914 1915
	unsigned unaligned, iter_count;
	bool sync = dio->sync, dropped_locks;
1916 1917 1918 1919 1920 1921
	long ret;

	if (dio->loop)
		goto loop;

	while (1) {
1922 1923
		iter_count = dio->iter.count;

Kent Overstreet's avatar
Kent Overstreet committed
1924 1925
		if (kthread)
			kthread_use_mm(dio->mm);
1926 1927 1928 1929 1930
		BUG_ON(current->faults_disabled_mapping);
		current->faults_disabled_mapping = mapping;

		ret = bio_iov_iter_get_pages(bio, &dio->iter);

1931 1932
		dropped_locks = fdm_dropped_locks();

1933
		current->faults_disabled_mapping = NULL;
Kent Overstreet's avatar
Kent Overstreet committed
1934 1935
		if (kthread)
			kthread_unuse_mm(dio->mm);
1936

1937 1938 1939 1940 1941 1942 1943 1944
		/*
		 * If the fault handler returned an error but also signalled
		 * that it dropped & retook ei_pagecache_lock, we just need to
		 * re-shoot down the page cache and retry:
		 */
		if (dropped_locks && ret)
			ret = 0;

1945 1946 1947
		if (unlikely(ret < 0))
			goto err;

1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
		if (unlikely(dropped_locks)) {
			ret = write_invalidate_inode_pages_range(mapping,
					req->ki_pos,
					req->ki_pos + iter_count - 1);
			if (unlikely(ret))
				goto err;

			if (!bio->bi_iter.bi_size)
				continue;
		}

1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
		unaligned = bio->bi_iter.bi_size & (block_bytes(c) - 1);
		bio->bi_iter.bi_size -= unaligned;
		iov_iter_revert(&dio->iter, unaligned);

		if (!bio->bi_iter.bi_size) {
			/*
			 * bio_iov_iter_get_pages was only able to get <
			 * blocksize worth of pages:
			 */
			ret = -EFAULT;
			goto err;
		}

1972 1973 1974 1975 1976
		bch2_write_op_init(&dio->op, c, io_opts(c, &inode->ei_inode));
		dio->op.end_io		= bch2_dio_write_loop_async;
		dio->op.target		= dio->op.opts.foreground_target;
		dio->op.write_point	= writepoint_hashed((unsigned long) current);
		dio->op.nr_replicas	= dio->op.opts.data_replicas;
1977
		dio->op.subvol		= inode->ei_subvol;
1978 1979 1980 1981 1982
		dio->op.pos		= POS(inode->v.i_ino, (u64) req->ki_pos >> 9);

		if ((req->ki_flags & IOCB_DSYNC) &&
		    !c->opts.journal_flush_disabled)
			dio->op.flags |= BCH_WRITE_FLUSH;
1983
		dio->op.flags |= BCH_WRITE_CHECK_ENOSPC;
1984 1985 1986 1987

		ret = bch2_disk_reservation_get(c, &dio->op.res, bio_sectors(bio),
						dio->op.opts.data_replicas, 0);
		if (unlikely(ret) &&
1988 1989
		    !bch2_check_range_allocated(c, inode_inum(inode),
				dio->op.pos.offset, bio_sectors(bio),
1990 1991
				dio->op.opts.data_replicas,
				dio->op.opts.compression != 0))
1992
			goto err;
1993 1994 1995 1996 1997

		task_io_account_write(bio->bi_iter.bi_size);

		if (!dio->sync && !dio->loop && dio->iter.count) {
			if (bch2_dio_write_copy_iov(dio)) {
1998
				dio->sync = sync = true;
1999
				goto do_io;
2000 2001
			}
		}
2002
do_io:
2003
		dio->loop = true;
2004
		closure_call(&dio->op.cl, bch2_write, NULL, NULL);
2005

2006
		if (sync)
2007 2008
			wait_for_completion(&dio->done);
		else
2009 2010
			return -EIOCBQUEUED;
loop:
2011 2012
		i_sectors_acct(c, inode, &dio->quota_res,
			       dio->op.i_sectors_delta);
2013 2014
		req->ki_pos += (u64) dio->op.written << 9;
		dio->written += dio->op.written;
2015 2016

		spin_lock(&inode->v.i_lock);
2017 2018
		if (req->ki_pos > inode->v.i_size)
			i_size_write(&inode->v, req->ki_pos);
2019 2020
		spin_unlock(&inode->v.i_lock);

2021
		bio_release_pages(bio, false);
2022
		bio->bi_vcnt = 0;
2023 2024 2025 2026 2027 2028 2029

		if (dio->op.error) {
			set_bit(EI_INODE_ERROR, &inode->ei_flags);
			break;
		}

		if (!dio->iter.count)
2030
			break;
2031

2032
		bio_reset(bio, NULL, REQ_OP_WRITE);
2033
		reinit_completion(&dio->done);
2034 2035
	}

2036
	ret = dio->op.error ?: ((long) dio->written << 9);
2037 2038
err:
	bch2_pagecache_block_put(&inode->ei_pagecache_lock);
2039
	bch2_quota_reservation_put(c, inode, &dio->quota_res);
2040 2041 2042 2043

	if (dio->free_iov)
		kfree(dio->iter.__iov);

2044
	bio_release_pages(bio, false);
2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
	bio_put(bio);

	/* inode->i_dio_count is our ref on inode and thus bch_fs */
	inode_dio_end(&inode->v);

	if (!sync) {
		req->ki_complete(req, ret);
		ret = -EIOCBQUEUED;
	}
	return ret;
}

2057
static void bch2_dio_write_loop_async(struct bch_write_op *op)
2058
{
2059
	struct dio_write *dio = container_of(op, struct dio_write, op);
2060

2061 2062 2063 2064
	if (dio->sync)
		complete(&dio->done);
	else
		bch2_dio_write_loop(dio);
2065 2066 2067 2068 2069 2070
}

static noinline
ssize_t bch2_direct_write(struct kiocb *req, struct iov_iter *iter)
{
	struct file *file = req->ki_filp;
2071
	struct address_space *mapping = file->f_mapping;
2072 2073 2074 2075
	struct bch_inode_info *inode = file_bch_inode(file);
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
	struct dio_write *dio;
	struct bio *bio;
2076
	bool locked = true, extending;
2077 2078
	ssize_t ret;

2079 2080 2081 2082
	prefetch(&c->opts);
	prefetch((void *) &c->opts + 64);
	prefetch(&inode->ei_inode);
	prefetch((void *) &inode->ei_inode + 64);
2083

2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
	inode_lock(&inode->v);

	ret = generic_write_checks(req, iter);
	if (unlikely(ret <= 0))
		goto err;

	ret = file_remove_privs(file);
	if (unlikely(ret))
		goto err;

	ret = file_update_time(file);
	if (unlikely(ret))
		goto err;
2097

2098
	if (unlikely((req->ki_pos|iter->count) & (block_bytes(c) - 1)))
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
		goto err;

	inode_dio_begin(&inode->v);
	bch2_pagecache_block_get(&inode->ei_pagecache_lock);

	extending = req->ki_pos + iter->count > inode->v.i_size;
	if (!extending) {
		inode_unlock(&inode->v);
		locked = false;
	}
2109 2110

	bio = bio_alloc_bioset(NULL,
2111 2112 2113
			       iov_iter_is_bvec(iter)
			       ? 0
			       : iov_iter_npages(iter, BIO_MAX_VECS),
2114 2115 2116
			       REQ_OP_WRITE,
			       GFP_KERNEL,
			       &c->dio_write_bioset);
2117
	dio = container_of(bio, struct dio_write, op.wbio.bio);
2118
	init_completion(&dio->done);
2119
	dio->req		= req;
Kent Overstreet's avatar
Kent Overstreet committed
2120
	dio->mm			= current->mm;
2121
	dio->loop		= false;
2122
	dio->sync		= is_sync_kiocb(req) || extending;
2123 2124
	dio->free_iov		= false;
	dio->quota_res.sectors	= 0;
2125
	dio->written		= 0;
2126
	dio->iter		= *iter;
2127

2128 2129 2130
	ret = bch2_quota_reservation_add(c, inode, &dio->quota_res,
					 iter->count >> 9, true);
	if (unlikely(ret))
2131
		goto err_put_bio;
2132

2133 2134 2135 2136 2137 2138 2139
	if (unlikely(mapping->nrpages)) {
		ret = write_invalidate_inode_pages_range(mapping,
						req->ki_pos,
						req->ki_pos + iter->count - 1);
		if (unlikely(ret))
			goto err_put_bio;
	}
2140

2141
	ret = bch2_dio_write_loop(dio);
2142
err:
2143 2144 2145 2146 2147
	if (locked)
		inode_unlock(&inode->v);
	return ret;
err_put_bio:
	bch2_pagecache_block_put(&inode->ei_pagecache_lock);
2148 2149
	bch2_quota_reservation_put(c, inode, &dio->quota_res);
	bio_put(bio);
2150 2151
	inode_dio_end(&inode->v);
	goto err;
2152 2153
}

2154
ssize_t bch2_write_iter(struct kiocb *iocb, struct iov_iter *from)
2155 2156
{
	struct file *file = iocb->ki_filp;
2157
	struct bch_inode_info *inode = file_bch_inode(file);
2158 2159 2160 2161 2162
	ssize_t	ret;

	if (iocb->ki_flags & IOCB_DIRECT)
		return bch2_direct_write(iocb, from);

2163 2164 2165 2166 2167 2168
	inode_lock(&inode->v);

	ret = generic_write_checks(iocb, from);
	if (ret <= 0)
		goto unlock;

2169 2170
	ret = file_remove_privs(file);
	if (ret)
2171
		goto unlock;
2172 2173 2174

	ret = file_update_time(file);
	if (ret)
2175
		goto unlock;
2176

2177
	ret = bch2_buffered_write(iocb, from);
2178 2179
	if (likely(ret > 0))
		iocb->ki_pos += ret;
2180
unlock:
2181 2182
	inode_unlock(&inode->v);

2183
	if (ret > 0)
2184 2185 2186 2187 2188 2189 2190
		ret = generic_write_sync(iocb, ret);

	return ret;
}

/* fsync: */

2191 2192 2193 2194 2195
/*
 * inode->ei_inode.bi_journal_seq won't be up to date since it's set in an
 * insert trigger: look up the btree inode instead
 */
static int bch2_flush_inode(struct bch_fs *c, subvol_inum inum)
2196
{
2197 2198
	struct bch_inode_unpacked inode;
	int ret;
2199

2200 2201 2202 2203
	if (c->opts.journal_flush_disabled)
		return 0;

	ret = bch2_inode_find_by_inum(c, inum, &inode);
2204 2205 2206
	if (ret)
		return ret;

2207 2208
	return bch2_journal_flush_seq(&c->journal, inode.bi_journal_seq);
}
2209

2210 2211 2212 2213 2214 2215 2216 2217 2218
int bch2_fsync(struct file *file, loff_t start, loff_t end, int datasync)
{
	struct bch_inode_info *inode = file_bch_inode(file);
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
	int ret, ret2, ret3;

	ret = file_write_and_wait_range(file, start, end);
	ret2 = sync_inode_metadata(&inode->v, 1);
	ret3 = bch2_flush_inode(c, inode_inum(inode));
2219

2220
	return ret ?: ret2 ?: ret3;
2221 2222 2223 2224
}

/* truncate: */

2225 2226 2227
static inline int range_has_data(struct bch_fs *c, u32 subvol,
				 struct bpos start,
				 struct bpos end)
2228
{
2229
	struct btree_trans trans;
Kent Overstreet's avatar
Kent Overstreet committed
2230
	struct btree_iter iter;
2231 2232 2233
	struct bkey_s_c k;
	int ret = 0;

2234
	bch2_trans_init(&trans, c, 0, 0);
2235 2236 2237 2238 2239 2240
retry:
	bch2_trans_begin(&trans);

	ret = bch2_subvolume_get_snapshot(&trans, subvol, &start.snapshot);
	if (ret)
		goto err;
2241

2242
	for_each_btree_key_norestart(&trans, iter, BTREE_ID_extents, start, 0, k, ret) {
2243 2244 2245 2246 2247 2248 2249 2250
		if (bkey_cmp(bkey_start_pos(k.k), end) >= 0)
			break;

		if (bkey_extent_is_data(k.k)) {
			ret = 1;
			break;
		}
	}
2251
	start = iter.pos;
Kent Overstreet's avatar
Kent Overstreet committed
2252
	bch2_trans_iter_exit(&trans, &iter);
2253 2254 2255
err:
	if (ret == -EINTR)
		goto retry;
2256

2257 2258
	bch2_trans_exit(&trans);
	return ret;
2259 2260 2261 2262 2263 2264 2265
}

static int __bch2_truncate_page(struct bch_inode_info *inode,
				pgoff_t index, loff_t start, loff_t end)
{
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
	struct address_space *mapping = inode->v.i_mapping;
2266
	struct bch_page_state *s;
2267 2268
	unsigned start_offset = start & (PAGE_SIZE - 1);
	unsigned end_offset = ((end - 1) & (PAGE_SIZE - 1)) + 1;
2269
	unsigned i;
2270
	struct page *page;
2271
	s64 i_sectors_delta = 0;
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
	int ret = 0;

	/* Page boundary? Nothing to do */
	if (!((index == start >> PAGE_SHIFT && start_offset) ||
	      (index == end >> PAGE_SHIFT && end_offset != PAGE_SIZE)))
		return 0;

	/* Above i_size? */
	if (index << PAGE_SHIFT >= inode->v.i_size)
		return 0;

	page = find_lock_page(mapping, index);
	if (!page) {
		/*
		 * XXX: we're doing two index lookups when we end up reading the
		 * page
		 */
2289
		ret = range_has_data(c, inode->ei_subvol,
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
				POS(inode->v.i_ino, index << PAGE_SECTOR_SHIFT),
				POS(inode->v.i_ino, (index + 1) << PAGE_SECTOR_SHIFT));
		if (ret <= 0)
			return ret;

		page = find_or_create_page(mapping, index, GFP_KERNEL);
		if (unlikely(!page)) {
			ret = -ENOMEM;
			goto out;
		}
	}

2302 2303 2304 2305 2306 2307
	s = bch2_page_state_create(page, 0);
	if (!s) {
		ret = -ENOMEM;
		goto unlock;
	}

2308 2309 2310 2311 2312 2313
	if (!PageUptodate(page)) {
		ret = bch2_read_single_page(page, mapping);
		if (ret)
			goto unlock;
	}

2314 2315 2316 2317 2318 2319 2320 2321 2322
	if (index != start >> PAGE_SHIFT)
		start_offset = 0;
	if (index != end >> PAGE_SHIFT)
		end_offset = PAGE_SIZE;

	for (i = round_up(start_offset, block_bytes(c)) >> 9;
	     i < round_down(end_offset, block_bytes(c)) >> 9;
	     i++) {
		s->s[i].nr_replicas	= 0;
2323 2324
		if (s->s[i].state == SECTOR_DIRTY)
			i_sectors_delta--;
2325 2326 2327
		s->s[i].state		= SECTOR_UNALLOCATED;
	}

2328 2329
	i_sectors_acct(c, inode, NULL, i_sectors_delta);

2330 2331 2332 2333 2334 2335 2336 2337
	/*
	 * Caller needs to know whether this page will be written out by
	 * writeback - doing an i_size update if necessary - or whether it will
	 * be responsible for the i_size update:
	 */
	ret = s->s[(min_t(u64, inode->v.i_size - (index << PAGE_SHIFT),
			  PAGE_SIZE) - 1) >> 9].state >= SECTOR_DIRTY;

2338 2339
	zero_user_segment(page, start_offset, end_offset);

2340 2341 2342 2343 2344 2345
	/*
	 * Bit of a hack - we don't want truncate to fail due to -ENOSPC.
	 *
	 * XXX: because we aren't currently tracking whether the page has actual
	 * data in it (vs. just 0s, or only partially written) this wrong. ick.
	 */
2346
	BUG_ON(bch2_get_page_disk_reservation(c, inode, page, false));
2347

2348 2349 2350 2351 2352 2353
	/*
	 * This removes any writeable userspace mappings; we need to force
	 * .page_mkwrite to be called again before any mmapped writes, to
	 * redirty the full page:
	 */
	page_mkclean(page);
2354
	filemap_dirty_folio(mapping, page_folio(page));
2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
unlock:
	unlock_page(page);
	put_page(page);
out:
	return ret;
}

static int bch2_truncate_page(struct bch_inode_info *inode, loff_t from)
{
	return __bch2_truncate_page(inode, from >> PAGE_SHIFT,
2365
				    from, round_up(from, PAGE_SIZE));
2366 2367
}

2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
static int bch2_truncate_pages(struct bch_inode_info *inode,
			       loff_t start, loff_t end)
{
	int ret = __bch2_truncate_page(inode, start >> PAGE_SHIFT,
				       start, end);

	if (ret >= 0 &&
	    start >> PAGE_SHIFT != end >> PAGE_SHIFT)
		ret = __bch2_truncate_page(inode,
					   end >> PAGE_SHIFT,
					   start, end);
	return ret;
}

2382 2383
static int bch2_extend(struct mnt_idmap *idmap,
		       struct bch_inode_info *inode,
2384 2385
		       struct bch_inode_unpacked *inode_u,
		       struct iattr *iattr)
2386 2387 2388 2389
{
	struct address_space *mapping = inode->v.i_mapping;
	int ret;

2390 2391
	/*
	 * sync appends:
2392 2393
	 *
	 * this has to be done _before_ extending i_size:
2394 2395
	 */
	ret = filemap_write_and_wait_range(mapping, inode_u->bi_size, S64_MAX);
2396 2397 2398 2399 2400
	if (ret)
		return ret;

	truncate_setsize(&inode->v, iattr->ia_size);

2401
	return bch2_setattr_nonsize(idmap, inode, iattr);
2402 2403
}

2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
static int bch2_truncate_finish_fn(struct bch_inode_info *inode,
				   struct bch_inode_unpacked *bi,
				   void *p)
{
	bi->bi_flags &= ~BCH_INODE_I_SIZE_DIRTY;
	return 0;
}

static int bch2_truncate_start_fn(struct bch_inode_info *inode,
				  struct bch_inode_unpacked *bi, void *p)
{
	u64 *new_i_size = p;

	bi->bi_flags |= BCH_INODE_I_SIZE_DIRTY;
	bi->bi_size = *new_i_size;
	return 0;
}

2422 2423
int bch2_truncate(struct mnt_idmap *idmap,
		  struct bch_inode_info *inode, struct iattr *iattr)
2424 2425 2426
{
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
	struct address_space *mapping = inode->v.i_mapping;
2427
	struct bch_inode_unpacked inode_u;
2428
	u64 new_i_size = iattr->ia_size;
2429
	s64 i_sectors_delta = 0;
2430 2431
	int ret = 0;

2432
	/*
2433 2434 2435
	 * If the truncate call with change the size of the file, the
	 * cmtimes should be updated. If the size will not change, we
	 * do not need to update the cmtimes.
2436
	 */
2437 2438 2439 2440 2441 2442 2443
	if (iattr->ia_size != inode->v.i_size) {
		if (!(iattr->ia_valid & ATTR_MTIME))
			ktime_get_coarse_real_ts64(&iattr->ia_mtime);
		if (!(iattr->ia_valid & ATTR_CTIME))
			ktime_get_coarse_real_ts64(&iattr->ia_ctime);
		iattr->ia_valid |= ATTR_MTIME|ATTR_CTIME;
	}
2444

2445 2446 2447
	inode_dio_wait(&inode->v);
	bch2_pagecache_block_get(&inode->ei_pagecache_lock);

2448
	ret = bch2_inode_find_by_inum(c, inode_inum(inode), &inode_u);
2449 2450 2451 2452 2453 2454 2455 2456 2457
	if (ret)
		goto err;

	/*
	 * check this before next assertion; on filesystem error our normal
	 * invariants are a bit broken (truncate has to truncate the page cache
	 * before the inode).
	 */
	ret = bch2_journal_error(&c->journal);
2458 2459
	if (ret)
		goto err;
2460

2461 2462
	WARN_ON(!test_bit(EI_INODE_ERROR, &inode->ei_flags) &&
		inode->v.i_size < inode_u.bi_size);
2463

2464
	if (iattr->ia_size > inode->v.i_size) {
2465
		ret = bch2_extend(idmap, inode, &inode_u, iattr);
2466
		goto err;
2467 2468
	}

2469 2470
	iattr->ia_valid &= ~ATTR_SIZE;

2471
	ret = bch2_truncate_page(inode, iattr->ia_size);
2472
	if (unlikely(ret < 0))
2473
		goto err;
2474

2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
	/*
	 * When extending, we're going to write the new i_size to disk
	 * immediately so we need to flush anything above the current on disk
	 * i_size first:
	 *
	 * Also, when extending we need to flush the page that i_size currently
	 * straddles - if it's mapped to userspace, we need to ensure that
	 * userspace has to redirty it and call .mkwrite -> set_page_dirty
	 * again to allocate the part of the page that was extended.
	 */
2485
	if (iattr->ia_size > inode_u.bi_size)
2486
		ret = filemap_write_and_wait_range(mapping,
2487
				inode_u.bi_size,
2488 2489 2490 2491 2492 2493
				iattr->ia_size - 1);
	else if (iattr->ia_size & (PAGE_SIZE - 1))
		ret = filemap_write_and_wait_range(mapping,
				round_down(iattr->ia_size, PAGE_SIZE),
				iattr->ia_size - 1);
	if (ret)
2494
		goto err;
2495

2496 2497 2498 2499
	mutex_lock(&inode->ei_update_lock);
	ret = bch2_write_inode(c, inode, bch2_truncate_start_fn,
			       &new_i_size, 0);
	mutex_unlock(&inode->ei_update_lock);
2500 2501

	if (unlikely(ret))
2502
		goto err;
2503 2504 2505

	truncate_setsize(&inode->v, iattr->ia_size);

2506
	ret = bch2_fpunch(c, inode_inum(inode),
2507
			round_up(iattr->ia_size, block_bytes(c)) >> 9,
2508
			U64_MAX, &i_sectors_delta);
2509 2510
	i_sectors_acct(c, inode, NULL, i_sectors_delta);

2511
	if (unlikely(ret))
2512
		goto err;
2513

2514
	mutex_lock(&inode->ei_update_lock);
2515
	ret = bch2_write_inode(c, inode, bch2_truncate_finish_fn, NULL, 0);
2516
	mutex_unlock(&inode->ei_update_lock);
2517 2518

	ret = bch2_setattr_nonsize(idmap, inode, iattr);
2519
err:
2520 2521 2522 2523 2524 2525
	bch2_pagecache_block_put(&inode->ei_pagecache_lock);
	return ret;
}

/* fallocate: */

2526 2527 2528 2529 2530 2531 2532 2533 2534
static int inode_update_times_fn(struct bch_inode_info *inode,
				 struct bch_inode_unpacked *bi, void *p)
{
	struct bch_fs *c = inode->v.i_sb->s_fs_info;

	bi->bi_mtime = bi->bi_ctime = bch2_current_time(c);
	return 0;
}

2535
static long bchfs_fpunch(struct bch_inode_info *inode, loff_t offset, loff_t len)
2536 2537
{
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
2538 2539 2540 2541
	u64 end		= offset + len;
	u64 block_start	= round_up(offset, block_bytes(c));
	u64 block_end	= round_down(end, block_bytes(c));
	bool truncated_last_page;
2542 2543
	int ret = 0;

2544 2545
	ret = bch2_truncate_pages(inode, offset, end);
	if (unlikely(ret < 0))
2546 2547
		goto err;

2548
	truncated_last_page = ret;
2549

2550
	truncate_pagecache_range(&inode->v, offset, end - 1);
2551

2552
	if (block_start < block_end ) {
2553 2554
		s64 i_sectors_delta = 0;

2555
		ret = bch2_fpunch(c, inode_inum(inode),
2556
				  block_start >> 9, block_end >> 9,
2557 2558 2559
				  &i_sectors_delta);
		i_sectors_acct(c, inode, NULL, i_sectors_delta);
	}
2560 2561

	mutex_lock(&inode->ei_update_lock);
2562 2563 2564 2565 2566 2567 2568
	if (end >= inode->v.i_size && !truncated_last_page) {
		ret = bch2_write_inode_size(c, inode, inode->v.i_size,
					    ATTR_MTIME|ATTR_CTIME);
	} else {
		ret = bch2_write_inode(c, inode, inode_update_times_fn, NULL,
				       ATTR_MTIME|ATTR_CTIME);
	}
2569
	mutex_unlock(&inode->ei_update_lock);
2570 2571 2572 2573
err:
	return ret;
}

2574
static long bchfs_fcollapse_finsert(struct bch_inode_info *inode,
2575 2576
				   loff_t offset, loff_t len,
				   bool insert)
2577 2578 2579
{
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
	struct address_space *mapping = inode->v.i_mapping;
2580
	struct bkey_buf copy;
2581
	struct btree_trans trans;
Kent Overstreet's avatar
Kent Overstreet committed
2582
	struct btree_iter src, dst, del;
2583 2584
	loff_t shift, new_size;
	u64 src_start;
2585
	int ret = 0;
2586 2587 2588 2589

	if ((offset | len) & (block_bytes(c) - 1))
		return -EINVAL;

2590 2591
	if (insert) {
		if (inode->v.i_sb->s_maxbytes - inode->v.i_size < len)
2592
			return -EFBIG;
2593

2594
		if (offset >= inode->v.i_size)
2595
			return -EINVAL;
2596

2597 2598 2599 2600
		src_start	= U64_MAX;
		shift		= len;
	} else {
		if (offset + len >= inode->v.i_size)
2601
			return -EINVAL;
2602

2603 2604 2605 2606 2607
		src_start	= offset + len;
		shift		= -len;
	}

	new_size = inode->v.i_size + shift;
2608

2609
	ret = write_invalidate_inode_pages_range(mapping, offset, LLONG_MAX);
2610
	if (ret)
2611
		return ret;
2612

2613 2614 2615 2616 2617 2618 2619
	if (insert) {
		i_size_write(&inode->v, new_size);
		mutex_lock(&inode->ei_update_lock);
		ret = bch2_write_inode_size(c, inode, new_size,
					    ATTR_MTIME|ATTR_CTIME);
		mutex_unlock(&inode->ei_update_lock);
	} else {
2620 2621
		s64 i_sectors_delta = 0;

2622
		ret = bch2_fpunch(c, inode_inum(inode),
2623 2624 2625 2626
				  offset >> 9, (offset + len) >> 9,
				  &i_sectors_delta);
		i_sectors_acct(c, inode, NULL, i_sectors_delta);

2627
		if (ret)
2628
			return ret;
2629
	}
2630

2631
	bch2_bkey_buf_init(&copy);
2632
	bch2_trans_init(&trans, c, BTREE_ITER_MAX, 1024);
Kent Overstreet's avatar
Kent Overstreet committed
2633
	bch2_trans_iter_init(&trans, &src, BTREE_ID_extents,
2634
			POS(inode->v.i_ino, src_start >> 9),
2635
			BTREE_ITER_INTENT);
Kent Overstreet's avatar
Kent Overstreet committed
2636 2637
	bch2_trans_copy_iter(&dst, &src);
	bch2_trans_copy_iter(&del, &src);
2638

2639
	while (ret == 0 || ret == -EINTR) {
2640 2641 2642 2643 2644
		struct disk_reservation disk_res =
			bch2_disk_reservation_init(c, 0);
		struct bkey_i delete;
		struct bkey_s_c k;
		struct bpos next_pos;
2645 2646
		struct bpos move_pos = POS(inode->v.i_ino, offset >> 9);
		struct bpos atomic_end;
2647
		unsigned trigger_flags = 0;
2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659
		u32 snapshot;

		bch2_trans_begin(&trans);

		ret = bch2_subvolume_get_snapshot(&trans,
					inode->ei_subvol, &snapshot);
		if (ret)
			continue;

		bch2_btree_iter_set_snapshot(&src, snapshot);
		bch2_btree_iter_set_snapshot(&dst, snapshot);
		bch2_btree_iter_set_snapshot(&del, snapshot);
2660

2661 2662
		bch2_trans_begin(&trans);

2663
		k = insert
Kent Overstreet's avatar
Kent Overstreet committed
2664 2665
			? bch2_btree_iter_peek_prev(&src)
			: bch2_btree_iter_peek(&src);
2666
		if ((ret = bkey_err(k)))
2667
			continue;
2668

2669 2670
		if (!k.k || k.k->p.inode != inode->v.i_ino)
			break;
2671

2672 2673 2674 2675
		if (insert &&
		    bkey_cmp(k.k->p, POS(inode->v.i_ino, offset >> 9)) <= 0)
			break;
reassemble:
2676
		bch2_bkey_buf_reassemble(&copy, c, k);
2677 2678

		if (insert &&
2679
		    bkey_cmp(bkey_start_pos(k.k), move_pos) < 0)
Kent Overstreet's avatar
Kent Overstreet committed
2680
			bch2_cut_front(move_pos, copy.k);
2681

Kent Overstreet's avatar
Kent Overstreet committed
2682
		copy.k->k.p.offset += shift >> 9;
Kent Overstreet's avatar
Kent Overstreet committed
2683
		bch2_btree_iter_set_pos(&dst, bkey_start_pos(&copy.k->k));
2684

Kent Overstreet's avatar
Kent Overstreet committed
2685
		ret = bch2_extent_atomic_end(&trans, &dst, copy.k, &atomic_end);
2686
		if (ret)
2687
			continue;
2688

Kent Overstreet's avatar
Kent Overstreet committed
2689
		if (bkey_cmp(atomic_end, copy.k->k.p)) {
2690 2691 2692 2693 2694
			if (insert) {
				move_pos = atomic_end;
				move_pos.offset -= shift >> 9;
				goto reassemble;
			} else {
2695
				bch2_cut_back(atomic_end, copy.k);
2696 2697 2698
			}
		}

2699
		bkey_init(&delete.k);
2700 2701 2702
		delete.k.p = copy.k->k.p;
		delete.k.size = copy.k->k.size;
		delete.k.p.offset -= shift >> 9;
Kent Overstreet's avatar
Kent Overstreet committed
2703
		bch2_btree_iter_set_pos(&del, bkey_start_pos(&delete.k));
2704

2705
		next_pos = insert ? bkey_start_pos(&delete.k) : delete.k.p;
2706

Kent Overstreet's avatar
Kent Overstreet committed
2707
		if (copy.k->k.size == k.k->size) {
2708 2709 2710 2711
			/*
			 * If we're moving the entire extent, we can skip
			 * running triggers:
			 */
2712
			trigger_flags |= BTREE_TRIGGER_NORUN;
2713 2714 2715
		} else {
			/* We might end up splitting compressed extents: */
			unsigned nr_ptrs =
2716
				bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(copy.k));
2717 2718

			ret = bch2_disk_reservation_get(c, &disk_res,
Kent Overstreet's avatar
Kent Overstreet committed
2719
					copy.k->k.size, nr_ptrs,
2720 2721 2722 2723
					BCH_DISK_RESERVATION_NOFAIL);
			BUG_ON(ret);
		}

Kent Overstreet's avatar
Kent Overstreet committed
2724 2725 2726
		ret =   bch2_btree_iter_traverse(&del) ?:
			bch2_trans_update(&trans, &del, &delete, trigger_flags) ?:
			bch2_trans_update(&trans, &dst, copy.k, trigger_flags) ?:
2727
			bch2_trans_commit(&trans, &disk_res, NULL,
2728
					  BTREE_INSERT_NOFAIL);
2729
		bch2_disk_reservation_put(c, &disk_res);
2730

2731
		if (!ret)
Kent Overstreet's avatar
Kent Overstreet committed
2732
			bch2_btree_iter_set_pos(&src, next_pos);
2733
	}
Kent Overstreet's avatar
Kent Overstreet committed
2734 2735 2736
	bch2_trans_iter_exit(&trans, &del);
	bch2_trans_iter_exit(&trans, &dst);
	bch2_trans_iter_exit(&trans, &src);
2737 2738 2739 2740
	bch2_trans_exit(&trans);
	bch2_bkey_buf_exit(&copy, c);

	if (ret)
2741
		return ret;
2742

2743
	mutex_lock(&inode->ei_update_lock);
2744 2745 2746 2747
	if (!insert) {
		i_size_write(&inode->v, new_size);
		ret = bch2_write_inode_size(c, inode, new_size,
					    ATTR_MTIME|ATTR_CTIME);
2748 2749 2750 2751
	} else {
		/* We need an inode update to update bi_journal_seq for fsync: */
		ret = bch2_write_inode(c, inode, inode_update_times_fn, NULL,
				       ATTR_MTIME|ATTR_CTIME);
2752
	}
2753
	mutex_unlock(&inode->ei_update_lock);
2754 2755 2756
	return ret;
}

2757 2758
static int __bchfs_fallocate(struct bch_inode_info *inode, int mode,
			     u64 start_sector, u64 end_sector)
2759 2760
{
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
2761
	struct btree_trans trans;
Kent Overstreet's avatar
Kent Overstreet committed
2762
	struct btree_iter iter;
2763
	struct bpos end_pos = POS(inode->v.i_ino, end_sector);
2764
	unsigned replicas = io_opts(c, &inode->ei_inode).data_replicas;
2765
	int ret = 0;
2766

2767
	bch2_trans_init(&trans, c, BTREE_ITER_MAX, 512);
2768

Kent Overstreet's avatar
Kent Overstreet committed
2769
	bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
2770
			POS(inode->v.i_ino, start_sector),
2771
			BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
2772

Kent Overstreet's avatar
Kent Overstreet committed
2773
	while (!ret && bkey_cmp(iter.pos, end_pos) < 0) {
2774
		s64 i_sectors_delta = 0;
2775
		struct disk_reservation disk_res = { 0 };
2776
		struct quota_res quota_res = { 0 };
2777 2778
		struct bkey_i_reservation reservation;
		struct bkey_s_c k;
2779
		unsigned sectors;
2780
		u32 snapshot;
2781

2782
		bch2_trans_begin(&trans);
2783

2784 2785 2786 2787 2788 2789 2790
		ret = bch2_subvolume_get_snapshot(&trans,
					inode->ei_subvol, &snapshot);
		if (ret)
			goto bkey_err;

		bch2_btree_iter_set_snapshot(&iter, snapshot);

Kent Overstreet's avatar
Kent Overstreet committed
2791
		k = bch2_btree_iter_peek_slot(&iter);
2792 2793
		if ((ret = bkey_err(k)))
			goto bkey_err;
2794 2795

		/* already reserved */
2796
		if (k.k->type == KEY_TYPE_reservation &&
2797
		    bkey_s_c_to_reservation(k).v->nr_replicas >= replicas) {
Kent Overstreet's avatar
Kent Overstreet committed
2798
			bch2_btree_iter_advance(&iter);
2799 2800 2801
			continue;
		}

2802 2803
		if (bkey_extent_is_data(k.k) &&
		    !(mode & FALLOC_FL_ZERO_RANGE)) {
Kent Overstreet's avatar
Kent Overstreet committed
2804
			bch2_btree_iter_advance(&iter);
2805
			continue;
2806 2807 2808
		}

		bkey_reservation_init(&reservation.k_i);
2809
		reservation.k.type	= KEY_TYPE_reservation;
2810 2811 2812
		reservation.k.p		= k.k->p;
		reservation.k.size	= k.k->size;

Kent Overstreet's avatar
Kent Overstreet committed
2813
		bch2_cut_front(iter.pos,	&reservation.k_i);
2814
		bch2_cut_back(end_pos,		&reservation.k_i);
2815 2816

		sectors = reservation.k.size;
2817
		reservation.v.nr_replicas = bch2_bkey_nr_ptrs_allocated(k);
2818 2819 2820

		if (!bkey_extent_is_allocation(k.k)) {
			ret = bch2_quota_reservation_add(c, inode,
2821
					&quota_res,
2822 2823
					sectors, true);
			if (unlikely(ret))
2824
				goto bkey_err;
2825 2826 2827
		}

		if (reservation.v.nr_replicas < replicas ||
2828
		    bch2_bkey_sectors_compressed(k)) {
2829 2830 2831
			ret = bch2_disk_reservation_get(c, &disk_res, sectors,
							replicas, 0);
			if (unlikely(ret))
2832
				goto bkey_err;
2833 2834 2835 2836

			reservation.v.nr_replicas = disk_res.nr_replicas;
		}

2837 2838
		ret = bch2_extent_update(&trans, inode_inum(inode), &iter,
					 &reservation.k_i,
2839
				&disk_res, NULL,
2840
				0, &i_sectors_delta, true);
2841 2842
		if (ret)
			goto bkey_err;
2843
		i_sectors_acct(c, inode, &quota_res, i_sectors_delta);
2844
bkey_err:
2845
		bch2_quota_reservation_put(c, inode, &quota_res);
2846 2847 2848 2849
		bch2_disk_reservation_put(c, &disk_res);
		if (ret == -EINTR)
			ret = 0;
	}
2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860

	if (ret == -ENOSPC && (mode & FALLOC_FL_ZERO_RANGE)) {
		struct quota_res quota_res = { 0 };
		s64 i_sectors_delta = 0;

		bch2_fpunch_at(&trans, &iter, inode_inum(inode),
			       end_sector, &i_sectors_delta);
		i_sectors_acct(c, inode, &quota_res, i_sectors_delta);
		bch2_quota_reservation_put(c, inode, &quota_res);
	}

Kent Overstreet's avatar
Kent Overstreet committed
2861
	bch2_trans_iter_exit(&trans, &iter);
2862 2863 2864
	bch2_trans_exit(&trans);
	return ret;
}
2865

2866 2867 2868 2869
static long bchfs_fallocate(struct bch_inode_info *inode, int mode,
			    loff_t offset, loff_t len)
{
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
2870 2871 2872 2873 2874
	u64 end		= offset + len;
	u64 block_start	= round_down(offset,	block_bytes(c));
	u64 block_end	= round_up(end,		block_bytes(c));
	bool truncated_last_page = false;
	int ret, ret2 = 0;
2875 2876 2877 2878

	if (!(mode & FALLOC_FL_KEEP_SIZE) && end > inode->v.i_size) {
		ret = inode_newsize_ok(&inode->v, end);
		if (ret)
2879
			return ret;
2880 2881 2882
	}

	if (mode & FALLOC_FL_ZERO_RANGE) {
2883 2884 2885
		ret = bch2_truncate_pages(inode, offset, end);
		if (unlikely(ret < 0))
			return ret;
2886

2887
		truncated_last_page = ret;
2888 2889

		truncate_pagecache_range(&inode->v, offset, end - 1);
2890 2891 2892

		block_start	= round_up(offset,	block_bytes(c));
		block_end	= round_down(end,	block_bytes(c));
2893 2894 2895
	}

	ret = __bchfs_fallocate(inode, mode, block_start >> 9, block_end >> 9);
2896

2897
	/*
2898 2899
	 * On -ENOSPC in ZERO_RANGE mode, we still want to do the inode update,
	 * so that the VFS cache i_size is consistent with the btree i_size:
2900
	 */
2901 2902 2903
	if (ret &&
	    !(ret == -ENOSPC && (mode & FALLOC_FL_ZERO_RANGE)))
		return ret;
2904

2905 2906
	if (mode & FALLOC_FL_KEEP_SIZE && end > inode->v.i_size)
		end = inode->v.i_size;
2907

2908 2909 2910 2911 2912 2913
	if (end >= inode->v.i_size &&
	    (((mode & FALLOC_FL_ZERO_RANGE) && !truncated_last_page) ||
	     !(mode & FALLOC_FL_KEEP_SIZE))) {
		spin_lock(&inode->v.i_lock);
		i_size_write(&inode->v, end);
		spin_unlock(&inode->v.i_lock);
2914 2915

		mutex_lock(&inode->ei_update_lock);
2916
		ret2 = bch2_write_inode_size(c, inode, end, 0);
2917
		mutex_unlock(&inode->ei_update_lock);
2918
	}
2919 2920

	return ret ?: ret2;
2921 2922 2923 2924 2925 2926
}

long bch2_fallocate_dispatch(struct file *file, int mode,
			     loff_t offset, loff_t len)
{
	struct bch_inode_info *inode = file_bch_inode(file);
2927 2928
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
	long ret;
2929

2930 2931
	if (!percpu_ref_tryget(&c->writes))
		return -EROFS;
2932

2933 2934 2935 2936
	inode_lock(&inode->v);
	inode_dio_wait(&inode->v);
	bch2_pagecache_block_get(&inode->ei_pagecache_lock);

2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947
	if (!(mode & ~(FALLOC_FL_KEEP_SIZE|FALLOC_FL_ZERO_RANGE)))
		ret = bchfs_fallocate(inode, mode, offset, len);
	else if (mode == (FALLOC_FL_PUNCH_HOLE|FALLOC_FL_KEEP_SIZE))
		ret = bchfs_fpunch(inode, offset, len);
	else if (mode == FALLOC_FL_INSERT_RANGE)
		ret = bchfs_fcollapse_finsert(inode, offset, len, true);
	else if (mode == FALLOC_FL_COLLAPSE_RANGE)
		ret = bchfs_fcollapse_finsert(inode, offset, len, false);
	else
		ret = -EOPNOTSUPP;

2948 2949 2950

	bch2_pagecache_block_put(&inode->ei_pagecache_lock);
	inode_unlock(&inode->v);
2951
	percpu_ref_put(&c->writes);
2952

2953
	return ret;
2954 2955
}

Kent Overstreet's avatar
Kent Overstreet committed
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974
static void mark_range_unallocated(struct bch_inode_info *inode,
				   loff_t start, loff_t end)
{
	pgoff_t index = start >> PAGE_SHIFT;
	pgoff_t end_index = (end - 1) >> PAGE_SHIFT;
	struct folio_batch fbatch;
	unsigned i, j;

	folio_batch_init(&fbatch);

	while (filemap_get_folios(inode->v.i_mapping,
				  &index, end_index, &fbatch)) {
		for (i = 0; i < folio_batch_count(&fbatch); i++) {
			struct folio *folio = fbatch.folios[i];
			struct bch_page_state *s;

			folio_lock(folio);
			s = bch2_page_state(&folio->page);

2975 2976
			if (s) {
				spin_lock(&s->lock);
Kent Overstreet's avatar
Kent Overstreet committed
2977 2978
				for (j = 0; j < PAGE_SECTORS; j++)
					s->s[j].nr_replicas = 0;
2979 2980
				spin_unlock(&s->lock);
			}
Kent Overstreet's avatar
Kent Overstreet committed
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995

			folio_unlock(folio);
		}
		folio_batch_release(&fbatch);
		cond_resched();
	}
}

loff_t bch2_remap_file_range(struct file *file_src, loff_t pos_src,
			     struct file *file_dst, loff_t pos_dst,
			     loff_t len, unsigned remap_flags)
{
	struct bch_inode_info *src = file_bch_inode(file_src);
	struct bch_inode_info *dst = file_bch_inode(file_dst);
	struct bch_fs *c = src->v.i_sb->s_fs_info;
2996
	s64 i_sectors_delta = 0;
2997
	u64 aligned_len;
Kent Overstreet's avatar
Kent Overstreet committed
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015
	loff_t ret = 0;

	if (remap_flags & ~(REMAP_FILE_DEDUP|REMAP_FILE_ADVISORY))
		return -EINVAL;

	if (remap_flags & REMAP_FILE_DEDUP)
		return -EOPNOTSUPP;

	if ((pos_src & (block_bytes(c) - 1)) ||
	    (pos_dst & (block_bytes(c) - 1)))
		return -EINVAL;

	if (src == dst &&
	    abs(pos_src - pos_dst) < len)
		return -EINVAL;

	bch2_lock_inodes(INODE_LOCK|INODE_PAGECACHE_BLOCK, src, dst);

3016 3017
	file_update_time(file_dst);

Kent Overstreet's avatar
Kent Overstreet committed
3018 3019 3020 3021 3022 3023 3024
	inode_dio_wait(&src->v);
	inode_dio_wait(&dst->v);

	ret = generic_remap_file_range_prep(file_src, pos_src,
					    file_dst, pos_dst,
					    &len, remap_flags);
	if (ret < 0 || len == 0)
3025
		goto err;
Kent Overstreet's avatar
Kent Overstreet committed
3026

3027
	aligned_len = round_up((u64) len, block_bytes(c));
Kent Overstreet's avatar
Kent Overstreet committed
3028 3029

	ret = write_invalidate_inode_pages_range(dst->v.i_mapping,
3030
				pos_dst, pos_dst + len - 1);
Kent Overstreet's avatar
Kent Overstreet committed
3031
	if (ret)
3032
		goto err;
Kent Overstreet's avatar
Kent Overstreet committed
3033 3034 3035

	mark_range_unallocated(src, pos_src, pos_src + aligned_len);

3036
	ret = bch2_remap_range(c,
3037 3038
			       inode_inum(dst), pos_dst >> 9,
			       inode_inum(src), pos_src >> 9,
Kent Overstreet's avatar
Kent Overstreet committed
3039
			       aligned_len >> 9,
3040 3041 3042
			       pos_dst + len, &i_sectors_delta);
	if (ret < 0)
		goto err;
Kent Overstreet's avatar
Kent Overstreet committed
3043

3044 3045 3046
	/*
	 * due to alignment, we might have remapped slightly more than requsted
	 */
3047
	ret = min((u64) ret << 9, (u64) len);
3048 3049 3050 3051 3052

	/* XXX get a quota reservation */
	i_sectors_acct(c, dst, NULL, i_sectors_delta);

	spin_lock(&dst->v.i_lock);
3053 3054
	if (pos_dst + ret > dst->v.i_size)
		i_size_write(&dst->v, pos_dst + ret);
3055
	spin_unlock(&dst->v.i_lock);
3056

3057 3058 3059
	if ((file_dst->f_flags & (__O_SYNC | O_DSYNC)) ||
	    IS_SYNC(file_inode(file_dst)))
		ret = bch2_flush_inode(c, inode_inum(dst));
3060
err:
Kent Overstreet's avatar
Kent Overstreet committed
3061 3062 3063 3064 3065
	bch2_unlock_inodes(INODE_LOCK|INODE_PAGECACHE_BLOCK, src, dst);

	return ret;
}

3066 3067
/* fseek: */

3068
static int folio_data_offset(struct folio *folio, unsigned offset)
3069
{
3070 3071 3072
	struct bch_page_state *s = bch2_page_state(&folio->page);
	unsigned i;

3073 3074 3075 3076
	if (s)
		for (i = offset >> 9; i < PAGE_SECTORS; i++)
			if (s->s[i].state >= SECTOR_DIRTY)
				return i << 9;
3077

3078
	return -1;
3079 3080
}

3081
static loff_t bch2_seek_pagecache_data(struct inode *vinode,
3082 3083 3084 3085 3086 3087 3088 3089
				       loff_t start_offset,
				       loff_t end_offset)
{
	struct folio_batch fbatch;
	pgoff_t start_index	= start_offset >> PAGE_SHIFT;
	pgoff_t end_index	= end_offset >> PAGE_SHIFT;
	pgoff_t index		= start_index;
	unsigned i;
3090 3091
	loff_t ret;
	int offset;
3092 3093 3094 3095 3096 3097 3098 3099 3100

	folio_batch_init(&fbatch);

	while (filemap_get_folios(vinode->i_mapping,
				  &index, end_index, &fbatch)) {
		for (i = 0; i < folio_batch_count(&fbatch); i++) {
			struct folio *folio = fbatch.folios[i];

			folio_lock(folio);
3101 3102 3103 3104 3105 3106 3107 3108
			offset = folio_data_offset(folio,
					folio->index == start_index
					? start_offset & (PAGE_SIZE - 1)
					: 0);
			if (offset >= 0) {
				ret = clamp(((loff_t) folio->index << PAGE_SHIFT) +
					    offset,
					    start_offset, end_offset);
3109 3110
				folio_unlock(folio);
				folio_batch_release(&fbatch);
3111
				return ret;
3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125
			}
			folio_unlock(folio);
		}
		folio_batch_release(&fbatch);
		cond_resched();
	}

	return end_offset;
}

static loff_t bch2_seek_data(struct file *file, u64 offset)
{
	struct bch_inode_info *inode = file_bch_inode(file);
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
3126
	struct btree_trans trans;
Kent Overstreet's avatar
Kent Overstreet committed
3127
	struct btree_iter iter;
3128
	struct bkey_s_c k;
3129
	subvol_inum inum = inode_inum(inode);
3130
	u64 isize, next_data = MAX_LFS_FILESIZE;
3131
	u32 snapshot;
3132 3133 3134 3135 3136 3137
	int ret;

	isize = i_size_read(&inode->v);
	if (offset >= isize)
		return -ENXIO;

3138
	bch2_trans_init(&trans, c, 0, 0);
3139 3140 3141 3142 3143 3144
retry:
	bch2_trans_begin(&trans);

	ret = bch2_subvolume_get_snapshot(&trans, inum.subvol, &snapshot);
	if (ret)
		goto err;
3145

3146
	for_each_btree_key_norestart(&trans, iter, BTREE_ID_extents,
3147
			   SPOS(inode->v.i_ino, offset >> 9, snapshot), 0, k, ret) {
3148 3149 3150 3151 3152 3153 3154 3155
		if (k.k->p.inode != inode->v.i_ino) {
			break;
		} else if (bkey_extent_is_data(k.k)) {
			next_data = max(offset, bkey_start_offset(k.k) << 9);
			break;
		} else if (k.k->p.offset >> 9 > isize)
			break;
	}
Kent Overstreet's avatar
Kent Overstreet committed
3156
	bch2_trans_iter_exit(&trans, &iter);
3157 3158 3159
err:
	if (ret == -EINTR)
		goto retry;
3160

3161
	bch2_trans_exit(&trans);
3162 3163 3164 3165
	if (ret)
		return ret;

	if (next_data > offset)
3166
		next_data = bch2_seek_pagecache_data(&inode->v,
3167 3168
						     offset, next_data);

3169
	if (next_data >= isize)
3170 3171 3172 3173 3174
		return -ENXIO;

	return vfs_setpos(file, next_data, MAX_LFS_FILESIZE);
}

3175
static int __page_hole_offset(struct page *page, unsigned offset)
3176
{
3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192
	struct bch_page_state *s = bch2_page_state(page);
	unsigned i;

	if (!s)
		return 0;

	for (i = offset >> 9; i < PAGE_SECTORS; i++)
		if (s->s[i].state < SECTOR_DIRTY)
			return i << 9;

	return -1;
}

static loff_t page_hole_offset(struct address_space *mapping, loff_t offset)
{
	pgoff_t index = offset >> PAGE_SHIFT;
3193
	struct page *page;
3194 3195
	int pg_offset;
	loff_t ret = -1;
3196 3197 3198

	page = find_lock_page(mapping, index);
	if (!page)
3199 3200 3201 3202 3203
		return offset;

	pg_offset = __page_hole_offset(page, offset & (PAGE_SIZE - 1));
	if (pg_offset >= 0)
		ret = ((loff_t) index << PAGE_SHIFT) + pg_offset;
3204 3205 3206 3207 3208 3209

	unlock_page(page);

	return ret;
}

3210
static loff_t bch2_seek_pagecache_hole(struct inode *vinode,
3211 3212 3213 3214
				       loff_t start_offset,
				       loff_t end_offset)
{
	struct address_space *mapping = vinode->i_mapping;
3215
	loff_t offset = start_offset, hole;
3216

3217 3218 3219 3220 3221 3222 3223 3224
	while (offset < end_offset) {
		hole = page_hole_offset(mapping, offset);
		if (hole >= 0 && hole <= end_offset)
			return max(start_offset, hole);

		offset += PAGE_SIZE;
		offset &= PAGE_MASK;
	}
3225 3226 3227 3228 3229 3230 3231 3232

	return end_offset;
}

static loff_t bch2_seek_hole(struct file *file, u64 offset)
{
	struct bch_inode_info *inode = file_bch_inode(file);
	struct bch_fs *c = inode->v.i_sb->s_fs_info;
3233
	struct btree_trans trans;
Kent Overstreet's avatar
Kent Overstreet committed
3234
	struct btree_iter iter;
3235
	struct bkey_s_c k;
3236
	subvol_inum inum = inode_inum(inode);
3237
	u64 isize, next_hole = MAX_LFS_FILESIZE;
3238
	u32 snapshot;
3239 3240 3241 3242 3243 3244
	int ret;

	isize = i_size_read(&inode->v);
	if (offset >= isize)
		return -ENXIO;

3245
	bch2_trans_init(&trans, c, 0, 0);
3246 3247 3248 3249 3250 3251
retry:
	bch2_trans_begin(&trans);

	ret = bch2_subvolume_get_snapshot(&trans, inum.subvol, &snapshot);
	if (ret)
		goto err;
3252

3253
	for_each_btree_key_norestart(&trans, iter, BTREE_ID_extents,
3254
			   SPOS(inode->v.i_ino, offset >> 9, snapshot),
3255
			   BTREE_ITER_SLOTS, k, ret) {
3256
		if (k.k->p.inode != inode->v.i_ino) {
3257
			next_hole = bch2_seek_pagecache_hole(&inode->v,
3258 3259 3260
					offset, MAX_LFS_FILESIZE);
			break;
		} else if (!bkey_extent_is_data(k.k)) {
3261
			next_hole = bch2_seek_pagecache_hole(&inode->v,
3262 3263 3264 3265 3266 3267 3268 3269 3270
					max(offset, bkey_start_offset(k.k) << 9),
					k.k->p.offset << 9);

			if (next_hole < k.k->p.offset << 9)
				break;
		} else {
			offset = max(offset, bkey_start_offset(k.k) << 9);
		}
	}
Kent Overstreet's avatar
Kent Overstreet committed
3271
	bch2_trans_iter_exit(&trans, &iter);
3272 3273 3274
err:
	if (ret == -EINTR)
		goto retry;
3275

3276
	bch2_trans_exit(&trans);
3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315
	if (ret)
		return ret;

	if (next_hole > isize)
		next_hole = isize;

	return vfs_setpos(file, next_hole, MAX_LFS_FILESIZE);
}

loff_t bch2_llseek(struct file *file, loff_t offset, int whence)
{
	switch (whence) {
	case SEEK_SET:
	case SEEK_CUR:
	case SEEK_END:
		return generic_file_llseek(file, offset, whence);
	case SEEK_DATA:
		return bch2_seek_data(file, offset);
	case SEEK_HOLE:
		return bch2_seek_hole(file, offset);
	}

	return -EINVAL;
}

void bch2_fs_fsio_exit(struct bch_fs *c)
{
	bioset_exit(&c->dio_write_bioset);
	bioset_exit(&c->dio_read_bioset);
	bioset_exit(&c->writepage_bioset);
}

int bch2_fs_fsio_init(struct bch_fs *c)
{
	int ret = 0;

	pr_verbose_init(c->opts, "");

	if (bioset_init(&c->writepage_bioset,
3316
			4, offsetof(struct bch_writepage_io, op.wbio.bio),
3317 3318 3319 3320 3321
			BIOSET_NEED_BVECS) ||
	    bioset_init(&c->dio_read_bioset,
			4, offsetof(struct dio_read, rbio.bio),
			BIOSET_NEED_BVECS) ||
	    bioset_init(&c->dio_write_bioset,
3322
			4, offsetof(struct dio_write, op.wbio.bio),
3323 3324 3325 3326 3327 3328 3329 3330
			BIOSET_NEED_BVECS))
		ret = -ENOMEM;

	pr_verbose_init(c->opts, "ret %i", ret);
	return ret;
}

#endif /* NO_BCACHEFS_FS */