1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "snapuserd_core.h"
18 
19 /*
20  * Readahead is used to optimize the merge of COPY and XOR Ops.
21  *
22  * We create a scratch space of 2MB to store the read-ahead data in the COW
23  * device.
24  *
25  *      +-----------------------+
26  *      |     Header (fixed)    |
27  *      +-----------------------+
28  *      |    Scratch space      |  <-- 2MB
29  *      +-----------------------+
30  *
31  *      Scratch space is as follows:
32  *
33  *      +-----------------------+
34  *      |       Metadata        | <- 4k page
35  *      +-----------------------+
36  *      |       Metadata        | <- 4k page
37  *      +-----------------------+
38  *      |                       |
39  *      |    Read-ahead data    |
40  *      |                       |
41  *      +-----------------------+
42  *
43  *
44  * * ===================================================================
45  *
46  * Example:
47  *
48  * We have 6 copy operations to be executed in OTA. Update-engine
49  * will write to COW file as follows:
50  *
51  * Op-1: 20 -> 23
52  * Op-2: 19 -> 22
53  * Op-3: 18 -> 21
54  * Op-4: 17 -> 20
55  * Op-5: 16 -> 19
56  * Op-6: 15 -> 18
57  *
58  * Read-ahead thread will read all the 6 source blocks and store the data in the
59  * scratch space. Metadata will contain the destination block numbers. Thus,
60  * scratch space will look something like this:
61  *
62  * +--------------+
63  * | Block   23   |
64  * | offset - 1   |
65  * +--------------+
66  * | Block   22   |
67  * | offset - 2   |
68  * +--------------+
69  * | Block   21   |
70  * | offset - 3   |
71  * +--------------+
72  *    ...
73  *    ...
74  * +--------------+
75  * | Data-Block 20| <-- offset - 1
76  * +--------------+
77  * | Data-Block 19| <-- offset - 2
78  * +--------------+
79  * | Data-Block 18| <-- offset - 3
80  * +--------------+
81  *     ...
82  *     ...
83  *
84  * ====================================================================
85  *
86  *
87  *  Read-ahead thread will process the COW Ops in fixed set. Consider
88  *  the following example:
89  *
90  *  +--------------------------+
91  *  |op-1|op-2|op-3|....|op-510|
92  *  +--------------------------+
93  *
94  *  <------ One RA Block ------>
95  *
96  *  RA thread will read 510 ordered COW ops at a time and will store
97  *  the data in the scratch space.
98  *
99  *  RA thread and Merge thread will go lock-step wherein RA thread
100  *  will make sure that 510 COW operation data are read upfront
101  *  and is in memory. Thus, when merge thread will pick up the data
102  *  directly from memory and write it back to base device.
103  *
104  *
105  *  +--------------------------+------------------------------------+
106  *  |op-1|op-2|op-3|....|op-510|op-511|op-512|op-513........|op-1020|
107  *  +--------------------------+------------------------------------+
108  *
109  *  <------Merge 510 Blocks----><-Prepare 510 blocks for merge by RA->
110  *           ^                                  ^
111  *           |                                  |
112  *      Merge thread                        RA thread
113  *
114  * Both Merge and RA thread will strive to work in parallel.
115  *
116  * ===========================================================================
117  *
118  * State transitions and communication between RA thread and Merge thread:
119  *
120  *  Merge Thread                                      RA Thread
121  *  ----------------------------------------------------------------------------
122  *
123  *          |                                         |
124  *    WAIT for RA Block N                     READ one RA Block (N)
125  *        for merge                                   |
126  *          |                                         |
127  *          |                                         |
128  *          <--------------MERGE BEGIN--------READ Block N done(copy to scratch)
129  *          |                                         |
130  *          |                                         |
131  *    Merge Begin Block N                     READ one RA BLock (N+1)
132  *          |                                         |
133  *          |                                         |
134  *          |                                  READ done. Wait for merge complete
135  *          |                                         |
136  *          |                                        WAIT
137  *          |                                         |
138  *    Merge done Block N                              |
139  *          ----------------MERGE READY-------------->|
140  *    WAIT for RA Block N+1                     Copy RA Block (N+1)
141  *        for merge                              to scratch space
142  *          |                                         |
143  *          <---------------MERGE BEGIN---------BLOCK N+1 Done
144  *          |                                         |
145  *          |                                         |
146  *    Merge Begin Block N+1                   READ one RA BLock (N+2)
147  *          |                                         |
148  *          |                                         |
149  *          |                                  READ done. Wait for merge complete
150  *          |                                         |
151  *          |                                        WAIT
152  *          |                                         |
153  *    Merge done Block N+1                            |
154  *          ----------------MERGE READY-------------->|
155  *    WAIT for RA Block N+2                     Copy RA Block (N+2)
156  *        for merge                              to scratch space
157  *          |                                         |
158  *          <---------------MERGE BEGIN---------BLOCK N+2 Done
159  */
160 
161 namespace android {
162 namespace snapshot {
163 
164 using namespace android;
165 using namespace android::dm;
166 using android::base::unique_fd;
167 
MonitorMerge()168 void SnapshotHandler::MonitorMerge() {
169     {
170         std::lock_guard<std::mutex> lock(lock_);
171         merge_monitored_ = true;
172     }
173 }
174 
175 // This is invoked once primarily by update-engine to initiate
176 // the merge
InitiateMerge()177 void SnapshotHandler::InitiateMerge() {
178     {
179         std::lock_guard<std::mutex> lock(lock_);
180         merge_initiated_ = true;
181 
182         // If there are only REPLACE ops to be merged, then we need
183         // to explicitly set the state to MERGE_BEGIN as there
184         // is no read-ahead thread
185         if (!ra_thread_) {
186             io_state_ = MERGE_IO_TRANSITION::MERGE_BEGIN;
187         }
188     }
189     cv.notify_all();
190 }
191 
192 // Invoked by Merge thread - Waits on RA thread to resume merging. Will
193 // be waken up RA thread.
WaitForMergeBegin()194 bool SnapshotHandler::WaitForMergeBegin() {
195     {
196         std::unique_lock<std::mutex> lock(lock_);
197         while (!MergeInitiated()) {
198             cv.wait(lock);
199 
200             if (io_state_ == MERGE_IO_TRANSITION::READ_AHEAD_FAILURE ||
201                 io_state_ == MERGE_IO_TRANSITION::IO_TERMINATED) {
202                 return false;
203             }
204         }
205 
206         while (!(io_state_ == MERGE_IO_TRANSITION::MERGE_BEGIN ||
207                  io_state_ == MERGE_IO_TRANSITION::READ_AHEAD_FAILURE ||
208                  io_state_ == MERGE_IO_TRANSITION::IO_TERMINATED)) {
209             cv.wait(lock);
210         }
211 
212         if (io_state_ == MERGE_IO_TRANSITION::READ_AHEAD_FAILURE ||
213             io_state_ == MERGE_IO_TRANSITION::IO_TERMINATED) {
214             return false;
215         }
216 
217         return true;
218     }
219 }
220 
221 // Invoked by RA thread - Flushes the RA block to scratch space if necessary
222 // and then notifies the merge thread to resume merging
ReadAheadIOCompleted(bool sync)223 bool SnapshotHandler::ReadAheadIOCompleted(bool sync) {
224     if (sync) {
225         // Flush the entire buffer region
226         int ret = msync(mapped_addr_, total_mapped_addr_length_, MS_SYNC);
227         if (ret < 0) {
228             PLOG(ERROR) << "msync failed after ReadAheadIOCompleted: " << ret;
229             return false;
230         }
231 
232         // Metadata and data are synced. Now, update the state.
233         // We need to update the state after flushing data; if there is a crash
234         // when read-ahead IO is in progress, the state of data in the COW file
235         // is unknown. kCowReadAheadDone acts as a checkpoint wherein the data
236         // in the scratch space is good and during next reboot, read-ahead thread
237         // can safely re-construct the data.
238         struct BufferState* ra_state = GetBufferState();
239         ra_state->read_ahead_state = kCowReadAheadDone;
240 
241         ret = msync(mapped_addr_, BLOCK_SZ, MS_SYNC);
242         if (ret < 0) {
243             PLOG(ERROR) << "msync failed to flush Readahead completion state...";
244             return false;
245         }
246     }
247 
248     // Notify the merge thread to resume merging
249     {
250         std::lock_guard<std::mutex> lock(lock_);
251         if (io_state_ != MERGE_IO_TRANSITION::IO_TERMINATED &&
252             io_state_ != MERGE_IO_TRANSITION::MERGE_FAILED) {
253             io_state_ = MERGE_IO_TRANSITION::MERGE_BEGIN;
254         }
255     }
256 
257     cv.notify_all();
258     return true;
259 }
260 
261 // Invoked by RA thread - Waits for merge thread to finish merging
262 // RA Block N - RA thread would be ready will with Block N+1 but
263 // will wait to merge thread to finish Block N. Once Block N
264 // is merged, RA thread will be woken up by Merge thread and will
265 // flush the data of Block N+1 to scratch space
WaitForMergeReady()266 bool SnapshotHandler::WaitForMergeReady() {
267     {
268         std::unique_lock<std::mutex> lock(lock_);
269         while (!(io_state_ == MERGE_IO_TRANSITION::MERGE_READY ||
270                  io_state_ == MERGE_IO_TRANSITION::MERGE_FAILED ||
271                  io_state_ == MERGE_IO_TRANSITION::MERGE_COMPLETE ||
272                  io_state_ == MERGE_IO_TRANSITION::IO_TERMINATED)) {
273             cv.wait(lock);
274         }
275 
276         // Check if merge failed
277         if (io_state_ == MERGE_IO_TRANSITION::MERGE_FAILED ||
278             io_state_ == MERGE_IO_TRANSITION::MERGE_COMPLETE ||
279             io_state_ == MERGE_IO_TRANSITION::IO_TERMINATED) {
280             return false;
281         }
282         return true;
283     }
284 }
285 
286 // Invoked by Merge thread - Notify RA thread about Merge completion
287 // for Block N and wake up
NotifyRAForMergeReady()288 void SnapshotHandler::NotifyRAForMergeReady() {
289     {
290         std::lock_guard<std::mutex> lock(lock_);
291         if (io_state_ != MERGE_IO_TRANSITION::IO_TERMINATED &&
292             io_state_ != MERGE_IO_TRANSITION::READ_AHEAD_FAILURE) {
293             io_state_ = MERGE_IO_TRANSITION::MERGE_READY;
294         }
295     }
296 
297     cv.notify_all();
298 }
299 
300 // The following transitions are mostly in the failure paths
MergeFailed()301 void SnapshotHandler::MergeFailed() {
302     {
303         std::lock_guard<std::mutex> lock(lock_);
304         io_state_ = MERGE_IO_TRANSITION::MERGE_FAILED;
305     }
306 
307     cv.notify_all();
308 }
309 
MergeCompleted()310 void SnapshotHandler::MergeCompleted() {
311     {
312         std::lock_guard<std::mutex> lock(lock_);
313         io_state_ = MERGE_IO_TRANSITION::MERGE_COMPLETE;
314     }
315 
316     cv.notify_all();
317 }
318 
319 // This is invoked by worker threads.
320 //
321 // Worker threads are terminated either by two scenarios:
322 //
323 // 1: If dm-user device is destroyed
324 // 2: We had an I/O failure when reading root partitions
325 //
326 // In case (1), this would be a graceful shutdown. In this case, merge
327 // thread and RA thread should have _already_ terminated by this point. We will be
328 // destroying the dm-user device only _after_ merge is completed.
329 //
330 // In case (2), if merge thread had started, then it will be
331 // continuing to merge; however, since we had an I/O failure and the
332 // I/O on root partitions are no longer served, we will terminate the
333 // merge.
334 //
335 // This functions is about handling case (2)
NotifyIOTerminated()336 void SnapshotHandler::NotifyIOTerminated() {
337     {
338         std::lock_guard<std::mutex> lock(lock_);
339         io_state_ = MERGE_IO_TRANSITION::IO_TERMINATED;
340     }
341 
342     cv.notify_all();
343 }
344 
IsIOTerminated()345 bool SnapshotHandler::IsIOTerminated() {
346     std::lock_guard<std::mutex> lock(lock_);
347     return (io_state_ == MERGE_IO_TRANSITION::IO_TERMINATED);
348 }
349 
350 // Invoked by RA thread
ReadAheadIOFailed()351 void SnapshotHandler::ReadAheadIOFailed() {
352     {
353         std::lock_guard<std::mutex> lock(lock_);
354         io_state_ = MERGE_IO_TRANSITION::READ_AHEAD_FAILURE;
355     }
356 
357     cv.notify_all();
358 }
359 
WaitForMergeComplete()360 void SnapshotHandler::WaitForMergeComplete() {
361     std::unique_lock<std::mutex> lock(lock_);
362     while (!(io_state_ == MERGE_IO_TRANSITION::MERGE_COMPLETE ||
363              io_state_ == MERGE_IO_TRANSITION::MERGE_FAILED ||
364              io_state_ == MERGE_IO_TRANSITION::IO_TERMINATED)) {
365         cv.wait(lock);
366     }
367 }
368 
GetMergeStatus()369 std::string SnapshotHandler::GetMergeStatus() {
370     bool merge_not_initiated = false;
371     bool merge_monitored = false;
372     bool merge_failed = false;
373 
374     {
375         std::lock_guard<std::mutex> lock(lock_);
376 
377         if (MergeMonitored()) {
378             merge_monitored = true;
379         }
380 
381         if (!MergeInitiated()) {
382             merge_not_initiated = true;
383         }
384 
385         if (io_state_ == MERGE_IO_TRANSITION::MERGE_FAILED) {
386             merge_failed = true;
387         }
388     }
389 
390     struct CowHeader* ch = reinterpret_cast<struct CowHeader*>(mapped_addr_);
391     bool merge_complete = (ch->num_merge_ops == reader_->get_num_total_data_ops());
392 
393     if (merge_not_initiated) {
394         // Merge was not initiated yet; however, we have merge completion
395         // recorded in the COW Header. This can happen if the device was
396         // rebooted during merge. During next reboot, libsnapshot will
397         // query the status and if the merge is completed, then snapshot-status
398         // file will be deleted
399         if (merge_complete) {
400             return "snapshot-merge-complete";
401         }
402 
403         // Merge monitor thread is tracking the merge but the merge thread
404         // is not started yet.
405         if (merge_monitored) {
406             return "snapshot-merge";
407         }
408 
409         // Return the state as "snapshot". If the device was rebooted during
410         // merge, we will return the status as "snapshot". This is ok, as
411         // libsnapshot will explicitly resume the merge. This is slightly
412         // different from kernel snapshot wherein once the snapshot was switched
413         // to merge target, during next boot, we immediately switch to merge
414         // target. We don't do that here because, during first stage init, we
415         // don't want to initiate the merge. The problem is that we have daemon
416         // transition between first and second stage init. If the merge was
417         // started, then we will have to quiesce the merge before switching
418         // the dm tables. Instead, we just wait until second stage daemon is up
419         // before resuming the merge.
420         return "snapshot";
421     }
422 
423     if (merge_failed) {
424         return "snapshot-merge-failed";
425     }
426 
427     // Merge complete
428     if (merge_complete) {
429         return "snapshot-merge-complete";
430     }
431 
432     // Merge is in-progress
433     return "snapshot-merge";
434 }
435 
436 //========== End of Read-ahead state transition functions ====================
437 
438 /*
439  * Root partitions are mounted off dm-user and the I/O's are served
440  * by snapuserd worker threads.
441  *
442  * When there is an I/O request to be served by worker threads, we check
443  * if the corresponding sector is "changed" due to OTA by doing a lookup.
444  * If the lookup succeeds then the sector has been changed and that can
445  * either fall into 4 COW operations viz: COPY, XOR, REPLACE and ZERO.
446  *
447  * For the case of REPLACE and ZERO ops, there is not much of a concern
448  * as there is no dependency between blocks. Hence all the I/O request
449  * mapped to these two COW operations will be served by reading the COW device.
450  *
451  * However, COPY and XOR ops are tricky. Since the merge operations are
452  * in-progress, we cannot just go and read from the source device. We need
453  * to be in sync with the state of the merge thread before serving the I/O.
454  *
455  * Given that we know merge thread processes a set of COW ops called as RA
456  * Blocks - These set of COW ops are fixed size wherein each Block comprises
457  * of 510 COW ops.
458  *
459  *  +--------------------------+
460  *  |op-1|op-2|op-3|....|op-510|
461  *  +--------------------------+
462  *
463  *  <------ Merge Group Block N ------>
464  *
465  * Thus, a Merge Group Block N, will fall into one of these states and will
466  * transition the states in the following order:
467  *
468  * 1: GROUP_MERGE_PENDING
469  * 2: GROUP_MERGE_RA_READY
470  * 2: GROUP_MERGE_IN_PROGRESS
471  * 3: GROUP_MERGE_COMPLETED
472  * 4: GROUP_MERGE_FAILED
473  *
474  * Let's say that we have the I/O request from dm-user whose sector gets mapped
475  * to a COPY operation with op-10 in the above "Merge Group Block N".
476  *
477  * 1: If the Group is in "GROUP_MERGE_PENDING" state:
478  *
479  *    Just read the data from source block based on COW op->source field. Note,
480  *    that we will take a ref count on "Block N". This ref count will prevent
481  *    merge thread to begin merging if there are any pending I/Os. Once the I/O
482  *    is completed, ref count on "Group N" is decremented. Merge thread will
483  *    resume merging "Group N" if there are no pending I/Os.
484  *
485  * 2: If the Group is in "GROUP_MERGE_IN_PROGRESS" or "GROUP_MERGE_RA_READY" state:
486  *
487  *    When the merge thread is ready to process a "Group", it will first move
488  *    the state to GROUP_MERGE_PENDING -> GROUP_MERGE_RA_READY. From this point
489  *    onwards, I/O will be served from Read-ahead buffer. However, merge thread
490  *    cannot start merging this "Group" immediately. If there were any in-flight
491  *    I/O requests, merge thread should wait and allow those I/O's to drain.
492  *    Once all the in-flight I/O's are completed, merge thread will move the
493  *    state from "GROUP_MERGE_RA_READY" -> "GROUP_MERGE_IN_PROGRESS". I/O will
494  *    be continued to serve from Read-ahead buffer during the entire duration
495  *    of the merge.
496  *
497  *    See SetMergeInProgress().
498  *
499  * 3: If the Group is in "GROUP_MERGE_COMPLETED" state:
500  *
501  *    This is straightforward. We just read the data directly from "Base"
502  *    device. We should not be reading the COW op->source field.
503  *
504  * 4: If the Block is in "GROUP_MERGE_FAILED" state:
505  *
506  *    Terminate the I/O with an I/O error as we don't know which "op" in the
507  *    "Group" failed.
508  *
509  *    Transition ensures that the I/O from root partitions are never made to
510  *    wait and are processed immediately. Thus the state transition for any
511  *    "Group" is:
512  *
513  *    GROUP_MERGE_PENDING
514  *          |
515  *          |
516  *          v
517  *    GROUP_MERGE_RA_READY
518  *          |
519  *          |
520  *          v
521  *    GROUP_MERGE_IN_PROGRESS
522  *          |
523  *          |----------------------------(on failure)
524  *          |                           |
525  *          v                           v
526  *    GROUP_MERGE_COMPLETED           GROUP_MERGE_FAILED
527  *
528  */
529 
530 // Invoked by Merge thread
SetMergeCompleted(size_t ra_index)531 void SnapshotHandler::SetMergeCompleted(size_t ra_index) {
532     MergeGroupState* blk_state = merge_blk_state_[ra_index].get();
533     {
534         std::lock_guard<std::mutex> lock(blk_state->m_lock);
535 
536         CHECK(blk_state->merge_state_ == MERGE_GROUP_STATE::GROUP_MERGE_IN_PROGRESS);
537         CHECK(blk_state->num_ios_in_progress == 0);
538 
539         // Merge is complete - All I/O henceforth should be read directly
540         // from base device
541         blk_state->merge_state_ = MERGE_GROUP_STATE::GROUP_MERGE_COMPLETED;
542     }
543 }
544 
545 // Invoked by Merge thread. This is called just before the beginning
546 // of merging a given Block of 510 ops. If there are any in-flight I/O's
547 // from dm-user then wait for them to complete.
SetMergeInProgress(size_t ra_index)548 void SnapshotHandler::SetMergeInProgress(size_t ra_index) {
549     MergeGroupState* blk_state = merge_blk_state_[ra_index].get();
550     {
551         std::unique_lock<std::mutex> lock(blk_state->m_lock);
552 
553         // We may have fallback from Async-merge to synchronous merging
554         // on the existing block. There is no need to reset as the
555         // merge is already in progress.
556         if (blk_state->merge_state_ == MERGE_GROUP_STATE::GROUP_MERGE_IN_PROGRESS) {
557             return;
558         }
559 
560         CHECK(blk_state->merge_state_ == MERGE_GROUP_STATE::GROUP_MERGE_PENDING);
561 
562         // First set the state to RA_READY so that in-flight I/O will drain
563         // and any new I/O will start reading from RA buffer
564         blk_state->merge_state_ = MERGE_GROUP_STATE::GROUP_MERGE_RA_READY;
565 
566         // Wait if there are any in-flight I/O's - we cannot merge at this point
567         while (!(blk_state->num_ios_in_progress == 0)) {
568             blk_state->m_cv.wait(lock);
569         }
570 
571         blk_state->merge_state_ = MERGE_GROUP_STATE::GROUP_MERGE_IN_PROGRESS;
572     }
573 }
574 
575 // Invoked by Merge thread on failure
SetMergeFailed(size_t ra_index)576 void SnapshotHandler::SetMergeFailed(size_t ra_index) {
577     MergeGroupState* blk_state = merge_blk_state_[ra_index].get();
578     {
579         std::unique_lock<std::mutex> lock(blk_state->m_lock);
580 
581         blk_state->merge_state_ = MERGE_GROUP_STATE::GROUP_MERGE_FAILED;
582     }
583 }
584 
585 // Invoked by worker threads when I/O is complete on a "MERGE_PENDING"
586 // Block. If there are no more in-flight I/Os, wake up merge thread
587 // to resume merging.
NotifyIOCompletion(uint64_t new_block)588 void SnapshotHandler::NotifyIOCompletion(uint64_t new_block) {
589     auto it = block_to_ra_index_.find(new_block);
590     CHECK(it != block_to_ra_index_.end()) << " invalid block: " << new_block;
591 
592     bool pending_ios = true;
593 
594     int ra_index = it->second;
595     MergeGroupState* blk_state = merge_blk_state_[ra_index].get();
596     {
597         std::unique_lock<std::mutex> lock(blk_state->m_lock);
598 
599         blk_state->num_ios_in_progress -= 1;
600         if (blk_state->num_ios_in_progress == 0) {
601             pending_ios = false;
602         }
603     }
604 
605     // Give a chance to merge-thread to resume merge
606     // as there are no pending I/O.
607     if (!pending_ios) {
608         blk_state->m_cv.notify_all();
609     }
610 }
611 
GetRABuffer(std::unique_lock<std::mutex> * lock,uint64_t block,void * buffer)612 bool SnapshotHandler::GetRABuffer(std::unique_lock<std::mutex>* lock, uint64_t block,
613                                   void* buffer) {
614     if (!lock->owns_lock()) {
615         SNAP_LOG(ERROR) << "GetRABuffer - Lock not held";
616         return false;
617     }
618     std::unordered_map<uint64_t, void*>::iterator it = read_ahead_buffer_map_.find(block);
619 
620     if (it == read_ahead_buffer_map_.end()) {
621         SNAP_LOG(ERROR) << "Block: " << block << " not found in RA buffer";
622         return false;
623     }
624 
625     memcpy(buffer, it->second, BLOCK_SZ);
626     return true;
627 }
628 
629 // Invoked by worker threads in the I/O path. This is called when a sector
630 // is mapped to a COPY/XOR COW op.
ProcessMergingBlock(uint64_t new_block,void * buffer)631 MERGE_GROUP_STATE SnapshotHandler::ProcessMergingBlock(uint64_t new_block, void* buffer) {
632     auto it = block_to_ra_index_.find(new_block);
633     if (it == block_to_ra_index_.end()) {
634         return MERGE_GROUP_STATE::GROUP_INVALID;
635     }
636 
637     int ra_index = it->second;
638     MergeGroupState* blk_state = merge_blk_state_[ra_index].get();
639     {
640         std::unique_lock<std::mutex> lock(blk_state->m_lock);
641 
642         MERGE_GROUP_STATE state = blk_state->merge_state_;
643         switch (state) {
644             case MERGE_GROUP_STATE::GROUP_MERGE_PENDING: {
645                 blk_state->num_ios_in_progress += 1;  // ref count
646                 [[fallthrough]];
647             }
648             case MERGE_GROUP_STATE::GROUP_MERGE_COMPLETED: {
649                 [[fallthrough]];
650             }
651             case MERGE_GROUP_STATE::GROUP_MERGE_FAILED: {
652                 return state;
653             }
654             // Fetch the data from RA buffer.
655             case MERGE_GROUP_STATE::GROUP_MERGE_RA_READY: {
656                 [[fallthrough]];
657             }
658             case MERGE_GROUP_STATE::GROUP_MERGE_IN_PROGRESS: {
659                 if (!GetRABuffer(&lock, new_block, buffer)) {
660                     return MERGE_GROUP_STATE::GROUP_INVALID;
661                 }
662                 return state;
663             }
664             default: {
665                 return MERGE_GROUP_STATE::GROUP_INVALID;
666             }
667         }
668     }
669 }
670 
671 }  // namespace snapshot
672 }  // namespace android
673