Suppress vdex madvise calls for metadata access

The vdex madvise calls were made to improve app startup. However, vdex
files can also be loaded in other scenarios, like when system_server
queries the dex optimization status for various packages during app
transitions, or during a global dumpsys. Avoid calling madvise in such
situations, as it incurs unnecessary latency/memory overhead.

A follow-up CL will consolidate the different dex and vdex madvise
paths; much of the dex madvise behavior was conditioned on 512MB
Go devices, and is no longer actively used.

Test: Verified madvise only called on app startup, and not from
    deprecated calls to DexFile opt status queries from system_server.
Bug: 195793112
Change-Id: I715af7f34b31f2e9060f3d3d57a2a3171f01187b
diff --git a/runtime/oat_file_manager.cc b/runtime/oat_file_manager.cc
index dfa4518..3449919 100644
--- a/runtime/oat_file_manager.cc
+++ b/runtime/oat_file_manager.cc
@@ -344,6 +344,18 @@
       }
 
       if (oat_file != nullptr) {
+        VdexFile* vdex_file = oat_file->GetVdexFile();
+        if (vdex_file != nullptr) {
+          // Opened vdex file from an oat file, madvise it to its loaded state.
+          // TODO(b/196052575): Unify dex and vdex madvise knobs and behavior.
+          const size_t madvise_size_limit = Runtime::Current()->GetMadviseWillNeedSizeVdex();
+          Runtime::MadviseFileForRange(madvise_size_limit,
+                                       vdex_file->Size(),
+                                       vdex_file->Begin(),
+                                       vdex_file->End(),
+                                       vdex_file->GetName());
+        }
+
         VLOG(class_linker) << "Registering " << oat_file->GetLocation();
         *out_oat_file = RegisterOatFile(std::move(oat_file));
       }
diff --git a/runtime/vdex_file.cc b/runtime/vdex_file.cc
index 58bb357..0afa131 100644
--- a/runtime/vdex_file.cc
+++ b/runtime/vdex_file.cc
@@ -151,20 +151,6 @@
     return nullptr;
   }
 
-  if (!writable) {
-    Runtime* runtime = Runtime::Current();
-    // The runtime might not be available at this point if we're running
-    // dex2oat or oatdump.
-    if (runtime != nullptr) {
-      size_t madvise_size_limit = runtime->GetMadviseWillNeedSizeVdex();
-      Runtime::MadviseFileForRange(madvise_size_limit,
-                                   vdex->Size(),
-                                   vdex->Begin(),
-                                   vdex->End(),
-                                   vdex_filename);
-    }
-  }
-
   return vdex;
 }