Merge tag 'x86-asm-2024-01-08' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip
[linux-2.6-microblaze.git] / fs / bcachefs / fs-io-direct.c
1 // SPDX-License-Identifier: GPL-2.0
2 #ifndef NO_BCACHEFS_FS
3
4 #include "bcachefs.h"
5 #include "alloc_foreground.h"
6 #include "fs.h"
7 #include "fs-io.h"
8 #include "fs-io-direct.h"
9 #include "fs-io-pagecache.h"
10 #include "io_read.h"
11 #include "io_write.h"
12
13 #include <linux/kthread.h>
14 #include <linux/pagemap.h>
15 #include <linux/prefetch.h>
16 #include <linux/task_io_accounting_ops.h>
17
18 /* O_DIRECT reads */
19
20 struct dio_read {
21         struct closure                  cl;
22         struct kiocb                    *req;
23         long                            ret;
24         bool                            should_dirty;
25         struct bch_read_bio             rbio;
26 };
27
28 static void bio_check_or_release(struct bio *bio, bool check_dirty)
29 {
30         if (check_dirty) {
31                 bio_check_pages_dirty(bio);
32         } else {
33                 bio_release_pages(bio, false);
34                 bio_put(bio);
35         }
36 }
37
38 static CLOSURE_CALLBACK(bch2_dio_read_complete)
39 {
40         closure_type(dio, struct dio_read, cl);
41
42         dio->req->ki_complete(dio->req, dio->ret);
43         bio_check_or_release(&dio->rbio.bio, dio->should_dirty);
44 }
45
46 static void bch2_direct_IO_read_endio(struct bio *bio)
47 {
48         struct dio_read *dio = bio->bi_private;
49
50         if (bio->bi_status)
51                 dio->ret = blk_status_to_errno(bio->bi_status);
52
53         closure_put(&dio->cl);
54 }
55
56 static void bch2_direct_IO_read_split_endio(struct bio *bio)
57 {
58         struct dio_read *dio = bio->bi_private;
59         bool should_dirty = dio->should_dirty;
60
61         bch2_direct_IO_read_endio(bio);
62         bio_check_or_release(bio, should_dirty);
63 }
64
65 static int bch2_direct_IO_read(struct kiocb *req, struct iov_iter *iter)
66 {
67         struct file *file = req->ki_filp;
68         struct bch_inode_info *inode = file_bch_inode(file);
69         struct bch_fs *c = inode->v.i_sb->s_fs_info;
70         struct bch_io_opts opts;
71         struct dio_read *dio;
72         struct bio *bio;
73         loff_t offset = req->ki_pos;
74         bool sync = is_sync_kiocb(req);
75         size_t shorten;
76         ssize_t ret;
77
78         bch2_inode_opts_get(&opts, c, &inode->ei_inode);
79
80         if ((offset|iter->count) & (block_bytes(c) - 1))
81                 return -EINVAL;
82
83         ret = min_t(loff_t, iter->count,
84                     max_t(loff_t, 0, i_size_read(&inode->v) - offset));
85
86         if (!ret)
87                 return ret;
88
89         shorten = iov_iter_count(iter) - round_up(ret, block_bytes(c));
90         iter->count -= shorten;
91
92         bio = bio_alloc_bioset(NULL,
93                                bio_iov_vecs_to_alloc(iter, BIO_MAX_VECS),
94                                REQ_OP_READ,
95                                GFP_KERNEL,
96                                &c->dio_read_bioset);
97
98         bio->bi_end_io = bch2_direct_IO_read_endio;
99
100         dio = container_of(bio, struct dio_read, rbio.bio);
101         closure_init(&dio->cl, NULL);
102
103         /*
104          * this is a _really_ horrible hack just to avoid an atomic sub at the
105          * end:
106          */
107         if (!sync) {
108                 set_closure_fn(&dio->cl, bch2_dio_read_complete, NULL);
109                 atomic_set(&dio->cl.remaining,
110                            CLOSURE_REMAINING_INITIALIZER -
111                            CLOSURE_RUNNING +
112                            CLOSURE_DESTRUCTOR);
113         } else {
114                 atomic_set(&dio->cl.remaining,
115                            CLOSURE_REMAINING_INITIALIZER + 1);
116                 dio->cl.closure_get_happened = true;
117         }
118
119         dio->req        = req;
120         dio->ret        = ret;
121         /*
122          * This is one of the sketchier things I've encountered: we have to skip
123          * the dirtying of requests that are internal from the kernel (i.e. from
124          * loopback), because we'll deadlock on page_lock.
125          */
126         dio->should_dirty = iter_is_iovec(iter);
127
128         goto start;
129         while (iter->count) {
130                 bio = bio_alloc_bioset(NULL,
131                                        bio_iov_vecs_to_alloc(iter, BIO_MAX_VECS),
132                                        REQ_OP_READ,
133                                        GFP_KERNEL,
134                                        &c->bio_read);
135                 bio->bi_end_io          = bch2_direct_IO_read_split_endio;
136 start:
137                 bio->bi_opf             = REQ_OP_READ|REQ_SYNC;
138                 bio->bi_iter.bi_sector  = offset >> 9;
139                 bio->bi_private         = dio;
140
141                 ret = bio_iov_iter_get_pages(bio, iter);
142                 if (ret < 0) {
143                         /* XXX: fault inject this path */
144                         bio->bi_status = BLK_STS_RESOURCE;
145                         bio_endio(bio);
146                         break;
147                 }
148
149                 offset += bio->bi_iter.bi_size;
150
151                 if (dio->should_dirty)
152                         bio_set_pages_dirty(bio);
153
154                 if (iter->count)
155                         closure_get(&dio->cl);
156
157                 bch2_read(c, rbio_init(bio, opts), inode_inum(inode));
158         }
159
160         iter->count += shorten;
161
162         if (sync) {
163                 closure_sync(&dio->cl);
164                 closure_debug_destroy(&dio->cl);
165                 ret = dio->ret;
166                 bio_check_or_release(&dio->rbio.bio, dio->should_dirty);
167                 return ret;
168         } else {
169                 return -EIOCBQUEUED;
170         }
171 }
172
173 ssize_t bch2_read_iter(struct kiocb *iocb, struct iov_iter *iter)
174 {
175         struct file *file = iocb->ki_filp;
176         struct bch_inode_info *inode = file_bch_inode(file);
177         struct address_space *mapping = file->f_mapping;
178         size_t count = iov_iter_count(iter);
179         ssize_t ret;
180
181         if (!count)
182                 return 0; /* skip atime */
183
184         if (iocb->ki_flags & IOCB_DIRECT) {
185                 struct blk_plug plug;
186
187                 if (unlikely(mapping->nrpages)) {
188                         ret = filemap_write_and_wait_range(mapping,
189                                                 iocb->ki_pos,
190                                                 iocb->ki_pos + count - 1);
191                         if (ret < 0)
192                                 goto out;
193                 }
194
195                 file_accessed(file);
196
197                 blk_start_plug(&plug);
198                 ret = bch2_direct_IO_read(iocb, iter);
199                 blk_finish_plug(&plug);
200
201                 if (ret >= 0)
202                         iocb->ki_pos += ret;
203         } else {
204                 bch2_pagecache_add_get(inode);
205                 ret = generic_file_read_iter(iocb, iter);
206                 bch2_pagecache_add_put(inode);
207         }
208 out:
209         return bch2_err_class(ret);
210 }
211
212 /* O_DIRECT writes */
213
214 struct dio_write {
215         struct kiocb                    *req;
216         struct address_space            *mapping;
217         struct bch_inode_info           *inode;
218         struct mm_struct                *mm;
219         const struct iovec              *iov;
220         unsigned                        loop:1,
221                                         extending:1,
222                                         sync:1,
223                                         flush:1;
224         struct quota_res                quota_res;
225         u64                             written;
226
227         struct iov_iter                 iter;
228         struct iovec                    inline_vecs[2];
229
230         /* must be last: */
231         struct bch_write_op             op;
232 };
233
234 static bool bch2_check_range_allocated(struct bch_fs *c, subvol_inum inum,
235                                        u64 offset, u64 size,
236                                        unsigned nr_replicas, bool compressed)
237 {
238         struct btree_trans *trans = bch2_trans_get(c);
239         struct btree_iter iter;
240         struct bkey_s_c k;
241         u64 end = offset + size;
242         u32 snapshot;
243         bool ret = true;
244         int err;
245 retry:
246         bch2_trans_begin(trans);
247
248         err = bch2_subvolume_get_snapshot(trans, inum.subvol, &snapshot);
249         if (err)
250                 goto err;
251
252         for_each_btree_key_norestart(trans, iter, BTREE_ID_extents,
253                            SPOS(inum.inum, offset, snapshot),
254                            BTREE_ITER_SLOTS, k, err) {
255                 if (bkey_ge(bkey_start_pos(k.k), POS(inum.inum, end)))
256                         break;
257
258                 if (k.k->p.snapshot != snapshot ||
259                     nr_replicas > bch2_bkey_replicas(c, k) ||
260                     (!compressed && bch2_bkey_sectors_compressed(k))) {
261                         ret = false;
262                         break;
263                 }
264         }
265
266         offset = iter.pos.offset;
267         bch2_trans_iter_exit(trans, &iter);
268 err:
269         if (bch2_err_matches(err, BCH_ERR_transaction_restart))
270                 goto retry;
271         bch2_trans_put(trans);
272
273         return err ? false : ret;
274 }
275
276 static noinline bool bch2_dio_write_check_allocated(struct dio_write *dio)
277 {
278         struct bch_fs *c = dio->op.c;
279         struct bch_inode_info *inode = dio->inode;
280         struct bio *bio = &dio->op.wbio.bio;
281
282         return bch2_check_range_allocated(c, inode_inum(inode),
283                                 dio->op.pos.offset, bio_sectors(bio),
284                                 dio->op.opts.data_replicas,
285                                 dio->op.opts.compression != 0);
286 }
287
288 static void bch2_dio_write_loop_async(struct bch_write_op *);
289 static __always_inline long bch2_dio_write_done(struct dio_write *dio);
290
291 /*
292  * We're going to return -EIOCBQUEUED, but we haven't finished consuming the
293  * iov_iter yet, so we need to stash a copy of the iovec: it might be on the
294  * caller's stack, we're not guaranteed that it will live for the duration of
295  * the IO:
296  */
297 static noinline int bch2_dio_write_copy_iov(struct dio_write *dio)
298 {
299         struct iovec *iov = dio->inline_vecs;
300
301         /*
302          * iov_iter has a single embedded iovec - nothing to do:
303          */
304         if (iter_is_ubuf(&dio->iter))
305                 return 0;
306
307         /*
308          * We don't currently handle non-iovec iov_iters here - return an error,
309          * and we'll fall back to doing the IO synchronously:
310          */
311         if (!iter_is_iovec(&dio->iter))
312                 return -1;
313
314         if (dio->iter.nr_segs > ARRAY_SIZE(dio->inline_vecs)) {
315                 dio->iov = iov = kmalloc_array(dio->iter.nr_segs, sizeof(*iov),
316                                     GFP_KERNEL);
317                 if (unlikely(!iov))
318                         return -ENOMEM;
319         }
320
321         memcpy(iov, dio->iter.__iov, dio->iter.nr_segs * sizeof(*iov));
322         dio->iter.__iov = iov;
323         return 0;
324 }
325
326 static CLOSURE_CALLBACK(bch2_dio_write_flush_done)
327 {
328         closure_type(dio, struct dio_write, op.cl);
329         struct bch_fs *c = dio->op.c;
330
331         closure_debug_destroy(cl);
332
333         dio->op.error = bch2_journal_error(&c->journal);
334
335         bch2_dio_write_done(dio);
336 }
337
338 static noinline void bch2_dio_write_flush(struct dio_write *dio)
339 {
340         struct bch_fs *c = dio->op.c;
341         struct bch_inode_unpacked inode;
342         int ret;
343
344         dio->flush = 0;
345
346         closure_init(&dio->op.cl, NULL);
347
348         if (!dio->op.error) {
349                 ret = bch2_inode_find_by_inum(c, inode_inum(dio->inode), &inode);
350                 if (ret) {
351                         dio->op.error = ret;
352                 } else {
353                         bch2_journal_flush_seq_async(&c->journal, inode.bi_journal_seq,
354                                                      &dio->op.cl);
355                         bch2_inode_flush_nocow_writes_async(c, dio->inode, &dio->op.cl);
356                 }
357         }
358
359         if (dio->sync) {
360                 closure_sync(&dio->op.cl);
361                 closure_debug_destroy(&dio->op.cl);
362         } else {
363                 continue_at(&dio->op.cl, bch2_dio_write_flush_done, NULL);
364         }
365 }
366
367 static __always_inline long bch2_dio_write_done(struct dio_write *dio)
368 {
369         struct kiocb *req = dio->req;
370         struct bch_inode_info *inode = dio->inode;
371         bool sync = dio->sync;
372         long ret;
373
374         if (unlikely(dio->flush)) {
375                 bch2_dio_write_flush(dio);
376                 if (!sync)
377                         return -EIOCBQUEUED;
378         }
379
380         bch2_pagecache_block_put(inode);
381
382         kfree(dio->iov);
383
384         ret = dio->op.error ?: ((long) dio->written << 9);
385         bio_put(&dio->op.wbio.bio);
386
387         /* inode->i_dio_count is our ref on inode and thus bch_fs */
388         inode_dio_end(&inode->v);
389
390         if (ret < 0)
391                 ret = bch2_err_class(ret);
392
393         if (!sync) {
394                 req->ki_complete(req, ret);
395                 ret = -EIOCBQUEUED;
396         }
397         return ret;
398 }
399
400 static __always_inline void bch2_dio_write_end(struct dio_write *dio)
401 {
402         struct bch_fs *c = dio->op.c;
403         struct kiocb *req = dio->req;
404         struct bch_inode_info *inode = dio->inode;
405         struct bio *bio = &dio->op.wbio.bio;
406
407         req->ki_pos     += (u64) dio->op.written << 9;
408         dio->written    += dio->op.written;
409
410         if (dio->extending) {
411                 spin_lock(&inode->v.i_lock);
412                 if (req->ki_pos > inode->v.i_size)
413                         i_size_write(&inode->v, req->ki_pos);
414                 spin_unlock(&inode->v.i_lock);
415         }
416
417         if (dio->op.i_sectors_delta || dio->quota_res.sectors) {
418                 mutex_lock(&inode->ei_quota_lock);
419                 __bch2_i_sectors_acct(c, inode, &dio->quota_res, dio->op.i_sectors_delta);
420                 __bch2_quota_reservation_put(c, inode, &dio->quota_res);
421                 mutex_unlock(&inode->ei_quota_lock);
422         }
423
424         bio_release_pages(bio, false);
425
426         if (unlikely(dio->op.error))
427                 set_bit(EI_INODE_ERROR, &inode->ei_flags);
428 }
429
430 static __always_inline long bch2_dio_write_loop(struct dio_write *dio)
431 {
432         struct bch_fs *c = dio->op.c;
433         struct kiocb *req = dio->req;
434         struct address_space *mapping = dio->mapping;
435         struct bch_inode_info *inode = dio->inode;
436         struct bch_io_opts opts;
437         struct bio *bio = &dio->op.wbio.bio;
438         unsigned unaligned, iter_count;
439         bool sync = dio->sync, dropped_locks;
440         long ret;
441
442         bch2_inode_opts_get(&opts, c, &inode->ei_inode);
443
444         while (1) {
445                 iter_count = dio->iter.count;
446
447                 EBUG_ON(current->faults_disabled_mapping);
448                 current->faults_disabled_mapping = mapping;
449
450                 ret = bio_iov_iter_get_pages(bio, &dio->iter);
451
452                 dropped_locks = fdm_dropped_locks();
453
454                 current->faults_disabled_mapping = NULL;
455
456                 /*
457                  * If the fault handler returned an error but also signalled
458                  * that it dropped & retook ei_pagecache_lock, we just need to
459                  * re-shoot down the page cache and retry:
460                  */
461                 if (dropped_locks && ret)
462                         ret = 0;
463
464                 if (unlikely(ret < 0))
465                         goto err;
466
467                 if (unlikely(dropped_locks)) {
468                         ret = bch2_write_invalidate_inode_pages_range(mapping,
469                                         req->ki_pos,
470                                         req->ki_pos + iter_count - 1);
471                         if (unlikely(ret))
472                                 goto err;
473
474                         if (!bio->bi_iter.bi_size)
475                                 continue;
476                 }
477
478                 unaligned = bio->bi_iter.bi_size & (block_bytes(c) - 1);
479                 bio->bi_iter.bi_size -= unaligned;
480                 iov_iter_revert(&dio->iter, unaligned);
481
482                 if (!bio->bi_iter.bi_size) {
483                         /*
484                          * bio_iov_iter_get_pages was only able to get <
485                          * blocksize worth of pages:
486                          */
487                         ret = -EFAULT;
488                         goto err;
489                 }
490
491                 bch2_write_op_init(&dio->op, c, opts);
492                 dio->op.end_io          = sync
493                         ? NULL
494                         : bch2_dio_write_loop_async;
495                 dio->op.target          = dio->op.opts.foreground_target;
496                 dio->op.write_point     = writepoint_hashed((unsigned long) current);
497                 dio->op.nr_replicas     = dio->op.opts.data_replicas;
498                 dio->op.subvol          = inode->ei_subvol;
499                 dio->op.pos             = POS(inode->v.i_ino, (u64) req->ki_pos >> 9);
500                 dio->op.devs_need_flush = &inode->ei_devs_need_flush;
501
502                 if (sync)
503                         dio->op.flags |= BCH_WRITE_SYNC;
504                 dio->op.flags |= BCH_WRITE_CHECK_ENOSPC;
505
506                 ret = bch2_quota_reservation_add(c, inode, &dio->quota_res,
507                                                  bio_sectors(bio), true);
508                 if (unlikely(ret))
509                         goto err;
510
511                 ret = bch2_disk_reservation_get(c, &dio->op.res, bio_sectors(bio),
512                                                 dio->op.opts.data_replicas, 0);
513                 if (unlikely(ret) &&
514                     !bch2_dio_write_check_allocated(dio))
515                         goto err;
516
517                 task_io_account_write(bio->bi_iter.bi_size);
518
519                 if (unlikely(dio->iter.count) &&
520                     !dio->sync &&
521                     !dio->loop &&
522                     bch2_dio_write_copy_iov(dio))
523                         dio->sync = sync = true;
524
525                 dio->loop = true;
526                 closure_call(&dio->op.cl, bch2_write, NULL, NULL);
527
528                 if (!sync)
529                         return -EIOCBQUEUED;
530
531                 bch2_dio_write_end(dio);
532
533                 if (likely(!dio->iter.count) || dio->op.error)
534                         break;
535
536                 bio_reset(bio, NULL, REQ_OP_WRITE);
537         }
538 out:
539         return bch2_dio_write_done(dio);
540 err:
541         dio->op.error = ret;
542
543         bio_release_pages(bio, false);
544
545         bch2_quota_reservation_put(c, inode, &dio->quota_res);
546         goto out;
547 }
548
549 static noinline __cold void bch2_dio_write_continue(struct dio_write *dio)
550 {
551         struct mm_struct *mm = dio->mm;
552
553         bio_reset(&dio->op.wbio.bio, NULL, REQ_OP_WRITE);
554
555         if (mm)
556                 kthread_use_mm(mm);
557         bch2_dio_write_loop(dio);
558         if (mm)
559                 kthread_unuse_mm(mm);
560 }
561
562 static void bch2_dio_write_loop_async(struct bch_write_op *op)
563 {
564         struct dio_write *dio = container_of(op, struct dio_write, op);
565
566         bch2_dio_write_end(dio);
567
568         if (likely(!dio->iter.count) || dio->op.error)
569                 bch2_dio_write_done(dio);
570         else
571                 bch2_dio_write_continue(dio);
572 }
573
574 ssize_t bch2_direct_write(struct kiocb *req, struct iov_iter *iter)
575 {
576         struct file *file = req->ki_filp;
577         struct address_space *mapping = file->f_mapping;
578         struct bch_inode_info *inode = file_bch_inode(file);
579         struct bch_fs *c = inode->v.i_sb->s_fs_info;
580         struct dio_write *dio;
581         struct bio *bio;
582         bool locked = true, extending;
583         ssize_t ret;
584
585         prefetch(&c->opts);
586         prefetch((void *) &c->opts + 64);
587         prefetch(&inode->ei_inode);
588         prefetch((void *) &inode->ei_inode + 64);
589
590         inode_lock(&inode->v);
591
592         ret = generic_write_checks(req, iter);
593         if (unlikely(ret <= 0))
594                 goto err;
595
596         ret = file_remove_privs(file);
597         if (unlikely(ret))
598                 goto err;
599
600         ret = file_update_time(file);
601         if (unlikely(ret))
602                 goto err;
603
604         if (unlikely((req->ki_pos|iter->count) & (block_bytes(c) - 1)))
605                 goto err;
606
607         inode_dio_begin(&inode->v);
608         bch2_pagecache_block_get(inode);
609
610         extending = req->ki_pos + iter->count > inode->v.i_size;
611         if (!extending) {
612                 inode_unlock(&inode->v);
613                 locked = false;
614         }
615
616         bio = bio_alloc_bioset(NULL,
617                                bio_iov_vecs_to_alloc(iter, BIO_MAX_VECS),
618                                REQ_OP_WRITE,
619                                GFP_KERNEL,
620                                &c->dio_write_bioset);
621         dio = container_of(bio, struct dio_write, op.wbio.bio);
622         dio->req                = req;
623         dio->mapping            = mapping;
624         dio->inode              = inode;
625         dio->mm                 = current->mm;
626         dio->iov                = NULL;
627         dio->loop               = false;
628         dio->extending          = extending;
629         dio->sync               = is_sync_kiocb(req) || extending;
630         dio->flush              = iocb_is_dsync(req) && !c->opts.journal_flush_disabled;
631         dio->quota_res.sectors  = 0;
632         dio->written            = 0;
633         dio->iter               = *iter;
634         dio->op.c               = c;
635
636         if (unlikely(mapping->nrpages)) {
637                 ret = bch2_write_invalidate_inode_pages_range(mapping,
638                                                 req->ki_pos,
639                                                 req->ki_pos + iter->count - 1);
640                 if (unlikely(ret))
641                         goto err_put_bio;
642         }
643
644         ret = bch2_dio_write_loop(dio);
645 err:
646         if (locked)
647                 inode_unlock(&inode->v);
648         return ret;
649 err_put_bio:
650         bch2_pagecache_block_put(inode);
651         bio_put(bio);
652         inode_dio_end(&inode->v);
653         goto err;
654 }
655
656 void bch2_fs_fs_io_direct_exit(struct bch_fs *c)
657 {
658         bioset_exit(&c->dio_write_bioset);
659         bioset_exit(&c->dio_read_bioset);
660 }
661
662 int bch2_fs_fs_io_direct_init(struct bch_fs *c)
663 {
664         if (bioset_init(&c->dio_read_bioset,
665                         4, offsetof(struct dio_read, rbio.bio),
666                         BIOSET_NEED_BVECS))
667                 return -BCH_ERR_ENOMEM_dio_read_bioset_init;
668
669         if (bioset_init(&c->dio_write_bioset,
670                         4, offsetof(struct dio_write, op.wbio.bio),
671                         BIOSET_NEED_BVECS))
672                 return -BCH_ERR_ENOMEM_dio_write_bioset_init;
673
674         return 0;
675 }
676
677 #endif /* NO_BCACHEFS_FS */