1 // SPDX-License-Identifier: GPL-2.0
2 #ifndef NO_BCACHEFS_FS
3 
4 #include "bcachefs.h"
5 #include "alloc_foreground.h"
6 #include "bkey_buf.h"
7 #include "fs-io.h"
8 #include "fs-io-buffered.h"
9 #include "fs-io-direct.h"
10 #include "fs-io-pagecache.h"
11 #include "io_read.h"
12 #include "io_write.h"
13 
14 #include <linux/backing-dev.h>
15 #include <linux/pagemap.h>
16 #include <linux/writeback.h>
17 
bio_full(struct bio * bio,unsigned len)18 static inline bool bio_full(struct bio *bio, unsigned len)
19 {
20 	if (bio->bi_vcnt >= bio->bi_max_vecs)
21 		return true;
22 	if (bio->bi_iter.bi_size > UINT_MAX - len)
23 		return true;
24 	return false;
25 }
26 
27 /* readpage(s): */
28 
bch2_readpages_end_io(struct bio * bio)29 static void bch2_readpages_end_io(struct bio *bio)
30 {
31 	struct folio_iter fi;
32 
33 	bio_for_each_folio_all(fi, bio)
34 		folio_end_read(fi.folio, bio->bi_status == BLK_STS_OK);
35 
36 	bio_put(bio);
37 }
38 
39 struct readpages_iter {
40 	struct address_space	*mapping;
41 	unsigned		idx;
42 	folios			folios;
43 };
44 
readpages_iter_init(struct readpages_iter * iter,struct readahead_control * ractl)45 static int readpages_iter_init(struct readpages_iter *iter,
46 			       struct readahead_control *ractl)
47 {
48 	struct folio *folio;
49 
50 	*iter = (struct readpages_iter) { ractl->mapping };
51 
52 	while ((folio = __readahead_folio(ractl))) {
53 		if (!bch2_folio_create(folio, GFP_KERNEL) ||
54 		    darray_push(&iter->folios, folio)) {
55 			bch2_folio_release(folio);
56 			ractl->_nr_pages += folio_nr_pages(folio);
57 			ractl->_index -= folio_nr_pages(folio);
58 			return iter->folios.nr ? 0 : -ENOMEM;
59 		}
60 
61 		folio_put(folio);
62 	}
63 
64 	return 0;
65 }
66 
readpage_iter_peek(struct readpages_iter * iter)67 static inline struct folio *readpage_iter_peek(struct readpages_iter *iter)
68 {
69 	if (iter->idx >= iter->folios.nr)
70 		return NULL;
71 	return iter->folios.data[iter->idx];
72 }
73 
readpage_iter_advance(struct readpages_iter * iter)74 static inline void readpage_iter_advance(struct readpages_iter *iter)
75 {
76 	iter->idx++;
77 }
78 
extent_partial_reads_expensive(struct bkey_s_c k)79 static bool extent_partial_reads_expensive(struct bkey_s_c k)
80 {
81 	struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
82 	struct bch_extent_crc_unpacked crc;
83 	const union bch_extent_entry *i;
84 
85 	bkey_for_each_crc(k.k, ptrs, crc, i)
86 		if (crc.csum_type || crc.compression_type)
87 			return true;
88 	return false;
89 }
90 
readpage_bio_extend(struct btree_trans * trans,struct readpages_iter * iter,struct bio * bio,unsigned sectors_this_extent,bool get_more)91 static int readpage_bio_extend(struct btree_trans *trans,
92 			       struct readpages_iter *iter,
93 			       struct bio *bio,
94 			       unsigned sectors_this_extent,
95 			       bool get_more)
96 {
97 	/* Don't hold btree locks while allocating memory: */
98 	bch2_trans_unlock(trans);
99 
100 	while (bio_sectors(bio) < sectors_this_extent &&
101 	       bio->bi_vcnt < bio->bi_max_vecs) {
102 		struct folio *folio = readpage_iter_peek(iter);
103 		int ret;
104 
105 		if (folio) {
106 			readpage_iter_advance(iter);
107 		} else {
108 			pgoff_t folio_offset = bio_end_sector(bio) >> PAGE_SECTORS_SHIFT;
109 
110 			if (!get_more)
111 				break;
112 
113 			unsigned sectors_remaining = sectors_this_extent - bio_sectors(bio);
114 
115 			if (sectors_remaining < PAGE_SECTORS << mapping_min_folio_order(iter->mapping))
116 				break;
117 
118 			unsigned order = ilog2(rounddown_pow_of_two(sectors_remaining) / PAGE_SECTORS);
119 
120 			/* ensure proper alignment */
121 			order = min(order, __ffs(folio_offset|BIT(31)));
122 
123 			folio = xa_load(&iter->mapping->i_pages, folio_offset);
124 			if (folio && !xa_is_value(folio))
125 				break;
126 
127 			folio = filemap_alloc_folio(readahead_gfp_mask(iter->mapping), order);
128 			if (!folio)
129 				break;
130 
131 			if (!__bch2_folio_create(folio, GFP_KERNEL)) {
132 				folio_put(folio);
133 				break;
134 			}
135 
136 			ret = filemap_add_folio(iter->mapping, folio, folio_offset, GFP_KERNEL);
137 			if (ret) {
138 				__bch2_folio_release(folio);
139 				folio_put(folio);
140 				break;
141 			}
142 
143 			folio_put(folio);
144 		}
145 
146 		BUG_ON(folio_sector(folio) != bio_end_sector(bio));
147 
148 		BUG_ON(!bio_add_folio(bio, folio, folio_size(folio), 0));
149 	}
150 
151 	return bch2_trans_relock(trans);
152 }
153 
bchfs_read(struct btree_trans * trans,struct bch_read_bio * rbio,subvol_inum inum,struct readpages_iter * readpages_iter)154 static void bchfs_read(struct btree_trans *trans,
155 		       struct bch_read_bio *rbio,
156 		       subvol_inum inum,
157 		       struct readpages_iter *readpages_iter)
158 {
159 	struct bch_fs *c = trans->c;
160 	struct btree_iter iter;
161 	struct bkey_buf sk;
162 	int flags = BCH_READ_retry_if_stale|
163 		BCH_READ_may_promote;
164 	int ret = 0;
165 
166 	rbio->subvol = inum.subvol;
167 
168 	bch2_bkey_buf_init(&sk);
169 	bch2_trans_begin(trans);
170 	bch2_trans_iter_init(trans, &iter, BTREE_ID_extents,
171 			     POS(inum.inum, rbio->bio.bi_iter.bi_sector),
172 			     BTREE_ITER_slots);
173 	while (1) {
174 		struct bkey_s_c k;
175 		unsigned bytes, sectors;
176 		s64 offset_into_extent;
177 		enum btree_id data_btree = BTREE_ID_extents;
178 
179 		bch2_trans_begin(trans);
180 
181 		u32 snapshot;
182 		ret = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
183 		if (ret)
184 			goto err;
185 
186 		bch2_btree_iter_set_snapshot(trans, &iter, snapshot);
187 
188 		bch2_btree_iter_set_pos(trans, &iter,
189 				POS(inum.inum, rbio->bio.bi_iter.bi_sector));
190 
191 		k = bch2_btree_iter_peek_slot(trans, &iter);
192 		ret = bkey_err(k);
193 		if (ret)
194 			goto err;
195 
196 		offset_into_extent = iter.pos.offset -
197 			bkey_start_offset(k.k);
198 		sectors = k.k->size - offset_into_extent;
199 
200 		bch2_bkey_buf_reassemble(&sk, c, k);
201 
202 		ret = bch2_read_indirect_extent(trans, &data_btree,
203 					&offset_into_extent, &sk);
204 		if (ret)
205 			goto err;
206 
207 		k = bkey_i_to_s_c(sk.k);
208 
209 		sectors = min_t(unsigned, sectors, k.k->size - offset_into_extent);
210 
211 		if (readpages_iter) {
212 			ret = readpage_bio_extend(trans, readpages_iter, &rbio->bio, sectors,
213 						  extent_partial_reads_expensive(k));
214 			if (ret)
215 				goto err;
216 		}
217 
218 		bytes = min(sectors, bio_sectors(&rbio->bio)) << 9;
219 		swap(rbio->bio.bi_iter.bi_size, bytes);
220 
221 		if (rbio->bio.bi_iter.bi_size == bytes)
222 			flags |= BCH_READ_last_fragment;
223 
224 		bch2_bio_page_state_set(&rbio->bio, k);
225 
226 		bch2_read_extent(trans, rbio, iter.pos,
227 				 data_btree, k, offset_into_extent, flags);
228 		/*
229 		 * Careful there's a landmine here if bch2_read_extent() ever
230 		 * starts returning transaction restarts here.
231 		 *
232 		 * We've changed rbio->bi_iter.bi_size to be "bytes we can read
233 		 * from this extent" with the swap call, and we restore it
234 		 * below. That restore needs to come before checking for
235 		 * errors.
236 		 *
237 		 * But unlike __bch2_read(), we use the rbio bvec iter, not one
238 		 * on the stack, so we can't do the restore right after the
239 		 * bch2_read_extent() call: we don't own that iterator anymore
240 		 * if BCH_READ_last_fragment is set, since we may have submitted
241 		 * that rbio instead of cloning it.
242 		 */
243 
244 		if (flags & BCH_READ_last_fragment)
245 			break;
246 
247 		swap(rbio->bio.bi_iter.bi_size, bytes);
248 		bio_advance(&rbio->bio, bytes);
249 err:
250 		if (ret &&
251 		    !bch2_err_matches(ret, BCH_ERR_transaction_restart))
252 			break;
253 	}
254 	bch2_trans_iter_exit(trans, &iter);
255 
256 	if (ret) {
257 		struct printbuf buf = PRINTBUF;
258 		lockrestart_do(trans,
259 			bch2_inum_offset_err_msg_trans(trans, &buf, inum, iter.pos.offset << 9));
260 		prt_printf(&buf, "read error %i from btree lookup", ret);
261 		bch_err_ratelimited(c, "%s", buf.buf);
262 		printbuf_exit(&buf);
263 
264 		rbio->bio.bi_status = BLK_STS_IOERR;
265 		bio_endio(&rbio->bio);
266 	}
267 
268 	bch2_bkey_buf_exit(&sk, c);
269 }
270 
bch2_readahead(struct readahead_control * ractl)271 void bch2_readahead(struct readahead_control *ractl)
272 {
273 	struct bch_inode_info *inode = to_bch_ei(ractl->mapping->host);
274 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
275 	struct bch_io_opts opts;
276 	struct folio *folio;
277 	struct readpages_iter readpages_iter;
278 	struct blk_plug plug;
279 
280 	bch2_inode_opts_get(&opts, c, &inode->ei_inode);
281 
282 	int ret = readpages_iter_init(&readpages_iter, ractl);
283 	if (ret)
284 		return;
285 
286 	/*
287 	 * Besides being a general performance optimization, plugging helps with
288 	 * avoiding btree transaction srcu warnings - submitting a bio can
289 	 * block, and we don't want todo that with the transaction locked.
290 	 *
291 	 * However, plugged bios are submitted when we schedule; we ideally
292 	 * would have our own scheduler hook to call unlock_long() before
293 	 * scheduling.
294 	 */
295 	blk_start_plug(&plug);
296 	bch2_pagecache_add_get(inode);
297 
298 	struct btree_trans *trans = bch2_trans_get(c);
299 	while ((folio = readpage_iter_peek(&readpages_iter))) {
300 		unsigned n = min_t(unsigned,
301 				   readpages_iter.folios.nr -
302 				   readpages_iter.idx,
303 				   BIO_MAX_VECS);
304 		struct bch_read_bio *rbio =
305 			rbio_init(bio_alloc_bioset(NULL, n, REQ_OP_READ,
306 						   GFP_KERNEL, &c->bio_read),
307 				  c,
308 				  opts,
309 				  bch2_readpages_end_io);
310 
311 		readpage_iter_advance(&readpages_iter);
312 
313 		rbio->bio.bi_iter.bi_sector = folio_sector(folio);
314 		BUG_ON(!bio_add_folio(&rbio->bio, folio, folio_size(folio), 0));
315 
316 		bchfs_read(trans, rbio, inode_inum(inode),
317 			   &readpages_iter);
318 		bch2_trans_unlock(trans);
319 	}
320 	bch2_trans_put(trans);
321 
322 	bch2_pagecache_add_put(inode);
323 	blk_finish_plug(&plug);
324 	darray_exit(&readpages_iter.folios);
325 }
326 
bch2_read_single_folio_end_io(struct bio * bio)327 static void bch2_read_single_folio_end_io(struct bio *bio)
328 {
329 	complete(bio->bi_private);
330 }
331 
bch2_read_single_folio(struct folio * folio,struct address_space * mapping)332 int bch2_read_single_folio(struct folio *folio, struct address_space *mapping)
333 {
334 	struct bch_inode_info *inode = to_bch_ei(mapping->host);
335 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
336 	struct bch_read_bio *rbio;
337 	struct bch_io_opts opts;
338 	struct blk_plug plug;
339 	int ret;
340 	DECLARE_COMPLETION_ONSTACK(done);
341 
342 	BUG_ON(folio_test_uptodate(folio));
343 	BUG_ON(folio_test_dirty(folio));
344 
345 	if (!bch2_folio_create(folio, GFP_KERNEL))
346 		return -ENOMEM;
347 
348 	bch2_inode_opts_get(&opts, c, &inode->ei_inode);
349 
350 	rbio = rbio_init(bio_alloc_bioset(NULL, 1, REQ_OP_READ, GFP_KERNEL, &c->bio_read),
351 			 c,
352 			 opts,
353 			 bch2_read_single_folio_end_io);
354 	rbio->bio.bi_private = &done;
355 	rbio->bio.bi_opf = REQ_OP_READ|REQ_SYNC;
356 	rbio->bio.bi_iter.bi_sector = folio_sector(folio);
357 	BUG_ON(!bio_add_folio(&rbio->bio, folio, folio_size(folio), 0));
358 
359 	blk_start_plug(&plug);
360 	bch2_trans_run(c, (bchfs_read(trans, rbio, inode_inum(inode), NULL), 0));
361 	blk_finish_plug(&plug);
362 	wait_for_completion(&done);
363 
364 	ret = blk_status_to_errno(rbio->bio.bi_status);
365 	bio_put(&rbio->bio);
366 
367 	if (ret < 0)
368 		return ret;
369 
370 	folio_mark_uptodate(folio);
371 	return 0;
372 }
373 
bch2_read_folio(struct file * file,struct folio * folio)374 int bch2_read_folio(struct file *file, struct folio *folio)
375 {
376 	int ret;
377 
378 	ret = bch2_read_single_folio(folio, folio->mapping);
379 	folio_unlock(folio);
380 	return bch2_err_class(ret);
381 }
382 
383 /* writepages: */
384 
385 struct bch_writepage_io {
386 	struct bch_inode_info		*inode;
387 
388 	/* must be last: */
389 	struct bch_write_op		op;
390 };
391 
392 struct bch_writepage_state {
393 	struct bch_writepage_io	*io;
394 	struct bch_io_opts	opts;
395 	struct bch_folio_sector	*tmp;
396 	unsigned		tmp_sectors;
397 };
398 
bch_writepage_state_init(struct bch_fs * c,struct bch_inode_info * inode)399 static inline struct bch_writepage_state bch_writepage_state_init(struct bch_fs *c,
400 								  struct bch_inode_info *inode)
401 {
402 	struct bch_writepage_state ret = { 0 };
403 
404 	bch2_inode_opts_get(&ret.opts, c, &inode->ei_inode);
405 	return ret;
406 }
407 
408 /*
409  * Determine when a writepage io is full. We have to limit writepage bios to a
410  * single page per bvec (i.e. 1MB with 4k pages) because that is the limit to
411  * what the bounce path in bch2_write_extent() can handle. In theory we could
412  * loosen this restriction for non-bounce I/O, but we don't have that context
413  * here. Ideally, we can up this limit and make it configurable in the future
414  * when the bounce path can be enhanced to accommodate larger source bios.
415  */
bch_io_full(struct bch_writepage_io * io,unsigned len)416 static inline bool bch_io_full(struct bch_writepage_io *io, unsigned len)
417 {
418 	struct bio *bio = &io->op.wbio.bio;
419 	return bio_full(bio, len) ||
420 		(bio->bi_iter.bi_size + len > BIO_MAX_VECS * PAGE_SIZE);
421 }
422 
bch2_writepage_io_done(struct bch_write_op * op)423 static void bch2_writepage_io_done(struct bch_write_op *op)
424 {
425 	struct bch_writepage_io *io =
426 		container_of(op, struct bch_writepage_io, op);
427 	struct bch_fs *c = io->op.c;
428 	struct bio *bio = &io->op.wbio.bio;
429 	struct folio_iter fi;
430 	unsigned i;
431 
432 	if (io->op.error) {
433 		set_bit(EI_INODE_ERROR, &io->inode->ei_flags);
434 
435 		bio_for_each_folio_all(fi, bio) {
436 			struct bch_folio *s;
437 
438 			mapping_set_error(fi.folio->mapping, -EIO);
439 
440 			s = __bch2_folio(fi.folio);
441 			spin_lock(&s->lock);
442 			for (i = 0; i < folio_sectors(fi.folio); i++)
443 				s->s[i].nr_replicas = 0;
444 			spin_unlock(&s->lock);
445 		}
446 	}
447 
448 	if (io->op.flags & BCH_WRITE_wrote_data_inline) {
449 		bio_for_each_folio_all(fi, bio) {
450 			struct bch_folio *s;
451 
452 			s = __bch2_folio(fi.folio);
453 			spin_lock(&s->lock);
454 			for (i = 0; i < folio_sectors(fi.folio); i++)
455 				s->s[i].nr_replicas = 0;
456 			spin_unlock(&s->lock);
457 		}
458 	}
459 
460 	/*
461 	 * racing with fallocate can cause us to add fewer sectors than
462 	 * expected - but we shouldn't add more sectors than expected:
463 	 */
464 	WARN_ON_ONCE(io->op.i_sectors_delta > 0);
465 
466 	/*
467 	 * (error (due to going RO) halfway through a page can screw that up
468 	 * slightly)
469 	 * XXX wtf?
470 	   BUG_ON(io->op.op.i_sectors_delta >= PAGE_SECTORS);
471 	 */
472 
473 	/*
474 	 * The writeback flag is effectively our ref on the inode -
475 	 * fixup i_blocks before calling folio_end_writeback:
476 	 */
477 	bch2_i_sectors_acct(c, io->inode, NULL, io->op.i_sectors_delta);
478 
479 	bio_for_each_folio_all(fi, bio) {
480 		struct bch_folio *s = __bch2_folio(fi.folio);
481 
482 		if (atomic_dec_and_test(&s->write_count))
483 			folio_end_writeback(fi.folio);
484 	}
485 
486 	bio_put(&io->op.wbio.bio);
487 }
488 
bch2_writepage_do_io(struct bch_writepage_state * w)489 static void bch2_writepage_do_io(struct bch_writepage_state *w)
490 {
491 	struct bch_writepage_io *io = w->io;
492 
493 	w->io = NULL;
494 	closure_call(&io->op.cl, bch2_write, NULL, NULL);
495 }
496 
497 /*
498  * Get a bch_writepage_io and add @page to it - appending to an existing one if
499  * possible, else allocating a new one:
500  */
bch2_writepage_io_alloc(struct bch_fs * c,struct writeback_control * wbc,struct bch_writepage_state * w,struct bch_inode_info * inode,u64 sector,unsigned nr_replicas)501 static void bch2_writepage_io_alloc(struct bch_fs *c,
502 				    struct writeback_control *wbc,
503 				    struct bch_writepage_state *w,
504 				    struct bch_inode_info *inode,
505 				    u64 sector,
506 				    unsigned nr_replicas)
507 {
508 	struct bch_write_op *op;
509 
510 	w->io = container_of(bio_alloc_bioset(NULL, BIO_MAX_VECS,
511 					      REQ_OP_WRITE,
512 					      GFP_KERNEL,
513 					      &c->writepage_bioset),
514 			     struct bch_writepage_io, op.wbio.bio);
515 
516 	w->io->inode		= inode;
517 	op			= &w->io->op;
518 	bch2_write_op_init(op, c, w->opts);
519 	op->target		= w->opts.foreground_target;
520 	op->nr_replicas		= nr_replicas;
521 	op->res.nr_replicas	= nr_replicas;
522 	op->write_point		= writepoint_hashed(inode->ei_last_dirtied);
523 	op->subvol		= inode->ei_inum.subvol;
524 	op->pos			= POS(inode->v.i_ino, sector);
525 	op->end_io		= bch2_writepage_io_done;
526 	op->devs_need_flush	= &inode->ei_devs_need_flush;
527 	op->wbio.bio.bi_iter.bi_sector = sector;
528 	op->wbio.bio.bi_opf	= wbc_to_write_flags(wbc);
529 }
530 
__bch2_writepage(struct folio * folio,struct writeback_control * wbc,void * data)531 static int __bch2_writepage(struct folio *folio,
532 			    struct writeback_control *wbc,
533 			    void *data)
534 {
535 	struct bch_inode_info *inode = to_bch_ei(folio->mapping->host);
536 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
537 	struct bch_writepage_state *w = data;
538 	struct bch_folio *s;
539 	unsigned i, offset, f_sectors, nr_replicas_this_write = U32_MAX;
540 	loff_t i_size = i_size_read(&inode->v);
541 	int ret;
542 
543 	EBUG_ON(!folio_test_uptodate(folio));
544 
545 	/* Is the folio fully inside i_size? */
546 	if (folio_end_pos(folio) <= i_size)
547 		goto do_io;
548 
549 	/* Is the folio fully outside i_size? (truncate in progress) */
550 	if (folio_pos(folio) >= i_size) {
551 		folio_unlock(folio);
552 		return 0;
553 	}
554 
555 	/*
556 	 * The folio straddles i_size.  It must be zeroed out on each and every
557 	 * writepage invocation because it may be mmapped.  "A file is mapped
558 	 * in multiples of the folio size.  For a file that is not a multiple of
559 	 * the  folio size, the remaining memory is zeroed when mapped, and
560 	 * writes to that region are not written out to the file."
561 	 */
562 	folio_zero_segment(folio,
563 			   i_size - folio_pos(folio),
564 			   folio_size(folio));
565 do_io:
566 	f_sectors = folio_sectors(folio);
567 	s = bch2_folio(folio);
568 
569 	if (f_sectors > w->tmp_sectors) {
570 		kfree(w->tmp);
571 		w->tmp = kcalloc(f_sectors, sizeof(struct bch_folio_sector), GFP_NOFS|__GFP_NOFAIL);
572 		w->tmp_sectors = f_sectors;
573 	}
574 
575 	/*
576 	 * Things get really hairy with errors during writeback:
577 	 */
578 	ret = bch2_get_folio_disk_reservation(c, inode, folio, false);
579 	BUG_ON(ret);
580 
581 	/* Before unlocking the page, get copy of reservations: */
582 	spin_lock(&s->lock);
583 	memcpy(w->tmp, s->s, sizeof(struct bch_folio_sector) * f_sectors);
584 
585 	for (i = 0; i < f_sectors; i++) {
586 		if (s->s[i].state < SECTOR_dirty)
587 			continue;
588 
589 		nr_replicas_this_write =
590 			min_t(unsigned, nr_replicas_this_write,
591 			      s->s[i].nr_replicas +
592 			      s->s[i].replicas_reserved);
593 	}
594 
595 	for (i = 0; i < f_sectors; i++) {
596 		if (s->s[i].state < SECTOR_dirty)
597 			continue;
598 
599 		s->s[i].nr_replicas = w->opts.compression
600 			? 0 : nr_replicas_this_write;
601 
602 		s->s[i].replicas_reserved = 0;
603 		bch2_folio_sector_set(folio, s, i, SECTOR_allocated);
604 	}
605 	spin_unlock(&s->lock);
606 
607 	BUG_ON(atomic_read(&s->write_count));
608 	atomic_set(&s->write_count, 1);
609 
610 	BUG_ON(folio_test_writeback(folio));
611 	folio_start_writeback(folio);
612 
613 	folio_unlock(folio);
614 
615 	offset = 0;
616 	while (1) {
617 		unsigned sectors = 0, dirty_sectors = 0, reserved_sectors = 0;
618 		u64 sector;
619 
620 		while (offset < f_sectors &&
621 		       w->tmp[offset].state < SECTOR_dirty)
622 			offset++;
623 
624 		if (offset == f_sectors)
625 			break;
626 
627 		while (offset + sectors < f_sectors &&
628 		       w->tmp[offset + sectors].state >= SECTOR_dirty) {
629 			reserved_sectors += w->tmp[offset + sectors].replicas_reserved;
630 			dirty_sectors += w->tmp[offset + sectors].state == SECTOR_dirty;
631 			sectors++;
632 		}
633 		BUG_ON(!sectors);
634 
635 		sector = folio_sector(folio) + offset;
636 
637 		if (w->io &&
638 		    (w->io->op.res.nr_replicas != nr_replicas_this_write ||
639 		     bch_io_full(w->io, sectors << 9) ||
640 		     bio_end_sector(&w->io->op.wbio.bio) != sector))
641 			bch2_writepage_do_io(w);
642 
643 		if (!w->io)
644 			bch2_writepage_io_alloc(c, wbc, w, inode, sector,
645 						nr_replicas_this_write);
646 
647 		atomic_inc(&s->write_count);
648 
649 		BUG_ON(inode != w->io->inode);
650 		BUG_ON(!bio_add_folio(&w->io->op.wbio.bio, folio,
651 				     sectors << 9, offset << 9));
652 
653 		w->io->op.res.sectors += reserved_sectors;
654 		w->io->op.i_sectors_delta -= dirty_sectors;
655 		w->io->op.new_i_size = i_size;
656 
657 		offset += sectors;
658 	}
659 
660 	if (atomic_dec_and_test(&s->write_count))
661 		folio_end_writeback(folio);
662 
663 	return 0;
664 }
665 
bch2_writepages(struct address_space * mapping,struct writeback_control * wbc)666 int bch2_writepages(struct address_space *mapping, struct writeback_control *wbc)
667 {
668 	struct bch_fs *c = mapping->host->i_sb->s_fs_info;
669 	struct bch_writepage_state w =
670 		bch_writepage_state_init(c, to_bch_ei(mapping->host));
671 	struct blk_plug plug;
672 	int ret;
673 
674 	blk_start_plug(&plug);
675 	ret = write_cache_pages(mapping, wbc, __bch2_writepage, &w);
676 	if (w.io)
677 		bch2_writepage_do_io(&w);
678 	blk_finish_plug(&plug);
679 	kfree(w.tmp);
680 	return bch2_err_class(ret);
681 }
682 
683 /* buffered writes: */
684 
bch2_write_begin(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,struct folio ** foliop,void ** fsdata)685 int bch2_write_begin(struct file *file, struct address_space *mapping,
686 		     loff_t pos, unsigned len,
687 		     struct folio **foliop, void **fsdata)
688 {
689 	struct bch_inode_info *inode = to_bch_ei(mapping->host);
690 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
691 	struct bch2_folio_reservation *res;
692 	struct folio *folio;
693 	unsigned offset;
694 	int ret = -ENOMEM;
695 
696 	res = kmalloc(sizeof(*res), GFP_KERNEL);
697 	if (!res)
698 		return -ENOMEM;
699 
700 	bch2_folio_reservation_init(c, inode, res);
701 	*fsdata = res;
702 
703 	bch2_pagecache_add_get(inode);
704 
705 	folio = __filemap_get_folio(mapping, pos >> PAGE_SHIFT,
706 				    FGP_WRITEBEGIN | fgf_set_order(len),
707 				    mapping_gfp_mask(mapping));
708 	if (IS_ERR(folio))
709 		goto err_unlock;
710 
711 	offset = pos - folio_pos(folio);
712 	len = min_t(size_t, len, folio_end_pos(folio) - pos);
713 
714 	if (folio_test_uptodate(folio))
715 		goto out;
716 
717 	/* If we're writing entire folio, don't need to read it in first: */
718 	if (!offset && len == folio_size(folio))
719 		goto out;
720 
721 	if (!offset && pos + len >= inode->v.i_size) {
722 		folio_zero_segment(folio, len, folio_size(folio));
723 		flush_dcache_folio(folio);
724 		goto out;
725 	}
726 
727 	if (folio_pos(folio) >= inode->v.i_size) {
728 		folio_zero_segments(folio, 0, offset, offset + len, folio_size(folio));
729 		flush_dcache_folio(folio);
730 		goto out;
731 	}
732 readpage:
733 	ret = bch2_read_single_folio(folio, mapping);
734 	if (ret)
735 		goto err;
736 out:
737 	ret = bch2_folio_set(c, inode_inum(inode), &folio, 1);
738 	if (ret)
739 		goto err;
740 
741 	ret = bch2_folio_reservation_get(c, inode, folio, res, offset, len);
742 	if (ret) {
743 		if (!folio_test_uptodate(folio)) {
744 			/*
745 			 * If the folio hasn't been read in, we won't know if we
746 			 * actually need a reservation - we don't actually need
747 			 * to read here, we just need to check if the folio is
748 			 * fully backed by uncompressed data:
749 			 */
750 			goto readpage;
751 		}
752 
753 		goto err;
754 	}
755 
756 	*foliop = folio;
757 	return 0;
758 err:
759 	folio_unlock(folio);
760 	folio_put(folio);
761 err_unlock:
762 	bch2_pagecache_add_put(inode);
763 	kfree(res);
764 	*fsdata = NULL;
765 	return bch2_err_class(ret);
766 }
767 
bch2_write_end(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct folio * folio,void * fsdata)768 int bch2_write_end(struct file *file, struct address_space *mapping,
769 		   loff_t pos, unsigned len, unsigned copied,
770 		   struct folio *folio, void *fsdata)
771 {
772 	struct bch_inode_info *inode = to_bch_ei(mapping->host);
773 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
774 	struct bch2_folio_reservation *res = fsdata;
775 	unsigned offset = pos - folio_pos(folio);
776 
777 	lockdep_assert_held(&inode->v.i_rwsem);
778 	BUG_ON(offset + copied > folio_size(folio));
779 
780 	if (unlikely(copied < len && !folio_test_uptodate(folio))) {
781 		/*
782 		 * The folio needs to be read in, but that would destroy
783 		 * our partial write - simplest thing is to just force
784 		 * userspace to redo the write:
785 		 */
786 		folio_zero_range(folio, 0, folio_size(folio));
787 		flush_dcache_folio(folio);
788 		copied = 0;
789 	}
790 
791 	spin_lock(&inode->v.i_lock);
792 	if (pos + copied > inode->v.i_size)
793 		i_size_write(&inode->v, pos + copied);
794 	spin_unlock(&inode->v.i_lock);
795 
796 	if (copied) {
797 		if (!folio_test_uptodate(folio))
798 			folio_mark_uptodate(folio);
799 
800 		bch2_set_folio_dirty(c, inode, folio, res, offset, copied);
801 
802 		inode->ei_last_dirtied = (unsigned long) current;
803 	}
804 
805 	folio_unlock(folio);
806 	folio_put(folio);
807 	bch2_pagecache_add_put(inode);
808 
809 	bch2_folio_reservation_put(c, inode, res);
810 	kfree(res);
811 
812 	return copied;
813 }
814 
folios_trunc(folios * fs,struct folio ** fi)815 static noinline void folios_trunc(folios *fs, struct folio **fi)
816 {
817 	while (fs->data + fs->nr > fi) {
818 		struct folio *f = darray_pop(fs);
819 
820 		folio_unlock(f);
821 		folio_put(f);
822 	}
823 }
824 
__bch2_buffered_write(struct bch_inode_info * inode,struct address_space * mapping,struct iov_iter * iter,loff_t pos,unsigned len)825 static int __bch2_buffered_write(struct bch_inode_info *inode,
826 				 struct address_space *mapping,
827 				 struct iov_iter *iter,
828 				 loff_t pos, unsigned len)
829 {
830 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
831 	struct bch2_folio_reservation res;
832 	folios fs;
833 	struct folio *f;
834 	unsigned copied = 0, f_offset, f_copied;
835 	u64 end = pos + len, f_pos, f_len;
836 	loff_t last_folio_pos = inode->v.i_size;
837 	int ret = 0;
838 
839 	BUG_ON(!len);
840 
841 	bch2_folio_reservation_init(c, inode, &res);
842 	darray_init(&fs);
843 
844 	ret = bch2_filemap_get_contig_folios_d(mapping, pos, end,
845 					       FGP_WRITEBEGIN | fgf_set_order(len),
846 					       mapping_gfp_mask(mapping), &fs);
847 	if (ret)
848 		goto out;
849 
850 	BUG_ON(!fs.nr);
851 
852 	f = darray_first(fs);
853 	if (pos != folio_pos(f) && !folio_test_uptodate(f)) {
854 		ret = bch2_read_single_folio(f, mapping);
855 		if (ret)
856 			goto out;
857 	}
858 
859 	f = darray_last(fs);
860 	end = min(end, folio_end_pos(f));
861 	last_folio_pos = folio_pos(f);
862 	if (end != folio_end_pos(f) && !folio_test_uptodate(f)) {
863 		if (end >= inode->v.i_size) {
864 			folio_zero_range(f, 0, folio_size(f));
865 		} else {
866 			ret = bch2_read_single_folio(f, mapping);
867 			if (ret)
868 				goto out;
869 		}
870 	}
871 
872 	ret = bch2_folio_set(c, inode_inum(inode), fs.data, fs.nr);
873 	if (ret)
874 		goto out;
875 
876 	f_pos = pos;
877 	f_offset = pos - folio_pos(darray_first(fs));
878 	darray_for_each(fs, fi) {
879 		ssize_t f_reserved;
880 
881 		f = *fi;
882 		f_len = min(end, folio_end_pos(f)) - f_pos;
883 		f_reserved = bch2_folio_reservation_get_partial(c, inode, f, &res, f_offset, f_len);
884 
885 		if (unlikely(f_reserved != f_len)) {
886 			if (f_reserved < 0) {
887 				if (f == darray_first(fs)) {
888 					ret = f_reserved;
889 					goto out;
890 				}
891 
892 				folios_trunc(&fs, fi);
893 				end = min(end, folio_end_pos(darray_last(fs)));
894 			} else {
895 				if (!folio_test_uptodate(f)) {
896 					ret = bch2_read_single_folio(f, mapping);
897 					if (ret)
898 						goto out;
899 				}
900 
901 				folios_trunc(&fs, fi + 1);
902 				end = f_pos + f_reserved;
903 			}
904 
905 			break;
906 		}
907 
908 		f_pos = folio_end_pos(f);
909 		f_offset = 0;
910 	}
911 
912 	if (mapping_writably_mapped(mapping))
913 		darray_for_each(fs, fi)
914 			flush_dcache_folio(*fi);
915 
916 	f_pos = pos;
917 	f_offset = pos - folio_pos(darray_first(fs));
918 	darray_for_each(fs, fi) {
919 		f = *fi;
920 		f_len = min(end, folio_end_pos(f)) - f_pos;
921 		f_copied = copy_folio_from_iter_atomic(f, f_offset, f_len, iter);
922 		if (!f_copied) {
923 			folios_trunc(&fs, fi);
924 			break;
925 		}
926 
927 		if (!folio_test_uptodate(f) &&
928 		    f_copied != folio_size(f) &&
929 		    pos + copied + f_copied < inode->v.i_size) {
930 			iov_iter_revert(iter, f_copied);
931 			folio_zero_range(f, 0, folio_size(f));
932 			folios_trunc(&fs, fi);
933 			break;
934 		}
935 
936 		flush_dcache_folio(f);
937 		copied += f_copied;
938 
939 		if (f_copied != f_len) {
940 			folios_trunc(&fs, fi + 1);
941 			break;
942 		}
943 
944 		f_pos = folio_end_pos(f);
945 		f_offset = 0;
946 	}
947 
948 	if (!copied)
949 		goto out;
950 
951 	end = pos + copied;
952 
953 	spin_lock(&inode->v.i_lock);
954 	if (end > inode->v.i_size)
955 		i_size_write(&inode->v, end);
956 	spin_unlock(&inode->v.i_lock);
957 
958 	f_pos = pos;
959 	f_offset = pos - folio_pos(darray_first(fs));
960 	darray_for_each(fs, fi) {
961 		f = *fi;
962 		f_len = min(end, folio_end_pos(f)) - f_pos;
963 
964 		if (!folio_test_uptodate(f))
965 			folio_mark_uptodate(f);
966 
967 		bch2_set_folio_dirty(c, inode, f, &res, f_offset, f_len);
968 
969 		f_pos = folio_end_pos(f);
970 		f_offset = 0;
971 	}
972 
973 	inode->ei_last_dirtied = (unsigned long) current;
974 out:
975 	darray_for_each(fs, fi) {
976 		folio_unlock(*fi);
977 		folio_put(*fi);
978 	}
979 
980 	/*
981 	 * If the last folio added to the mapping starts beyond current EOF, we
982 	 * performed a short write but left around at least one post-EOF folio.
983 	 * Clean up the mapping before we return.
984 	 */
985 	if (last_folio_pos >= inode->v.i_size)
986 		truncate_pagecache(&inode->v, inode->v.i_size);
987 
988 	darray_exit(&fs);
989 	bch2_folio_reservation_put(c, inode, &res);
990 
991 	return copied ?: ret;
992 }
993 
bch2_buffered_write(struct kiocb * iocb,struct iov_iter * iter)994 static ssize_t bch2_buffered_write(struct kiocb *iocb, struct iov_iter *iter)
995 {
996 	struct file *file = iocb->ki_filp;
997 	struct address_space *mapping = file->f_mapping;
998 	struct bch_inode_info *inode = file_bch_inode(file);
999 	loff_t pos = iocb->ki_pos;
1000 	ssize_t written = 0;
1001 	int ret = 0;
1002 
1003 	bch2_pagecache_add_get(inode);
1004 
1005 	do {
1006 		unsigned offset = pos & (PAGE_SIZE - 1);
1007 		unsigned bytes = iov_iter_count(iter);
1008 again:
1009 		/*
1010 		 * Bring in the user page that we will copy from _first_.
1011 		 * Otherwise there's a nasty deadlock on copying from the
1012 		 * same page as we're writing to, without it being marked
1013 		 * up-to-date.
1014 		 *
1015 		 * Not only is this an optimisation, but it is also required
1016 		 * to check that the address is actually valid, when atomic
1017 		 * usercopies are used, below.
1018 		 */
1019 		if (unlikely(fault_in_iov_iter_readable(iter, bytes))) {
1020 			bytes = min_t(unsigned long, iov_iter_count(iter),
1021 				      PAGE_SIZE - offset);
1022 
1023 			if (unlikely(fault_in_iov_iter_readable(iter, bytes))) {
1024 				ret = -EFAULT;
1025 				break;
1026 			}
1027 		}
1028 
1029 		if (unlikely(fatal_signal_pending(current))) {
1030 			ret = -EINTR;
1031 			break;
1032 		}
1033 
1034 		ret = __bch2_buffered_write(inode, mapping, iter, pos, bytes);
1035 		if (unlikely(ret < 0))
1036 			break;
1037 
1038 		cond_resched();
1039 
1040 		if (unlikely(ret == 0)) {
1041 			/*
1042 			 * If we were unable to copy any data at all, we must
1043 			 * fall back to a single segment length write.
1044 			 *
1045 			 * If we didn't fallback here, we could livelock
1046 			 * because not all segments in the iov can be copied at
1047 			 * once without a pagefault.
1048 			 */
1049 			bytes = min_t(unsigned long, PAGE_SIZE - offset,
1050 				      iov_iter_single_seg_count(iter));
1051 			goto again;
1052 		}
1053 		pos += ret;
1054 		written += ret;
1055 		ret = 0;
1056 
1057 		balance_dirty_pages_ratelimited(mapping);
1058 	} while (iov_iter_count(iter));
1059 
1060 	bch2_pagecache_add_put(inode);
1061 
1062 	return written ? written : ret;
1063 }
1064 
bch2_write_iter(struct kiocb * iocb,struct iov_iter * from)1065 ssize_t bch2_write_iter(struct kiocb *iocb, struct iov_iter *from)
1066 {
1067 	struct file *file = iocb->ki_filp;
1068 	struct bch_inode_info *inode = file_bch_inode(file);
1069 	ssize_t ret;
1070 
1071 	if (iocb->ki_flags & IOCB_DIRECT) {
1072 		ret = bch2_direct_write(iocb, from);
1073 		goto out;
1074 	}
1075 
1076 	inode_lock(&inode->v);
1077 
1078 	ret = generic_write_checks(iocb, from);
1079 	if (ret <= 0)
1080 		goto unlock;
1081 
1082 	ret = file_remove_privs(file);
1083 	if (ret)
1084 		goto unlock;
1085 
1086 	ret = file_update_time(file);
1087 	if (ret)
1088 		goto unlock;
1089 
1090 	ret = bch2_buffered_write(iocb, from);
1091 	if (likely(ret > 0))
1092 		iocb->ki_pos += ret;
1093 unlock:
1094 	inode_unlock(&inode->v);
1095 
1096 	if (ret > 0)
1097 		ret = generic_write_sync(iocb, ret);
1098 out:
1099 	return bch2_err_class(ret);
1100 }
1101 
bch2_fs_fs_io_buffered_exit(struct bch_fs * c)1102 void bch2_fs_fs_io_buffered_exit(struct bch_fs *c)
1103 {
1104 	bioset_exit(&c->writepage_bioset);
1105 }
1106 
bch2_fs_fs_io_buffered_init(struct bch_fs * c)1107 int bch2_fs_fs_io_buffered_init(struct bch_fs *c)
1108 {
1109 	if (bioset_init(&c->writepage_bioset,
1110 			4, offsetof(struct bch_writepage_io, op.wbio.bio),
1111 			BIOSET_NEED_BVECS))
1112 		return -BCH_ERR_ENOMEM_writepage_bioset_init;
1113 
1114 	return 0;
1115 }
1116 
1117 #endif /* NO_BCACHEFS_FS */
1118