Merge "trusty: Add unique component names to each vm" into main
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt b/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
index a4663c8..50aaa33 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
@@ -19,15 +19,13 @@
 import android.os.FileUtils
 import android.system.ErrnoException
 import android.system.Os
+import android.system.OsConstants
 import android.util.Log
 import com.android.virtualization.terminal.MainActivity.Companion.TAG
 import java.io.BufferedReader
 import java.io.FileReader
 import java.io.IOException
 import java.io.RandomAccessFile
-import java.lang.IllegalArgumentException
-import java.lang.NumberFormatException
-import java.lang.RuntimeException
 import java.nio.file.Files
 import java.nio.file.Path
 import java.nio.file.StandardCopyOption
@@ -86,11 +84,18 @@
     }
 
     @Throws(IOException::class)
-    fun getSize(): Long {
+    fun getApparentSize(): Long {
         return Files.size(rootPartition)
     }
 
     @Throws(IOException::class)
+    fun getPhysicalSize(): Long {
+        val stat = RandomAccessFile(rootPartition.toFile(), "rw").use { raf -> Os.fstat(raf.fd) }
+        // The unit of st_blocks is 512 byte in Android.
+        return 512L * stat.st_blocks
+    }
+
+    @Throws(IOException::class)
     fun getSmallestSizePossible(): Long {
         runE2fsck(rootPartition)
         val p: String = rootPartition.toAbsolutePath().toString()
@@ -114,7 +119,7 @@
     @Throws(IOException::class)
     fun resize(desiredSize: Long): Long {
         val roundedUpDesiredSize = roundUp(desiredSize)
-        val curSize = getSize()
+        val curSize = getApparentSize()
 
         runE2fsck(rootPartition)
 
@@ -123,10 +128,58 @@
         }
 
         if (roundedUpDesiredSize > curSize) {
-            allocateSpace(rootPartition, roundedUpDesiredSize)
+            if (!allocateSpace(roundedUpDesiredSize)) {
+                return curSize
+            }
         }
         resizeFilesystem(rootPartition, roundedUpDesiredSize)
-        return getSize()
+        return getApparentSize()
+    }
+
+    @Throws(IOException::class)
+    private fun allocateSpace(sizeInBytes: Long): Boolean {
+        val curSizeInBytes = getApparentSize()
+        try {
+            RandomAccessFile(rootPartition.toFile(), "rw").use { raf ->
+                Os.posix_fallocate(raf.fd, 0, sizeInBytes)
+            }
+            Log.d(TAG, "Allocated space to: $sizeInBytes bytes")
+            return true
+        } catch (e: ErrnoException) {
+            Log.e(TAG, "Failed to allocate space", e)
+            if (e.errno == OsConstants.ENOSPC) {
+                Log.d(TAG, "Trying to truncate disk into the original size")
+                truncate(curSizeInBytes)
+                return false
+            } else {
+                throw IOException("Failed to allocate space", e)
+            }
+        }
+    }
+
+    @Throws(IOException::class)
+    fun shrinkToMinimumSize(): Long {
+        // Fix filesystem before resizing.
+        runE2fsck(rootPartition)
+
+        val p: String = rootPartition.toAbsolutePath().toString()
+        runCommand("/system/bin/resize2fs", "-M", p)
+        Log.d(TAG, "resize2fs -M completed: $rootPartition")
+
+        // resize2fs may result in an inconsistent filesystem state. Fix with e2fsck.
+        runE2fsck(rootPartition)
+        return getApparentSize()
+    }
+
+    @Throws(IOException::class)
+    fun truncate(size: Long) {
+        try {
+            RandomAccessFile(rootPartition.toFile(), "rw").use { raf -> Os.ftruncate(raf.fd, size) }
+            Log.d(TAG, "Truncated space to: $size bytes")
+        } catch (e: ErrnoException) {
+            Log.e(TAG, "Failed to truncate space", e)
+            throw IOException("Failed to truncate space", e)
+        }
     }
 
     companion object {
@@ -146,20 +199,6 @@
         }
 
         @Throws(IOException::class)
-        private fun allocateSpace(path: Path, sizeInBytes: Long) {
-            try {
-                val raf = RandomAccessFile(path.toFile(), "rw")
-                val fd = raf.fd
-                Os.posix_fallocate(fd, 0, sizeInBytes)
-                raf.close()
-                Log.d(TAG, "Allocated space to: $sizeInBytes bytes")
-            } catch (e: ErrnoException) {
-                Log.e(TAG, "Failed to allocate space", e)
-                throw IOException("Failed to allocate space", e)
-            }
-        }
-
-        @Throws(IOException::class)
         private fun runE2fsck(path: Path) {
             val p: String = path.toAbsolutePath().toString()
             runCommand("/system/bin/e2fsck", "-y", "-f", p)
@@ -199,7 +238,7 @@
             }
         }
 
-        private fun roundUp(bytes: Long): Long {
+        internal fun roundUp(bytes: Long): Long {
             // Round up every diskSizeStep MB
             return ceil((bytes.toDouble()) / RESIZE_STEP_BYTES).toLong() * RESIZE_STEP_BYTES
         }
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
index e4eaecb..52afef4 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
@@ -49,7 +49,8 @@
 import androidx.viewpager2.widget.ViewPager2
 import com.android.internal.annotations.VisibleForTesting
 import com.android.microdroid.test.common.DeviceProperties
-import com.android.system.virtualmachine.flags.Flags.terminalGuiSupport
+import com.android.system.virtualmachine.flags.Flags
+import com.android.virtualization.terminal.ErrorActivity.Companion.start
 import com.android.virtualization.terminal.VmLauncherService.VmLauncherServiceCallback
 import com.google.android.material.tabs.TabLayout
 import com.google.android.material.tabs.TabLayoutMediator
@@ -125,9 +126,9 @@
         }
 
         displayMenu?.also {
-            it.visibility = if (terminalGuiSupport()) View.VISIBLE else View.GONE
+            it.visibility = if (Flags.terminalGuiSupport()) View.VISIBLE else View.GONE
             it.setEnabled(false)
-            if (terminalGuiSupport()) {
+            if (Flags.terminalGuiSupport()) {
                 it.setOnClickListener {
                     val intent = Intent(this, DisplayActivity::class.java)
                     intent.flags =
@@ -368,7 +369,7 @@
                 )
                 .build()
 
-        val diskSize = intent.getLongExtra(EXTRA_DISK_SIZE, image.getSize())
+        val diskSize = intent.getLongExtra(EXTRA_DISK_SIZE, image.getApparentSize())
 
         val intent =
             VmLauncherService.getIntentForStart(
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsActivity.kt
index a4a0a84..1183b46 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsActivity.kt
@@ -19,6 +19,7 @@
 import androidx.appcompat.app.AppCompatActivity
 import androidx.recyclerview.widget.LinearLayoutManager
 import androidx.recyclerview.widget.RecyclerView
+import com.android.system.virtualmachine.flags.Flags
 import com.google.android.material.appbar.MaterialToolbar
 
 class SettingsActivity : AppCompatActivity() {
@@ -29,27 +30,34 @@
 
         val toolbar: MaterialToolbar = findViewById(R.id.settings_toolbar)
         setSupportActionBar(toolbar)
-        val settingsItems =
-            arrayOf(
+        var settingsItems = mutableListOf<SettingsItem>()
+        if (!Flags.terminalStorageBalloon()) {
+            settingsItems.add(
                 SettingsItem(
                     resources.getString(R.string.settings_disk_resize_title),
                     resources.getString(R.string.settings_disk_resize_sub_title),
                     R.drawable.baseline_storage_24,
                     SettingsItemEnum.DiskResize,
-                ),
-                SettingsItem(
-                    resources.getString(R.string.settings_port_forwarding_title),
-                    resources.getString(R.string.settings_port_forwarding_sub_title),
-                    R.drawable.baseline_call_missed_outgoing_24,
-                    SettingsItemEnum.PortForwarding,
-                ),
-                SettingsItem(
-                    resources.getString(R.string.settings_recovery_title),
-                    resources.getString(R.string.settings_recovery_sub_title),
-                    R.drawable.baseline_settings_backup_restore_24,
-                    SettingsItemEnum.Recovery,
-                ),
+                )
             )
+        }
+        settingsItems.add(
+            SettingsItem(
+                resources.getString(R.string.settings_port_forwarding_title),
+                resources.getString(R.string.settings_port_forwarding_sub_title),
+                R.drawable.baseline_call_missed_outgoing_24,
+                SettingsItemEnum.PortForwarding,
+            )
+        )
+        settingsItems.add(
+            SettingsItem(
+                resources.getString(R.string.settings_recovery_title),
+                resources.getString(R.string.settings_recovery_sub_title),
+                R.drawable.baseline_settings_backup_restore_24,
+                SettingsItemEnum.Recovery,
+            )
+        )
+
         val settingsListItemAdapter = SettingsItemAdapter(settingsItems)
 
         val recyclerView: RecyclerView = findViewById(R.id.settings_list_recycler_view)
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt
index af1ae95..da07b19 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsDiskResizeActivity.kt
@@ -33,6 +33,7 @@
 import androidx.core.view.isVisible
 import com.android.virtualization.terminal.VmLauncherService.VmLauncherServiceCallback
 import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.google.android.material.snackbar.Snackbar
 import java.util.Locale
 import java.util.regex.Pattern
 
@@ -46,6 +47,7 @@
     private lateinit var cancelButton: View
     private lateinit var resizeButton: View
     private lateinit var diskSizeText: TextView
+    private lateinit var diskMaxSizeText: TextView
     private lateinit var diskSizeSlider: SeekBar
 
     private fun bytesToMb(bytes: Long): Long {
@@ -56,6 +58,13 @@
         return bytes shl 20
     }
 
+    private fun getAvailableSizeMb(): Long {
+        val usableSpaceMb =
+            bytesToMb(Environment.getDataDirectory().getUsableSpace()) and
+                (diskSizeStepMb - 1).inv()
+        return diskSizeMb + usableSpaceMb
+    }
+
     private fun mbToProgress(bytes: Long): Int {
         return (bytes / diskSizeStepMb).toInt()
     }
@@ -71,15 +80,12 @@
         diskSizeStepMb = 1L shl resources.getInteger(R.integer.disk_size_round_up_step_size_in_mb)
 
         val image = InstalledImage.getDefault(this)
-        diskSizeMb = bytesToMb(image.getSize())
+        diskSizeMb = bytesToMb(image.getApparentSize())
         val minDiskSizeMb = bytesToMb(image.getSmallestSizePossible()).coerceAtMost(diskSizeMb)
-        val usableSpaceMb =
-            bytesToMb(Environment.getDataDirectory().getUsableSpace()) and
-                (diskSizeStepMb - 1).inv()
-        val maxDiskSizeMb = defaultMaxDiskSizeMb.coerceAtMost(diskSizeMb + usableSpaceMb)
+        val maxDiskSizeMb = defaultMaxDiskSizeMb.coerceAtMost(getAvailableSizeMb())
 
         diskSizeText = findViewById<TextView>(R.id.settings_disk_resize_resize_gb_assigned)!!
-        val diskMaxSizeText = findViewById<TextView>(R.id.settings_disk_resize_resize_gb_max)
+        diskMaxSizeText = findViewById<TextView>(R.id.settings_disk_resize_resize_gb_max)
         diskMaxSizeText.text =
             getString(
                 R.string.settings_disk_resize_resize_gb_max_format,
@@ -138,7 +144,22 @@
     }
 
     private fun resize() {
-        diskSizeMb = progressToMb(diskSizeSlider.progress)
+        val desiredDiskSizeMb = progressToMb(diskSizeSlider.progress)
+        val availableSizeMb = getAvailableSizeMb()
+        if (availableSizeMb < desiredDiskSizeMb) {
+            Snackbar.make(
+                    findViewById(android.R.id.content),
+                    R.string.settings_disk_resize_not_enough_space_message,
+                    Snackbar.LENGTH_SHORT,
+                )
+                .show()
+            diskSizeSlider.max = mbToProgress(availableSizeMb)
+            updateMaxSizeText(availableSizeMb)
+            cancel()
+            return
+        }
+
+        diskSizeMb = desiredDiskSizeMb
         buttons.isVisible = false
 
         // Note: we first stop the VM, and wait for it to fully stop. Then we (re) start the Main
@@ -186,6 +207,14 @@
             )
     }
 
+    fun updateMaxSizeText(sizeMb: Long) {
+        diskMaxSizeText.text =
+            getString(
+                R.string.settings_disk_resize_resize_gb_max_format,
+                localizedFileSize(sizeMb, /* isShort= */ true),
+            )
+    }
+
     fun localizedFileSize(sizeMb: Long, isShort: Boolean): String {
         val sizeGb = sizeMb / (1 shl 10).toFloat()
         val measure = Measure(sizeGb, MeasureUnit.GIGABYTE)
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt
index 132d749..aa0c3f5 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsItemAdapter.kt
@@ -24,7 +24,7 @@
 import androidx.recyclerview.widget.RecyclerView
 import com.google.android.material.card.MaterialCardView
 
-class SettingsItemAdapter(private val dataSet: Array<SettingsItem>) :
+class SettingsItemAdapter(private val dataSet: List<SettingsItem>) :
     RecyclerView.Adapter<SettingsItemAdapter.ViewHolder>() {
 
     class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt
index 7562779..2653ba9 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SplitInitializer.kt
@@ -15,16 +15,96 @@
  */
 package com.android.virtualization.terminal
 
+import android.content.ComponentName
 import android.content.Context
+import android.content.Intent
 import androidx.startup.Initializer
+import androidx.window.embedding.ActivityFilter
+import androidx.window.embedding.EmbeddingAspectRatio
 import androidx.window.embedding.RuleController
+import androidx.window.embedding.SplitAttributes
+import androidx.window.embedding.SplitPairFilter
+import androidx.window.embedding.SplitPairRule
+import androidx.window.embedding.SplitPlaceholderRule
+import androidx.window.embedding.SplitRule
+import com.android.system.virtualmachine.flags.Flags
 
 class SplitInitializer : Initializer<RuleController> {
 
     override fun create(context: Context): RuleController {
-        return RuleController.getInstance(context).apply {
-            setRules(RuleController.parseRules(context, R.xml.main_split_config))
+        val filters =
+            mutableSetOf(
+                SplitPairFilter(
+                    ComponentName(context, SettingsActivity::class.java),
+                    ComponentName(context, SettingsPortForwardingActivity::class.java),
+                    null,
+                )
+            )
+
+        if (Flags.terminalStorageBalloon()) {
+            filters.add(
+                SplitPairFilter(
+                    ComponentName(context, SettingsActivity::class.java),
+                    ComponentName(context, SettingsDiskResizeActivity::class.java),
+                    null,
+                )
+            )
         }
+
+        filters.add(
+            SplitPairFilter(
+                ComponentName(context, SettingsActivity::class.java),
+                ComponentName(context, SettingsRecoveryActivity::class.java),
+                null,
+            )
+        )
+        val splitPairRules =
+            SplitPairRule.Builder(filters)
+                .setClearTop(true)
+                .setFinishPrimaryWithSecondary(SplitRule.FinishBehavior.ADJACENT)
+                .setFinishSecondaryWithPrimary(SplitRule.FinishBehavior.ALWAYS)
+                .setDefaultSplitAttributes(
+                    SplitAttributes.Builder()
+                        .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+                        .setSplitType(
+                            SplitAttributes.SplitType.ratio(
+                                context.resources.getFloat(R.dimen.activity_split_ratio)
+                            )
+                        )
+                        .build()
+                )
+                .setMaxAspectRatioInPortrait(EmbeddingAspectRatio.ALWAYS_ALLOW)
+                .setMinWidthDp(context.resources.getInteger(R.integer.split_min_width))
+                .build()
+
+        val placeholderRule =
+            SplitPlaceholderRule.Builder(
+                    setOf(
+                        ActivityFilter(ComponentName(context, SettingsActivity::class.java), null)
+                    ),
+                    Intent(context, SettingsDiskResizeActivity::class.java),
+                )
+                .setFinishPrimaryWithPlaceholder(SplitRule.FinishBehavior.ADJACENT)
+                .setDefaultSplitAttributes(
+                    SplitAttributes.Builder()
+                        .setLayoutDirection(SplitAttributes.LayoutDirection.LOCALE)
+                        .setSplitType(
+                            SplitAttributes.SplitType.ratio(
+                                context.resources.getFloat(R.dimen.activity_split_ratio)
+                            )
+                        )
+                        .build()
+                )
+                .setMaxAspectRatioInPortrait(EmbeddingAspectRatio.ALWAYS_ALLOW)
+                .setMinWidthDp(context.resources.getInteger(R.integer.split_min_width))
+                .setSticky(false)
+                .build()
+
+        val ruleController = RuleController.getInstance(context)
+        ruleController.addRule(splitPairRules)
+        ruleController.addRule(placeholderRule)
+
+        return ruleController
     }
 
     override fun dependencies(): List<Class<out Initializer<*>>> {
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt b/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
index 067d540..84168e5 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
@@ -31,6 +31,7 @@
 import android.os.Parcel
 import android.os.Parcelable
 import android.os.ResultReceiver
+import android.os.StatFs
 import android.os.SystemProperties
 import android.system.virtualmachine.VirtualMachine
 import android.system.virtualmachine.VirtualMachineCustomImageConfig
@@ -40,6 +41,7 @@
 import android.widget.Toast
 import androidx.annotation.WorkerThread
 import com.android.system.virtualmachine.flags.Flags
+import com.android.virtualization.terminal.InstalledImage.Companion.roundUp
 import com.android.virtualization.terminal.MainActivity.Companion.PREFIX
 import com.android.virtualization.terminal.MainActivity.Companion.TAG
 import io.grpc.Grpc
@@ -119,7 +121,7 @@
                 // Note: this doesn't always do the resizing. If the current image size is the same
                 // as the requested size which is rounded up to the page alignment, resizing is not
                 // done.
-                val diskSize = intent.getLongExtra(EXTRA_DISK_SIZE, image.getSize())
+                val diskSize = intent.getLongExtra(EXTRA_DISK_SIZE, image.getApparentSize())
 
                 mainWorkerThread.submit({
                     doStart(notification, displayInfo, diskSize, resultReceiver)
@@ -139,6 +141,64 @@
         return START_NOT_STICKY
     }
 
+    private fun calculateSparseDiskSize(): Long {
+        // With storage ballooning enabled, we create a sparse file with 95% of the total size.
+        val statFs = StatFs(filesDir.absolutePath)
+        val hostSize = statFs.totalBytes
+        return roundUp(hostSize * GUEST_SPARSE_DISK_SIZE_PERCENTAGE / 100)
+    }
+
+    private fun truncateDiskIfNecessary(image: InstalledImage) {
+        val curSize = image.getApparentSize()
+        val physicalSize = image.getPhysicalSize()
+
+        val expectedSize = calculateSparseDiskSize()
+        Log.d(
+            TAG,
+            "rootfs apparent size=$curSize, physical size=$physicalSize, expectedSize=$expectedSize",
+        )
+
+        if (curSize != expectedSize) {
+            try {
+                image.truncate(expectedSize)
+            } catch (e: IOException) {
+                throw RuntimeException("Failed to truncate a disk", e)
+            }
+        }
+    }
+
+    // Convert the rootfs disk to a non-sparse file.
+    private fun convertToNonSparseDiskIfNecessary(image: InstalledImage) {
+        try {
+            val curApparentSize = image.getApparentSize()
+            val curPhysicalSize = image.getPhysicalSize()
+            Log.d(TAG, "Current disk size: apparent=$curApparentSize, physical=$curPhysicalSize")
+
+            // If storage ballooning was enabled via Flags.terminalStorageBalloon() before but it's
+            // now disabled, the disk is still a sparse file whose apparent size is too large.
+            // We need to shrink it to the minimum size.
+            //
+            // The disk file is considered sparse if its apparent disk size matches the expected
+            // sparse disk size.
+            // In addition, we consider it sparse if the physical size is clearly smaller than its
+            // apparent size. This additional condition is a fallback for cases
+            // where the logic of calculating the expected sparse disk size since the disk is
+            // created.
+            if (
+                curApparentSize == calculateSparseDiskSize() ||
+                    curPhysicalSize <
+                        curApparentSize * EXPECTED_PHYSICAL_SIZE_PERCENTAGE_FOR_NON_SPARSE / 100
+            ) {
+                Log.d(TAG, "A sparse disk is detected. Shrink it to the minimum size.")
+                val newSize = image.shrinkToMinimumSize()
+                Log.d(TAG, "Shrink the disk image: $curApparentSize -> $newSize")
+            }
+        } catch (e: IOException) {
+            throw RuntimeException("Failed to shrink rootfs disk", e)
+            return
+        }
+    }
+
     @WorkerThread
     private fun doStart(
         notification: Notification,
@@ -150,7 +210,19 @@
         val json = ConfigJson.from(this, image.configPath)
         val configBuilder = json.toConfigBuilder(this)
         val customImageConfigBuilder = json.toCustomImageConfigBuilder(this)
-        image.resize(diskSize)
+
+        if (Flags.terminalStorageBalloon()) {
+            // When storage ballooning flag is enabled, convert rootfs disk into a sparse file.
+            truncateDiskIfNecessary(image)
+        } else {
+            // Convert rootfs disk into a sparse file if storage ballooning flag had been enabled
+            // and then disabled.
+            convertToNonSparseDiskIfNecessary(image)
+
+            // Note: this doesn't always do the resizing. If the current image size is the same as
+            // the requested size which is rounded up to the page alignment, resizing is not done.
+            image.resize(diskSize)
+        }
 
         customImageConfigBuilder.setAudioConfig(
             AudioConfig.Builder().setUseSpeaker(true).setUseMicrophone(true).build()
@@ -391,15 +463,32 @@
 
     @WorkerThread
     private fun doShutdown(resultReceiver: ResultReceiver?) {
-        stopForeground(STOP_FOREGROUND_REMOVE)
+        runner?.exitStatus?.thenAcceptAsync { success: Boolean ->
+            resultReceiver?.send(if (success) RESULT_STOP else RESULT_ERROR, null)
+            stopSelf()
+        }
         if (debianService != null && debianService!!.shutdownDebian()) {
             // During shutdown, change the notification content to indicate that it's closing
             val notification = createNotificationForTerminalClose()
             getSystemService<NotificationManager?>(NotificationManager::class.java)
                 .notify(this.hashCode(), notification)
-            runner?.exitStatus?.thenAcceptAsync { success: Boolean ->
-                resultReceiver?.send(if (success) RESULT_STOP else RESULT_ERROR, null)
-                stopSelf()
+
+            runner?.also { r ->
+                // For the case that shutdown from the guest agent fails.
+                // When timeout is set, the original CompletableFuture's every `thenAcceptAsync` is
+                // canceled as well. So add empty `thenAcceptAsync` to avoid interference.
+                r.exitStatus
+                    .thenAcceptAsync {}
+                    .orTimeout(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)
+                    .exceptionally {
+                        Log.e(
+                            TAG,
+                            "Stop the service directly because the VM instance isn't stopped with " +
+                                "graceful shutdown",
+                        )
+                        r.vm.stop()
+                        null
+                    }
             }
             runner = null
         } else {
@@ -426,6 +515,7 @@
         stopDebianServer()
         bgThreads.shutdownNow()
         mainWorkerThread.shutdown()
+        stopForeground(STOP_FOREGROUND_REMOVE)
         super.onDestroy()
     }
 
@@ -445,6 +535,11 @@
         private const val KEY_TERMINAL_IPADDRESS = "address"
         private const val KEY_TERMINAL_PORT = "port"
 
+        private const val SHUTDOWN_TIMEOUT_SECONDS = 3L
+
+        private const val GUEST_SPARSE_DISK_SIZE_PERCENTAGE = 95
+        private const val EXPECTED_PHYSICAL_SIZE_PERCENTAGE_FOR_NON_SPARSE = 90
+
         private val VM_BOOT_TIMEOUT_SECONDS: Int =
             {
                 val deviceName = SystemProperties.get("ro.product.vendor.device", "")
diff --git a/android/TerminalApp/res/values/config.xml b/android/TerminalApp/res/values/config.xml
index 7f0b5e6..a2c9183 100644
--- a/android/TerminalApp/res/values/config.xml
+++ b/android/TerminalApp/res/values/config.xml
@@ -16,4 +16,5 @@
 
 <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
     <bool name="terminal_portrait_only">true</bool>
+    <item name="activity_split_ratio" format="float" type="dimen">0.3</item>
 </resources>
diff --git a/android/TerminalApp/res/values/dimens.xml b/android/TerminalApp/res/values/dimens.xml
deleted file mode 100644
index e00ef7c..0000000
--- a/android/TerminalApp/res/values/dimens.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--  Copyright 2024 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
- -->
-
-<resources>
-    <dimen name="activity_split_ratio">0.3</dimen>
-</resources>
\ No newline at end of file
diff --git a/android/TerminalApp/res/values/strings.xml b/android/TerminalApp/res/values/strings.xml
index a6d461e..273032e 100644
--- a/android/TerminalApp/res/values/strings.xml
+++ b/android/TerminalApp/res/values/strings.xml
@@ -75,6 +75,8 @@
     <string name="settings_disk_resize_resize_gb_assigned_format"><xliff:g id="assigned_size" example="10GB">\u200E%1$s\u200E</xliff:g> assigned</string>
     <!-- Settings menu option description format of the maximum resizable disk size. [CHAR LIMIT=none] -->
     <string name="settings_disk_resize_resize_gb_max_format"><xliff:g id="max_size" example="256GB">\u200E%1$s\u200E</xliff:g> max</string>
+    <!-- Snackbar message for showing not enough space error. [CHAR LIMIT=none] -->
+    <string name="settings_disk_resize_not_enough_space_message">Not enough space on the device to resize disk</string>
     <!-- Settings menu button to cancel disk resize. [CHAR LIMIT=16] -->
     <string name="settings_disk_resize_resize_cancel">Cancel</string>
     <!-- Settings menu button to apply change Terminal app. This will launch a confirmation dialog [CHAR LIMIT=16] -->
diff --git a/android/TerminalApp/res/xml/main_split_config.xml b/android/TerminalApp/res/xml/main_split_config.xml
deleted file mode 100644
index bd0271b..0000000
--- a/android/TerminalApp/res/xml/main_split_config.xml
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--  Copyright 2024 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
- -->
-
-<resources xmlns:window="http://schemas.android.com/apk/res-auto">
-
-    <!-- Define a split for the named activities. -->
-    <SplitPairRule
-        window:clearTop="true"
-        window:finishPrimaryWithSecondary="adjacent"
-        window:finishSecondaryWithPrimary="always"
-        window:splitLayoutDirection="locale"
-        window:splitMaxAspectRatioInPortrait="alwaysAllow"
-        window:splitMinWidthDp="@integer/split_min_width"
-        window:splitRatio="@dimen/activity_split_ratio">
-        <SplitPairFilter
-            window:primaryActivityName="com.android.virtualization.terminal.SettingsActivity"
-            window:secondaryActivityName="com.android.virtualization.terminal.SettingsDiskResizeActivity" />
-        <SplitPairFilter
-            window:primaryActivityName="com.android.virtualization.terminal.SettingsActivity"
-            window:secondaryActivityName="com.android.virtualization.terminal.SettingsPortForwardingActivity" />
-        <SplitPairFilter
-            window:primaryActivityName="com.android.virtualization.terminal.SettingsActivity"
-            window:secondaryActivityName="com.android.virtualization.terminal.SettingsRecoveryActivity" />
-    </SplitPairRule>
-
-    <SplitPlaceholderRule
-        window:placeholderActivityName="com.android.virtualization.terminal.SettingsDiskResizeActivity"
-        window:finishPrimaryWithPlaceholder="adjacent"
-        window:splitLayoutDirection="locale"
-        window:splitMaxAspectRatioInPortrait="alwaysAllow"
-        window:splitMinWidthDp="@integer/split_min_width"
-        window:splitRatio="@dimen/activity_split_ratio"
-        window:stickyPlaceholder="false">
-        <ActivityFilter
-            window:activityName="com.android.virtualization.terminal.SettingsActivity"/>
-    </SplitPlaceholderRule>
-</resources>
\ No newline at end of file
diff --git a/android/virtmgr/src/aidl.rs b/android/virtmgr/src/aidl.rs
index 1e756eb..190acc7 100644
--- a/android/virtmgr/src/aidl.rs
+++ b/android/virtmgr/src/aidl.rs
@@ -641,6 +641,24 @@
 
         let calling_partition = find_partition(CALLING_EXE_PATH.as_deref())?;
 
+        let instance_id = extract_instance_id(config);
+        // Require vendor instance IDs to start with a specific prefix so that they don't conflict
+        // with system instance IDs.
+        //
+        // We should also make sure that non-vendor VMs do not use the vendor prefix, but there are
+        // already system VMs in the wild that may have randomly generated IDs with the prefix, so,
+        // for now, we only check in one direction.
+        const INSTANCE_ID_VENDOR_PREFIX: &[u8] = &[0xFF, 0xFF, 0xFF, 0xFF];
+        if matches!(calling_partition, CallingPartition::Vendor | CallingPartition::Odm)
+            && !instance_id.starts_with(INSTANCE_ID_VENDOR_PREFIX)
+        {
+            return Err(anyhow!(
+                "vendor initiated VMs must have instance IDs starting with 0xFFFFFFFF, got {}",
+                hex::encode(instance_id)
+            ))
+            .or_service_specific_exception(-1);
+        }
+
         check_config_features(config)?;
 
         if cfg!(early) {
@@ -668,7 +686,6 @@
             check_gdb_allowed(config)?;
         }
 
-        let instance_id = extract_instance_id(config);
         let mut device_tree_overlays = vec![];
         if let Some(dt_overlay) =
             maybe_create_reference_dt_overlay(config, &instance_id, &temporary_directory)?
@@ -798,9 +815,8 @@
                 .or_service_specific_exception(-1)?;
         }
 
-        // Check if files for payloads and bases are NOT coming from /vendor and /odm, as they may
-        // have unstable interfaces.
-        // TODO(b/316431494): remove once Treble interfaces are stabilized.
+        // Check if files for payloads and bases are on the same side of the Treble boundary as the
+        // calling process, as they may have unstable interfaces.
         check_partitions_for_files(config, calling_partition).or_service_specific_exception(-1)?;
 
         let zero_filler_path = temporary_directory.join("zero.img");
diff --git a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl
index 5193e21..7db5135 100644
--- a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl
+++ b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineAppConfig.aidl
@@ -23,7 +23,11 @@
     /** Name of VM */
     String name;
 
-    /** Id of the VM instance */
+    /**
+     * Id of the VM instance
+     *
+     * See AVirtualMachineRawConfig_setInstanceId for details.
+     */
     byte[64] instanceId;
 
     /** Main APK */
diff --git a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl
index c5fe982..1e4fe03 100644
--- a/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl
+++ b/android/virtualizationservice/aidl/android/system/virtualizationservice/VirtualMachineRawConfig.aidl
@@ -31,7 +31,11 @@
     /** Name of VM */
     String name;
 
-    /** Id of the VM instance */
+    /**
+     * Id of the VM instance
+     *
+     * See AVirtualMachineRawConfig_setInstanceId for details.
+     */
     byte[64] instanceId;
 
     /** The kernel image, if any. */
diff --git a/android/virtualizationservice/src/aidl.rs b/android/virtualizationservice/src/aidl.rs
index 1646117..e26cd4f 100644
--- a/android/virtualizationservice/src/aidl.rs
+++ b/android/virtualizationservice/src/aidl.rs
@@ -489,6 +489,9 @@
         id.try_fill(&mut rand::thread_rng())
             .context("Failed to allocate instance_id")
             .or_service_specific_exception(-1)?;
+        // Randomly allocated IDs always start with all 7s to avoid colliding with statically
+        // assigned IDs.
+        id[..4].fill(0x77);
         let uid = get_calling_uid();
         info!("Allocated a VM's instance_id: {:?}..., for uid: {:?}", &hex::encode(id)[..8], uid);
         self.try_updating_sk_state(&id);
diff --git a/build/apex/Android.bp b/build/apex/Android.bp
index 8934de0..f0eba7f 100644
--- a/build/apex/Android.bp
+++ b/build/apex/Android.bp
@@ -56,6 +56,7 @@
         "libvirtualizationservice_jni",
         "libvirtualmachine_jni",
     ],
+    native_shared_libs: ["libavf"],
     // TODO(b/295593640) Unfortunately these are added to the apex even though they are unused.
     // Once the build system is fixed, remove this.
     unwanted_transitive_deps: [
@@ -108,7 +109,6 @@
                 "rialto_bin",
                 "android_bootloader_crosvm_aarch64",
             ],
-            native_shared_libs: ["libavf"],
         },
         x86_64: {
             binaries: [
@@ -129,7 +129,6 @@
             prebuilts: [
                 "android_bootloader_crosvm_x86_64",
             ],
-            native_shared_libs: ["libavf"],
         },
     },
     binaries: [
diff --git a/guest/pvmfw/README.md b/guest/pvmfw/README.md
index 652ca90..08b0d5c 100644
--- a/guest/pvmfw/README.md
+++ b/guest/pvmfw/README.md
@@ -1,19 +1,30 @@
 # Protected Virtual Machine Firmware
 
+## Protected VM (_"pVM"_)
+
 In the context of the [Android Virtualization Framework][AVF], a hypervisor
 (_e.g._ [pKVM]) enforces full memory isolation between its virtual machines
-(VMs) and the host.  As a result, the host is only allowed to access memory that
-has been explicitly shared back by a VM. Such _protected VMs_ (“pVMs”) are
-therefore able to manipulate secrets without being at risk of an attacker
-stealing them by compromising the Android host.
+(VMs) and the host. As a result, such VMs are given strong guarantees regarding
+their confidentiality and integrity.
 
-As pVMs are started dynamically by a _virtual machine manager_ (“VMM”) running
-as a host process and as pVMs must not trust the host (see [_Why
-AVF?_][why-avf]), the virtual machine it configures can't be trusted either.
-Furthermore, even though the isolation mentioned above allows pVMs to protect
-their secrets from the host, it does not help with provisioning them during
-boot. In particular, the threat model would prohibit the host from ever having
-access to those secrets, preventing the VMM from passing them to the pVM.
+A _protected VMs_ (“pVMs”) is a VM running in the non-secure or realm world,
+started dynamically by a _virtual machine manager_ (“VMM”) running as a process
+of the untrusted Android host (see [_Why AVF?_][why-avf]) and which is isolated
+from the host OS so that access to its memory is restricted, even in the event
+of a compromised Android host. pVMs support rich environments, including
+Linux-based distributions.
+
+The pVM concept is not Google-exclusive. Partner-defined VMs (SoC/OEM) meeting
+isolation/memory access restrictions are also pVMs.
+
+## Protected VM Root-of-Trust: pvmfw
+
+As pVMs are managed by a VMM running on the untrusted host, the virtual machine
+it configures can't be trusted either. Furthermore, even though the isolation
+mentioned above allows pVMs to protect their secrets from the host, it does not
+help with provisioning them during boot. In particular, the threat model would
+prohibit the host from ever having access to those secrets, preventing the VMM
+from passing them to the pVM.
 
 To address these concerns the hypervisor securely loads the pVM firmware
 (“pvmfw”) in the pVM from a protected memory region (this prevents the host or
@@ -147,6 +158,10 @@
 |  offset = (FOURTH - HEAD)     |
 |  size = (FOURTH_END - FOURTH) |
 +-------------------------------+
+|           [Entry 4]           | <-- Entry 4 is present since version 1.3
+|  offset = (FIFTH - HEAD)      |
+|  size = (FIFTH_END - FIFTH)   |
++-------------------------------+
 |              ...              |
 +-------------------------------+
 |           [Entry n]           |
@@ -168,7 +183,11 @@
 | {Fourth blob: VM reference DT}|
 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ <-- FOURTH_END
 | (Padding to 8-byte alignment) |
-+===============================+
++===============================+ <-- FIFTH
+| {Fifth blob: Reserved Memory} |
++~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ <-- FIFTH_END
+| (Padding to 8-byte alignment) |
++===============================+ <-- FIFTH
 |              ...              |
 +===============================+ <-- TAIL
 ```
@@ -238,6 +257,31 @@
 [secretkeeper_key]: https://android.googlesource.com/platform/system/secretkeeper/+/refs/heads/main/README.md#secretkeeper-public-key
 [vendor_hashtree_digest]: ../../build/microdroid/README.md#verification-of-vendor-image
 
+#### Version 1.3 {#pvmfw-data-v1-3}
+
+In version 1.3, a fifth blob is added.
+
+- entry 4, if present, contains potentially confidential data to be passed to
+  specific guests identified from their VM name. If the data is confidential,
+  this feature should only be used with guests using a fixed rollback
+  protection mechanism to prevent rollback attacks from a malicious host. Data
+  is passed as a reserved-memory region through the device tree with the
+  provided properties at an address which is implementation defined. Multiple
+  regions may be passed to the same guest. The format is as follows.
+
+  ```rust
+  #[repr(C)]
+  struct ReservedMemConfigEntry<const N: usize> {
+    /// The number of headers contained in this blob.
+    count: u32,
+    /// The [reserved memory headers](src/reserved_mem.rs) describing the passed data.
+    headers: [RMemHeader; N]
+    /// The actual data being passed. The reserved memory headers point to
+    /// offsets within this array.
+    data: [u8],
+  }
+  ```
+
 #### Virtual Platform DICE Chain Handover
 
 The format of the DICE chain entry mentioned above, compatible with the
diff --git a/guest/pvmfw/src/arch/aarch64/exceptions.rs b/guest/pvmfw/src/arch/aarch64/exceptions.rs
index 4c867fb..c8c0156 100644
--- a/guest/pvmfw/src/arch/aarch64/exceptions.rs
+++ b/guest/pvmfw/src/arch/aarch64/exceptions.rs
@@ -18,9 +18,7 @@
     arch::aarch64::exceptions::{
         handle_permission_fault, handle_translation_fault, ArmException, Esr, HandleExceptionError,
     },
-    eprintln, logger,
-    power::reboot,
-    read_sysreg,
+    logger, read_sysreg,
 };
 
 fn handle_exception(exception: &ArmException) -> Result<(), HandleExceptionError> {
@@ -41,55 +39,44 @@
 
     let exception = ArmException::from_el1_regs();
     if let Err(e) = handle_exception(&exception) {
-        exception.print("sync_exception_current", e, elr);
-        reboot()
+        exception.print_and_reboot("sync_exception_current", e, elr);
     }
 }
 
 #[no_mangle]
 extern "C" fn irq_current(_elr: u64, _spsr: u64) {
-    eprintln!("irq_current");
-    reboot();
+    panic!("irq_current");
 }
 
 #[no_mangle]
 extern "C" fn fiq_current(_elr: u64, _spsr: u64) {
-    eprintln!("fiq_current");
-    reboot();
+    panic!("fiq_current");
 }
 
 #[no_mangle]
 extern "C" fn serr_current(_elr: u64, _spsr: u64) {
     let esr = read_sysreg!("esr_el1");
-    eprintln!("serr_current");
-    eprintln!("esr={esr:#08x}");
-    reboot();
+    panic!("serr_current, esr={esr:#08x}");
 }
 
 #[no_mangle]
 extern "C" fn sync_lower(_elr: u64, _spsr: u64) {
     let esr = read_sysreg!("esr_el1");
-    eprintln!("sync_lower");
-    eprintln!("esr={esr:#08x}");
-    reboot();
+    panic!("sync_lower, esr={esr:#08x}");
 }
 
 #[no_mangle]
 extern "C" fn irq_lower(_elr: u64, _spsr: u64) {
-    eprintln!("irq_lower");
-    reboot();
+    panic!("irq_lower");
 }
 
 #[no_mangle]
 extern "C" fn fiq_lower(_elr: u64, _spsr: u64) {
-    eprintln!("fiq_lower");
-    reboot();
+    panic!("fiq_lower");
 }
 
 #[no_mangle]
 extern "C" fn serr_lower(_elr: u64, _spsr: u64) {
     let esr = read_sysreg!("esr_el1");
-    eprintln!("serr_lower");
-    eprintln!("esr={esr:#08x}");
-    reboot();
+    panic!("serr_lower, esr={esr:#08x}");
 }
diff --git a/guest/pvmfw/src/bcc.rs b/guest/pvmfw/src/bcc.rs
index 9260d7f..7ce50e9 100644
--- a/guest/pvmfw/src/bcc.rs
+++ b/guest/pvmfw/src/bcc.rs
@@ -97,8 +97,6 @@
 }
 
 impl Bcc {
-    /// Returns whether any node in the received DICE chain is marked as debug (and hence is not
-    /// secure).
     pub fn new(received_bcc: Option<&[u8]>) -> Result<Bcc> {
         let received_bcc = received_bcc.unwrap_or(&[]);
         if received_bcc.is_empty() {
@@ -132,6 +130,8 @@
         Ok(Self { is_debug_mode, leaf_subject_pubkey })
     }
 
+    /// Returns whether any node in the received DICE chain is marked as debug (and hence is not
+    /// secure).
     pub fn is_debug_mode(&self) -> bool {
         self.is_debug_mode
     }
diff --git a/guest/pvmfw/src/entry.rs b/guest/pvmfw/src/entry.rs
index 8ada6a1..cde4cfe 100644
--- a/guest/pvmfw/src/entry.rs
+++ b/guest/pvmfw/src/entry.rs
@@ -98,7 +98,7 @@
     };
 
     const REBOOT_REASON_CONSOLE: usize = 1;
-    console_writeln!(REBOOT_REASON_CONSOLE, "{}", reboot_reason.as_avf_reboot_string());
+    console_writeln!(REBOOT_REASON_CONSOLE, "{}", reboot_reason.as_avf_reboot_string()).unwrap();
     reboot()
 
     // if we reach this point and return, vmbase::entry::rust_entry() will call power::shutdown().
diff --git a/guest/pvmfw/src/fdt.rs b/guest/pvmfw/src/fdt.rs
index 59399b3..6f55c21 100644
--- a/guest/pvmfw/src/fdt.rs
+++ b/guest/pvmfw/src/fdt.rs
@@ -1382,7 +1382,7 @@
         fdt.unpack()?;
     }
 
-    patch_dice_node(fdt, bcc.as_ptr() as usize, bcc.len())?;
+    patch_dice_node(fdt, bcc)?;
 
     if let Some(mut chosen) = fdt.chosen_mut()? {
         empty_or_delete_prop(&mut chosen, c"avf,strict-boot", strict_boot)?;
@@ -1401,16 +1401,14 @@
 }
 
 /// Patch the "google,open-dice"-compatible reserved-memory node to point to the bcc range
-fn patch_dice_node(fdt: &mut Fdt, addr: usize, size: usize) -> libfdt::Result<()> {
-    // We reject DTs with missing reserved-memory node as validation should have checked that the
-    // "swiotlb" subnode (compatible = "restricted-dma-pool") was present.
-    let node = fdt.node_mut(c"/reserved-memory")?.ok_or(libfdt::FdtError::NotFound)?;
-
+fn patch_dice_node(fdt: &mut Fdt, handover: &[u8]) -> libfdt::Result<()> {
+    // The node is assumed to be present in the template DT.
+    let node = fdt.node_mut(c"/reserved-memory")?.ok_or(FdtError::NotFound)?;
     let mut node = node.next_compatible(c"google,open-dice")?.ok_or(FdtError::NotFound)?;
 
-    let addr: u64 = addr.try_into().unwrap();
-    let size: u64 = size.try_into().unwrap();
-    node.setprop_inplace(c"reg", [addr.to_be_bytes(), size.to_be_bytes()].as_flattened())
+    let addr = (handover.as_ptr() as usize).try_into().unwrap();
+    let size = handover.len().try_into().unwrap();
+    node.setprop_addrrange_inplace(c"reg", addr, size)
 }
 
 fn empty_or_delete_prop(
diff --git a/guest/rialto/src/exceptions.rs b/guest/rialto/src/exceptions.rs
index 467a3a6..c8c0156 100644
--- a/guest/rialto/src/exceptions.rs
+++ b/guest/rialto/src/exceptions.rs
@@ -18,9 +18,7 @@
     arch::aarch64::exceptions::{
         handle_permission_fault, handle_translation_fault, ArmException, Esr, HandleExceptionError,
     },
-    eprintln, logger,
-    power::reboot,
-    read_sysreg,
+    logger, read_sysreg,
 };
 
 fn handle_exception(exception: &ArmException) -> Result<(), HandleExceptionError> {
@@ -41,58 +39,44 @@
 
     let exception = ArmException::from_el1_regs();
     if let Err(e) = handle_exception(&exception) {
-        exception.print("sync_exception_current", e, elr);
-        reboot()
+        exception.print_and_reboot("sync_exception_current", e, elr);
     }
 }
 
 #[no_mangle]
-extern "C" fn irq_current() {
-    eprintln!("irq_current");
-    reboot();
+extern "C" fn irq_current(_elr: u64, _spsr: u64) {
+    panic!("irq_current");
 }
 
 #[no_mangle]
-extern "C" fn fiq_current() {
-    eprintln!("fiq_current");
-    reboot();
+extern "C" fn fiq_current(_elr: u64, _spsr: u64) {
+    panic!("fiq_current");
 }
 
 #[no_mangle]
-extern "C" fn serr_current() {
-    eprintln!("serr_current");
-    print_esr();
-    reboot();
-}
-
-#[no_mangle]
-extern "C" fn sync_lower() {
-    eprintln!("sync_lower");
-    print_esr();
-    reboot();
-}
-
-#[no_mangle]
-extern "C" fn irq_lower() {
-    eprintln!("irq_lower");
-    reboot();
-}
-
-#[no_mangle]
-extern "C" fn fiq_lower() {
-    eprintln!("fiq_lower");
-    reboot();
-}
-
-#[no_mangle]
-extern "C" fn serr_lower() {
-    eprintln!("serr_lower");
-    print_esr();
-    reboot();
-}
-
-#[inline]
-fn print_esr() {
+extern "C" fn serr_current(_elr: u64, _spsr: u64) {
     let esr = read_sysreg!("esr_el1");
-    eprintln!("esr={:#08x}", esr);
+    panic!("serr_current, esr={esr:#08x}");
+}
+
+#[no_mangle]
+extern "C" fn sync_lower(_elr: u64, _spsr: u64) {
+    let esr = read_sysreg!("esr_el1");
+    panic!("sync_lower, esr={esr:#08x}");
+}
+
+#[no_mangle]
+extern "C" fn irq_lower(_elr: u64, _spsr: u64) {
+    panic!("irq_lower");
+}
+
+#[no_mangle]
+extern "C" fn fiq_lower(_elr: u64, _spsr: u64) {
+    panic!("fiq_lower");
+}
+
+#[no_mangle]
+extern "C" fn serr_lower(_elr: u64, _spsr: u64) {
+    let esr = read_sysreg!("esr_el1");
+    panic!("serr_lower, esr={esr:#08x}");
 }
diff --git a/guest/trusty/security_vm/security_vm.mk b/guest/trusty/security_vm/security_vm.mk
index 89c9cdc..8717399 100644
--- a/guest/trusty/security_vm/security_vm.mk
+++ b/guest/trusty/security_vm/security_vm.mk
@@ -14,10 +14,14 @@
 
 
 ifeq ($(findstring enabled, $(TRUSTY_SYSTEM_VM)),enabled)
-PRODUCT_PACKAGES += \
-	trusty_security_vm.elf \
+
+# This is the default set of packages to load the trusty system vm.
+# It can be overridden by device-specific configuration.
+TRUSTY_SYSTEM_VM_PRODUCT_PACKAGES ?= trusty_security_vm.elf \
 	trusty_security_vm_launcher \
 	trusty_security_vm_launcher.rc \
 	early_vms.xml \
 
+PRODUCT_PACKAGES += $(TRUSTY_SYSTEM_VM_PRODUCT_PACKAGES)
+
 endif
diff --git a/guest/vmbase_example/src/exceptions.rs b/guest/vmbase_example/src/exceptions.rs
index 5d7768a..0eb415c 100644
--- a/guest/vmbase_example/src/exceptions.rs
+++ b/guest/vmbase_example/src/exceptions.rs
@@ -14,62 +14,51 @@
 
 //! Exception handlers.
 
-use vmbase::{eprintln, power::reboot, read_sysreg};
+use vmbase::{arch::aarch64::exceptions::ArmException, read_sysreg};
 
 #[no_mangle]
-extern "C" fn sync_exception_current(_elr: u64, _spsr: u64) {
-    eprintln!("sync_exception_current");
-    print_esr();
-    reboot();
+extern "C" fn sync_exception_current(elr: u64, _spsr: u64) {
+    ArmException::from_el1_regs().print_and_reboot(
+        "sync_exception_current",
+        "Unexpected synchronous exception",
+        elr,
+    );
 }
 
 #[no_mangle]
 extern "C" fn irq_current(_elr: u64, _spsr: u64) {
-    eprintln!("irq_current");
-    reboot();
+    panic!("irq_current");
 }
 
 #[no_mangle]
 extern "C" fn fiq_current(_elr: u64, _spsr: u64) {
-    eprintln!("fiq_current");
-    reboot();
+    panic!("fiq_current");
 }
 
 #[no_mangle]
 extern "C" fn serr_current(_elr: u64, _spsr: u64) {
-    eprintln!("serr_current");
-    print_esr();
-    reboot();
+    let esr = read_sysreg!("esr_el1");
+    panic!("serr_current, esr={:#08x}", esr);
 }
 
 #[no_mangle]
 extern "C" fn sync_lower(_elr: u64, _spsr: u64) {
-    eprintln!("sync_lower");
-    print_esr();
-    reboot();
+    let esr = read_sysreg!("esr_el1");
+    panic!("sync_lower, esr={:#08x}", esr);
 }
 
 #[no_mangle]
 extern "C" fn irq_lower(_elr: u64, _spsr: u64) {
-    eprintln!("irq_lower");
-    reboot();
+    panic!("irq_lower");
 }
 
 #[no_mangle]
 extern "C" fn fiq_lower(_elr: u64, _spsr: u64) {
-    eprintln!("fiq_lower");
-    reboot();
+    panic!("fiq_lower");
 }
 
 #[no_mangle]
 extern "C" fn serr_lower(_elr: u64, _spsr: u64) {
-    eprintln!("serr_lower");
-    print_esr();
-    reboot();
-}
-
-#[inline]
-fn print_esr() {
     let esr = read_sysreg!("esr_el1");
-    eprintln!("esr={:#08x}", esr);
+    panic!("serr_lower, esr={:#08x}", esr);
 }
diff --git a/libs/dice/open_dice/src/error.rs b/libs/dice/open_dice/src/error.rs
index c9eb5cc..87d463e 100644
--- a/libs/dice/open_dice/src/error.rs
+++ b/libs/dice/open_dice/src/error.rs
@@ -33,6 +33,8 @@
     UnsupportedKeyAlgorithm(coset::iana::Algorithm),
     /// A failed fallible allocation. Used in no_std environments.
     MemoryAllocationError,
+    /// DICE chain not found in artifacts.
+    DiceChainNotFound,
 }
 
 /// This makes `DiceError` accepted by anyhow.
@@ -51,6 +53,7 @@
                 write!(f, "Unsupported key algorithm: {algorithm:?}")
             }
             Self::MemoryAllocationError => write!(f, "Memory allocation failed"),
+            Self::DiceChainNotFound => write!(f, "DICE chain not found in artifacts"),
         }
     }
 }
diff --git a/libs/dice/open_dice/src/retry.rs b/libs/dice/open_dice/src/retry.rs
index d793218..2b7b740 100644
--- a/libs/dice/open_dice/src/retry.rs
+++ b/libs/dice/open_dice/src/retry.rs
@@ -17,7 +17,7 @@
 //! of this buffer may fail and callers will see Error::MemoryAllocationError.
 //! When running with std, allocation may fail.
 
-use crate::bcc::{bcc_format_config_descriptor, bcc_main_flow, DiceConfigValues};
+use crate::bcc::{bcc_format_config_descriptor, bcc_main_flow, BccHandover, DiceConfigValues};
 use crate::dice::{
     dice_main_flow, Cdi, CdiValues, DiceArtifacts, InputValues, CDI_SIZE, PRIVATE_KEY_SEED_SIZE,
     PRIVATE_KEY_SIZE,
@@ -60,6 +60,20 @@
     }
 }
 
+impl TryFrom<BccHandover<'_>> for OwnedDiceArtifacts {
+    type Error = DiceError;
+
+    fn try_from(artifacts: BccHandover<'_>) -> Result<Self> {
+        let cdi_attest = artifacts.cdi_attest().to_vec().try_into().unwrap();
+        let cdi_seal = artifacts.cdi_seal().to_vec().try_into().unwrap();
+        let bcc = artifacts
+            .bcc()
+            .map(|bcc_slice| bcc_slice.to_vec())
+            .ok_or(DiceError::DiceChainNotFound)?;
+        Ok(OwnedDiceArtifacts { cdi_values: CdiValues { cdi_attest, cdi_seal }, bcc })
+    }
+}
+
 /// Retries the given function with bigger measured buffer size.
 fn retry_with_measured_buffer<F>(mut f: F) -> Result<Vec<u8>>
 where
diff --git a/libs/dice/sample_inputs/Android.bp b/libs/dice/sample_inputs/Android.bp
index c1c4566..4010741 100644
--- a/libs/dice/sample_inputs/Android.bp
+++ b/libs/dice/sample_inputs/Android.bp
@@ -80,3 +80,9 @@
     ],
     static_libs: ["libopen_dice_clear_memory"],
 }
+
+dirgroup {
+    name: "trusty_dirgroup_packages_modules_virtualization_libs_dice_sample_inputs",
+    visibility: ["//trusty/vendor/google/aosp/scripts"],
+    dirs: ["."],
+}
diff --git a/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java b/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
index ad63206..f6cd1cf 100644
--- a/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
+++ b/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
@@ -813,6 +813,10 @@
      */
     @GuardedBy("mLock")
     private void dropVm() {
+        if (mInputEventExecutor != null) {
+            mInputEventExecutor.shutdownNow();
+            mInputEventExecutor = null;
+        }
         if (mMemoryManagementCallbacks != null) {
             mContext.unregisterComponentCallbacks(mMemoryManagementCallbacks);
         }
diff --git a/libs/libavf/Android.bp b/libs/libavf/Android.bp
index aceb927..4469af5 100644
--- a/libs/libavf/Android.bp
+++ b/libs/libavf/Android.bp
@@ -40,30 +40,8 @@
     defaults: ["libavf.default"],
 }
 
-soong_config_module_type {
-    name: "virt_cc_defaults",
-    module_type: "cc_defaults",
-    config_namespace: "ANDROID",
-    bool_variables: [
-        "avf_enabled",
-    ],
-    properties: [
-        "apex_available",
-    ],
-}
-
-virt_cc_defaults {
-    name: "libavf_apex_available_defaults",
-    soong_config_variables: {
-        avf_enabled: {
-            apex_available: ["com.android.virt"],
-        },
-    },
-}
-
 cc_library {
     name: "libavf",
-    defaults: ["libavf_apex_available_defaults"],
     llndk: {
         symbol_file: "libavf.map.txt",
         moved_to_apex: true,
@@ -79,4 +57,5 @@
     stubs: {
         symbol_file: "libavf.map.txt",
     },
+    apex_available: ["com.android.virt"],
 }
diff --git a/libs/libavf/include/android/virtualization.h b/libs/libavf/include/android/virtualization.h
index 4bfe47a..e907ac4 100644
--- a/libs/libavf/include/android/virtualization.h
+++ b/libs/libavf/include/android/virtualization.h
@@ -78,6 +78,9 @@
  * The `instanceId` is expected to be re-used for the VM instance with an associated state (secret,
  * encrypted storage) - i.e., rebooting the VM must not change the instanceId.
  *
+ * `instanceId` MUST start with 0xFFFFFFFF if and only if this library is being
+ * called from code in a vendor or odm partition,
+ *
  * \param config a virtual machine config object.
  * \param instanceId a pointer to a 64-byte buffer for the instance ID.
  * \param instanceIdSize the number of bytes in `instanceId`.
diff --git a/libs/libvmbase/README.md b/libs/libvmbase/README.md
index 28d930a..3c05cc3 100644
--- a/libs/libvmbase/README.md
+++ b/libs/libvmbase/README.md
@@ -79,23 +79,16 @@
 use vmbase::power::reboot;
 
 extern "C" fn sync_exception_current() {
-    eprintln!("sync_exception_current");
-
     let mut esr: u64;
     unsafe {
         asm!("mrs {esr}, esr_el1", esr = out(reg) esr);
     }
-    eprintln!("esr={:#08x}", esr);
-
-    reboot();
+    panic!("sync_exception_current, esr={:#08x}", esr);
 }
 ```
 
 The `println!` macro shouldn't be used in exception handlers, because it relies on a global instance
 of the UART driver which might be locked when the exception happens, which would result in deadlock.
-Instead you can use `eprintln!`, which will re-initialize the UART every time to ensure that it can
-be used. This should still be used with care, as it may interfere with whatever the rest of the
-program is doing with the UART.
 
 See [example/src/exceptions.rs](examples/src/exceptions.rs) for a complete example.
 
diff --git a/libs/libvmbase/src/arch/aarch64/exceptions.rs b/libs/libvmbase/src/arch/aarch64/exceptions.rs
index 1868bf7..787ef37 100644
--- a/libs/libvmbase/src/arch/aarch64/exceptions.rs
+++ b/libs/libvmbase/src/arch/aarch64/exceptions.rs
@@ -14,12 +14,17 @@
 
 //! Helper functions and structs for exception handlers.
 
-use crate::memory::{MemoryTrackerError, MEMORY};
 use crate::{
-    arch::aarch64::layout::UART_PAGE_ADDR, arch::VirtualAddress, eprintln, memory::page_4kb_of,
+    arch::{
+        aarch64::layout::UART_PAGE_ADDR,
+        platform::{emergency_uart, DEFAULT_EMERGENCY_CONSOLE_INDEX},
+        VirtualAddress,
+    },
+    memory::{page_4kb_of, MemoryTrackerError, MEMORY},
+    power::reboot,
     read_sysreg,
 };
-use core::fmt;
+use core::fmt::{self, Write};
 use core::result;
 
 /// Represents an error that can occur while handling an exception.
@@ -122,14 +127,23 @@
         Self { esr, far: VirtualAddress(far) }
     }
 
-    /// Prints the details of an obj and the exception, excluding UART exceptions.
-    pub fn print<T: fmt::Display>(&self, exception_name: &str, obj: T, elr: u64) {
+    /// Prints the details of an obj and the exception, excluding UART exceptions, and then reboots.
+    ///
+    /// This uses the emergency console so can safely be called even for synchronous exceptions
+    /// without causing a deadlock.
+    pub fn print_and_reboot<T: fmt::Display>(&self, exception_name: &str, obj: T, elr: u64) -> ! {
         // Don't print to the UART if we are handling an exception it could raise.
         if !self.is_uart_exception() {
-            eprintln!("{exception_name}");
-            eprintln!("{obj}");
-            eprintln!("{}, elr={:#08x}", self, elr);
+            // SAFETY: We always reboot at the end of this method so there is no way for the
+            // original UART driver to be used after this.
+            if let Some(mut console) = unsafe { emergency_uart(DEFAULT_EMERGENCY_CONSOLE_INDEX) } {
+                // Ignore errors writing to emergency console, as we are about to reboot anyway.
+                _ = writeln!(console, "{exception_name}");
+                _ = writeln!(console, "{obj}");
+                _ = writeln!(console, "{}, elr={:#08x}", self, elr);
+            }
         }
+        reboot();
     }
 
     fn is_uart_exception(&self) -> bool {
diff --git a/libs/libvmbase/src/arch/aarch64/platform.rs b/libs/libvmbase/src/arch/aarch64/platform.rs
index b33df68..7e002d0 100644
--- a/libs/libvmbase/src/arch/aarch64/platform.rs
+++ b/libs/libvmbase/src/arch/aarch64/platform.rs
@@ -104,18 +104,25 @@
 
 /// Return platform uart with specific index
 ///
-/// Panics if console was not initialized by calling [`init`] first.
-pub fn uart(id: usize) -> &'static spin::mutex::SpinMutex<Uart> {
-    CONSOLES[id].get().unwrap()
+/// Returns `None` if console was not initialized by calling [`init`] first.
+pub fn uart(id: usize) -> Option<&'static SpinMutex<Uart>> {
+    CONSOLES[id].get()
 }
 
-/// Reinitializes the emergency UART driver and returns it.
+/// Reinitializes the n-th UART driver and returns it.
 ///
 /// This is intended for use in situations where the UART may be in an unknown state or the global
-/// instance may be locked, such as in an exception handler or panic handler.
-pub fn emergency_uart() -> Uart {
+/// instance may be locked, such as in the synchronous exception handler.
+///
+/// # Safety
+///
+/// This takes over the UART from wherever it is being used, the existing UART instance should not
+/// be used after this is called. This should only be used immediately before aborting the VM.
+pub unsafe fn emergency_uart(id: usize) -> Option<Uart> {
+    let addr = *ADDRESSES[id].get()?;
+
     // SAFETY: Initialization of UART using dedicated const address.
-    unsafe { Uart::new(UART_ADDRESSES[DEFAULT_EMERGENCY_CONSOLE_INDEX]) }
+    Some(unsafe { Uart::new(addr) })
 }
 
 /// Makes a `PSCI_SYSTEM_OFF` call to shutdown the VM.
diff --git a/libs/libvmbase/src/console.rs b/libs/libvmbase/src/console.rs
index 6d9a4fe..dcaf1ad 100644
--- a/libs/libvmbase/src/console.rs
+++ b/libs/libvmbase/src/console.rs
@@ -14,33 +14,26 @@
 
 //! Console driver for 8250 UART.
 
-use crate::arch::platform;
-use core::fmt::{write, Arguments, Write};
+use crate::arch::platform::{self, emergency_uart, DEFAULT_EMERGENCY_CONSOLE_INDEX};
+use crate::power::reboot;
+use core::fmt::{self, write, Arguments, Write};
+use core::panic::PanicInfo;
 
 /// Writes a formatted string followed by a newline to the n-th console.
 ///
-/// Panics if the n-th console was not initialized by calling [`init`] first.
-pub fn writeln(n: usize, format_args: Arguments) {
-    let uart = &mut *platform::uart(n).lock();
-    write(uart, format_args).unwrap();
-    let _ = uart.write_str("\n");
-}
+/// Returns an error if the n-th console was not initialized by calling [`init`] first.
+pub fn writeln(n: usize, format_args: Arguments) -> fmt::Result {
+    let uart = &mut *platform::uart(n).ok_or(fmt::Error)?.lock();
 
-/// Reinitializes the emergency UART driver and writes a formatted string followed by a newline to
-/// it.
-///
-/// This is intended for use in situations where the UART may be in an unknown state or the global
-/// instance may be locked, such as in an exception handler or panic handler.
-pub fn ewriteln(format_args: Arguments) {
-    let mut uart = platform::emergency_uart();
-    let _ = write(&mut uart, format_args);
-    let _ = uart.write_str("\n");
+    write(uart, format_args)?;
+    uart.write_str("\n")?;
+    Ok(())
 }
 
 /// Prints the given formatted string to the n-th console, followed by a newline.
 ///
-/// Panics if the console has not yet been initialized. May hang if used in an exception context;
-/// use `eprintln!` instead.
+/// Returns an error if the console has not yet been initialized. May deadlock if used in a
+/// synchronous exception handler.
 #[macro_export]
 macro_rules! console_writeln {
     ($n:expr, $($arg:tt)*) => ({
@@ -48,27 +41,24 @@
     })
 }
 
-pub(crate) use console_writeln;
-
 /// Prints the given formatted string to the console, followed by a newline.
 ///
-/// Panics if the console has not yet been initialized. May hang if used in an exception context;
-/// use `eprintln!` instead.
+/// Panics if the console has not yet been initialized. May hang if used in an exception context.
 macro_rules! println {
     ($($arg:tt)*) => ({
-        $crate::console::console_writeln!($crate::arch::platform::DEFAULT_CONSOLE_INDEX, $($arg)*)
+        $crate::console_writeln!($crate::arch::platform::DEFAULT_CONSOLE_INDEX, $($arg)*).unwrap()
     })
 }
 
 pub(crate) use println; // Make it available in this crate.
 
-/// Prints the given string followed by a newline to the console in an emergency, such as an
-/// exception handler.
-///
-/// Never panics.
-#[macro_export]
-macro_rules! eprintln {
-    ($($arg:tt)*) => ({
-        $crate::console::ewriteln(format_args!($($arg)*))
-    })
+#[panic_handler]
+fn panic(info: &PanicInfo) -> ! {
+    // SAFETY: We always reboot at the end of this method so there is no way for the
+    // original UART driver to be used after this.
+    if let Some(mut console) = unsafe { emergency_uart(DEFAULT_EMERGENCY_CONSOLE_INDEX) } {
+        // Ignore errors, to avoid a panic loop.
+        let _ = writeln!(console, "{}", info);
+    }
+    reboot()
 }
diff --git a/libs/libvmbase/src/lib.rs b/libs/libvmbase/src/lib.rs
index d254038..afb62fc 100644
--- a/libs/libvmbase/src/lib.rs
+++ b/libs/libvmbase/src/lib.rs
@@ -32,12 +32,3 @@
 pub mod uart;
 pub mod util;
 pub mod virtio;
-
-use core::panic::PanicInfo;
-use power::reboot;
-
-#[panic_handler]
-fn panic(info: &PanicInfo) -> ! {
-    eprintln!("{}", info);
-    reboot()
-}
diff --git a/libs/libvmbase/src/logger.rs b/libs/libvmbase/src/logger.rs
index 9130918..0059d11 100644
--- a/libs/libvmbase/src/logger.rs
+++ b/libs/libvmbase/src/logger.rs
@@ -16,7 +16,7 @@
 //!
 //! Internally uses the println! vmbase macro, which prints to crosvm's UART.
 //! Note: may not work if the VM is in an inconsistent state. Exception handlers
-//! should avoid using this logger and instead print with eprintln!.
+//! should avoid using this logger.
 
 use crate::console::println;
 use core::sync::atomic::{AtomicBool, Ordering};