cocoon-tpm-storage 0.1.3

Cocoon TPM project - secure persistent storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023-2025 SUSE LLC
// Author: Nicolai Stange <nstange@suse.de>

//! Implementation of [`Transaction`].

extern crate alloc;
use alloc::{boxed::Box, vec::Vec};

use crate::{
    blkdev,
    crypto::rng,
    fs::{
        NvFsError,
        cocoonfs::{
            alloc_bitmap, auth_tree, extents,
            fs::{CocoonFsPendingTransactionsSyncState, CocoonFsSyncStateMemberRef},
            inode_index, journal, layout,
        },
    },
    utils_async::sync_types,
    utils_common::fixed_vec::FixedVec,
};

pub(super) mod auth_tree_data_blocks_update_states;
pub use auth_tree_data_blocks_update_states::AuthTreeDataBlocksUpdateStates;
mod prepare_staged_updates_application;
pub(super) use prepare_staged_updates_application::TransactionPrepareStagedUpdatesApplicationFuture;
mod apply_journal;
mod auth_tree_updates;
mod cleanup;
mod journal_allocations;
pub(super) mod read_authenticate_data;
mod read_missing_data;
mod write_dirty_data;
mod write_journal;

#[cfg(doc)]
use crate::fs::cocoonfs::fs::CocoonFs;
#[cfg(doc)]
use auth_tree_data_blocks_update_states::AllocationBlockUpdateStagedUpdate;
#[cfg(doc)]
use layout::ImageLayout;

/// Internal representation of a pending transaction.
pub struct Transaction {
    /// Pending updates to data on storage.
    pub(super) auth_tree_data_blocks_update_states: AuthTreeDataBlocksUpdateStates,

    /// Optional journal staging copy disguising.
    ///
    /// If `None`, journal staging copy disguising is disabled, otherwise
    /// the `Some` wraps a pair of an
    /// [`JournalStagingCopyDisguise`](journal::staging_copy_disguise::JournalStagingCopyDisguise)
    /// instance alongside its associated, lazily instantiated
    /// [`JournalStagingCopyUndisguise`](journal::staging_copy_disguise::JournalStagingCopyUndisguise).
    pub(super) journal_staging_copy_disguise: Option<(
        journal::staging_copy_disguise::JournalStagingCopyDisguise,
        Option<journal::staging_copy_disguise::JournalStagingCopyUndisguise>,
    )>,

    /// Verbatim value of [`ImageLayout::allocation_block_size_128b_log2`].
    allocation_block_size_128b_log2: u8,
    /// Verbatim value of
    /// [`ImageLayout::auth_tree_data_block_allocation_blocks_log2`].
    auth_tree_data_block_allocation_blocks_log2: u8,
    /// Verbatim value of [`ImageLayout::io_block_allocation_blocks_log2`].
    io_block_allocation_blocks_log2: u8,
    /// Cached value of
    /// [NvBlkDev::io_block_size_128b_log2()](blkdev::NvBlkDev::io_block_size_128b_log2).
    blkdev_io_block_size_128b_log2: u32,
    /// Cached value of
    /// [NvBlkDev::preferred_io_blocks_bulk_log2()](blkdev::NvBlkDev::preferred_io_blocks_bulk_log2).
    preferred_blkdev_io_blocks_bulk_log2: u32,

    /// Allocations and deallocations staged on behalf of the [`Transaction`].
    pub(super) allocs: TransactionAllocations,

    /// List of recollected abandoned journal staging copy blocks.
    ///
    /// Collection of blocks, all equal to the larger of the [Authentication
    /// Tree Data
    /// Block](ImageLayout::auth_tree_data_block_allocation_blocks_log2) and the
    /// [IO Block](ImageLayout::io_block_allocation_blocks_log2) size,
    /// identified by their respective beginning on storage.
    abandoned_journal_staging_copy_blocks: Vec<layout::PhysicalAllocBlockIndex>,

    /// Whether the [`Transaction`] has been elected as the primary one among
    /// the pending.
    ///
    /// The primary [`Transaction`] has more freedom regarding in-place writes.
    pub(super) is_primary_pending: bool,

    /// State transferred from [`CocoonFs::pending_transactions_sync_state`]
    /// upon [`Transaction`] commit.
    accumulated_fs_instance_pending_transactions_sync_state: CocoonFsPendingTransactionsSyncState,

    /// Updates to the inode index staged at the [`Transaction`].
    pub(super) inode_index_updates: inode_index::TransactionInodeIndexUpdates,

    /// Pending updates to the authentication tree.
    ///
    /// Populated at [`Transaction`] commit and applied to the authentication
    /// tree once the journal has been written.
    pending_auth_tree_updates: TransactionPendingAuthTreeUpdates,

    /// The extents allocated to the journal log's chained encrypted extents'
    /// tail.
    ///
    /// Comprises all the journal log's extents but the head stored at the
    /// fixed, well-known location.
    journal_log_tail_extents: extents::PhysicalExtents,

    /// Whether to fail the online journal application.
    ///
    /// Used for testing journal replay.
    #[cfg(test)]
    pub(super) test_fail_apply_journal: bool,
}

impl Transaction {
    /// Instantiate a new [`Transaction`].
    ///
    /// # Arguments:
    ///
    /// * `fs_instance_sync_state` - Reference to [`CocoonFs::sync_state`].
    /// * `is_primary_pending` - Whether the [`Transaction`] is the primary one
    ///   among the pending. There must be at most one pending with this
    ///   attribute at any time.
    /// * `rng` - The [random number generator](rng::RngCoreDispatchable) used
    ///   for generating the [journal staging copy
    ///   disguising](journal::staging_copy_disguise::JournalStagingCopyDisguise)
    ///   key.
    pub fn new<ST: sync_types::SyncTypes, B: blkdev::NvBlkDev>(
        fs_instance_sync_state: &mut CocoonFsSyncStateMemberRef<'_, ST, B>,
        is_primary_pending: bool,
        rng: &mut dyn rng::RngCoreDispatchable,
    ) -> Result<Self, NvFsError> {
        let fs_instance = fs_instance_sync_state.get_fs_ref();
        let image_layout = &fs_instance.fs_config.image_layout;
        let journal_staging_copy_disguise =
            journal::staging_copy_disguise::JournalStagingCopyDisguise::generate(image_layout.block_cipher_alg, rng)?;

        let allocation_block_size_128b_log2 = image_layout.allocation_block_size_128b_log2;
        let auth_tree_data_block_allocation_blocks_log2 = image_layout.auth_tree_data_block_allocation_blocks_log2;
        let io_block_allocation_blocks_log2 = image_layout.io_block_allocation_blocks_log2;
        let blkdev = &fs_instance.blkdev;
        let blkdev_io_block_size_128b_log2 = blkdev.io_block_size_128b_log2();
        let preferred_blkdev_io_blocks_bulk_log2 = blkdev.preferred_io_blocks_bulk_log2();

        Ok(Self {
            auth_tree_data_blocks_update_states: AuthTreeDataBlocksUpdateStates::new(
                io_block_allocation_blocks_log2,
                auth_tree_data_block_allocation_blocks_log2,
                allocation_block_size_128b_log2,
            ),
            journal_staging_copy_disguise: Some((journal_staging_copy_disguise, None)),
            allocation_block_size_128b_log2,
            auth_tree_data_block_allocation_blocks_log2,
            io_block_allocation_blocks_log2,
            blkdev_io_block_size_128b_log2,
            preferred_blkdev_io_blocks_bulk_log2,
            allocs: TransactionAllocations::new(),
            abandoned_journal_staging_copy_blocks: Vec::new(),
            is_primary_pending,
            accumulated_fs_instance_pending_transactions_sync_state: CocoonFsPendingTransactionsSyncState::new(),
            inode_index_updates: inode_index::TransactionInodeIndexUpdates::new(&fs_instance_sync_state.inode_index),
            pending_auth_tree_updates: TransactionPendingAuthTreeUpdates::new(),
            journal_log_tail_extents: extents::PhysicalExtents::new(),
            #[cfg(test)]
            test_fail_apply_journal: false,
        })
    }

    /// Deallocate a power-of-two sized, aligned block.
    ///
    /// Mark the block identified by `block_allocation_blocks_begin` and of size
    /// as determined by `block_allocation_blocks_log2` as freed at
    /// [`Transaction::allocs`] and move any of the
    /// existing [`Transaction::auth_tree_data_blocks_update_states`]'
    /// [Allocation Block level
    /// entries](auth_tree_data_blocks_update_states::AllocationBlockUpdateState) overlapping with
    /// it to the [`AllocationBlockUpdateStagedUpdate::Deallocate`] staged
    /// update state.
    ///
    /// The changes made to [`Transaction::allocs`] may get [rolled
    /// back](Self::rollback_block_free) again unless
    /// [`TransactionAllocations::reset_rollback()`] has been invoked on it. Any
    /// data updates previously staged however cannot be recovered. They
    /// need to [get
    /// applied](AuthTreeDataBlocksUpdateStates::apply_allocation_blocks_staged_updates) first
    /// before the deallocation should that be needed.  Note that the ability to
    /// rollback comes at some additional memory overhead, so users should
    /// invoke [`TransactionAllocations::reset_rollback()`] on
    /// [`Transaction::allocs`] once it's not longer needed.
    ///
    /// # Arguments:
    ///
    /// * `transaction_allocs` - `mut` reference to [`Transaction::allocs`].
    /// * `transaction_updates_states` - `mut` reference to
    ///   [`Transaction::auth_tree_data_blocks_update_states`].
    /// * `block_allocation_blocks_begin` - Beginning of the block on storage.
    ///   Must be aligned to the size as determined by
    ///   `block_allocation_blocks_log2`.
    /// * `block_allocation_blocks_log2` - Base-2 logarithm of the block size in
    ///   units of [Allocation
    ///   Blocks](ImageLayout::allocation_block_size_128b_log2).
    pub fn free_block(
        transaction_allocs: &mut TransactionAllocations,
        transaction_updates_states: &mut AuthTreeDataBlocksUpdateStates,
        block_allocation_blocks_begin: layout::PhysicalAllocBlockIndex,
        block_allocation_blocks_log2: u32,
    ) -> Result<(), NvFsError> {
        transaction_allocs
            .pending_frees
            .add_block(block_allocation_blocks_begin, block_allocation_blocks_log2)?;
        transaction_allocs
            .pending_allocs
            .remove_block(block_allocation_blocks_begin, block_allocation_blocks_log2);
        transaction_updates_states
            .stage_block_deallocation_updates(block_allocation_blocks_begin, block_allocation_blocks_log2);
        Ok(())
    }

    /// Deallocate some power-of-two sized, aligned blocks.
    ///
    /// Mark the blocks at the locations obtained from
    /// `blocks_allocation_blocks_begin_iter` and of size as determined by
    /// `block_allocation_blocks_log2` each as freed at
    /// [`Transaction::allocs`] and move any of the existing
    /// [`Transaction::auth_tree_data_blocks_update_states`]' [Allocation Block
    /// level
    /// entries](auth_tree_data_blocks_update_states::AllocationBlockUpdateState) overlapping with
    /// them to the [`AllocationBlockUpdateStagedUpdate::Deallocate`] staged
    /// update state.
    ///
    /// The changes made to [`Transaction::allocs`] may get [rolled
    /// back](Self::rollback_blocks_free) again unless
    /// [`TransactionAllocations::reset_rollback()`] has been invoked on it.
    /// Any data updates previously staged however cannot be recovered. They
    /// need to [get
    /// applied](AuthTreeDataBlocksUpdateStates::apply_allocation_blocks_staged_updates) first
    /// before the deallocation should that be needed.
    ///
    /// # Arguments:
    ///
    /// * `transaction_allocs` - `mut` reference to [`Transaction::allocs`].
    /// * `transaction_updates_states` - `mut` reference to
    ///   [`Transaction::auth_tree_data_blocks_update_states`].
    /// * `block_allocation_blocks_begin_iter` - Iterator over the blocks'
    ///   beginnings of the block on storage each. Must be aligned to the size
    ///   as determined by `block_allocation_blocks_log2`.
    /// * `block_allocation_blocks_log2` - Base-2 logarithm of the block size in
    ///   units of [Allocation
    ///   Blocks](ImageLayout::allocation_block_size_128b_log2).
    #[allow(dead_code)]
    pub fn free_blocks<BI: Iterator<Item = layout::PhysicalAllocBlockIndex> + Clone>(
        transaction_allocs: &mut TransactionAllocations,
        transaction_updates_states: &mut AuthTreeDataBlocksUpdateStates,
        blocks_allocation_blocks_begin_iter: BI,
        block_allocation_blocks_log2: u32,
    ) -> Result<(), NvFsError> {
        transaction_allocs.pending_frees.add_blocks(
            blocks_allocation_blocks_begin_iter.clone(),
            block_allocation_blocks_log2,
        )?;
        transaction_allocs.pending_allocs.remove_blocks(
            blocks_allocation_blocks_begin_iter.clone(),
            block_allocation_blocks_log2,
        );
        transaction_updates_states
            .stage_blocks_deallocation_updates(blocks_allocation_blocks_begin_iter, block_allocation_blocks_log2);
        Ok(())
    }

    /// Deallocate some storage extents.
    ///
    /// Mark the extents obtained from `extents_iter` as freed at
    /// [`Transaction::allocs`] and move any of the existing
    /// [`Transaction::auth_tree_data_blocks_update_states`]' [Allocation Block
    /// level entries](auth_tree_data_blocks_update_states::AllocationBlockUpdateState) overlapping
    /// with them to the [`AllocationBlockUpdateStagedUpdate::Deallocate`]
    /// staged update state.
    ///
    /// The changes made to [`Transaction::allocs`] may get [rolled
    /// back](Self::rollback_extents_free) again unless
    /// [`TransactionAllocations::reset_rollback()`] has been invoked on it.
    /// Any data updates previously staged however cannot be recovered. They
    /// need to [get
    /// applied](AuthTreeDataBlocksUpdateStates::apply_allocation_blocks_staged_updates) first
    /// before the deallocation should that be needed.
    ///
    /// # Arguments:
    ///
    /// * `transaction_allocs` - `mut` reference to [`Transaction::allocs`].
    /// * `transaction_updates_states` - `mut` reference to
    ///   [`Transaction::auth_tree_data_blocks_update_states`].
    /// * `extents_iter` - Iterator over the extents.
    /// * `block_allocation_blocks_log2` - Base-2 logarithm of the block size in
    ///   units of [Allocation
    ///   Blocks](ImageLayout::allocation_block_size_128b_log2).
    pub fn free_extents<EI: Iterator<Item = layout::PhysicalAllocBlockRange> + Clone>(
        transaction_allocs: &mut TransactionAllocations,
        transaction_updates_states: &mut AuthTreeDataBlocksUpdateStates,
        extents_iter: EI,
    ) -> Result<(), NvFsError> {
        transaction_allocs.pending_frees.add_extents(extents_iter.clone())?;
        transaction_allocs.pending_allocs.remove_extents(extents_iter.clone());
        transaction_updates_states.stage_extents_deallocation_updates(extents_iter);
        Ok(())
    }

    /// Rollback the allocation of a power-of-two sized, aligned block.
    ///
    /// Rollback the allocation of the block identified by
    /// `block_allocation_blocks_begin` and of size as determined by
    /// `block_allocation_blocks_log2` at [`Transaction::allocs`] and move any
    /// of the existing [`Transaction::auth_tree_data_blocks_update_states`]'
    /// [Allocation Block
    /// level entries](auth_tree_data_blocks_update_states::AllocationBlockUpdateState) overlapping
    /// with it to the [`AllocationBlockUpdateStagedUpdate::Deallocate`] staged
    /// update state.
    ///
    /// Must get invoked only if [`TransactionAllocations::reset_rollback()`]
    /// has not been invoked on [`Transaction::allocs`] since the allocation,
    /// and is failsafe then.
    ///
    /// # Arguments:
    ///
    /// * `block_allocation_blocks_begin` - Beginning of the block on storage.
    ///   Must be aligned to the size as determined by
    ///   `block_allocation_blocks_log2`.
    /// * `block_allocation_blocks_log2` - Base-2 logarithm of the block size in
    ///   units of [Allocation
    ///   Blocks](ImageLayout::allocation_block_size_128b_log2).
    /// * `alloc_bitmap` - The filesystem's
    ///   [`AllocBitmap`](alloc_bitmap::AllocBitmap) in the state from before
    ///   the [`Transaction`].
    pub fn rollback_block_allocation(
        mut self: Box<Self>,
        block_allocation_blocks_begin: layout::PhysicalAllocBlockIndex,
        block_allocation_blocks_log2: u32,
        alloc_bitmap: &alloc_bitmap::AllocBitmap,
    ) -> Result<Box<Self>, NvFsError> {
        self.allocs
            .pending_allocs
            .remove_block(block_allocation_blocks_begin, block_allocation_blocks_log2);
        // If something had been allocated, it must have been free before.
        self.allocs.pending_frees.rollback_remove_block(
            block_allocation_blocks_begin,
            block_allocation_blocks_log2,
            alloc_bitmap,
            false,
        )?;

        self.auth_tree_data_blocks_update_states
            .stage_block_deallocation_updates(block_allocation_blocks_begin, block_allocation_blocks_log2);

        Ok(self)
    }

    /// Rollback the deallocation of a power-of-two sized, aligned block.
    ///
    /// Rollback the deallocation of the block identified by
    /// `block_allocation_blocks_begin` and of size as determined by
    /// `block_allocation_blocks_log2` at [`Transaction::allocs`] and reset
    /// any updates staged at the
    /// [`Transaction::auth_tree_data_blocks_update_states`]' [Allocation Block
    /// level entries](auth_tree_data_blocks_update_states::AllocationBlockUpdateState)
    /// overlapping with it.
    ///
    /// Must get invoked only if [`TransactionAllocations::reset_rollback()`]
    /// has not been invoked on [`Transaction::allocs`] since the deallocation,
    /// and is failsafe then.
    ///
    /// # Arguments:
    ///
    /// * `block_allocation_blocks_begin` - Beginning of the block on storage.
    ///   Must be aligned to the size as determined by
    ///   `block_allocation_blocks_log2`.
    /// * `block_allocation_blocks_log2` - Base-2 logarithm of the block size in
    ///   units of [Allocation
    ///   Blocks](ImageLayout::allocation_block_size_128b_log2).
    /// * `alloc_bitmap` - The filesystem's
    ///   [`AllocBitmap`](alloc_bitmap::AllocBitmap) in the state from before
    ///   the [`Transaction`].
    pub fn rollback_block_free(
        mut self: Box<Self>,
        block_allocation_blocks_begin: layout::PhysicalAllocBlockIndex,
        block_allocation_blocks_log2: u32,
        alloc_bitmap: &alloc_bitmap::AllocBitmap,
    ) -> Result<Box<Self>, NvFsError> {
        self.allocs
            .pending_frees
            .remove_block(block_allocation_blocks_begin, block_allocation_blocks_log2);
        // If something had been freed, it must have been allocated before.
        self.allocs.pending_allocs.rollback_remove_block(
            block_allocation_blocks_begin,
            block_allocation_blocks_log2,
            alloc_bitmap,
            true,
        )?;

        self.auth_tree_data_blocks_update_states
            .reset_staged_block_updates(block_allocation_blocks_begin, block_allocation_blocks_log2);

        Ok(self)
    }

    /// Rollback the allocation of some power-of-two sized, aligned blocks.
    ///
    /// Rollback the allocation of the blocks at the locations obtained from
    /// `blocks_allocation_blocks_begin_iter` and of size as determined by
    /// `block_allocation_blocks_log2` each at [`Transaction::allocs`] and move
    /// any of the existing
    /// [`Transaction::auth_tree_data_blocks_update_states`]' [Allocation Block
    /// level
    /// entries](auth_tree_data_blocks_update_states::AllocationBlockUpdateState) overlapping with
    /// them to the [`AllocationBlockUpdateStagedUpdate::Deallocate`] staged
    /// update state.
    ///
    /// Must get invoked only if [`TransactionAllocations::reset_rollback()`]
    /// has not been invoked on [`Transaction::allocs`] since the allocation,
    /// and is failsafe then.
    ///
    /// # Arguments:
    ///
    /// * `block_allocation_blocks_begin_iter` - Iterator over the blocks'
    ///   beginnings of the block on storage each. Must be aligned to the size
    ///   as determined by `block_allocation_blocks_log2`.
    /// * `block_allocation_blocks_log2` - Base-2 logarithm of the block size in
    ///   units of [Allocation
    ///   Blocks](ImageLayout::allocation_block_size_128b_log2).
    /// * `alloc_bitmap` - The filesystem's
    ///   [`AllocBitmap`](alloc_bitmap::AllocBitmap) in the state from before
    ///   the [`Transaction`].
    pub fn rollback_blocks_allocation<BI: Iterator<Item = layout::PhysicalAllocBlockIndex> + Clone>(
        mut self: Box<Self>,
        blocks_allocation_blocks_begin_iter: BI,
        block_allocation_blocks_log2: u32,
        alloc_bitmap: &alloc_bitmap::AllocBitmap,
    ) -> Result<Box<Self>, NvFsError> {
        self.allocs.pending_allocs.remove_blocks(
            blocks_allocation_blocks_begin_iter.clone(),
            block_allocation_blocks_log2,
        );
        // If something had been allocated, it must have been free before.
        self.allocs.pending_frees.rollback_remove_blocks(
            blocks_allocation_blocks_begin_iter.clone(),
            block_allocation_blocks_log2,
            alloc_bitmap,
            false,
        )?;

        self.auth_tree_data_blocks_update_states
            .stage_blocks_deallocation_updates(blocks_allocation_blocks_begin_iter, block_allocation_blocks_log2);

        Ok(self)
    }

    /// Rollback the deallocation of some power-of-two sized, aligned blocks.
    ///
    /// Rollback the deallocation of the blocks at the locations obtained from
    /// `blocks_allocation_blocks_begin_iter` and of size as determined by
    /// `block_allocation_blocks_log2` each at [`Transaction::allocs`] and reset
    /// any updates staged at the
    /// [`Transaction::auth_tree_data_blocks_update_states`]' [Allocation Block
    /// level entries](auth_tree_data_blocks_update_states::AllocationBlockUpdateState)
    /// overlapping with them.
    ///
    /// Must get invoked only if [`TransactionAllocations::reset_rollback()`]
    /// has not been invoked on [`Transaction::allocs`] since the allocation,
    /// and is failsafe then.
    ///
    /// # Arguments:
    ///
    /// * `block_allocation_blocks_begin_iter` - Iterator over the blocks'
    ///   beginnings of the block on storage each. Must all be aligned to the
    ///   size as determined by `block_allocation_blocks_log2`.
    /// * `block_allocation_blocks_log2` - Base-2 logarithm of the block size in
    ///   units of [Allocation
    ///   Blocks](ImageLayout::allocation_block_size_128b_log2).
    /// * `alloc_bitmap` - The filesystem's
    ///   [`AllocBitmap`](alloc_bitmap::AllocBitmap) in the state from before
    ///   the [`Transaction`].
    #[allow(dead_code)]
    pub fn rollback_blocks_free<BI: Iterator<Item = layout::PhysicalAllocBlockIndex> + Clone>(
        mut self: Box<Self>,
        blocks_allocation_blocks_begin_iter: BI,
        block_allocation_blocks_log2: u32,
        alloc_bitmap: &alloc_bitmap::AllocBitmap,
    ) -> Result<Box<Self>, NvFsError> {
        self.allocs.pending_frees.remove_blocks(
            blocks_allocation_blocks_begin_iter.clone(),
            block_allocation_blocks_log2,
        );
        // If something had been freed, it must have been allocated before.
        self.allocs.pending_allocs.rollback_remove_blocks(
            blocks_allocation_blocks_begin_iter.clone(),
            block_allocation_blocks_log2,
            alloc_bitmap,
            true,
        )?;

        self.auth_tree_data_blocks_update_states
            .reset_staged_blocks_updates(blocks_allocation_blocks_begin_iter, block_allocation_blocks_log2);

        Ok(self)
    }

    /// Rollback the allocation of some extents.
    ///
    /// Rollback the allocation of the extents obtained from `extents_iter` at
    /// [`Transaction::allocs`] and move any of the existing
    /// [`Transaction::auth_tree_data_blocks_update_states`]' [Allocation Block
    /// level
    /// entries](auth_tree_data_blocks_update_states::AllocationBlockUpdateState) overlapping with
    /// them to the [`AllocationBlockUpdateStagedUpdate::Deallocate`] staged
    /// update state.
    ///
    /// Must get invoked only if [`TransactionAllocations::reset_rollback()`]
    /// has not been invoked on [`Transaction::allocs`] since the allocation,
    /// and is failsafe then.
    ///
    /// # Arguments:
    ///
    /// * `extents_iter` - Iterator over the extents.
    /// * `alloc_bitmap` - The filesystem's
    ///   [`AllocBitmap`](alloc_bitmap::AllocBitmap) in the state from before
    ///   the [`Transaction`].
    pub fn rollback_extents_allocation<EI: Iterator<Item = layout::PhysicalAllocBlockRange> + Clone>(
        mut self: Box<Self>,
        extents_iter: EI,
        alloc_bitmap: &alloc_bitmap::AllocBitmap,
    ) -> Result<Box<Self>, NvFsError> {
        self.allocs.pending_allocs.remove_extents(extents_iter.clone());
        // If something had been allocated, it must have been free before.
        self.allocs
            .pending_frees
            .rollback_remove_extents(extents_iter.clone(), alloc_bitmap, false)?;

        self.auth_tree_data_blocks_update_states
            .stage_extents_deallocation_updates(extents_iter);

        Ok(self)
    }

    /// Rollback the deallocation of some extents.
    ///
    /// Rollback the deallocation of the extents obtained from `extents_iter` at
    /// [`Transaction::allocs`] and reset
    /// any updates staged at the
    /// [`Transaction::auth_tree_data_blocks_update_states`]' [Allocation Block
    /// level entries](auth_tree_data_blocks_update_states::AllocationBlockUpdateState)
    /// overlapping with them.
    ///
    /// Must get invoked only if [`TransactionAllocations::reset_rollback()`]
    /// has not been invoked on [`Transaction::allocs`] since the allocation,
    /// and is failsafe then.
    ///
    /// # Arguments:
    ///
    /// * `extents_iter` - Iterator over the extents.
    /// * `alloc_bitmap` - The filesystem's
    ///   [`AllocBitmap`](alloc_bitmap::AllocBitmap) in the state from before
    ///   the [`Transaction`].
    /// * `contents_indeterminate` - Whether the reset of the updates staged at
    ///   the [`Transaction::auth_tree_data_blocks_update_states`] makes the the
    ///   extents' contents indeterminate. Should be set to `true` if the
    ///   previously staged updates from before the corresponding deallocation
    ///   had not been
    ///   [applied](AuthTreeDataBlocksUpdateStates::apply_allocation_blocks_staged_updates)
    ///   first before that deallocation.
    pub fn rollback_extents_free<EI: Iterator<Item = layout::PhysicalAllocBlockRange> + Clone>(
        mut self: Box<Self>,
        extents_iter: EI,
        alloc_bitmap: &alloc_bitmap::AllocBitmap,
        contents_indeterminate: bool,
    ) -> Result<Box<Self>, NvFsError> {
        self.allocs.pending_frees.remove_extents(extents_iter.clone());
        // If something had been freed, it must have been allocated before.
        self.allocs
            .pending_allocs
            .rollback_remove_extents(extents_iter.clone(), alloc_bitmap, true)?;

        if !contents_indeterminate {
            self.auth_tree_data_blocks_update_states
                .reset_staged_extents_updates(extents_iter);
        } else {
            // If the staged updates possibly present at the time of the deallocation had
            // not been applied before the free, then the contents are
            // indeterminate now.
            self.auth_tree_data_blocks_update_states
                .reset_staged_extents_updates_to_failed(extents_iter);
        }

        Ok(self)
    }
}

/// Allocations and deallocations made on behalf of the [`Transaction`].
///
/// Track allocations and deallocations relative to
/// the filesystem's [`AllocBitmap`](alloc_bitmap::AllocBitmap) from before the
/// [`Transaction`].
pub(super) struct TransactionAllocations {
    /// New, to be committed allocations.
    pub pending_allocs: alloc_bitmap::SparseAllocBitmap,
    /// New, to be committed deallocations.
    pub pending_frees: alloc_bitmap::SparseAllocBitmap,
    /// Temporary allocations for the lifetime of the journal.
    pub journal_allocs: alloc_bitmap::SparseAllocBitmap,
}

impl TransactionAllocations {
    /// Instantiate a new, empty [`TransactionAllocations`].
    pub fn new() -> Self {
        Self {
            pending_allocs: alloc_bitmap::SparseAllocBitmap::new(),
            pending_frees: alloc_bitmap::SparseAllocBitmap::new(),
            journal_allocs: alloc_bitmap::SparseAllocBitmap::new(),
        }
    }

    /// Reset the rollback memory reserves.
    pub fn reset_rollback(&mut self) {
        self.pending_allocs.reset_remove_rollback();
        self.pending_frees.reset_remove_rollback();
    }
}

/// Pending authentication tree updates to get applied once the journal has been
/// written.
///
/// Populated only at [`Transaction`] commit.
pub(super) struct TransactionPendingAuthTreeUpdates {
    /// The updated authentication tree root HMAC.
    updated_root_hmac_digest: FixedVec<u8, 5>,
    /// Updates to the authentication tree's nodes.
    pending_nodes_updates: auth_tree::AuthTreePendingNodesUpdates,
}

impl TransactionPendingAuthTreeUpdates {
    /// Instantiate a new, empty [`TransactionPendingAuthTreeUpdates`].
    fn new() -> Self {
        Self {
            updated_root_hmac_digest: FixedVec::new_empty(),
            pending_nodes_updates: auth_tree::AuthTreePendingNodesUpdates::new(),
        }
    }
}

pub(super) use apply_journal::TransactionApplyJournalFuture;
pub(super) use auth_tree_updates::TransactionJournalUpdateAuthDigestsScriptIterator;
pub(super) use cleanup::{TransactionAbortJournalFuture, TransactionCleanupPreCommitCancelledFuture};
pub(super) use write_journal::TransactionWriteJournalFuture;