Debian Codegraph @

transaction.c

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright (C) 2019 Ernesto A. Fernández <[email protected]>
4 */
5
6 #include <linux/blkdev.h>
7 #include <linux/rmap.h>
8 #include "apfs.h"
9
10 /**
11 * apfs_checkpoint_end - End the new checkpoint
12 * @sb: filesystem superblock
13 *
14 * Flushes all changes to disk, and commits the new checkpoint by setting the
15 * fletcher checksum on its superblock. Returns 0 on success, or a negative
16 * error code in case of failure.
17 */
18 static int apfs_checkpoint_end(struct super_block *sb)
19 {
20 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
21 struct apfs_obj_phys *obj = &nxi->nx_raw->nx_o;
22 struct buffer_head *bh = NULL;
23 struct apfs_blkdev_info *bd_info = nxi->nx_blkdev_info;
24 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 10, 0)
25 struct address_space *bdev_map = bd_info->blki_bdev->bd_mapping;
26 #else
27 struct inode *bdev_inode = bd_info->blki_bdev->bd_inode;
28 struct address_space *bdev_map = bdev_inode->i_mapping;
29 #endif
30 int err;
31
32 ASSERT(!(sb->s_flags & SB_RDONLY));
33
34 bh = apfs_getblk(sb, nxi->nx_bno);
35 if (!bh) {
36 apfs_err(sb, "failed to map new checkpoint superblock");
37 return -EIO;
38 }
39 obj->o_xid = cpu_to_le64(nxi->nx_xid);
40 apfs_obj_set_csum(sb, obj);
41 memcpy(bh->b_data, obj, sb->s_blocksize);
42
43 err = filemap_write_and_wait(bdev_map);
44 if (err)
45 goto out;
46
47 mark_buffer_dirty(bh);
48 err = sync_dirty_buffer(bh);
49 if (err)
50 goto out;
51
52 err = filemap_write_and_wait(bdev_map);
53 out:
54 brelse(bh);
55 bh = NULL;
56 return err;
57 }
58
59 /**
60 * apfs_transaction_has_room - Is there enough free space for this transaction?
61 * @sb: superblock structure
62 * @kind: transaction kind for space preallocation
63 */
64 static bool apfs_transaction_has_room(struct super_block *sb, enum apfs_trans_kind kind)
65 {
66 struct apfs_nx_transaction *trans = NULL;
67 struct apfs_spaceman *sm = NULL;
68 u64 max_blks;
69
70 trans = &APFS_NXI(sb)->nx_transaction;
71 sm = APFS_SM(sb);
72
73 /*
74 * It's hard to keep track of the maximum number of blocks that each
75 * operation could need because of the complexities of apfs btrees,
76 * plus snapshots and clones. I try to keep things simple here.
77 */
78 switch (kind) {
79 case APFS_TRANS_REG:
80 /*
81 * For transactions that are expected to reduce free space, we
82 * use a very coarse bound (512 KiB) that is certain to be much
83 * more than enough, and will always leave room for deletions.
84 */
85 max_blks = APFS_REG_ROOM;
86 break;
87 case APFS_TRANS_DEL:
88 /*
89 * For transactions that are likely to increase free space, we
90 * use a much tighter bound (80 KiB), so that users have the
91 * opportunity to fix their ENOSPC situation.
92 *
93 * For huge filesystems with huge numbers of records, there is
94 * a tiny chance that this might be too permissive, in which
95 * case the transaction will later abort. I think that's
96 * acceptable.
97 */
98 max_blks = APFS_DEL_ROOM;
99 break;
100 case APFS_TRANS_SYNC:
101 /*
102 * We try to allow sync as much as possible, for the user's
103 * peace of mind and because flushing the free queues could
104 * make some room.
105 *
106 * Even if we do nothing the transaction still allocates a new
107 * volume superblock, and new roots for the omap and catalog,
108 * which consumes 6 blocks in total. This could be avoided...
109 */
110 if (trans->t_starts_count == 0)
111 max_blks = APFS_SYNC_ROOM;
112 else
113 max_blks = 0;
114 break;
115 default:
116 apfs_alert(sb, "invalid transaction kind %u - bug!", kind);
117 return false;
118 }
119
120 return max_blks <= sm->sm_free_count;
121 }
122
123 /**
124 * apfs_read_single_ephemeral_object - Read a single ephemeral object to memory
125 * @sb: filesystem superblock
126 * @map: checkpoint mapping for the object
127 *
128 * Returns 0 on success or a negative error code in case of failure.
129 */
130 static int apfs_read_single_ephemeral_object(struct super_block *sb, struct apfs_checkpoint_mapping *map)
131 {
132 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
133 struct apfs_nx_superblock *raw_sb = NULL;
134 struct apfs_ephemeral_object_info *list = NULL;
135 struct buffer_head *bh = NULL;
136 char *object = NULL;
137 int count;
138 u32 data_blks, size;
139 u64 data_base, bno, oid;
140 int err, i, data_idx;
141
142 raw_sb = nxi->nx_raw;
143 data_base = le64_to_cpu(raw_sb->nx_xp_data_base);
144 data_blks = le32_to_cpu(raw_sb->nx_xp_data_blocks);
145
146 list = nxi->nx_eph_list;
147 count = nxi->nx_eph_count;
148 if (count >= APFS_EPHEMERAL_LIST_LIMIT) {
149 apfs_err(sb, "too many ephemeral objects?");
150 return -EOPNOTSUPP;
151 }
152
153 bno = le64_to_cpu(map->cpm_paddr);
154 oid = le64_to_cpu(map->cpm_oid);
155 size = le32_to_cpu(map->cpm_size);
156 if (size > sb->s_blocksize << 1) {
157 /*
158 * No reason not to support bigger objects, but there has to be
159 * a limit somewhere and this is all I've seen so far.
160 */
161 apfs_warn(sb, "ephemeral object has more than 2 blocks");
162 return -EOPNOTSUPP;
163 }
164 if (!size || (size & (sb->s_blocksize - 1))) {
165 apfs_err(sb, "invalid object size (0x%x)", size);
166 return -EFSCORRUPTED;
167 }
168 object = kmalloc(size, GFP_KERNEL);
169 if (!object)
170 return -ENOMEM;
171
172 data_idx = bno - data_base;
173 for (i = 0; i < size >> sb->s_blocksize_bits; ++i) {
174 bh = apfs_sb_bread(sb, data_base + data_idx);
175 if (!bh) {
176 apfs_err(sb, "failed to read ephemeral block");
177 err = -EIO;
178 goto fail;
179 }
180 memcpy(object + (i << sb->s_blocksize_bits), bh->b_data, sb->s_blocksize);
181 brelse(bh);
182 bh = NULL;
183 /* Somewhat surprisingly, objects can wrap around */
184 if (++data_idx == data_blks)
185 data_idx = 0;
186 }
187
188 /*
189 * The official reference requires that we always verify ephemeral
190 * checksums on mount, so do it even if the user didn't ask. We should
191 * actually try to mount an older checkpoint when this fails (TODO),
192 * which I guess means that the official driver writes all checkpoint
193 * blocks at once, instead of leaving the superblock for last like we
194 * do.
195 */
196 if (!apfs_multiblock_verify_csum(object, size)) {
197 apfs_err(sb, "bad checksum for ephemeral object 0x%llx", oid);
198 err = -EFSBADCRC;
199 goto fail;
200 }
201
202 list[count].oid = oid;
203 list[count].size = size;
204 list[count].object = object;
205 object = NULL;
206 nxi->nx_eph_count = count + 1;
207 return 0;
208
209 fail:
210 kfree(object);
211 object = NULL;
212 return err;
213 }
214
215 /**
216 * apfs_read_single_cpm_block - Read all ephemeral objects in a cpm block
217 * @sb: filesystem superblock
218 * @cpm_bno: block number for the cpm block
219 *
220 * Returns 0 on success or a negative error code in case of failure.
221 */
222 static int apfs_read_single_cpm_block(struct super_block *sb, u64 cpm_bno)
223 {
224 struct buffer_head *bh = NULL;
225 struct apfs_checkpoint_map_phys *cpm = NULL;
226 u32 map_count;
227 int err, i;
228
229 bh = apfs_sb_bread(sb, cpm_bno);
230 if (!bh) {
231 apfs_err(sb, "failed to read cpm block");
232 return -EIO;
233 }
234 if (!apfs_obj_verify_csum(sb, bh)) {
235 /*
236 * The reference seems to imply that we need to check these on
237 * mount, and retry an older checkpoint on failure (TODO).
238 */
239 apfs_err(sb, "bad checksum for cpm block at 0x%llx", cpm_bno);
240 err = -EFSBADCRC;
241 goto out;
242 }
243 cpm = (struct apfs_checkpoint_map_phys *)bh->b_data;
244
245 map_count = le32_to_cpu(cpm->cpm_count);
246 if (map_count > apfs_max_maps_per_block(sb)) {
247 apfs_err(sb, "block has too many maps (%d)", map_count);
248 err = -EFSCORRUPTED;
249 goto out;
250 }
251
252 for (i = 0; i < map_count; ++i) {
253 err = apfs_read_single_ephemeral_object(sb, &cpm->cpm_map[i]);
254 if (err) {
255 apfs_err(sb, "failed to read ephemeral object %u", i);
256 goto out;
257 }
258 }
259
260 out:
261 brelse(bh);
262 cpm = NULL;
263 return err;
264 }
265
266 static void apfs_force_readonly(struct apfs_nxsb_info *nxi);
267
268 /**
269 * apfs_read_ephemeral_objects - Read all ephemeral objects to memory
270 * @sb: superblock structure
271 *
272 * Returns 0 on success or a negative error code in case of failure.
273 */
274 int apfs_read_ephemeral_objects(struct super_block *sb)
275 {
276 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
277 struct apfs_nx_superblock *raw_sb = nxi->nx_raw;
278 u64 desc_base;
279 u32 desc_index, desc_blks, desc_len, i;
280 int err;
281
282 if (nxi->nx_eph_list) {
283 apfs_alert(sb, "attempt to reread ephemeral object list");
284 return -EFSCORRUPTED;
285 }
286 nxi->nx_eph_list = kzalloc(APFS_EPHEMERAL_LIST_SIZE, GFP_KERNEL);
287 if (!nxi->nx_eph_list)
288 return -ENOMEM;
289 nxi->nx_eph_count = 0;
290
291 desc_base = le64_to_cpu(raw_sb->nx_xp_desc_base);
292 desc_index = le32_to_cpu(raw_sb->nx_xp_desc_index);
293 desc_blks = le32_to_cpu(raw_sb->nx_xp_desc_blocks);
294 desc_len = le32_to_cpu(raw_sb->nx_xp_desc_len);
295
296 /* Last block in the area is superblock; the rest are mapping blocks */
297 for (i = 0; i < desc_len - 1; ++i) {
298 u64 cpm_bno = desc_base + (desc_index + i) % desc_blks;
299
300 err = apfs_read_single_cpm_block(sb, cpm_bno);
301 if (err) {
302 apfs_err(sb, "failed to read cpm block %u", i);
303 /* No transaction to abort yet */
304 apfs_force_readonly(nxi);
305 return err;
306 }
307 }
308 return 0;
309 }
310
311 static void apfs_trans_commit_work(struct work_struct *work)
312 {
313 struct super_block *sb = NULL;
314 struct apfs_nxsb_info *nxi = NULL;
315 struct apfs_nx_transaction *trans = NULL;
316 int err;
317
318 trans = container_of(to_delayed_work(work), struct apfs_nx_transaction, t_work);
319 nxi = container_of(trans, struct apfs_nxsb_info, nx_transaction);
320 sb = trans->t_work_sb;
321
322 /*
323 * If sb is set then the transaction already started, there is no need
324 * for apfs_transaction_start() here. It would be cleaner to call it
325 * anyway (and check in there if sb is set), but maxops is a problem
326 * because we don't need any space. I really need to rethink that stuff
327 * (TODO).
328 */
329 down_write(&nxi->nx_big_sem);
330 if (!sb || sb->s_flags & SB_RDONLY) {
331 /* The commit already took place, or there was an abort */
332 up_write(&nxi->nx_big_sem);
333 return;
334 }
335
336 trans->t_state |= APFS_NX_TRANS_FORCE_COMMIT;
337 err = apfs_transaction_commit(sb);
338 if (err) {
339 apfs_err(sb, "queued commit failed (err:%d)", err);
340 apfs_transaction_abort(sb);
341 }
342 }
343
344 /**
345 * apfs_transaction_init - Initialize the transaction struct for the container
346 * @trans: the transaction structure
347 */
348 void apfs_transaction_init(struct apfs_nx_transaction *trans)
349 {
350 trans->t_state = 0;
351 INIT_DELAYED_WORK(&trans->t_work, apfs_trans_commit_work);
352 INIT_LIST_HEAD(&trans->t_inodes);
353 INIT_LIST_HEAD(&trans->t_buffers);
354 trans->t_buffers_count = 0;
355 trans->t_starts_count = 0;
356 }
357
358 /**
359 * apfs_transaction_start - Begin a new transaction
360 * @sb: superblock structure
361 * @kind: transaction kind for space preallocation
362 *
363 * Also locks the filesystem for writing; returns 0 on success or a negative
364 * error code in case of failure.
365 */
366 int apfs_transaction_start(struct super_block *sb, enum apfs_trans_kind kind)
367 {
368 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
369 struct apfs_nx_transaction *nx_trans = &nxi->nx_transaction;
370 int err;
371
372 down_write(&nxi->nx_big_sem);
373
374 if (sb->s_flags & SB_RDONLY) {
375 /* A previous transaction has failed; this should be rare */
376 up_write(&nxi->nx_big_sem);
377 return -EROFS;
378 }
379
380 /*
381 * Ephemeral objects are read only once, kept in memory, and committed
382 * to disk along with each transaction.
383 */
384 if (!nxi->nx_eph_list) {
385 err = apfs_read_ephemeral_objects(sb);
386 if (err) {
387 up_write(&nxi->nx_big_sem);
388 apfs_err(sb, "failed to read the ephemeral objects");
389 return err;
390 }
391 }
392
393 if (nx_trans->t_starts_count == 0) {
394 ++nxi->nx_xid;
395 nxi->nx_raw->nx_next_xid = cpu_to_le64(nxi->nx_xid + 1);
396
397 err = apfs_read_spaceman(sb);
398 if (err) {
399 apfs_err(sb, "failed to read the spaceman");
400 goto fail;
401 }
402 }
403
404 /* Don't start transactions unless we are sure they fit in disk */
405 if (!apfs_transaction_has_room(sb, kind)) {
406 /* Commit what we have so far to flush the queues */
407 nx_trans->t_state |= APFS_NX_TRANS_FORCE_COMMIT;
408 err = apfs_transaction_commit(sb);
409 if (err) {
410 apfs_err(sb, "commit failed");
411 goto fail;
412 }
413 return -ENOSPC;
414 }
415
416 if (nx_trans->t_starts_count == 0) {
417 err = apfs_map_volume_super(sb, true /* write */);
418 if (err) {
419 apfs_err(sb, "CoW failed for volume super");
420 goto fail;
421 }
422
423 /* TODO: don't copy these nodes for transactions that don't use them */
424 err = apfs_read_omap(sb, true /* write */);
425 if (err) {
426 apfs_err(sb, "CoW failed for omap");
427 goto fail;
428 }
429 err = apfs_read_catalog(sb, true /* write */);
430 if (err) {
431 apfs_err(sb, "Cow failed for catalog");
432 goto fail;
433 }
434 }
435
436 nx_trans->t_starts_count++;
437 return 0;
438
439 fail:
440 apfs_transaction_abort(sb);
441 return err;
442 }
443
444 /**
445 * apfs_transaction_flush_all_inodes - Flush inode metadata to the buffer heads
446 * @sb: superblock structure
447 *
448 * This messes a lot with the disk layout, so it must be called ahead of time
449 * if we need it to be stable for the rest or the transaction (for example, if
450 * we are setting up a snapshot).
451 */
452 int apfs_transaction_flush_all_inodes(struct super_block *sb)
453 {
454 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
455 struct apfs_nx_transaction *nx_trans = &nxi->nx_transaction;
456 int err = 0, curr_err;
457
458 ASSERT(!(sb->s_flags & SB_RDONLY));
459
460 while (!list_empty(&nx_trans->t_inodes)) {
461 struct apfs_inode_info *ai = NULL;
462 struct inode *inode = NULL;
463
464 ai = list_first_entry(&nx_trans->t_inodes, struct apfs_inode_info, i_list);
465 inode = &ai->vfs_inode;
466
467 /* This is a bit wasteful if the inode will get deleted */
468 curr_err = apfs_update_inode(inode, NULL /* new_name */);
469 if (curr_err)
470 err = curr_err;
471 apfs_inode_state_clear_raw(inode, I_DIRTY_ALL);
472
473 /*
474 * The same inode may get dirtied again as soon as we release
475 * the lock, and we don't want to miss that.
476 */
477 list_del_init(&ai->i_list);
478
479 nx_trans->t_state |= APFS_NX_TRANS_COMMITTING;
480 up_write(&nxi->nx_big_sem);
481
482 /* Unlocked, so it may call evict() and wait for writeback */
483 iput(inode);
484
485 down_write(&nxi->nx_big_sem);
486 nx_trans->t_state = 0;
487
488 /* Transaction aborted during writeback, error code is lost */
489 if (sb->s_flags & SB_RDONLY) {
490 apfs_err(sb, "abort during inode writeback");
491 return -EROFS;
492 }
493 }
494
495 return err;
496 }
497
498 /**
499 * apfs_write_single_ephemeral_object - Write a single ephemeral object to bh's
500 * @sb: filesystem superblock
501 * @obj_raw: contents of the object
502 * @map: checkpoint mapping for the object, already updated
503 *
504 * Returns 0 on success or a negative error code in case of failure.
505 */
506 static int apfs_write_single_ephemeral_object(struct super_block *sb, struct apfs_obj_phys *obj_raw, const struct apfs_checkpoint_mapping *map)
507 {
508 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
509 struct apfs_nx_superblock *raw_sb = NULL;
510 struct buffer_head *bh = NULL;
511 u64 data_base, bno;
512 u32 data_blks, size;
513 int err, i, data_idx;
514
515 raw_sb = nxi->nx_raw;
516 data_base = le64_to_cpu(raw_sb->nx_xp_data_base);
517 data_blks = le32_to_cpu(raw_sb->nx_xp_data_blocks);
518
519 bno = le64_to_cpu(map->cpm_paddr);
520 size = le32_to_cpu(map->cpm_size);
521 obj_raw->o_xid = cpu_to_le64(nxi->nx_xid);
522 apfs_multiblock_set_csum((char *)obj_raw, size);
523
524 data_idx = bno - data_base;
525 for (i = 0; i < size >> sb->s_blocksize_bits; ++i) {
526 bh = apfs_getblk(sb, data_base + data_idx);
527 if (!bh) {
528 apfs_err(sb, "failed to map ephemeral block");
529 return -EIO;
530 }
531 err = apfs_transaction_join(sb, bh);
532 if (err) {
533 brelse(bh);
534 bh = NULL;
535 return err;
536 }
537 memcpy(bh->b_data, (char *)obj_raw + (i << sb->s_blocksize_bits), sb->s_blocksize);
538 brelse(bh);
539 bh = NULL;
540 /* Somewhat surprisingly, objects can wrap around */
541 if (++data_idx == data_blks)
542 data_idx = 0;
543 }
544 return 0;
545 }
546
547 /**
548 * apfs_write_ephemeral_objects - Write all ephemeral objects to bh's
549 * @sb: filesystem superblock
550 *
551 * Returns 0 on sucess, or a negative error code in case of failure.
552 */
553 static int apfs_write_ephemeral_objects(struct super_block *sb)
554 {
555 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
556 struct apfs_nx_superblock *raw_sb = nxi->nx_raw;
557 struct apfs_checkpoint_map_phys *cpm = NULL;
558 struct buffer_head *cpm_bh = NULL;
559 struct apfs_ephemeral_object_info *eph_info = NULL;
560 u64 cpm_bno;
561 u64 desc_base, data_base;
562 u32 desc_index, desc_blks, desc_len, desc_next;
563 u32 data_index, data_blks, data_len, data_next;
564 u32 desc_limit, data_limit;
565 u32 obj_blkcnt;
566 int err, i, cpm_start;
567
568 if (!nxi->nx_eph_list) {
569 apfs_alert(sb, "missing ephemeral object list");
570 return -EFSCORRUPTED;
571 }
572
573 desc_next = le32_to_cpu(raw_sb->nx_xp_desc_next);
574 desc_base = le64_to_cpu(raw_sb->nx_xp_desc_base);
575 desc_index = desc_next; /* New checkpoint */
576 desc_blks = le32_to_cpu(raw_sb->nx_xp_desc_blocks);
577 desc_len = 0; /* For now */
578
579 data_next = le32_to_cpu(raw_sb->nx_xp_data_next);
580 data_base = le64_to_cpu(raw_sb->nx_xp_data_base);
581 data_index = data_next; /* New checkpoint */
582 data_blks = le32_to_cpu(raw_sb->nx_xp_data_blocks);
583 data_len = 0; /* For now */
584
585 /*
586 * The reference doesn't mention anything about this, but I need to
587 * put some sort of a limit or else the rings could wrap around and
588 * corrupt themselves.
589 */
590 desc_limit = desc_blks >> 2;
591 data_limit = data_blks >> 2;
592
593 for (i = 0; i < nxi->nx_eph_count; ++i) {
594 if (data_len == data_limit) {
595 apfs_err(sb, "too many checkpoint data blocks");
596 return -EFSCORRUPTED;
597 }
598
599 if (!cpm) {
600 cpm_start = i;
601 if (desc_len == desc_limit) {
602 apfs_err(sb, "too many checkpoint descriptor blocks");
603 return -EFSCORRUPTED;
604 }
605 cpm_bno = desc_base + (desc_index + desc_len) % desc_blks;
606 err = apfs_create_cpm_block(sb, cpm_bno, &cpm_bh);
607 if (err) {
608 apfs_err(sb, "failed to create cpm block");
609 return err;
610 }
611 cpm = (void *)cpm_bh->b_data;
612 desc_len += 1;
613 }
614
615 eph_info = &nxi->nx_eph_list[i];
616 data_next = (data_index + data_len) % data_blks;
617 obj_blkcnt = eph_info->size >> sb->s_blocksize_bits;
618
619 err = apfs_create_cpoint_map(sb, cpm, eph_info->object, data_base + data_next, eph_info->size);
620 if (err) {
621 if (err == -ENOSPC)
622 cpm->cpm_flags = 0; /* No longer the last */
623 brelse(cpm_bh);
624 cpm = NULL;
625 cpm_bh = NULL;
626 if (err == -ENOSPC) {
627 --i;
628 continue;
629 }
630 apfs_err(sb, "failed to create cpm map %d", i);
631 return err;
632 }
633 err = apfs_write_single_ephemeral_object(sb, eph_info->object, &cpm->cpm_map[i - cpm_start]);
634 if (err) {
635 brelse(cpm_bh);
636 cpm = NULL;
637 cpm_bh = NULL;
638 apfs_err(sb, "failed to write ephemeral object %d", i);
639 return err;
640 }
641 data_len += obj_blkcnt;
642 }
643
644 /*
645 * The checkpoint superblock can't be set until the very end of the
646 * transaction commit, but allocate its block here already.
647 */
648 nxi->nx_bno = desc_base + (desc_index + desc_len) % desc_blks;
649 desc_len += 1;
650
651 desc_next = (desc_index + desc_len) % desc_blks;
652 data_next = (data_index + data_len) % data_blks;
653
654 raw_sb->nx_xp_desc_next = cpu_to_le32(desc_next);
655 raw_sb->nx_xp_desc_index = cpu_to_le32(desc_index);
656 raw_sb->nx_xp_desc_len = cpu_to_le32(desc_len);
657
658 raw_sb->nx_xp_data_next = cpu_to_le32(data_next);
659 raw_sb->nx_xp_data_index = cpu_to_le32(data_index);
660 raw_sb->nx_xp_data_len = cpu_to_le32(data_len);
661
662 return 0;
663 }
664
665 /**
666 * apfs_transaction_commit_nx - Definitely commit the current transaction
667 * @sb: superblock structure
668 */
669 static int apfs_transaction_commit_nx(struct super_block *sb)
670 {
671 struct apfs_spaceman *sm = APFS_SM(sb);
672 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
673 struct apfs_nx_transaction *nx_trans = &nxi->nx_transaction;
674 struct apfs_bh_info *bhi, *tmp;
675 int err = 0;
676
677 ASSERT(!(sb->s_flags & SB_RDONLY));
678
679 /* Before committing the bhs, write all inode metadata to them */
680 err = apfs_transaction_flush_all_inodes(sb);
681 if (err) {
682 apfs_err(sb, "failed to flush all inodes");
683 return err;
684 }
685
686 /*
687 * Now that nothing else will be freed, flush the last update to the
688 * free queues so that it can be committed to disk along with all the
689 * ephemeral objects.
690 */
691 if (sm->sm_free_cache_base) {
692 err = apfs_free_queue_insert_nocache(sb, sm->sm_free_cache_base, sm->sm_free_cache_blkcnt);
693 if (err) {
694 apfs_err(sb, "fq cache flush failed (0x%llx-0x%llx)", sm->sm_free_cache_base, sm->sm_free_cache_blkcnt);
695 return err;
696 }
697 sm->sm_free_cache_base = sm->sm_free_cache_blkcnt = 0;
698 }
699 /*
700 * Writing the ip bitmaps modifies the spaceman, so it must happen
701 * before we commit the ephemeral objects. It must also happen after we
702 * flush the free queue, in case the last freed range was in the ip.
703 */
704 err = apfs_write_ip_bitmaps(sb);
705 if (err) {
706 apfs_err(sb, "failed to commit the ip bitmaps");
707 return err;
708 }
709 err = apfs_write_ephemeral_objects(sb);
710 if (err)
711 return err;
712
713 list_for_each_entry(bhi, &nx_trans->t_buffers, list) {
714 struct buffer_head *bh = bhi->bh;
715
716 ASSERT(buffer_trans(bh));
717
718 if (buffer_csum(bh))
719 apfs_obj_set_csum(sb, (void *)bh->b_data);
720
721 clear_buffer_dirty(bh);
722 get_bh(bh);
723 lock_buffer(bh);
724 apfs_submit_bh(REQ_OP_WRITE, REQ_SYNC, bh);
725 }
726 list_for_each_entry_safe(bhi, tmp, &nx_trans->t_buffers, list) {
727 struct buffer_head *bh = bhi->bh;
728 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 0)
729 struct folio *folio = NULL;
730 #else
731 struct page *page = NULL;
732 #endif
733 bool is_metadata;
734
735 ASSERT(buffer_trans(bh));
736
737 wait_on_buffer(bh);
738 if (!buffer_uptodate(bh)) {
739 apfs_err(sb, "failed to write some blocks");
740 return -EIO;
741 }
742
743 list_del(&bhi->list);
744 clear_buffer_trans(bh);
745 nx_trans->t_buffers_count--;
746
747 bh->b_private = NULL;
748 bhi->bh = NULL;
749 kfree(bhi);
750 bhi = NULL;
751
752 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 0)
753 folio = page_folio(bh->b_page);
754 folio_get(folio);
755 #else
756 page = bh->b_page;
757 get_page(page);
758 #endif
759
760 is_metadata = buffer_csum(bh);
761 clear_buffer_csum(bh);
762 put_bh(bh);
763 bh = NULL;
764
765 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 0)
766 folio_lock(folio);
767 folio_mkclean(folio);
768 #else
769 /* Future writes to mmapped areas should fault for CoW */
770 lock_page(page);
771 page_mkclean(page);
772 #endif
773 /* XXX: otherwise, the page cache fills up and crashes the machine */
774 if (!is_metadata) {
775 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 0)
776 try_to_free_buffers(folio);
777 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(5, 19, 0) || RHEL_VERSION_GE(9, 3)
778 try_to_free_buffers(page_folio(page));
779 #else
780 try_to_free_buffers(page);
781 #endif
782 }
783 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 11, 0)
784 folio_unlock(folio);
785 folio_put(folio);
786 #else
787 unlock_page(page);
788 put_page(page);
789 #endif
790 }
791 err = apfs_checkpoint_end(sb);
792 if (err) {
793 apfs_err(sb, "failed to end the checkpoint");
794 return err;
795 }
796
797 nx_trans->t_starts_count = 0;
798 nx_trans->t_buffers_count = 0;
799 return 0;
800 }
801
802 /**
803 * apfs_transaction_need_commit - Evaluate if a commit is required
804 * @sb: superblock structure
805 */
806 static bool apfs_transaction_need_commit(struct super_block *sb)
807 {
808 struct apfs_spaceman *sm = APFS_SM(sb);
809 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
810 struct apfs_nx_transaction *nx_trans = &nxi->nx_transaction;
811
812 if (nx_trans->t_state & APFS_NX_TRANS_DEFER_COMMIT) {
813 nx_trans->t_state &= ~APFS_NX_TRANS_DEFER_COMMIT;
814 return false;
815 }
816
817 /* Avoid nested commits on inode writeback */
818 if (nx_trans->t_state & APFS_NX_TRANS_COMMITTING)
819 return false;
820
821 if (nx_trans->t_state & APFS_NX_TRANS_FORCE_COMMIT) {
822 nx_trans->t_state = 0;
823 return true;
824 }
825
826 if (sm) {
827 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
828 struct apfs_spaceman_free_queue *fq_ip = &sm_raw->sm_fq[APFS_SFQ_IP];
829 struct apfs_spaceman_free_queue *fq_main = &sm_raw->sm_fq[APFS_SFQ_MAIN];
830 int buffers_max = nxi->nx_trans_buffers_max;
831 int starts_max = APFS_TRANS_STARTS_MAX;
832 int mq_max = APFS_TRANS_MAIN_QUEUE_MAX;
833 int maxnodes;
834
835 /*
836 * Try to avoid committing halfway through a data block write,
837 * otherwise the block will be put through copy-on-write again,
838 * causing unnecessary fragmentation.
839 */
840 if (nx_trans->t_state & APFS_NX_TRANS_INCOMPLETE_BLOCK) {
841 buffers_max += 50;
842 starts_max += 50;
843 mq_max += 20;
844 }
845
846 if (nx_trans->t_buffers_count > buffers_max)
847 return true;
848 if (nx_trans->t_starts_count > starts_max)
849 return true;
850
851 /*
852 * The internal pool has enough blocks to map the container
853 * exactly 3 times. Don't allow large transactions if we can't
854 * be sure the bitmap changes will all fit.
855 */
856 if (le64_to_cpu(fq_ip->sfq_count) * 3 > le64_to_cpu(sm_raw->sm_ip_block_count))
857 return true;
858
859 /* Don't let the main queue get too full either */
860 if (le64_to_cpu(fq_main->sfq_count) > mq_max)
861 return true;
862
863 /*
864 * The main free queue can become unbalanced enough to reach
865 * the node limit while being mostly empty. For now, the only
866 * way I have to rebalance it is to flush it entirely with a
867 * new transaction. We could wait longer to do it, but I don't
868 * see the point.
869 */
870 maxnodes = le16_to_cpu(fq_main->sfq_tree_node_limit);
871 maxnodes = (maxnodes + 1) >> 1;
872 if (sm->sm_main_fq_nodes > 1 && sm->sm_main_fq_nodes >= maxnodes)
873 return true;
874 }
875
876 return false;
877 }
878
879 /**
880 * apfs_transaction_commit - Possibly commit the current transaction
881 * @sb: superblock structure
882 *
883 * On success returns 0 and releases the big filesystem lock. On failure,
884 * returns a negative error code, and the caller is responsibly for aborting
885 * the transaction.
886 */
887 int apfs_transaction_commit(struct super_block *sb)
888 {
889 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
890 struct apfs_nx_transaction *trans = NULL;
891 int err = 0;
892
893 trans = &nxi->nx_transaction;
894
895 if (apfs_transaction_need_commit(sb)) {
896 err = apfs_transaction_commit_nx(sb);
897 if (err) {
898 apfs_err(sb, "transaction commit failed");
899 return err;
900 }
901 trans->t_work_sb = NULL;
902 cancel_delayed_work(&trans->t_work);
903 } else {
904 trans->t_work_sb = sb;
905 mod_delayed_work(system_wq, &trans->t_work, msecs_to_jiffies(100));
906 }
907
908 up_write(&nxi->nx_big_sem);
909 return 0;
910 }
911
912 /**
913 * apfs_inode_join_transaction - Add an inode to the current transaction
914 * @sb: superblock structure
915 * @inode: vfs inode to add
916 */
917 void apfs_inode_join_transaction(struct super_block *sb, struct inode *inode)
918 {
919 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
920 struct apfs_nx_transaction *nx_trans = &nxi->nx_transaction;
921 struct apfs_inode_info *ai = APFS_I(inode);
922
923 ASSERT(!(sb->s_flags & SB_RDONLY));
924 lockdep_assert_held_write(&nxi->nx_big_sem);
925
926 if (!list_empty(&ai->i_list)) /* Already in the transaction */
927 return;
928
929 ihold(inode);
930 list_add(&ai->i_list, &nx_trans->t_inodes);
931 }
932
933 /**
934 * apfs_transaction_join - Add a buffer head to the current transaction
935 * @sb: superblock structure
936 * @bh: the buffer head
937 */
938 int apfs_transaction_join(struct super_block *sb, struct buffer_head *bh)
939 {
940 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
941 struct apfs_nx_transaction *nx_trans = &nxi->nx_transaction;
942 struct apfs_bh_info *bhi;
943
944 ASSERT(!(sb->s_flags & SB_RDONLY));
945 lockdep_assert_held_write(&nxi->nx_big_sem);
946
947 if (buffer_trans(bh)) /* Already part of the only transaction */
948 return 0;
949
950 /* TODO: use a slab cache */
951 bhi = kzalloc(sizeof(*bhi), GFP_NOFS);
952 if (!bhi)
953 return -ENOMEM;
954 get_bh(bh);
955 bhi->bh = bh;
956 list_add(&bhi->list, &nx_trans->t_buffers);
957 nx_trans->t_buffers_count++;
958
959 set_buffer_trans(bh);
960 bh->b_private = bhi;
961 return 0;
962 }
963
964 /**
965 * apfs_force_readonly - Set the whole container as read-only
966 * @nxi: container superblock info
967 */
968 static void apfs_force_readonly(struct apfs_nxsb_info *nxi)
969 {
970 struct apfs_sb_info *sbi = NULL;
971 struct super_block *sb = NULL;
972
973 list_for_each_entry(sbi, &nxi->vol_list, list) {
974 sb = sbi->s_vobject.sb;
975 sb->s_flags |= SB_RDONLY;
976 }
977 nxi->nx_flags &= ~APFS_READWRITE;
978 }
979
980 /**
981 * apfs_transaction_abort - Abort the current transaction
982 * @sb: superblock structure
983 *
984 * Releases the big filesystem lock and clears the in-memory transaction data;
985 * the on-disk changes are irrelevant because the superblock checksum hasn't
986 * been written yet. Leaves the filesystem in read-only state.
987 */
988 void apfs_transaction_abort(struct super_block *sb)
989 {
990 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
991 struct apfs_nx_transaction *nx_trans = &nxi->nx_transaction;
992 struct apfs_bh_info *bhi, *tmp;
993 struct apfs_inode_info *ai, *ai_tmp;
994
995 if (sb->s_flags & SB_RDONLY) {
996 /* Transaction already aborted, do nothing */
997 ASSERT(list_empty(&nx_trans->t_inodes));
998 ASSERT(list_empty(&nx_trans->t_buffers));
999 up_write(&nxi->nx_big_sem);
1000 return;
1001 }
1002
1003 nx_trans->t_state = 0;
1004 apfs_err(sb, "aborting transaction");
1005
1006 --nxi->nx_xid;
1007 list_for_each_entry_safe(bhi, tmp, &nx_trans->t_buffers, list) {
1008 struct buffer_head *bh = bhi->bh;
1009
1010 bh->b_private = NULL;
1011 clear_buffer_dirty(bh);
1012 clear_buffer_trans(bh);
1013 clear_buffer_csum(bh);
1014 brelse(bh);
1015 bhi->bh = NULL;
1016
1017 list_del(&bhi->list);
1018 kfree(bhi);
1019 }
1020
1021 /*
1022 * It's not possible to undo in-memory changes from old operations in
1023 * the aborted transaction. To avoid corruption, never write again.
1024 */
1025 apfs_force_readonly(nxi);
1026
1027 up_write(&nxi->nx_big_sem);
1028
1029 list_for_each_entry_safe(ai, ai_tmp, &nx_trans->t_inodes, i_list) {
1030 list_del_init(&ai->i_list);
1031 iput(&ai->vfs_inode);
1032 }
1033 }