Merge "Scan /sdcard/Download onPause" into main
diff --git a/android/TerminalApp/AndroidManifest.xml b/android/TerminalApp/AndroidManifest.xml
index aa702a3..48b53dd 100644
--- a/android/TerminalApp/AndroidManifest.xml
+++ b/android/TerminalApp/AndroidManifest.xml
@@ -65,6 +65,8 @@
         <activity android:name=".ErrorActivity"
             android:label="@string/error_title"
             android:process=":error" />
+        <activity android:name=".UpgradeActivity"
+            android:label="@string/upgrade_title" />
         <property
             android:name="android.window.PROPERTY_ACTIVITY_EMBEDDING_SPLITS_ENABLED"
             android:value="true" />
diff --git a/android/TerminalApp/assets/js/terminal_disconnect.js b/android/TerminalApp/assets/js/terminal_disconnect.js
new file mode 100644
index 0000000..1c89a13
--- /dev/null
+++ b/android/TerminalApp/assets/js/terminal_disconnect.js
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2025 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.
+ */
+
+(function() {
+  var originalLog = console.log;
+  console.log = function() {
+    console.log.history = console.log.history || [];
+    console.log.history.push(arguments);
+    originalLog.apply(console, arguments);
+    if (typeof arguments[0] === 'string' && arguments[0].startsWith("[ttyd] websocket connection closed with code: ")) {
+        TerminalApp.closeTab()
+    }
+  };
+})();
\ No newline at end of file
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt b/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
index 50aaa33..04d6813 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/InstalledImage.kt
@@ -67,6 +67,16 @@
         }
     }
 
+    fun isOlderThanCurrentVersion(): Boolean {
+        val year =
+            try {
+                buildId.split(" ").last().toInt()
+            } catch (_: Exception) {
+                0
+            }
+        return year < RELEASE_YEAR
+    }
+
     @Throws(IOException::class)
     fun uninstallAndBackup(): Path {
         Files.delete(marker)
@@ -191,6 +201,7 @@
         const val MARKER_FILENAME: String = "completed"
 
         const val RESIZE_STEP_BYTES: Long = 4 shl 20 // 4 MiB
+        const val RELEASE_YEAR: Int = 2025
 
         /** Returns InstalledImage for a given app context */
         fun getDefault(context: Context): InstalledImage {
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/Logger.kt b/android/TerminalApp/java/com/android/virtualization/terminal/Logger.kt
index ba03716..088744e 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/Logger.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/Logger.kt
@@ -17,9 +17,7 @@
 
 import android.system.virtualmachine.VirtualMachine
 import android.system.virtualmachine.VirtualMachineConfig
-import android.system.virtualmachine.VirtualMachineException
 import android.util.Log
-import com.android.virtualization.terminal.Logger.LineBufferedOutputStream
 import java.io.BufferedOutputStream
 import java.io.BufferedReader
 import java.io.IOException
@@ -56,19 +54,29 @@
             val logPath = dir.resolve(LocalDateTime.now().toString() + ".txt")
             val console = vm.getConsoleOutput()
             val file = Files.newOutputStream(logPath, StandardOpenOption.CREATE)
-            executor.submit<Int?> {
-                console.use { console ->
-                    LineBufferedOutputStream(file).use { fileOutput ->
-                        Streams.copy(console, fileOutput)
+            executor.execute({
+                try {
+                    console.use { console ->
+                        LineBufferedOutputStream(file).use { fileOutput ->
+                            Streams.copy(console, fileOutput)
+                        }
                     }
+                } catch (e: Exception) {
+                    Log.w(tag, "Failed to log console output. VM may be shutting down", e)
                 }
-            }
+            })
 
             val log = vm.getLogOutput()
-            executor.submit<Unit> { log.use { writeToLogd(it, tag) } }
-        } catch (e: VirtualMachineException) {
-            throw RuntimeException(e)
-        } catch (e: IOException) {
+            executor.execute({
+                log.use {
+                    try {
+                        writeToLogd(it, tag)
+                    } catch (e: Exception) {
+                        Log.w(tag, "Failed to log VM log output. VM may be shutting down", e)
+                    }
+                }
+            })
+        } catch (e: Exception) {
             throw RuntimeException(e)
         }
     }
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
index 0d70f37..37147eb 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/MainActivity.kt
@@ -104,7 +104,13 @@
 
         // if installer is launched, it will be handled in onActivityResult
         if (!launchInstaller) {
-            if (!Environment.isExternalStorageManager()) {
+            if (image.isOlderThanCurrentVersion()) {
+                val intent = Intent(this, UpgradeActivity::class.java)
+                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
+                startActivity(intent)
+                // Explicitly finish to make sure that user can't go back from ErrorActivity.
+                finish()
+            } else if (!Environment.isExternalStorageManager()) {
                 requestStoragePermissions(this, manageExternalStorageActivityResultLauncher)
             } else {
                 startVm()
@@ -180,20 +186,20 @@
         terminalViewModel.terminalTabs[tabId] = tab
         tab.customView!!
             .findViewById<Button>(R.id.tab_close_button)
-            .setOnClickListener(
-                View.OnClickListener { _: View? ->
-                    if (terminalTabAdapter.tabs.size == 1) {
-                        finishAndRemoveTask()
-                    }
-                    viewPager.offscreenPageLimit -= 1
-                    terminalTabAdapter.deleteTab(tab.position)
-                    tabLayout.removeTab(tab)
-                }
-            )
+            .setOnClickListener(View.OnClickListener { _: View? -> closeTab(tab) })
         // Add and select the tab
         tabLayout.addTab(tab, true)
     }
 
+    fun closeTab(tab: TabLayout.Tab) {
+        if (terminalTabAdapter.tabs.size == 1) {
+            finishAndRemoveTask()
+        }
+        viewPager.offscreenPageLimit -= 1
+        terminalTabAdapter.deleteTab(tab.position)
+        tabLayout.removeTab(tab)
+    }
+
     private fun lockOrientationIfNecessary() {
         val hasHwQwertyKeyboard = resources.configuration.keyboard == Configuration.KEYBOARD_QWERTY
         if (hasHwQwertyKeyboard) {
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/MemBalloonController.kt b/android/TerminalApp/java/com/android/virtualization/terminal/MemBalloonController.kt
index 7647d9b..2ed7217 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/MemBalloonController.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/MemBalloonController.kt
@@ -58,7 +58,7 @@
             // available memory to the virtual machine
             override fun onResume(owner: LifecycleOwner) {
                 ongoingInflation?.cancel(false)
-                executor.submit({
+                executor.execute({
                     Log.v(TAG, "app resumed. deflating mem balloon to the minimum")
                     vm.setMemoryBalloonByPercent(0)
                 })
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsRecoveryActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsRecoveryActivity.kt
index 319a53b..654cb57 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/SettingsRecoveryActivity.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/SettingsRecoveryActivity.kt
@@ -21,19 +21,23 @@
 import android.view.View
 import androidx.appcompat.app.AppCompatActivity
 import androidx.core.view.isVisible
-import androidx.lifecycle.lifecycleScope
 import com.android.virtualization.terminal.MainActivity.Companion.TAG
 import com.google.android.material.card.MaterialCardView
 import com.google.android.material.dialog.MaterialAlertDialogBuilder
 import com.google.android.material.snackbar.Snackbar
 import java.io.IOException
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Executors
 
 class SettingsRecoveryActivity : AppCompatActivity() {
+    private lateinit var executorService: ExecutorService
+
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
+
+        executorService =
+            Executors.newSingleThreadExecutor(TerminalThreadFactory(applicationContext))
+
         setContentView(R.layout.settings_recovery)
 
         val resetCard = findViewById<MaterialCardView>(R.id.settings_recovery_reset_card)
@@ -81,6 +85,12 @@
         }
     }
 
+    override fun onDestroy() {
+        super.onDestroy()
+
+        executorService.shutdown()
+    }
+
     private fun removeBackup(): Unit {
         try {
             InstalledImage.getDefault(this).deleteBackup()
@@ -116,27 +126,22 @@
         }
     }
 
-    private fun runInBackgroundAndRestartApp(
-        backgroundWork: suspend CoroutineScope.() -> Unit
-    ): Unit {
+    private fun runInBackgroundAndRestartApp(backgroundWork: Runnable) {
         findViewById<View>(R.id.setting_recovery_card_container).visibility = View.INVISIBLE
         findViewById<View>(R.id.recovery_boot_progress).visibility = View.VISIBLE
-        lifecycleScope
-            .launch(Dispatchers.IO) { backgroundWork() }
-            .invokeOnCompletion {
-                runOnUiThread {
-                    findViewById<View>(R.id.setting_recovery_card_container).visibility =
-                        View.VISIBLE
-                    findViewById<View>(R.id.recovery_boot_progress).visibility = View.INVISIBLE
-                    // Restart terminal
-                    val intent =
-                        baseContext.packageManager.getLaunchIntentForPackage(
-                            baseContext.packageName
-                        )
-                    intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
-                    finish()
-                    startActivity(intent)
-                }
+        executorService.execute({
+            backgroundWork.run()
+
+            runOnUiThread {
+                findViewById<View>(R.id.setting_recovery_card_container).visibility = View.VISIBLE
+                findViewById<View>(R.id.recovery_boot_progress).visibility = View.INVISIBLE
+                // Restart terminal
+                val intent =
+                    baseContext.packageManager.getLaunchIntentForPackage(baseContext.packageName)
+                intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
+                finish()
+                startActivity(intent)
             }
+        })
     }
 }
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/TerminalTabFragment.kt b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalTabFragment.kt
index a0c6e4e..8106f6e 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/TerminalTabFragment.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalTabFragment.kt
@@ -24,6 +24,7 @@
 import android.view.View
 import android.view.ViewGroup
 import android.webkit.ClientCertRequest
+import android.webkit.JavascriptInterface
 import android.webkit.SslErrorHandler
 import android.webkit.WebChromeClient
 import android.webkit.WebResourceError
@@ -92,6 +93,7 @@
 
         terminalView.webChromeClient = TerminalWebChromeClient()
         terminalView.webViewClient = TerminalWebViewClient()
+        terminalView.addJavascriptInterface(TerminalViewInterface(context!!), "TerminalApp")
 
         (activity as MainActivity).modifierKeysController.addTerminalView(terminalView)
         terminalViewModel.terminalViews.add(terminalView)
@@ -119,6 +121,18 @@
         }
     }
 
+    inner class TerminalViewInterface(private val mContext: android.content.Context) {
+        @JavascriptInterface
+        fun closeTab() {
+            if (activity != null) {
+                activity?.runOnUiThread {
+                    val mainActivity = (activity as MainActivity)
+                    mainActivity.closeTab(terminalViewModel.terminalTabs[id]!!)
+                }
+            }
+        }
+    }
+
     private inner class TerminalWebViewClient : WebViewClient() {
         private var loadFailed = false
         private var requestId: Long = 0
@@ -174,6 +188,7 @@
                             bootProgressView.visibility = View.GONE
                             terminalView.visibility = View.VISIBLE
                             terminalView.mapTouchToMouseEvent()
+                            terminalView.applyTerminalDisconnectCallback()
                             updateMainActivity()
                             updateFocus()
                         }
@@ -201,7 +216,7 @@
     }
 
     private fun updateMainActivity() {
-        val mainActivity = (activity as MainActivity)
+        val mainActivity = activity as MainActivity ?: return
         if (terminalGuiSupport()) {
             mainActivity.displayMenu!!.visibility = View.VISIBLE
             mainActivity.displayMenu!!.isEnabled = true
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/TerminalView.kt b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalView.kt
index 4b11c1d..9c83d8b 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/TerminalView.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/TerminalView.kt
@@ -41,6 +41,8 @@
     private val ctrlKeyHandler: String = readAssetAsString(context, "js/ctrl_key_handler.js")
     private val enableCtrlKey: String = readAssetAsString(context, "js/enable_ctrl_key.js")
     private val disableCtrlKey: String = readAssetAsString(context, "js/disable_ctrl_key.js")
+    private val terminalDisconnectCallback: String =
+        readAssetAsString(context, "js/terminal_disconnect.js")
     private val touchToMouseHandler: String =
         readAssetAsString(context, "js/touch_to_mouse_handler.js")
     private val a11yManager =
@@ -70,6 +72,10 @@
         this.evaluateJavascript(disableCtrlKey, null)
     }
 
+    fun applyTerminalDisconnectCallback() {
+        this.evaluateJavascript(terminalDisconnectCallback, null)
+    }
+
     override fun onAccessibilityStateChanged(enabled: Boolean) {
         Log.d(TAG, "accessibility $enabled")
         adjustToA11yStateChange()
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/UpgradeActivity.kt b/android/TerminalApp/java/com/android/virtualization/terminal/UpgradeActivity.kt
new file mode 100644
index 0000000..357de94
--- /dev/null
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/UpgradeActivity.kt
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2025 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.
+ */
+package com.android.virtualization.terminal
+
+import android.annotation.MainThread
+import android.content.Intent
+import android.os.Bundle
+import android.util.Log
+import android.view.View
+import com.google.android.material.snackbar.Snackbar
+import java.io.IOException
+import java.util.concurrent.ExecutorService
+import java.util.concurrent.Executors
+
+class UpgradeActivity : BaseActivity() {
+    private lateinit var executorService: ExecutorService
+
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+
+        executorService =
+            Executors.newSingleThreadExecutor(TerminalThreadFactory(applicationContext))
+
+        setContentView(R.layout.activity_upgrade)
+
+        val button = findViewById<View>(R.id.upgrade)
+        button.setOnClickListener { _ -> upgrade() }
+    }
+
+    override fun onDestroy() {
+        super.onDestroy()
+
+        executorService.shutdown()
+    }
+
+    private fun upgrade() {
+        findViewById<View>(R.id.progress).visibility = View.VISIBLE
+
+        executorService.execute {
+            val image = InstalledImage.getDefault(this)
+            try {
+                image.uninstallAndBackup()
+            } catch (e: IOException) {
+                Snackbar.make(
+                        findViewById<View>(android.R.id.content),
+                        R.string.upgrade_error,
+                        Snackbar.LENGTH_SHORT,
+                    )
+                    .show()
+                Log.e(MainActivity.Companion.TAG, "Failed to upgrade ", e)
+                return@execute
+            }
+
+            runOnUiThread {
+                findViewById<View>(R.id.progress).visibility = View.INVISIBLE
+                restartTerminal()
+            }
+        }
+    }
+
+    @MainThread
+    private fun restartTerminal() {
+        val intent = baseContext.packageManager.getLaunchIntentForPackage(baseContext.packageName)
+        intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
+        finish()
+        startActivity(intent)
+    }
+}
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt b/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
index 84168e5..0b34a8d 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/VmLauncherService.kt
@@ -94,7 +94,7 @@
 
     override fun onCreate() {
         super.onCreate()
-        val threadFactory = TerminalThreadFactory(getApplicationContext())
+        val threadFactory = TerminalThreadFactory(applicationContext)
         bgThreads = Executors.newCachedThreadPool(threadFactory)
         mainWorkerThread = Executors.newSingleThreadExecutor(threadFactory)
         image = InstalledImage.getDefault(this)
@@ -123,7 +123,7 @@
                 // done.
                 val diskSize = intent.getLongExtra(EXTRA_DISK_SIZE, image.getApparentSize())
 
-                mainWorkerThread.submit({
+                mainWorkerThread.execute({
                     doStart(notification, displayInfo, diskSize, resultReceiver)
                 })
 
@@ -131,7 +131,7 @@
                 // ForegroundServiceDidNotStartInTimeException
                 startForeground(this.hashCode(), notification)
             }
-            ACTION_SHUTDOWN_VM -> mainWorkerThread.submit({ doShutdown(resultReceiver) })
+            ACTION_SHUTDOWN_VM -> mainWorkerThread.execute({ doShutdown(resultReceiver) })
             else -> {
                 Log.e(TAG, "Unknown command " + intent.action)
                 stopSelf()
@@ -505,7 +505,7 @@
     }
 
     override fun onDestroy() {
-        mainWorkerThread.submit({
+        mainWorkerThread.execute({
             if (runner?.vm?.getStatus() == VirtualMachine.STATUS_RUNNING) {
                 doShutdown(null)
             }
diff --git a/android/TerminalApp/res/layout/activity_upgrade.xml b/android/TerminalApp/res/layout/activity_upgrade.xml
new file mode 100644
index 0000000..13e8404
--- /dev/null
+++ b/android/TerminalApp/res/layout/activity_upgrade.xml
@@ -0,0 +1,66 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--  Copyright 2025 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.
+ -->
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:fitsSystemWindows="true"
+    tools:context=".UpgradeActivity">
+
+    <TextView
+        android:id="@+id/title"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:text="@string/upgrade_title"
+        android:layout_marginVertical="24dp"
+        android:layout_marginHorizontal="24dp"
+        android:layout_alignParentTop="true"
+        android:hyphenationFrequency="full"
+        android:textSize="48sp" />
+
+    <com.google.android.material.progressindicator.LinearProgressIndicator
+        android:id="@+id/progress"
+        android:indeterminate="true"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_alignParentStart="true"
+        android:layout_below="@id/title"
+        android:visibility="invisible" />
+
+    <TextView
+        android:id="@+id/desc"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:text="@string/upgrade_desc"
+        android:lineSpacingExtra="5sp"
+        android:layout_marginTop="20dp"
+        android:layout_marginHorizontal="48dp"
+        android:layout_below="@id/progress"
+        android:textSize="20sp" />
+
+    <Button
+        android:id="@+id/upgrade"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentBottom="true"
+        android:layout_alignParentEnd="true"
+        android:layout_marginBottom="32dp"
+        android:layout_marginHorizontal="40dp"
+        android:backgroundTint="?attr/colorPrimaryDark"
+        android:text="@string/upgrade_button" />
+
+</RelativeLayout>
diff --git a/android/TerminalApp/res/values/strings.xml b/android/TerminalApp/res/values/strings.xml
index 273032e..a0e33e5 100644
--- a/android/TerminalApp/res/values/strings.xml
+++ b/android/TerminalApp/res/values/strings.xml
@@ -161,6 +161,15 @@
     <!-- Error page that shows detailed error code (error reason) for bugreport. [CHAR LIMIT=none] -->
     <string name="error_code">Error code: <xliff:g id="error_code" example="ACCESS_DENIED">%s</xliff:g></string>
 
+    <!-- Upgrade page's title. Tells users that you'll need to upgrade [CHAR LIMIT=none] -->
+    <string name="upgrade_title">Upgrade to newer terminal</string>
+    <!-- Upgrade page's description. Tell users that can't use as-is, and also explains next step. (/mnt/backup is the path which is supposed not to be translated) [CHAR LIMIT=none] -->
+    <string name="upgrade_desc">Linux terminal you were using is out of date. Please upgrade to proceed.\nData will be backed at <xliff:g id="path" example="/mnt/backup">/mnt/backup</xliff:g></string>
+    <!-- Upgrade page's button to start upgrade. [CHAR LIMIT=16] -->
+    <string name="upgrade_button">Upgrade</string>
+    <!-- Upgrade page's error toast message when upgrade failed. [CHAR LIMIT=none] -->
+    <string name="upgrade_error">Upgrade failed</string>
+
     <!-- Notification action button for settings [CHAR LIMIT=20] -->
     <string name="service_notification_settings">Settings</string>
     <!-- Notification title for foreground service notification [CHAR LIMIT=none] -->
diff --git a/build/apex/Android.bp b/build/apex/Android.bp
index f0eba7f..7496f4d 100644
--- a/build/apex/Android.bp
+++ b/build/apex/Android.bp
@@ -69,10 +69,7 @@
         default: [],
     }),
 
-    canned_fs_config: select(release_flag("RELEASE_AVF_ENABLE_VIRT_CPUFREQ"), {
-        true: "canned_fs_config_sys_nice",
-        default: "canned_fs_config",
-    }),
+    canned_fs_config: "canned_fs_config",
 }
 
 vintf_fragment {
diff --git a/build/apex/canned_fs_config b/build/apex/canned_fs_config
index 5afd9d6..90c9747 100644
--- a/build/apex/canned_fs_config
+++ b/build/apex/canned_fs_config
@@ -1 +1,3 @@
 /bin/virtualizationservice 0 2000 0755 capabilities=0x1000001  # CAP_CHOWN, CAP_SYS_RESOURCE
+/bin/crosvm 0 3013 0755 capabilities=0x800000  # CAP_SYS_NICE
+/bin/virtmgr 0 3013 0755 capabilities=0x800000 # CAP_SYS_NICE
diff --git a/build/apex/canned_fs_config_sys_nice b/build/apex/canned_fs_config_sys_nice
deleted file mode 100644
index 90c9747..0000000
--- a/build/apex/canned_fs_config_sys_nice
+++ /dev/null
@@ -1,3 +0,0 @@
-/bin/virtualizationservice 0 2000 0755 capabilities=0x1000001  # CAP_CHOWN, CAP_SYS_RESOURCE
-/bin/crosvm 0 3013 0755 capabilities=0x800000  # CAP_SYS_NICE
-/bin/virtmgr 0 3013 0755 capabilities=0x800000 # CAP_SYS_NICE
diff --git a/build/apex/manifest.json b/build/apex/manifest.json
index e596ce1..9be2aa6 100644
--- a/build/apex/manifest.json
+++ b/build/apex/manifest.json
@@ -1,6 +1,6 @@
 {
   "name": "com.android.virt",
-  "version": 2,
+  "version": 3,
   "requireNativeLibs": [
     "libEGL.so",
     "libGLESv2.so",
diff --git a/build/compos/manifest.json b/build/compos/manifest.json
index 7a07b1b..6d1f816 100644
--- a/build/compos/manifest.json
+++ b/build/compos/manifest.json
@@ -1,4 +1,4 @@
 {
   "name": "com.android.compos",
-  "version": 2
+  "version": 3
 }
diff --git a/build/microdroid/Android.bp b/build/microdroid/Android.bp
index 10b492b..9152091 100644
--- a/build/microdroid/Android.bp
+++ b/build/microdroid/Android.bp
@@ -506,7 +506,7 @@
     },
 }
 
-MICRODROID_GKI_ROLLBACK_INDEX = 1
+MICRODROID_GKI_ROLLBACK_INDEX = 2
 
 flag_aware_avb_add_hash_footer_defaults {
     name: "microdroid_kernel_cap_defaults",
diff --git a/guest/pvmfw/avb/tests/utils.rs b/guest/pvmfw/avb/tests/utils.rs
index 38541c5..843cca9 100644
--- a/guest/pvmfw/avb/tests/utils.rs
+++ b/guest/pvmfw/avb/tests/utils.rs
@@ -133,7 +133,9 @@
         initrd_digest,
         public_key: &public_key,
         capabilities,
-        rollback_index: 1,
+        // TODO(b/392081737): Capture expected rollback_index from build variables as we
+        // intend on auto-syncing rollback_index with security patch timestamps
+        rollback_index: 2,
         page_size,
         name: None,
     };
diff --git a/guest/pvmfw/src/arch/aarch64/payload.rs b/guest/pvmfw/src/arch/aarch64/payload.rs
index 3f3ee33..77e9a31 100644
--- a/guest/pvmfw/src/arch/aarch64/payload.rs
+++ b/guest/pvmfw/src/arch/aarch64/payload.rs
@@ -23,13 +23,10 @@
 /// Function boot payload after cleaning all secret from pvmfw memory
 pub fn jump_to_payload(entrypoint: usize, slices: &MemorySlices) -> ! {
     let fdt_address = slices.fdt.as_ptr() as usize;
-    let dice_handover = slices
-        .dice_handover
-        .map(|slice| {
-            let r = slice.as_ptr_range();
-            (r.start as usize)..(r.end as usize)
-        })
-        .expect("Missing DICE handover");
+    let dice_handover = slices.dice_handover.map(|slice| {
+        let r = slice.as_ptr_range();
+        (r.start as usize)..(r.end as usize)
+    });
 
     deactivate_dynamic_page_tables();
 
@@ -50,9 +47,14 @@
     assert_eq!(scratch.start.0 % ASM_STP_ALIGN, 0, "scratch memory is misaligned.");
     assert_eq!(scratch.end.0 % ASM_STP_ALIGN, 0, "scratch memory is misaligned.");
 
-    assert!(dice_handover.is_within(&(scratch.start.0..scratch.end.0)));
-    assert_eq!(dice_handover.start % ASM_STP_ALIGN, 0, "Misaligned guest DICE handover.");
-    assert_eq!(dice_handover.end % ASM_STP_ALIGN, 0, "Misaligned guest DICE handover.");
+    // A sub-region of the scratch memory might contain data for the next stage so skip zeroing it.
+    // Alternatively, an empty region at the start of the scratch region is compatible with the ASM
+    // implementation and results in the whole scratch region being zeroed.
+    let skipped = dice_handover.unwrap_or(scratch.start.0..scratch.start.0);
+
+    assert!(skipped.is_within(&(scratch.start.0..scratch.end.0)));
+    assert_eq!(skipped.start % ASM_STP_ALIGN, 0, "Misaligned skipped region.");
+    assert_eq!(skipped.end % ASM_STP_ALIGN, 0, "Misaligned skipped region.");
 
     let stack = layout::stack_range();
 
@@ -73,27 +75,22 @@
     // SAFETY: We're exiting pvmfw by passing the register values we need to a noreturn asm!().
     unsafe {
         asm!(
-            "cmp {scratch}, {dice_handover}",
-            "b.hs 1f",
-
-            // Zero .data & .bss until DICE handover.
+            // Zero .data & .bss until the start of the skipped region.
+            "b 1f",
             "0: stp xzr, xzr, [{scratch}], 16",
-            "cmp {scratch}, {dice_handover}",
+            "1: cmp {scratch}, {skipped}",
             "b.lo 0b",
 
-            "1:",
-            // Skip DICE handover.
-            "mov {scratch}, {dice_handover_end}",
-            "cmp {scratch}, {scratch_end}",
-            "b.hs 1f",
+            // Skip the skipped region.
+            "mov {scratch}, {skipped_end}",
 
             // Keep zeroing .data & .bss.
+            "b 1f",
             "0: stp xzr, xzr, [{scratch}], 16",
-            "cmp {scratch}, {scratch_end}",
+            "1: cmp {scratch}, {scratch_end}",
             "b.lo 0b",
 
-            "1:",
-            // Flush d-cache over .data & .bss (including DICE handover).
+            // Flush d-cache over .data & .bss (including skipped region).
             "0: dc cvau, {cache_line}",
             "add {cache_line}, {cache_line}, {dcache_line_size}",
             "cmp {cache_line}, {scratch_end}",
@@ -159,8 +156,8 @@
             "dsb nsh",
             "br x30",
             sctlr_el1_val = in(reg) SCTLR_EL1_VAL,
-            dice_handover = in(reg) u64::try_from(dice_handover.start).unwrap(),
-            dice_handover_end = in(reg) u64::try_from(dice_handover.end).unwrap(),
+            skipped = in(reg) u64::try_from(skipped.start).unwrap(),
+            skipped_end = in(reg) u64::try_from(skipped.end).unwrap(),
             cache_line = in(reg) u64::try_from(scratch.start.0).unwrap(),
             scratch = in(reg) u64::try_from(scratch.start.0).unwrap(),
             scratch_end = in(reg) u64::try_from(scratch.end.0).unwrap(),
diff --git a/guest/rialto/Android.bp b/guest/rialto/Android.bp
index 35ede7a..a49f11f 100644
--- a/guest/rialto/Android.bp
+++ b/guest/rialto/Android.bp
@@ -63,8 +63,8 @@
 
 // Both SERVICE_VM_VERSION and SERVICE_VM_VERSION_STRING should represent the
 // same version number for the service VM.
-SERVICE_VM_VERSION = 1
-SERVICE_VM_VERSION_STRING = "1"
+SERVICE_VM_VERSION = 2
+SERVICE_VM_VERSION_STRING = "2"
 
 genrule {
     name: "service_vm_version_rs",
diff --git a/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java b/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
index 4f58cd6..0d13695 100644
--- a/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
+++ b/libs/framework-virtualization/src/android/system/virtualmachine/VirtualMachine.java
@@ -758,7 +758,7 @@
             try {
                 status = stateToStatus(virtualMachine.getState());
             } catch (RemoteException e) {
-                throw e.rethrowAsRuntimeException();
+                status = STATUS_STOPPED;
             }
         }
         if (status == STATUS_STOPPED && !mVmRootPath.exists()) {
@@ -1890,9 +1890,7 @@
                     mVirtualMachine.stop();
                     dropVm();
                 }
-            } catch (RemoteException e) {
-                throw e.rethrowAsRuntimeException();
-            } catch (ServiceSpecificException e) {
+            } catch (RemoteException | ServiceSpecificException e) {
                 // Deliberately ignored; this almost certainly means the VM exited just as
                 // we tried to stop it.
                 Log.i(TAG, "Ignoring error on close()", e);
diff --git a/tests/old_images_avf_test/src/main.rs b/tests/old_images_avf_test/src/main.rs
index 018a80e..b72c706 100644
--- a/tests/old_images_avf_test/src/main.rs
+++ b/tests/old_images_avf_test/src/main.rs
@@ -173,20 +173,6 @@
 }
 
 #[test]
-fn test_run_rialto_protected() -> Result<()> {
-    if hypervisor_props::is_protected_vm_supported()? {
-        run_vm(
-            "/data/local/tmp/rialto.bin", /* image_path */
-            c"test_rialto",               /* test_name */
-            true,                         /* protected_vm */
-        )
-    } else {
-        info!("pVMs are not supported on device. skipping test");
-        Ok(())
-    }
-}
-
-#[test]
 fn test_run_rialto_non_protected() -> Result<()> {
     if hypervisor_props::is_vm_supported()? {
         run_vm(
@@ -201,20 +187,6 @@
 }
 
 #[test]
-fn test_run_android16_rialto_protected() -> Result<()> {
-    if hypervisor_props::is_protected_vm_supported()? {
-        run_vm(
-            "/data/local/tmp/android16_rialto.bin", /* image_path */
-            c"android16_test_rialto",               /* test_name */
-            true,                                   /* protected_vm */
-        )
-    } else {
-        info!("pVMs are not supported on device. skipping test");
-        Ok(())
-    }
-}
-
-#[test]
 fn test_run_android16_rialto_non_protected() -> Result<()> {
     if hypervisor_props::is_vm_supported()? {
         run_vm(