]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/io_write.c
Update bcachefs sources to 841a95c29f4c bcachefs: fix userspace build errors
[bcachefs-tools-debian] / libbcachefs / io_write.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
4  * Copyright 2012 Google, Inc.
5  */
6
7 #include "bcachefs.h"
8 #include "alloc_foreground.h"
9 #include "bkey_buf.h"
10 #include "bset.h"
11 #include "btree_update.h"
12 #include "buckets.h"
13 #include "checksum.h"
14 #include "clock.h"
15 #include "compress.h"
16 #include "debug.h"
17 #include "ec.h"
18 #include "error.h"
19 #include "extent_update.h"
20 #include "inode.h"
21 #include "io_write.h"
22 #include "journal.h"
23 #include "keylist.h"
24 #include "move.h"
25 #include "nocow_locking.h"
26 #include "rebalance.h"
27 #include "subvolume.h"
28 #include "super.h"
29 #include "super-io.h"
30 #include "trace.h"
31
32 #include <linux/blkdev.h>
33 #include <linux/prefetch.h>
34 #include <linux/random.h>
35 #include <linux/sched/mm.h>
36
37 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
38
39 static inline void bch2_congested_acct(struct bch_dev *ca, u64 io_latency,
40                                        u64 now, int rw)
41 {
42         u64 latency_capable =
43                 ca->io_latency[rw].quantiles.entries[QUANTILE_IDX(1)].m;
44         /* ideally we'd be taking into account the device's variance here: */
45         u64 latency_threshold = latency_capable << (rw == READ ? 2 : 3);
46         s64 latency_over = io_latency - latency_threshold;
47
48         if (latency_threshold && latency_over > 0) {
49                 /*
50                  * bump up congested by approximately latency_over * 4 /
51                  * latency_threshold - we don't need much accuracy here so don't
52                  * bother with the divide:
53                  */
54                 if (atomic_read(&ca->congested) < CONGESTED_MAX)
55                         atomic_add(latency_over >>
56                                    max_t(int, ilog2(latency_threshold) - 2, 0),
57                                    &ca->congested);
58
59                 ca->congested_last = now;
60         } else if (atomic_read(&ca->congested) > 0) {
61                 atomic_dec(&ca->congested);
62         }
63 }
64
65 void bch2_latency_acct(struct bch_dev *ca, u64 submit_time, int rw)
66 {
67         atomic64_t *latency = &ca->cur_latency[rw];
68         u64 now = local_clock();
69         u64 io_latency = time_after64(now, submit_time)
70                 ? now - submit_time
71                 : 0;
72         u64 old, new, v = atomic64_read(latency);
73
74         do {
75                 old = v;
76
77                 /*
78                  * If the io latency was reasonably close to the current
79                  * latency, skip doing the update and atomic operation - most of
80                  * the time:
81                  */
82                 if (abs((int) (old - io_latency)) < (old >> 1) &&
83                     now & ~(~0U << 5))
84                         break;
85
86                 new = ewma_add(old, io_latency, 5);
87         } while ((v = atomic64_cmpxchg(latency, old, new)) != old);
88
89         bch2_congested_acct(ca, io_latency, now, rw);
90
91         __bch2_time_stats_update(&ca->io_latency[rw], submit_time, now);
92 }
93
94 #endif
95
96 /* Allocate, free from mempool: */
97
98 void bch2_bio_free_pages_pool(struct bch_fs *c, struct bio *bio)
99 {
100         struct bvec_iter_all iter;
101         struct bio_vec *bv;
102
103         bio_for_each_segment_all(bv, bio, iter)
104                 if (bv->bv_page != ZERO_PAGE(0))
105                         mempool_free(bv->bv_page, &c->bio_bounce_pages);
106         bio->bi_vcnt = 0;
107 }
108
109 static struct page *__bio_alloc_page_pool(struct bch_fs *c, bool *using_mempool)
110 {
111         struct page *page;
112
113         if (likely(!*using_mempool)) {
114                 page = alloc_page(GFP_NOFS);
115                 if (unlikely(!page)) {
116                         mutex_lock(&c->bio_bounce_pages_lock);
117                         *using_mempool = true;
118                         goto pool_alloc;
119
120                 }
121         } else {
122 pool_alloc:
123                 page = mempool_alloc(&c->bio_bounce_pages, GFP_NOFS);
124         }
125
126         return page;
127 }
128
129 void bch2_bio_alloc_pages_pool(struct bch_fs *c, struct bio *bio,
130                                size_t size)
131 {
132         bool using_mempool = false;
133
134         while (size) {
135                 struct page *page = __bio_alloc_page_pool(c, &using_mempool);
136                 unsigned len = min_t(size_t, PAGE_SIZE, size);
137
138                 BUG_ON(!bio_add_page(bio, page, len, 0));
139                 size -= len;
140         }
141
142         if (using_mempool)
143                 mutex_unlock(&c->bio_bounce_pages_lock);
144 }
145
146 /* Extent update path: */
147
148 int bch2_sum_sector_overwrites(struct btree_trans *trans,
149                                struct btree_iter *extent_iter,
150                                struct bkey_i *new,
151                                bool *usage_increasing,
152                                s64 *i_sectors_delta,
153                                s64 *disk_sectors_delta)
154 {
155         struct bch_fs *c = trans->c;
156         struct btree_iter iter;
157         struct bkey_s_c old;
158         unsigned new_replicas = bch2_bkey_replicas(c, bkey_i_to_s_c(new));
159         bool new_compressed = bch2_bkey_sectors_compressed(bkey_i_to_s_c(new));
160         int ret = 0;
161
162         *usage_increasing       = false;
163         *i_sectors_delta        = 0;
164         *disk_sectors_delta     = 0;
165
166         bch2_trans_copy_iter(&iter, extent_iter);
167
168         for_each_btree_key_upto_continue_norestart(iter,
169                                 new->k.p, BTREE_ITER_SLOTS, old, ret) {
170                 s64 sectors = min(new->k.p.offset, old.k->p.offset) -
171                         max(bkey_start_offset(&new->k),
172                             bkey_start_offset(old.k));
173
174                 *i_sectors_delta += sectors *
175                         (bkey_extent_is_allocation(&new->k) -
176                          bkey_extent_is_allocation(old.k));
177
178                 *disk_sectors_delta += sectors * bch2_bkey_nr_ptrs_allocated(bkey_i_to_s_c(new));
179                 *disk_sectors_delta -= new->k.p.snapshot == old.k->p.snapshot
180                         ? sectors * bch2_bkey_nr_ptrs_fully_allocated(old)
181                         : 0;
182
183                 if (!*usage_increasing &&
184                     (new->k.p.snapshot != old.k->p.snapshot ||
185                      new_replicas > bch2_bkey_replicas(c, old) ||
186                      (!new_compressed && bch2_bkey_sectors_compressed(old))))
187                         *usage_increasing = true;
188
189                 if (bkey_ge(old.k->p, new->k.p))
190                         break;
191         }
192
193         bch2_trans_iter_exit(trans, &iter);
194         return ret;
195 }
196
197 static inline int bch2_extent_update_i_size_sectors(struct btree_trans *trans,
198                                                     struct btree_iter *extent_iter,
199                                                     u64 new_i_size,
200                                                     s64 i_sectors_delta)
201 {
202         struct btree_iter iter;
203         struct bkey_i *k;
204         struct bkey_i_inode_v3 *inode;
205         /*
206          * Crazy performance optimization:
207          * Every extent update needs to also update the inode: the inode trigger
208          * will set bi->journal_seq to the journal sequence number of this
209          * transaction - for fsync.
210          *
211          * But if that's the only reason we're updating the inode (we're not
212          * updating bi_size or bi_sectors), then we don't need the inode update
213          * to be journalled - if we crash, the bi_journal_seq update will be
214          * lost, but that's fine.
215          */
216         unsigned inode_update_flags = BTREE_UPDATE_NOJOURNAL;
217         int ret;
218
219         k = bch2_bkey_get_mut_noupdate(trans, &iter, BTREE_ID_inodes,
220                               SPOS(0,
221                                    extent_iter->pos.inode,
222                                    extent_iter->snapshot),
223                               BTREE_ITER_CACHED);
224         ret = PTR_ERR_OR_ZERO(k);
225         if (unlikely(ret))
226                 return ret;
227
228         if (unlikely(k->k.type != KEY_TYPE_inode_v3)) {
229                 k = bch2_inode_to_v3(trans, k);
230                 ret = PTR_ERR_OR_ZERO(k);
231                 if (unlikely(ret))
232                         goto err;
233         }
234
235         inode = bkey_i_to_inode_v3(k);
236
237         if (!(le64_to_cpu(inode->v.bi_flags) & BCH_INODE_i_size_dirty) &&
238             new_i_size > le64_to_cpu(inode->v.bi_size)) {
239                 inode->v.bi_size = cpu_to_le64(new_i_size);
240                 inode_update_flags = 0;
241         }
242
243         if (i_sectors_delta) {
244                 le64_add_cpu(&inode->v.bi_sectors, i_sectors_delta);
245                 inode_update_flags = 0;
246         }
247
248         if (inode->k.p.snapshot != iter.snapshot) {
249                 inode->k.p.snapshot = iter.snapshot;
250                 inode_update_flags = 0;
251         }
252
253         ret = bch2_trans_update(trans, &iter, &inode->k_i,
254                                 BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE|
255                                 inode_update_flags);
256 err:
257         bch2_trans_iter_exit(trans, &iter);
258         return ret;
259 }
260
261 int bch2_extent_update(struct btree_trans *trans,
262                        subvol_inum inum,
263                        struct btree_iter *iter,
264                        struct bkey_i *k,
265                        struct disk_reservation *disk_res,
266                        u64 new_i_size,
267                        s64 *i_sectors_delta_total,
268                        bool check_enospc)
269 {
270         struct bpos next_pos;
271         bool usage_increasing;
272         s64 i_sectors_delta = 0, disk_sectors_delta = 0;
273         int ret;
274
275         /*
276          * This traverses us the iterator without changing iter->path->pos to
277          * search_key() (which is pos + 1 for extents): we want there to be a
278          * path already traversed at iter->pos because
279          * bch2_trans_extent_update() will use it to attempt extent merging
280          */
281         ret = __bch2_btree_iter_traverse(iter);
282         if (ret)
283                 return ret;
284
285         ret = bch2_extent_trim_atomic(trans, iter, k);
286         if (ret)
287                 return ret;
288
289         next_pos = k->k.p;
290
291         ret = bch2_sum_sector_overwrites(trans, iter, k,
292                         &usage_increasing,
293                         &i_sectors_delta,
294                         &disk_sectors_delta);
295         if (ret)
296                 return ret;
297
298         if (disk_res &&
299             disk_sectors_delta > (s64) disk_res->sectors) {
300                 ret = bch2_disk_reservation_add(trans->c, disk_res,
301                                         disk_sectors_delta - disk_res->sectors,
302                                         !check_enospc || !usage_increasing
303                                         ? BCH_DISK_RESERVATION_NOFAIL : 0);
304                 if (ret)
305                         return ret;
306         }
307
308         /*
309          * Note:
310          * We always have to do an inode update - even when i_size/i_sectors
311          * aren't changing - for fsync to work properly; fsync relies on
312          * inode->bi_journal_seq which is updated by the trigger code:
313          */
314         ret =   bch2_extent_update_i_size_sectors(trans, iter,
315                                                   min(k->k.p.offset << 9, new_i_size),
316                                                   i_sectors_delta) ?:
317                 bch2_trans_update(trans, iter, k, 0) ?:
318                 bch2_trans_commit(trans, disk_res, NULL,
319                                 BCH_TRANS_COMMIT_no_check_rw|
320                                 BCH_TRANS_COMMIT_no_enospc);
321         if (unlikely(ret))
322                 return ret;
323
324         if (i_sectors_delta_total)
325                 *i_sectors_delta_total += i_sectors_delta;
326         bch2_btree_iter_set_pos(iter, next_pos);
327         return 0;
328 }
329
330 static int bch2_write_index_default(struct bch_write_op *op)
331 {
332         struct bch_fs *c = op->c;
333         struct bkey_buf sk;
334         struct keylist *keys = &op->insert_keys;
335         struct bkey_i *k = bch2_keylist_front(keys);
336         struct btree_trans *trans = bch2_trans_get(c);
337         struct btree_iter iter;
338         subvol_inum inum = {
339                 .subvol = op->subvol,
340                 .inum   = k->k.p.inode,
341         };
342         int ret;
343
344         BUG_ON(!inum.subvol);
345
346         bch2_bkey_buf_init(&sk);
347
348         do {
349                 bch2_trans_begin(trans);
350
351                 k = bch2_keylist_front(keys);
352                 bch2_bkey_buf_copy(&sk, c, k);
353
354                 ret = bch2_subvolume_get_snapshot(trans, inum.subvol,
355                                                   &sk.k->k.p.snapshot);
356                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
357                         continue;
358                 if (ret)
359                         break;
360
361                 bch2_trans_iter_init(trans, &iter, BTREE_ID_extents,
362                                      bkey_start_pos(&sk.k->k),
363                                      BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
364
365                 ret =   bch2_bkey_set_needs_rebalance(c, sk.k,
366                                         op->opts.background_target,
367                                         op->opts.background_compression) ?:
368                         bch2_extent_update(trans, inum, &iter, sk.k,
369                                         &op->res,
370                                         op->new_i_size, &op->i_sectors_delta,
371                                         op->flags & BCH_WRITE_CHECK_ENOSPC);
372                 bch2_trans_iter_exit(trans, &iter);
373
374                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
375                         continue;
376                 if (ret)
377                         break;
378
379                 if (bkey_ge(iter.pos, k->k.p))
380                         bch2_keylist_pop_front(&op->insert_keys);
381                 else
382                         bch2_cut_front(iter.pos, k);
383         } while (!bch2_keylist_empty(keys));
384
385         bch2_trans_put(trans);
386         bch2_bkey_buf_exit(&sk, c);
387
388         return ret;
389 }
390
391 /* Writes */
392
393 void bch2_submit_wbio_replicas(struct bch_write_bio *wbio, struct bch_fs *c,
394                                enum bch_data_type type,
395                                const struct bkey_i *k,
396                                bool nocow)
397 {
398         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
399         const struct bch_extent_ptr *ptr;
400         struct bch_write_bio *n;
401         struct bch_dev *ca;
402
403         BUG_ON(c->opts.nochanges);
404
405         bkey_for_each_ptr(ptrs, ptr) {
406                 BUG_ON(!bch2_dev_exists2(c, ptr->dev));
407
408                 ca = bch_dev_bkey_exists(c, ptr->dev);
409
410                 if (to_entry(ptr + 1) < ptrs.end) {
411                         n = to_wbio(bio_alloc_clone(NULL, &wbio->bio,
412                                                 GFP_NOFS, &ca->replica_set));
413
414                         n->bio.bi_end_io        = wbio->bio.bi_end_io;
415                         n->bio.bi_private       = wbio->bio.bi_private;
416                         n->parent               = wbio;
417                         n->split                = true;
418                         n->bounce               = false;
419                         n->put_bio              = true;
420                         n->bio.bi_opf           = wbio->bio.bi_opf;
421                         bio_inc_remaining(&wbio->bio);
422                 } else {
423                         n = wbio;
424                         n->split                = false;
425                 }
426
427                 n->c                    = c;
428                 n->dev                  = ptr->dev;
429                 n->have_ioref           = nocow || bch2_dev_get_ioref(ca,
430                                         type == BCH_DATA_btree ? READ : WRITE);
431                 n->nocow                = nocow;
432                 n->submit_time          = local_clock();
433                 n->inode_offset         = bkey_start_offset(&k->k);
434                 n->bio.bi_iter.bi_sector = ptr->offset;
435
436                 if (likely(n->have_ioref)) {
437                         this_cpu_add(ca->io_done->sectors[WRITE][type],
438                                      bio_sectors(&n->bio));
439
440                         bio_set_dev(&n->bio, ca->disk_sb.bdev);
441
442                         if (type != BCH_DATA_btree && unlikely(c->opts.no_data_io)) {
443                                 bio_endio(&n->bio);
444                                 continue;
445                         }
446
447                         submit_bio(&n->bio);
448                 } else {
449                         n->bio.bi_status        = BLK_STS_REMOVED;
450                         bio_endio(&n->bio);
451                 }
452         }
453 }
454
455 static void __bch2_write(struct bch_write_op *);
456
457 static void bch2_write_done(struct closure *cl)
458 {
459         struct bch_write_op *op = container_of(cl, struct bch_write_op, cl);
460         struct bch_fs *c = op->c;
461
462         EBUG_ON(op->open_buckets.nr);
463
464         bch2_time_stats_update(&c->times[BCH_TIME_data_write], op->start_time);
465         bch2_disk_reservation_put(c, &op->res);
466
467         if (!(op->flags & BCH_WRITE_MOVE))
468                 bch2_write_ref_put(c, BCH_WRITE_REF_write);
469         bch2_keylist_free(&op->insert_keys, op->inline_keys);
470
471         EBUG_ON(cl->parent);
472         closure_debug_destroy(cl);
473         if (op->end_io)
474                 op->end_io(op);
475 }
476
477 static noinline int bch2_write_drop_io_error_ptrs(struct bch_write_op *op)
478 {
479         struct keylist *keys = &op->insert_keys;
480         struct bch_extent_ptr *ptr;
481         struct bkey_i *src, *dst = keys->keys, *n;
482
483         for (src = keys->keys; src != keys->top; src = n) {
484                 n = bkey_next(src);
485
486                 if (bkey_extent_is_direct_data(&src->k)) {
487                         bch2_bkey_drop_ptrs(bkey_i_to_s(src), ptr,
488                                             test_bit(ptr->dev, op->failed.d));
489
490                         if (!bch2_bkey_nr_ptrs(bkey_i_to_s_c(src)))
491                                 return -EIO;
492                 }
493
494                 if (dst != src)
495                         memmove_u64s_down(dst, src, src->k.u64s);
496                 dst = bkey_next(dst);
497         }
498
499         keys->top = dst;
500         return 0;
501 }
502
503 /**
504  * __bch2_write_index - after a write, update index to point to new data
505  * @op:         bch_write_op to process
506  */
507 static void __bch2_write_index(struct bch_write_op *op)
508 {
509         struct bch_fs *c = op->c;
510         struct keylist *keys = &op->insert_keys;
511         unsigned dev;
512         int ret = 0;
513
514         if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
515                 ret = bch2_write_drop_io_error_ptrs(op);
516                 if (ret)
517                         goto err;
518         }
519
520         if (!bch2_keylist_empty(keys)) {
521                 u64 sectors_start = keylist_sectors(keys);
522
523                 ret = !(op->flags & BCH_WRITE_MOVE)
524                         ? bch2_write_index_default(op)
525                         : bch2_data_update_index_update(op);
526
527                 BUG_ON(bch2_err_matches(ret, BCH_ERR_transaction_restart));
528                 BUG_ON(keylist_sectors(keys) && !ret);
529
530                 op->written += sectors_start - keylist_sectors(keys);
531
532                 if (ret && !bch2_err_matches(ret, EROFS)) {
533                         struct bkey_i *insert = bch2_keylist_front(&op->insert_keys);
534
535                         bch_err_inum_offset_ratelimited(c,
536                                 insert->k.p.inode, insert->k.p.offset << 9,
537                                 "write error while doing btree update: %s",
538                                 bch2_err_str(ret));
539                 }
540
541                 if (ret)
542                         goto err;
543         }
544 out:
545         /* If some a bucket wasn't written, we can't erasure code it: */
546         for_each_set_bit(dev, op->failed.d, BCH_SB_MEMBERS_MAX)
547                 bch2_open_bucket_write_error(c, &op->open_buckets, dev);
548
549         bch2_open_buckets_put(c, &op->open_buckets);
550         return;
551 err:
552         keys->top = keys->keys;
553         op->error = ret;
554         op->flags |= BCH_WRITE_DONE;
555         goto out;
556 }
557
558 static inline void __wp_update_state(struct write_point *wp, enum write_point_state state)
559 {
560         if (state != wp->state) {
561                 u64 now = ktime_get_ns();
562
563                 if (wp->last_state_change &&
564                     time_after64(now, wp->last_state_change))
565                         wp->time[wp->state] += now - wp->last_state_change;
566                 wp->state = state;
567                 wp->last_state_change = now;
568         }
569 }
570
571 static inline void wp_update_state(struct write_point *wp, bool running)
572 {
573         enum write_point_state state;
574
575         state = running                  ? WRITE_POINT_running :
576                 !list_empty(&wp->writes) ? WRITE_POINT_waiting_io
577                                          : WRITE_POINT_stopped;
578
579         __wp_update_state(wp, state);
580 }
581
582 static CLOSURE_CALLBACK(bch2_write_index)
583 {
584         closure_type(op, struct bch_write_op, cl);
585         struct write_point *wp = op->wp;
586         struct workqueue_struct *wq = index_update_wq(op);
587         unsigned long flags;
588
589         if ((op->flags & BCH_WRITE_DONE) &&
590             (op->flags & BCH_WRITE_MOVE))
591                 bch2_bio_free_pages_pool(op->c, &op->wbio.bio);
592
593         spin_lock_irqsave(&wp->writes_lock, flags);
594         if (wp->state == WRITE_POINT_waiting_io)
595                 __wp_update_state(wp, WRITE_POINT_waiting_work);
596         list_add_tail(&op->wp_list, &wp->writes);
597         spin_unlock_irqrestore (&wp->writes_lock, flags);
598
599         queue_work(wq, &wp->index_update_work);
600 }
601
602 static inline void bch2_write_queue(struct bch_write_op *op, struct write_point *wp)
603 {
604         op->wp = wp;
605
606         if (wp->state == WRITE_POINT_stopped) {
607                 spin_lock_irq(&wp->writes_lock);
608                 __wp_update_state(wp, WRITE_POINT_waiting_io);
609                 spin_unlock_irq(&wp->writes_lock);
610         }
611 }
612
613 void bch2_write_point_do_index_updates(struct work_struct *work)
614 {
615         struct write_point *wp =
616                 container_of(work, struct write_point, index_update_work);
617         struct bch_write_op *op;
618
619         while (1) {
620                 spin_lock_irq(&wp->writes_lock);
621                 op = list_first_entry_or_null(&wp->writes, struct bch_write_op, wp_list);
622                 if (op)
623                         list_del(&op->wp_list);
624                 wp_update_state(wp, op != NULL);
625                 spin_unlock_irq(&wp->writes_lock);
626
627                 if (!op)
628                         break;
629
630                 op->flags |= BCH_WRITE_IN_WORKER;
631
632                 __bch2_write_index(op);
633
634                 if (!(op->flags & BCH_WRITE_DONE))
635                         __bch2_write(op);
636                 else
637                         bch2_write_done(&op->cl);
638         }
639 }
640
641 static void bch2_write_endio(struct bio *bio)
642 {
643         struct closure *cl              = bio->bi_private;
644         struct bch_write_op *op         = container_of(cl, struct bch_write_op, cl);
645         struct bch_write_bio *wbio      = to_wbio(bio);
646         struct bch_write_bio *parent    = wbio->split ? wbio->parent : NULL;
647         struct bch_fs *c                = wbio->c;
648         struct bch_dev *ca              = bch_dev_bkey_exists(c, wbio->dev);
649
650         if (bch2_dev_inum_io_err_on(bio->bi_status, ca, BCH_MEMBER_ERROR_write,
651                                     op->pos.inode,
652                                     wbio->inode_offset << 9,
653                                     "data write error: %s",
654                                     bch2_blk_status_to_str(bio->bi_status))) {
655                 set_bit(wbio->dev, op->failed.d);
656                 op->flags |= BCH_WRITE_IO_ERROR;
657         }
658
659         if (wbio->nocow)
660                 set_bit(wbio->dev, op->devs_need_flush->d);
661
662         if (wbio->have_ioref) {
663                 bch2_latency_acct(ca, wbio->submit_time, WRITE);
664                 percpu_ref_put(&ca->io_ref);
665         }
666
667         if (wbio->bounce)
668                 bch2_bio_free_pages_pool(c, bio);
669
670         if (wbio->put_bio)
671                 bio_put(bio);
672
673         if (parent)
674                 bio_endio(&parent->bio);
675         else
676                 closure_put(cl);
677 }
678
679 static void init_append_extent(struct bch_write_op *op,
680                                struct write_point *wp,
681                                struct bversion version,
682                                struct bch_extent_crc_unpacked crc)
683 {
684         struct bkey_i_extent *e;
685
686         op->pos.offset += crc.uncompressed_size;
687
688         e = bkey_extent_init(op->insert_keys.top);
689         e->k.p          = op->pos;
690         e->k.size       = crc.uncompressed_size;
691         e->k.version    = version;
692
693         if (crc.csum_type ||
694             crc.compression_type ||
695             crc.nonce)
696                 bch2_extent_crc_append(&e->k_i, crc);
697
698         bch2_alloc_sectors_append_ptrs_inlined(op->c, wp, &e->k_i, crc.compressed_size,
699                                        op->flags & BCH_WRITE_CACHED);
700
701         bch2_keylist_push(&op->insert_keys);
702 }
703
704 static struct bio *bch2_write_bio_alloc(struct bch_fs *c,
705                                         struct write_point *wp,
706                                         struct bio *src,
707                                         bool *page_alloc_failed,
708                                         void *buf)
709 {
710         struct bch_write_bio *wbio;
711         struct bio *bio;
712         unsigned output_available =
713                 min(wp->sectors_free << 9, src->bi_iter.bi_size);
714         unsigned pages = DIV_ROUND_UP(output_available +
715                                       (buf
716                                        ? ((unsigned long) buf & (PAGE_SIZE - 1))
717                                        : 0), PAGE_SIZE);
718
719         pages = min(pages, BIO_MAX_VECS);
720
721         bio = bio_alloc_bioset(NULL, pages, 0,
722                                GFP_NOFS, &c->bio_write);
723         wbio                    = wbio_init(bio);
724         wbio->put_bio           = true;
725         /* copy WRITE_SYNC flag */
726         wbio->bio.bi_opf        = src->bi_opf;
727
728         if (buf) {
729                 bch2_bio_map(bio, buf, output_available);
730                 return bio;
731         }
732
733         wbio->bounce            = true;
734
735         /*
736          * We can't use mempool for more than c->sb.encoded_extent_max
737          * worth of pages, but we'd like to allocate more if we can:
738          */
739         bch2_bio_alloc_pages_pool(c, bio,
740                                   min_t(unsigned, output_available,
741                                         c->opts.encoded_extent_max));
742
743         if (bio->bi_iter.bi_size < output_available)
744                 *page_alloc_failed =
745                         bch2_bio_alloc_pages(bio,
746                                              output_available -
747                                              bio->bi_iter.bi_size,
748                                              GFP_NOFS) != 0;
749
750         return bio;
751 }
752
753 static int bch2_write_rechecksum(struct bch_fs *c,
754                                  struct bch_write_op *op,
755                                  unsigned new_csum_type)
756 {
757         struct bio *bio = &op->wbio.bio;
758         struct bch_extent_crc_unpacked new_crc;
759         int ret;
760
761         /* bch2_rechecksum_bio() can't encrypt or decrypt data: */
762
763         if (bch2_csum_type_is_encryption(op->crc.csum_type) !=
764             bch2_csum_type_is_encryption(new_csum_type))
765                 new_csum_type = op->crc.csum_type;
766
767         ret = bch2_rechecksum_bio(c, bio, op->version, op->crc,
768                                   NULL, &new_crc,
769                                   op->crc.offset, op->crc.live_size,
770                                   new_csum_type);
771         if (ret)
772                 return ret;
773
774         bio_advance(bio, op->crc.offset << 9);
775         bio->bi_iter.bi_size = op->crc.live_size << 9;
776         op->crc = new_crc;
777         return 0;
778 }
779
780 static int bch2_write_decrypt(struct bch_write_op *op)
781 {
782         struct bch_fs *c = op->c;
783         struct nonce nonce = extent_nonce(op->version, op->crc);
784         struct bch_csum csum;
785         int ret;
786
787         if (!bch2_csum_type_is_encryption(op->crc.csum_type))
788                 return 0;
789
790         /*
791          * If we need to decrypt data in the write path, we'll no longer be able
792          * to verify the existing checksum (poly1305 mac, in this case) after
793          * it's decrypted - this is the last point we'll be able to reverify the
794          * checksum:
795          */
796         csum = bch2_checksum_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
797         if (bch2_crc_cmp(op->crc.csum, csum) && !c->opts.no_data_io)
798                 return -EIO;
799
800         ret = bch2_encrypt_bio(c, op->crc.csum_type, nonce, &op->wbio.bio);
801         op->crc.csum_type = 0;
802         op->crc.csum = (struct bch_csum) { 0, 0 };
803         return ret;
804 }
805
806 static enum prep_encoded_ret {
807         PREP_ENCODED_OK,
808         PREP_ENCODED_ERR,
809         PREP_ENCODED_CHECKSUM_ERR,
810         PREP_ENCODED_DO_WRITE,
811 } bch2_write_prep_encoded_data(struct bch_write_op *op, struct write_point *wp)
812 {
813         struct bch_fs *c = op->c;
814         struct bio *bio = &op->wbio.bio;
815
816         if (!(op->flags & BCH_WRITE_DATA_ENCODED))
817                 return PREP_ENCODED_OK;
818
819         BUG_ON(bio_sectors(bio) != op->crc.compressed_size);
820
821         /* Can we just write the entire extent as is? */
822         if (op->crc.uncompressed_size == op->crc.live_size &&
823             op->crc.uncompressed_size <= c->opts.encoded_extent_max >> 9 &&
824             op->crc.compressed_size <= wp->sectors_free &&
825             (op->crc.compression_type == bch2_compression_opt_to_type(op->compression_opt) ||
826              op->incompressible)) {
827                 if (!crc_is_compressed(op->crc) &&
828                     op->csum_type != op->crc.csum_type &&
829                     bch2_write_rechecksum(c, op, op->csum_type) &&
830                     !c->opts.no_data_io)
831                         return PREP_ENCODED_CHECKSUM_ERR;
832
833                 return PREP_ENCODED_DO_WRITE;
834         }
835
836         /*
837          * If the data is compressed and we couldn't write the entire extent as
838          * is, we have to decompress it:
839          */
840         if (crc_is_compressed(op->crc)) {
841                 struct bch_csum csum;
842
843                 if (bch2_write_decrypt(op))
844                         return PREP_ENCODED_CHECKSUM_ERR;
845
846                 /* Last point we can still verify checksum: */
847                 csum = bch2_checksum_bio(c, op->crc.csum_type,
848                                          extent_nonce(op->version, op->crc),
849                                          bio);
850                 if (bch2_crc_cmp(op->crc.csum, csum) && !c->opts.no_data_io)
851                         return PREP_ENCODED_CHECKSUM_ERR;
852
853                 if (bch2_bio_uncompress_inplace(c, bio, &op->crc))
854                         return PREP_ENCODED_ERR;
855         }
856
857         /*
858          * No longer have compressed data after this point - data might be
859          * encrypted:
860          */
861
862         /*
863          * If the data is checksummed and we're only writing a subset,
864          * rechecksum and adjust bio to point to currently live data:
865          */
866         if ((op->crc.live_size != op->crc.uncompressed_size ||
867              op->crc.csum_type != op->csum_type) &&
868             bch2_write_rechecksum(c, op, op->csum_type) &&
869             !c->opts.no_data_io)
870                 return PREP_ENCODED_CHECKSUM_ERR;
871
872         /*
873          * If we want to compress the data, it has to be decrypted:
874          */
875         if ((op->compression_opt ||
876              bch2_csum_type_is_encryption(op->crc.csum_type) !=
877              bch2_csum_type_is_encryption(op->csum_type)) &&
878             bch2_write_decrypt(op))
879                 return PREP_ENCODED_CHECKSUM_ERR;
880
881         return PREP_ENCODED_OK;
882 }
883
884 static int bch2_write_extent(struct bch_write_op *op, struct write_point *wp,
885                              struct bio **_dst)
886 {
887         struct bch_fs *c = op->c;
888         struct bio *src = &op->wbio.bio, *dst = src;
889         struct bvec_iter saved_iter;
890         void *ec_buf;
891         unsigned total_output = 0, total_input = 0;
892         bool bounce = false;
893         bool page_alloc_failed = false;
894         int ret, more = 0;
895
896         BUG_ON(!bio_sectors(src));
897
898         ec_buf = bch2_writepoint_ec_buf(c, wp);
899
900         switch (bch2_write_prep_encoded_data(op, wp)) {
901         case PREP_ENCODED_OK:
902                 break;
903         case PREP_ENCODED_ERR:
904                 ret = -EIO;
905                 goto err;
906         case PREP_ENCODED_CHECKSUM_ERR:
907                 goto csum_err;
908         case PREP_ENCODED_DO_WRITE:
909                 /* XXX look for bug here */
910                 if (ec_buf) {
911                         dst = bch2_write_bio_alloc(c, wp, src,
912                                                    &page_alloc_failed,
913                                                    ec_buf);
914                         bio_copy_data(dst, src);
915                         bounce = true;
916                 }
917                 init_append_extent(op, wp, op->version, op->crc);
918                 goto do_write;
919         }
920
921         if (ec_buf ||
922             op->compression_opt ||
923             (op->csum_type &&
924              !(op->flags & BCH_WRITE_PAGES_STABLE)) ||
925             (bch2_csum_type_is_encryption(op->csum_type) &&
926              !(op->flags & BCH_WRITE_PAGES_OWNED))) {
927                 dst = bch2_write_bio_alloc(c, wp, src,
928                                            &page_alloc_failed,
929                                            ec_buf);
930                 bounce = true;
931         }
932
933         saved_iter = dst->bi_iter;
934
935         do {
936                 struct bch_extent_crc_unpacked crc = { 0 };
937                 struct bversion version = op->version;
938                 size_t dst_len = 0, src_len = 0;
939
940                 if (page_alloc_failed &&
941                     dst->bi_iter.bi_size  < (wp->sectors_free << 9) &&
942                     dst->bi_iter.bi_size < c->opts.encoded_extent_max)
943                         break;
944
945                 BUG_ON(op->compression_opt &&
946                        (op->flags & BCH_WRITE_DATA_ENCODED) &&
947                        bch2_csum_type_is_encryption(op->crc.csum_type));
948                 BUG_ON(op->compression_opt && !bounce);
949
950                 crc.compression_type = op->incompressible
951                         ? BCH_COMPRESSION_TYPE_incompressible
952                         : op->compression_opt
953                         ? bch2_bio_compress(c, dst, &dst_len, src, &src_len,
954                                             op->compression_opt)
955                         : 0;
956                 if (!crc_is_compressed(crc)) {
957                         dst_len = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
958                         dst_len = min_t(unsigned, dst_len, wp->sectors_free << 9);
959
960                         if (op->csum_type)
961                                 dst_len = min_t(unsigned, dst_len,
962                                                 c->opts.encoded_extent_max);
963
964                         if (bounce) {
965                                 swap(dst->bi_iter.bi_size, dst_len);
966                                 bio_copy_data(dst, src);
967                                 swap(dst->bi_iter.bi_size, dst_len);
968                         }
969
970                         src_len = dst_len;
971                 }
972
973                 BUG_ON(!src_len || !dst_len);
974
975                 if (bch2_csum_type_is_encryption(op->csum_type)) {
976                         if (bversion_zero(version)) {
977                                 version.lo = atomic64_inc_return(&c->key_version);
978                         } else {
979                                 crc.nonce = op->nonce;
980                                 op->nonce += src_len >> 9;
981                         }
982                 }
983
984                 if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
985                     !crc_is_compressed(crc) &&
986                     bch2_csum_type_is_encryption(op->crc.csum_type) ==
987                     bch2_csum_type_is_encryption(op->csum_type)) {
988                         u8 compression_type = crc.compression_type;
989                         u16 nonce = crc.nonce;
990                         /*
991                          * Note: when we're using rechecksum(), we need to be
992                          * checksumming @src because it has all the data our
993                          * existing checksum covers - if we bounced (because we
994                          * were trying to compress), @dst will only have the
995                          * part of the data the new checksum will cover.
996                          *
997                          * But normally we want to be checksumming post bounce,
998                          * because part of the reason for bouncing is so the
999                          * data can't be modified (by userspace) while it's in
1000                          * flight.
1001                          */
1002                         if (bch2_rechecksum_bio(c, src, version, op->crc,
1003                                         &crc, &op->crc,
1004                                         src_len >> 9,
1005                                         bio_sectors(src) - (src_len >> 9),
1006                                         op->csum_type))
1007                                 goto csum_err;
1008                         /*
1009                          * rchecksum_bio sets compression_type on crc from op->crc,
1010                          * this isn't always correct as sometimes we're changing
1011                          * an extent from uncompressed to incompressible.
1012                          */
1013                         crc.compression_type = compression_type;
1014                         crc.nonce = nonce;
1015                 } else {
1016                         if ((op->flags & BCH_WRITE_DATA_ENCODED) &&
1017                             bch2_rechecksum_bio(c, src, version, op->crc,
1018                                         NULL, &op->crc,
1019                                         src_len >> 9,
1020                                         bio_sectors(src) - (src_len >> 9),
1021                                         op->crc.csum_type))
1022                                 goto csum_err;
1023
1024                         crc.compressed_size     = dst_len >> 9;
1025                         crc.uncompressed_size   = src_len >> 9;
1026                         crc.live_size           = src_len >> 9;
1027
1028                         swap(dst->bi_iter.bi_size, dst_len);
1029                         ret = bch2_encrypt_bio(c, op->csum_type,
1030                                                extent_nonce(version, crc), dst);
1031                         if (ret)
1032                                 goto err;
1033
1034                         crc.csum = bch2_checksum_bio(c, op->csum_type,
1035                                          extent_nonce(version, crc), dst);
1036                         crc.csum_type = op->csum_type;
1037                         swap(dst->bi_iter.bi_size, dst_len);
1038                 }
1039
1040                 init_append_extent(op, wp, version, crc);
1041
1042                 if (dst != src)
1043                         bio_advance(dst, dst_len);
1044                 bio_advance(src, src_len);
1045                 total_output    += dst_len;
1046                 total_input     += src_len;
1047         } while (dst->bi_iter.bi_size &&
1048                  src->bi_iter.bi_size &&
1049                  wp->sectors_free &&
1050                  !bch2_keylist_realloc(&op->insert_keys,
1051                                       op->inline_keys,
1052                                       ARRAY_SIZE(op->inline_keys),
1053                                       BKEY_EXTENT_U64s_MAX));
1054
1055         more = src->bi_iter.bi_size != 0;
1056
1057         dst->bi_iter = saved_iter;
1058
1059         if (dst == src && more) {
1060                 BUG_ON(total_output != total_input);
1061
1062                 dst = bio_split(src, total_input >> 9,
1063                                 GFP_NOFS, &c->bio_write);
1064                 wbio_init(dst)->put_bio = true;
1065                 /* copy WRITE_SYNC flag */
1066                 dst->bi_opf             = src->bi_opf;
1067         }
1068
1069         dst->bi_iter.bi_size = total_output;
1070 do_write:
1071         *_dst = dst;
1072         return more;
1073 csum_err:
1074         bch_err(c, "error verifying existing checksum while rewriting existing data (memory corruption?)");
1075         ret = -EIO;
1076 err:
1077         if (to_wbio(dst)->bounce)
1078                 bch2_bio_free_pages_pool(c, dst);
1079         if (to_wbio(dst)->put_bio)
1080                 bio_put(dst);
1081
1082         return ret;
1083 }
1084
1085 static bool bch2_extent_is_writeable(struct bch_write_op *op,
1086                                      struct bkey_s_c k)
1087 {
1088         struct bch_fs *c = op->c;
1089         struct bkey_s_c_extent e;
1090         struct extent_ptr_decoded p;
1091         const union bch_extent_entry *entry;
1092         unsigned replicas = 0;
1093
1094         if (k.k->type != KEY_TYPE_extent)
1095                 return false;
1096
1097         e = bkey_s_c_to_extent(k);
1098         extent_for_each_ptr_decode(e, p, entry) {
1099                 if (crc_is_encoded(p.crc) || p.has_ec)
1100                         return false;
1101
1102                 replicas += bch2_extent_ptr_durability(c, &p);
1103         }
1104
1105         return replicas >= op->opts.data_replicas;
1106 }
1107
1108 static inline void bch2_nocow_write_unlock(struct bch_write_op *op)
1109 {
1110         struct bch_fs *c = op->c;
1111         const struct bch_extent_ptr *ptr;
1112         struct bkey_i *k;
1113
1114         for_each_keylist_key(&op->insert_keys, k) {
1115                 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(bkey_i_to_s_c(k));
1116
1117                 bkey_for_each_ptr(ptrs, ptr)
1118                         bch2_bucket_nocow_unlock(&c->nocow_locks,
1119                                                PTR_BUCKET_POS(c, ptr),
1120                                                BUCKET_NOCOW_LOCK_UPDATE);
1121         }
1122 }
1123
1124 static int bch2_nocow_write_convert_one_unwritten(struct btree_trans *trans,
1125                                                   struct btree_iter *iter,
1126                                                   struct bkey_i *orig,
1127                                                   struct bkey_s_c k,
1128                                                   u64 new_i_size)
1129 {
1130         struct bkey_i *new;
1131         struct bkey_ptrs ptrs;
1132         struct bch_extent_ptr *ptr;
1133         int ret;
1134
1135         if (!bch2_extents_match(bkey_i_to_s_c(orig), k)) {
1136                 /* trace this */
1137                 return 0;
1138         }
1139
1140         new = bch2_bkey_make_mut_noupdate(trans, k);
1141         ret = PTR_ERR_OR_ZERO(new);
1142         if (ret)
1143                 return ret;
1144
1145         bch2_cut_front(bkey_start_pos(&orig->k), new);
1146         bch2_cut_back(orig->k.p, new);
1147
1148         ptrs = bch2_bkey_ptrs(bkey_i_to_s(new));
1149         bkey_for_each_ptr(ptrs, ptr)
1150                 ptr->unwritten = 0;
1151
1152         /*
1153          * Note that we're not calling bch2_subvol_get_snapshot() in this path -
1154          * that was done when we kicked off the write, and here it's important
1155          * that we update the extent that we wrote to - even if a snapshot has
1156          * since been created. The write is still outstanding, so we're ok
1157          * w.r.t. snapshot atomicity:
1158          */
1159         return  bch2_extent_update_i_size_sectors(trans, iter,
1160                                         min(new->k.p.offset << 9, new_i_size), 0) ?:
1161                 bch2_trans_update(trans, iter, new,
1162                                   BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE);
1163 }
1164
1165 static void bch2_nocow_write_convert_unwritten(struct bch_write_op *op)
1166 {
1167         struct bch_fs *c = op->c;
1168         struct btree_trans *trans = bch2_trans_get(c);
1169         struct btree_iter iter;
1170         struct bkey_i *orig;
1171         struct bkey_s_c k;
1172         int ret;
1173
1174         for_each_keylist_key(&op->insert_keys, orig) {
1175                 ret = for_each_btree_key_upto_commit(trans, iter, BTREE_ID_extents,
1176                                      bkey_start_pos(&orig->k), orig->k.p,
1177                                      BTREE_ITER_INTENT, k,
1178                                      NULL, NULL, BCH_TRANS_COMMIT_no_enospc, ({
1179                         bch2_nocow_write_convert_one_unwritten(trans, &iter, orig, k, op->new_i_size);
1180                 }));
1181
1182                 if (ret && !bch2_err_matches(ret, EROFS)) {
1183                         struct bkey_i *insert = bch2_keylist_front(&op->insert_keys);
1184
1185                         bch_err_inum_offset_ratelimited(c,
1186                                 insert->k.p.inode, insert->k.p.offset << 9,
1187                                 "write error while doing btree update: %s",
1188                                 bch2_err_str(ret));
1189                 }
1190
1191                 if (ret) {
1192                         op->error = ret;
1193                         break;
1194                 }
1195         }
1196
1197         bch2_trans_put(trans);
1198 }
1199
1200 static void __bch2_nocow_write_done(struct bch_write_op *op)
1201 {
1202         bch2_nocow_write_unlock(op);
1203
1204         if (unlikely(op->flags & BCH_WRITE_IO_ERROR)) {
1205                 op->error = -EIO;
1206         } else if (unlikely(op->flags & BCH_WRITE_CONVERT_UNWRITTEN))
1207                 bch2_nocow_write_convert_unwritten(op);
1208 }
1209
1210 static CLOSURE_CALLBACK(bch2_nocow_write_done)
1211 {
1212         closure_type(op, struct bch_write_op, cl);
1213
1214         __bch2_nocow_write_done(op);
1215         bch2_write_done(cl);
1216 }
1217
1218 static void bch2_nocow_write(struct bch_write_op *op)
1219 {
1220         struct bch_fs *c = op->c;
1221         struct btree_trans *trans;
1222         struct btree_iter iter;
1223         struct bkey_s_c k;
1224         struct bkey_ptrs_c ptrs;
1225         const struct bch_extent_ptr *ptr;
1226         struct {
1227                 struct bpos     b;
1228                 unsigned        gen;
1229                 struct nocow_lock_bucket *l;
1230         } buckets[BCH_REPLICAS_MAX];
1231         unsigned nr_buckets = 0;
1232         u32 snapshot;
1233         int ret, i;
1234
1235         if (op->flags & BCH_WRITE_MOVE)
1236                 return;
1237
1238         trans = bch2_trans_get(c);
1239 retry:
1240         bch2_trans_begin(trans);
1241
1242         ret = bch2_subvolume_get_snapshot(trans, op->subvol, &snapshot);
1243         if (unlikely(ret))
1244                 goto err;
1245
1246         bch2_trans_iter_init(trans, &iter, BTREE_ID_extents,
1247                              SPOS(op->pos.inode, op->pos.offset, snapshot),
1248                              BTREE_ITER_SLOTS);
1249         while (1) {
1250                 struct bio *bio = &op->wbio.bio;
1251
1252                 nr_buckets = 0;
1253
1254                 k = bch2_btree_iter_peek_slot(&iter);
1255                 ret = bkey_err(k);
1256                 if (ret)
1257                         break;
1258
1259                 /* fall back to normal cow write path? */
1260                 if (unlikely(k.k->p.snapshot != snapshot ||
1261                              !bch2_extent_is_writeable(op, k)))
1262                         break;
1263
1264                 if (bch2_keylist_realloc(&op->insert_keys,
1265                                         op->inline_keys,
1266                                         ARRAY_SIZE(op->inline_keys),
1267                                         k.k->u64s))
1268                         break;
1269
1270                 /* Get iorefs before dropping btree locks: */
1271                 ptrs = bch2_bkey_ptrs_c(k);
1272                 bkey_for_each_ptr(ptrs, ptr) {
1273                         buckets[nr_buckets].b = PTR_BUCKET_POS(c, ptr);
1274                         buckets[nr_buckets].gen = ptr->gen;
1275                         buckets[nr_buckets].l =
1276                                 bucket_nocow_lock(&c->nocow_locks,
1277                                                   bucket_to_u64(buckets[nr_buckets].b));
1278
1279                         prefetch(buckets[nr_buckets].l);
1280
1281                         if (unlikely(!bch2_dev_get_ioref(bch_dev_bkey_exists(c, ptr->dev), WRITE)))
1282                                 goto err_get_ioref;
1283
1284                         nr_buckets++;
1285
1286                         if (ptr->unwritten)
1287                                 op->flags |= BCH_WRITE_CONVERT_UNWRITTEN;
1288                 }
1289
1290                 /* Unlock before taking nocow locks, doing IO: */
1291                 bkey_reassemble(op->insert_keys.top, k);
1292                 bch2_trans_unlock(trans);
1293
1294                 bch2_cut_front(op->pos, op->insert_keys.top);
1295                 if (op->flags & BCH_WRITE_CONVERT_UNWRITTEN)
1296                         bch2_cut_back(POS(op->pos.inode, op->pos.offset + bio_sectors(bio)), op->insert_keys.top);
1297
1298                 for (i = 0; i < nr_buckets; i++) {
1299                         struct bch_dev *ca = bch_dev_bkey_exists(c, buckets[i].b.inode);
1300                         struct nocow_lock_bucket *l = buckets[i].l;
1301                         bool stale;
1302
1303                         __bch2_bucket_nocow_lock(&c->nocow_locks, l,
1304                                                  bucket_to_u64(buckets[i].b),
1305                                                  BUCKET_NOCOW_LOCK_UPDATE);
1306
1307                         rcu_read_lock();
1308                         stale = gen_after(*bucket_gen(ca, buckets[i].b.offset), buckets[i].gen);
1309                         rcu_read_unlock();
1310
1311                         if (unlikely(stale))
1312                                 goto err_bucket_stale;
1313                 }
1314
1315                 bio = &op->wbio.bio;
1316                 if (k.k->p.offset < op->pos.offset + bio_sectors(bio)) {
1317                         bio = bio_split(bio, k.k->p.offset - op->pos.offset,
1318                                         GFP_KERNEL, &c->bio_write);
1319                         wbio_init(bio)->put_bio = true;
1320                         bio->bi_opf = op->wbio.bio.bi_opf;
1321                 } else {
1322                         op->flags |= BCH_WRITE_DONE;
1323                 }
1324
1325                 op->pos.offset += bio_sectors(bio);
1326                 op->written += bio_sectors(bio);
1327
1328                 bio->bi_end_io  = bch2_write_endio;
1329                 bio->bi_private = &op->cl;
1330                 bio->bi_opf |= REQ_OP_WRITE;
1331                 closure_get(&op->cl);
1332                 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1333                                           op->insert_keys.top, true);
1334
1335                 bch2_keylist_push(&op->insert_keys);
1336                 if (op->flags & BCH_WRITE_DONE)
1337                         break;
1338                 bch2_btree_iter_advance(&iter);
1339         }
1340 out:
1341         bch2_trans_iter_exit(trans, &iter);
1342 err:
1343         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1344                 goto retry;
1345
1346         if (ret) {
1347                 bch_err_inum_offset_ratelimited(c,
1348                                 op->pos.inode,
1349                                 op->pos.offset << 9,
1350                                 "%s: btree lookup error %s",
1351                                 __func__, bch2_err_str(ret));
1352                 op->error = ret;
1353                 op->flags |= BCH_WRITE_DONE;
1354         }
1355
1356         bch2_trans_put(trans);
1357
1358         /* fallback to cow write path? */
1359         if (!(op->flags & BCH_WRITE_DONE)) {
1360                 closure_sync(&op->cl);
1361                 __bch2_nocow_write_done(op);
1362                 op->insert_keys.top = op->insert_keys.keys;
1363         } else if (op->flags & BCH_WRITE_SYNC) {
1364                 closure_sync(&op->cl);
1365                 bch2_nocow_write_done(&op->cl.work);
1366         } else {
1367                 /*
1368                  * XXX
1369                  * needs to run out of process context because ei_quota_lock is
1370                  * a mutex
1371                  */
1372                 continue_at(&op->cl, bch2_nocow_write_done, index_update_wq(op));
1373         }
1374         return;
1375 err_get_ioref:
1376         for (i = 0; i < nr_buckets; i++)
1377                 percpu_ref_put(&bch_dev_bkey_exists(c, buckets[i].b.inode)->io_ref);
1378
1379         /* Fall back to COW path: */
1380         goto out;
1381 err_bucket_stale:
1382         while (i >= 0) {
1383                 bch2_bucket_nocow_unlock(&c->nocow_locks,
1384                                          buckets[i].b,
1385                                          BUCKET_NOCOW_LOCK_UPDATE);
1386                 --i;
1387         }
1388         for (i = 0; i < nr_buckets; i++)
1389                 percpu_ref_put(&bch_dev_bkey_exists(c, buckets[i].b.inode)->io_ref);
1390
1391         /* We can retry this: */
1392         ret = -BCH_ERR_transaction_restart;
1393         goto out;
1394 }
1395
1396 static void __bch2_write(struct bch_write_op *op)
1397 {
1398         struct bch_fs *c = op->c;
1399         struct write_point *wp = NULL;
1400         struct bio *bio = NULL;
1401         unsigned nofs_flags;
1402         int ret;
1403
1404         nofs_flags = memalloc_nofs_save();
1405
1406         if (unlikely(op->opts.nocow && c->opts.nocow_enabled)) {
1407                 bch2_nocow_write(op);
1408                 if (op->flags & BCH_WRITE_DONE)
1409                         goto out_nofs_restore;
1410         }
1411 again:
1412         memset(&op->failed, 0, sizeof(op->failed));
1413
1414         do {
1415                 struct bkey_i *key_to_write;
1416                 unsigned key_to_write_offset = op->insert_keys.top_p -
1417                         op->insert_keys.keys_p;
1418
1419                 /* +1 for possible cache device: */
1420                 if (op->open_buckets.nr + op->nr_replicas + 1 >
1421                     ARRAY_SIZE(op->open_buckets.v))
1422                         break;
1423
1424                 if (bch2_keylist_realloc(&op->insert_keys,
1425                                         op->inline_keys,
1426                                         ARRAY_SIZE(op->inline_keys),
1427                                         BKEY_EXTENT_U64s_MAX))
1428                         break;
1429
1430                 /*
1431                  * The copygc thread is now global, which means it's no longer
1432                  * freeing up space on specific disks, which means that
1433                  * allocations for specific disks may hang arbitrarily long:
1434                  */
1435                 ret = bch2_trans_do(c, NULL, NULL, 0,
1436                         bch2_alloc_sectors_start_trans(trans,
1437                                 op->target,
1438                                 op->opts.erasure_code && !(op->flags & BCH_WRITE_CACHED),
1439                                 op->write_point,
1440                                 &op->devs_have,
1441                                 op->nr_replicas,
1442                                 op->nr_replicas_required,
1443                                 op->watermark,
1444                                 op->flags,
1445                                 (op->flags & (BCH_WRITE_ALLOC_NOWAIT|
1446                                               BCH_WRITE_ONLY_SPECIFIED_DEVS))
1447                                 ? NULL : &op->cl, &wp));
1448                 if (unlikely(ret)) {
1449                         if (bch2_err_matches(ret, BCH_ERR_operation_blocked))
1450                                 break;
1451
1452                         goto err;
1453                 }
1454
1455                 EBUG_ON(!wp);
1456
1457                 bch2_open_bucket_get(c, wp, &op->open_buckets);
1458                 ret = bch2_write_extent(op, wp, &bio);
1459
1460                 bch2_alloc_sectors_done_inlined(c, wp);
1461 err:
1462                 if (ret <= 0) {
1463                         op->flags |= BCH_WRITE_DONE;
1464
1465                         if (ret < 0) {
1466                                 op->error = ret;
1467                                 break;
1468                         }
1469                 }
1470
1471                 bio->bi_end_io  = bch2_write_endio;
1472                 bio->bi_private = &op->cl;
1473                 bio->bi_opf |= REQ_OP_WRITE;
1474
1475                 closure_get(bio->bi_private);
1476
1477                 key_to_write = (void *) (op->insert_keys.keys_p +
1478                                          key_to_write_offset);
1479
1480                 bch2_submit_wbio_replicas(to_wbio(bio), c, BCH_DATA_user,
1481                                           key_to_write, false);
1482         } while (ret);
1483
1484         /*
1485          * Sync or no?
1486          *
1487          * If we're running asynchronously, wne may still want to block
1488          * synchronously here if we weren't able to submit all of the IO at
1489          * once, as that signals backpressure to the caller.
1490          */
1491         if ((op->flags & BCH_WRITE_SYNC) ||
1492             (!(op->flags & BCH_WRITE_DONE) &&
1493              !(op->flags & BCH_WRITE_IN_WORKER))) {
1494                 closure_sync(&op->cl);
1495                 __bch2_write_index(op);
1496
1497                 if (!(op->flags & BCH_WRITE_DONE))
1498                         goto again;
1499                 bch2_write_done(&op->cl);
1500         } else {
1501                 bch2_write_queue(op, wp);
1502                 continue_at(&op->cl, bch2_write_index, NULL);
1503         }
1504 out_nofs_restore:
1505         memalloc_nofs_restore(nofs_flags);
1506 }
1507
1508 static void bch2_write_data_inline(struct bch_write_op *op, unsigned data_len)
1509 {
1510         struct bio *bio = &op->wbio.bio;
1511         struct bvec_iter iter;
1512         struct bkey_i_inline_data *id;
1513         unsigned sectors;
1514         int ret;
1515
1516         op->flags |= BCH_WRITE_WROTE_DATA_INLINE;
1517         op->flags |= BCH_WRITE_DONE;
1518
1519         bch2_check_set_feature(op->c, BCH_FEATURE_inline_data);
1520
1521         ret = bch2_keylist_realloc(&op->insert_keys, op->inline_keys,
1522                                    ARRAY_SIZE(op->inline_keys),
1523                                    BKEY_U64s + DIV_ROUND_UP(data_len, 8));
1524         if (ret) {
1525                 op->error = ret;
1526                 goto err;
1527         }
1528
1529         sectors = bio_sectors(bio);
1530         op->pos.offset += sectors;
1531
1532         id = bkey_inline_data_init(op->insert_keys.top);
1533         id->k.p         = op->pos;
1534         id->k.version   = op->version;
1535         id->k.size      = sectors;
1536
1537         iter = bio->bi_iter;
1538         iter.bi_size = data_len;
1539         memcpy_from_bio(id->v.data, bio, iter);
1540
1541         while (data_len & 7)
1542                 id->v.data[data_len++] = '\0';
1543         set_bkey_val_bytes(&id->k, data_len);
1544         bch2_keylist_push(&op->insert_keys);
1545
1546         __bch2_write_index(op);
1547 err:
1548         bch2_write_done(&op->cl);
1549 }
1550
1551 /**
1552  * bch2_write() - handle a write to a cache device or flash only volume
1553  * @cl:         &bch_write_op->cl
1554  *
1555  * This is the starting point for any data to end up in a cache device; it could
1556  * be from a normal write, or a writeback write, or a write to a flash only
1557  * volume - it's also used by the moving garbage collector to compact data in
1558  * mostly empty buckets.
1559  *
1560  * It first writes the data to the cache, creating a list of keys to be inserted
1561  * (if the data won't fit in a single open bucket, there will be multiple keys);
1562  * after the data is written it calls bch_journal, and after the keys have been
1563  * added to the next journal write they're inserted into the btree.
1564  *
1565  * If op->discard is true, instead of inserting the data it invalidates the
1566  * region of the cache represented by op->bio and op->inode.
1567  */
1568 CLOSURE_CALLBACK(bch2_write)
1569 {
1570         closure_type(op, struct bch_write_op, cl);
1571         struct bio *bio = &op->wbio.bio;
1572         struct bch_fs *c = op->c;
1573         unsigned data_len;
1574
1575         EBUG_ON(op->cl.parent);
1576         BUG_ON(!op->nr_replicas);
1577         BUG_ON(!op->write_point.v);
1578         BUG_ON(bkey_eq(op->pos, POS_MAX));
1579
1580         op->start_time = local_clock();
1581         bch2_keylist_init(&op->insert_keys, op->inline_keys);
1582         wbio_init(bio)->put_bio = false;
1583
1584         if (bio->bi_iter.bi_size & (c->opts.block_size - 1)) {
1585                 bch_err_inum_offset_ratelimited(c,
1586                         op->pos.inode,
1587                         op->pos.offset << 9,
1588                         "misaligned write");
1589                 op->error = -EIO;
1590                 goto err;
1591         }
1592
1593         if (c->opts.nochanges) {
1594                 op->error = -BCH_ERR_erofs_no_writes;
1595                 goto err;
1596         }
1597
1598         if (!(op->flags & BCH_WRITE_MOVE) &&
1599             !bch2_write_ref_tryget(c, BCH_WRITE_REF_write)) {
1600                 op->error = -BCH_ERR_erofs_no_writes;
1601                 goto err;
1602         }
1603
1604         this_cpu_add(c->counters[BCH_COUNTER_io_write], bio_sectors(bio));
1605         bch2_increment_clock(c, bio_sectors(bio), WRITE);
1606
1607         data_len = min_t(u64, bio->bi_iter.bi_size,
1608                          op->new_i_size - (op->pos.offset << 9));
1609
1610         if (c->opts.inline_data &&
1611             data_len <= min(block_bytes(c) / 2, 1024U)) {
1612                 bch2_write_data_inline(op, data_len);
1613                 return;
1614         }
1615
1616         __bch2_write(op);
1617         return;
1618 err:
1619         bch2_disk_reservation_put(c, &op->res);
1620
1621         closure_debug_destroy(&op->cl);
1622         if (op->end_io)
1623                 op->end_io(op);
1624 }
1625
1626 static const char * const bch2_write_flags[] = {
1627 #define x(f)    #f,
1628         BCH_WRITE_FLAGS()
1629 #undef x
1630         NULL
1631 };
1632
1633 void bch2_write_op_to_text(struct printbuf *out, struct bch_write_op *op)
1634 {
1635         prt_str(out, "pos: ");
1636         bch2_bpos_to_text(out, op->pos);
1637         prt_newline(out);
1638         printbuf_indent_add(out, 2);
1639
1640         prt_str(out, "started: ");
1641         bch2_pr_time_units(out, local_clock() - op->start_time);
1642         prt_newline(out);
1643
1644         prt_str(out, "flags: ");
1645         prt_bitflags(out, bch2_write_flags, op->flags);
1646         prt_newline(out);
1647
1648         prt_printf(out, "ref: %u", closure_nr_remaining(&op->cl));
1649         prt_newline(out);
1650
1651         printbuf_indent_sub(out, 2);
1652 }
1653
1654 void bch2_fs_io_write_exit(struct bch_fs *c)
1655 {
1656         mempool_exit(&c->bio_bounce_pages);
1657         bioset_exit(&c->bio_write);
1658 }
1659
1660 int bch2_fs_io_write_init(struct bch_fs *c)
1661 {
1662         if (bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
1663                         BIOSET_NEED_BVECS))
1664                 return -BCH_ERR_ENOMEM_bio_write_init;
1665
1666         if (mempool_init_page_pool(&c->bio_bounce_pages,
1667                                    max_t(unsigned,
1668                                          c->opts.btree_node_size,
1669                                          c->opts.encoded_extent_max) /
1670                                    PAGE_SIZE, 0))
1671                 return -BCH_ERR_ENOMEM_bio_bounce_pages_init;
1672
1673         return 0;
1674 }