Merge "Solve the infinite loop on clearExternalStorageDataSync" into nyc-dev
diff --git a/api/system-current.txt b/api/system-current.txt
index 3a2f29b..8240407 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -169,6 +169,7 @@
     field public static final java.lang.String READ_INSTALL_SESSIONS = "android.permission.READ_INSTALL_SESSIONS";
     field public static final java.lang.String READ_LOGS = "android.permission.READ_LOGS";
     field public static final java.lang.String READ_NETWORK_USAGE_HISTORY = "android.permission.READ_NETWORK_USAGE_HISTORY";
+    field public static final java.lang.String READ_OEM_UNLOCK_STATE = "android.permission.READ_OEM_UNLOCK_STATE";
     field public static final java.lang.String READ_PHONE_STATE = "android.permission.READ_PHONE_STATE";
     field public static final java.lang.String READ_PRIVILEGED_PHONE_STATE = "android.permission.READ_PRIVILEGED_PHONE_STATE";
     field public static final java.lang.String READ_SEARCH_INDEXABLES = "android.permission.READ_SEARCH_INDEXABLES";
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index a5fcec6..13cf46d 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -57,6 +57,7 @@
 import android.media.AudioManager;
 import android.media.session.MediaController;
 import android.net.Uri;
+import android.os.BadParcelableException;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.Handler;
@@ -5006,13 +5007,18 @@
     @Nullable
     public Uri getReferrer() {
         Intent intent = getIntent();
-        Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
-        if (referrer != null) {
-            return referrer;
-        }
-        String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
-        if (referrerName != null) {
-            return Uri.parse(referrerName);
+        try {
+            Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
+            if (referrer != null) {
+                return referrer;
+            }
+            String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
+            if (referrerName != null) {
+                return Uri.parse(referrerName);
+            }
+        } catch (BadParcelableException e) {
+            Log.w(TAG, "Cannot read referrer from intent;"
+                    + " intent extras contain unknown custom Parcelable objects");
         }
         if (mReferrer != null) {
             return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index b220b2e..0728bdf 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -16,6 +16,8 @@
 
 package android.app;
 
+import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.app.assist.AssistContent;
 import android.app.assist.AssistStructure;
 import android.app.backup.BackupAgent;
@@ -1180,8 +1182,11 @@
                 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
                     @Override
                     public void run() {
-                        dumpDatabaseInfo(dup.getFileDescriptor(), args);
-                        IoUtils.closeQuietly(dup);
+                        try {
+                            dumpDatabaseInfo(dup.getFileDescriptor(), args);
+                        } finally {
+                            IoUtils.closeQuietly(dup);
+                        }
                     }
                 });
             } else {
@@ -4575,20 +4580,37 @@
     }
 
     /**
+     * Creates a new Configuration only if override would modify base. Otherwise returns base.
+     * @param base The base configuration.
+     * @param override The update to apply to the base configuration. Can be null.
+     * @return A Configuration representing base with override applied.
+     */
+    private static Configuration createNewConfigAndUpdateIfNotNull(@NonNull Configuration base,
+            @Nullable Configuration override) {
+        if (override == null) {
+            return base;
+        }
+        Configuration newConfig = new Configuration(base);
+        newConfig.updateFrom(override);
+        return newConfig;
+    }
+
+    /**
      * Decides whether to update an Activity's configuration and whether to tell the
      * Activity/Component about it.
      * @param cb The component callback to notify of configuration change.
      * @param activityToken The Activity binder token for which this configuration change happened.
      *                      If the change is global, this is null.
      * @param newConfig The new configuration.
-     * @param overrideConfig The override config that differentiates the Activity's configuration
+     * @param amOverrideConfig The override config that differentiates the Activity's configuration
      *                       from the base global configuration.
+     *                       This is supplied by ActivityManager.
      * @param reportToActivity Notify the Activity of the change.
      */
     private void performConfigurationChanged(ComponentCallbacks2 cb,
                                              IBinder activityToken,
                                              Configuration newConfig,
-                                             Configuration overrideConfig,
+                                             Configuration amOverrideConfig,
                                              boolean reportToActivity) {
         // Only for Activity objects, check that they actually call up to their
         // superclass implementation.  ComponentCallbacks2 is an interface, so
@@ -4602,7 +4624,6 @@
         if ((activity == null) || (activity.mCurrentConfig == null)) {
             shouldChangeConfig = true;
         } else {
-
             // If the new config is the same as the config this Activity
             // is already running with then don't bother calling
             // onConfigurationChanged
@@ -4612,34 +4633,36 @@
             }
         }
 
-        if (DEBUG_CONFIGURATION) {
-            Slog.v(TAG, "Config callback " + cb + ": shouldChangeConfig=" + shouldChangeConfig);
-        }
-
         if (shouldChangeConfig) {
+            // Propagate the configuration change to the Activity and ResourcesManager.
+
+            // ContextThemeWrappers may override the configuration for that context.
+            // We must check and apply any overrides defined.
+            Configuration contextThemeWrapperOverrideConfig = null;
+            if (cb instanceof ContextThemeWrapper) {
+                final ContextThemeWrapper contextThemeWrapper = (ContextThemeWrapper) cb;
+                contextThemeWrapperOverrideConfig = contextThemeWrapper.getOverrideConfiguration();
+            }
+
+            // We only update an Activity's configuration if this is not a global
+            // configuration change. This must also be done before the callback,
+            // or else we violate the contract that the new resources are available
+            // in {@link ComponentCallbacks2#onConfigurationChanged(Configuration)}.
             if (activityToken != null) {
-                // We only update an Activity's configuration if this is not a global
-                // configuration change. This must also be done before the callback,
-                // or else we violate the contract that the new resources are available
-                // in {@link ComponentCallbacks2#onConfigurationChanged(Configuration)}.
-                mResourcesManager.updateResourcesForActivity(activityToken, overrideConfig);
+                // Apply the ContextThemeWrapper override if necessary.
+                // NOTE: Make sure the configurations are not modified, as they are treated
+                // as immutable in many places.
+                final Configuration finalOverrideConfig = createNewConfigAndUpdateIfNotNull(
+                        amOverrideConfig, contextThemeWrapperOverrideConfig);
+                mResourcesManager.updateResourcesForActivity(activityToken, finalOverrideConfig);
             }
 
             if (reportToActivity) {
-                Configuration configToReport = newConfig;
-
-                if (cb instanceof ContextThemeWrapper) {
-                    // ContextThemeWrappers may override the configuration for that context.
-                    // We must check and apply any overrides defined.
-                    ContextThemeWrapper contextThemeWrapper = (ContextThemeWrapper) cb;
-                    final Configuration localOverrideConfig =
-                            contextThemeWrapper.getOverrideConfiguration();
-                    if (localOverrideConfig != null) {
-                        configToReport = new Configuration(newConfig);
-                        configToReport.updateFrom(localOverrideConfig);
-                    }
-                }
-
+                // Apply the ContextThemeWrapper override if necessary.
+                // NOTE: Make sure the configurations are not modified, as they are treated
+                // as immutable in many places.
+                final Configuration configToReport = createNewConfigAndUpdateIfNotNull(
+                        newConfig, contextThemeWrapperOverrideConfig);
                 cb.onConfigurationChanged(configToReport);
             }
 
@@ -5257,7 +5280,7 @@
         // code is loaded to prevent issues with instances of TLS objects being created before
         // the provider is installed.
         Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
-        NetworkSecurityConfigProvider.install(appContext, data.appInfo);
+        NetworkSecurityConfigProvider.install(appContext);
         Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
 
         // Continue loading instrumentation.
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index 87511ee..8cc1bc4 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -1245,15 +1245,18 @@
             return mContext.mMainThread.getSystemContext().getResources();
         }
         final boolean sameUid = (app.uid == Process.myUid());
-        final Resources r = mContext.mMainThread.getTopLevelResources(
-                sameUid ? app.sourceDir : app.publicSourceDir,
-                sameUid ? app.splitSourceDirs : app.splitPublicSourceDirs,
-                app.resourceDirs, app.sharedLibraryFiles, Display.DEFAULT_DISPLAY,
-                mContext.mPackageInfo);
-        if (r != null) {
-            return r;
+        try {
+            return mContext.mMainThread.getTopLevelResources(
+                    sameUid ? app.sourceDir : app.publicSourceDir,
+                    sameUid ? app.splitSourceDirs : app.splitPublicSourceDirs,
+                    app.resourceDirs, app.sharedLibraryFiles, Display.DEFAULT_DISPLAY,
+                    mContext.mPackageInfo);
+        } catch (Resources.NotFoundException cause) {
+            final NameNotFoundException ex =
+                    new NameNotFoundException("Unable to open " + app.publicSourceDir);
+            ex.initCause(cause);
+            throw ex;
         }
-        throw new NameNotFoundException("Unable to open " + app.publicSourceDir);
     }
 
     @Override
diff --git a/core/java/android/app/LoadedApk.java b/core/java/android/app/LoadedApk.java
index 152f45e..0b62ed2 100644
--- a/core/java/android/app/LoadedApk.java
+++ b/core/java/android/app/LoadedApk.java
@@ -1191,14 +1191,18 @@
 
         public void performReceive(Intent intent, int resultCode, String data,
                 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
-            if (ActivityThread.DEBUG_BROADCAST) {
-                int seq = intent.getIntExtra("seq", -1);
-                Slog.i(ActivityThread.TAG, "Enqueueing broadcast " + intent.getAction() + " seq=" + seq
-                        + " to " + mReceiver);
-            }
-            Args args = new Args(intent, resultCode, data, extras, ordered,
+            final Args args = new Args(intent, resultCode, data, extras, ordered,
                     sticky, sendingUser);
-            if (!mActivityThread.post(args)) {
+            if (intent == null) {
+                Log.wtf(TAG, "Null intent received");
+            } else {
+                if (ActivityThread.DEBUG_BROADCAST) {
+                    int seq = intent.getIntExtra("seq", -1);
+                    Slog.i(ActivityThread.TAG, "Enqueueing broadcast " + intent.getAction()
+                            + " seq=" + seq + " to " + mReceiver);
+                }
+            }
+            if (intent == null || !mActivityThread.post(args)) {
                 if (mRegistered && ordered) {
                     IActivityManager mgr = ActivityManagerNative.getDefault();
                     if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
diff --git a/core/java/android/app/ResourcesManager.java b/core/java/android/app/ResourcesManager.java
index 31d254dc..a4688d1 100644
--- a/core/java/android/app/ResourcesManager.java
+++ b/core/java/android/app/ResourcesManager.java
@@ -156,7 +156,7 @@
      * Protected so that tests can override and returns something a fixed value.
      */
     @VisibleForTesting
-    protected DisplayMetrics getDisplayMetrics(int displayId) {
+    protected @NonNull DisplayMetrics getDisplayMetrics(int displayId) {
         DisplayMetrics dm = new DisplayMetrics();
         final Display display =
                 getAdjustedDisplay(displayId, DisplayAdjustments.DEFAULT_DISPLAY_ADJUSTMENTS);
@@ -250,14 +250,14 @@
         // already.
         if (key.mResDir != null) {
             if (assets.addAssetPath(key.mResDir) == 0) {
-                throw new IllegalArgumentException("failed to add asset path " + key.mResDir);
+                throw new Resources.NotFoundException("failed to add asset path " + key.mResDir);
             }
         }
 
         if (key.mSplitResDirs != null) {
             for (final String splitResDir : key.mSplitResDirs) {
                 if (assets.addAssetPath(splitResDir) == 0) {
-                    throw new IllegalArgumentException(
+                    throw new Resources.NotFoundException(
                             "failed to add split asset path " + splitResDir);
                 }
             }
@@ -303,7 +303,7 @@
         return config;
     }
 
-    private ResourcesImpl createResourcesImpl(@NonNull ResourcesKey key) {
+    private @NonNull ResourcesImpl createResourcesImpl(@NonNull ResourcesKey key) {
         AssetManager assets = createAssetManager(key);
         DisplayMetrics dm = getDisplayMetrics(key.mDisplayId);
         Configuration config = generateConfig(key, dm);
@@ -359,7 +359,7 @@
      * Gets an existing Resources object tied to this Activity, or creates one if it doesn't exist
      * or the class loader is different.
      */
-    private Resources getOrCreateResourcesForActivityLocked(@NonNull IBinder activityToken,
+    private @NonNull Resources getOrCreateResourcesForActivityLocked(@NonNull IBinder activityToken,
             @NonNull ClassLoader classLoader, @NonNull ResourcesImpl impl) {
         final ActivityResources activityResources = getOrCreateActivityResourcesStructLocked(
                 activityToken);
@@ -393,7 +393,7 @@
      * Gets an existing Resources object if the class loader and ResourcesImpl are the same,
      * otherwise creates a new Resources object.
      */
-    private Resources getOrCreateResourcesLocked(@NonNull ClassLoader classLoader,
+    private @NonNull Resources getOrCreateResourcesLocked(@NonNull ClassLoader classLoader,
             @NonNull ResourcesImpl impl) {
         // Find an existing Resources that has this ResourcesImpl set.
         final int refCount = mResourceReferences.size();
@@ -441,7 +441,7 @@
      *                    {@link ClassLoader#getSystemClassLoader()} is used.
      * @return a Resources object from which to access resources.
      */
-    public Resources createBaseActivityResources(@NonNull IBinder activityToken,
+    public @NonNull Resources createBaseActivityResources(@NonNull IBinder activityToken,
             @Nullable String resDir,
             @Nullable String[] splitResDirs,
             @Nullable String[] overlayDirs,
@@ -495,7 +495,7 @@
      *         {@link #applyConfigurationToResourcesLocked(Configuration, CompatibilityInfo)}
      *         is called.
      */
-    private Resources getOrCreateResources(@Nullable IBinder activityToken,
+    private @NonNull Resources getOrCreateResources(@Nullable IBinder activityToken,
             @NonNull ResourcesKey key, @NonNull ClassLoader classLoader) {
         synchronized (this) {
             if (DEBUG) {
@@ -603,7 +603,7 @@
      * {@link ClassLoader#getSystemClassLoader()} is used.
      * @return a Resources object from which to access resources.
      */
-    public Resources getResources(@Nullable IBinder activityToken,
+    public @NonNull Resources getResources(@Nullable IBinder activityToken,
             @Nullable String resDir,
             @Nullable String[] splitResDirs,
             @Nullable String[] overlayDirs,
diff --git a/core/java/android/app/WallpaperManager.java b/core/java/android/app/WallpaperManager.java
index 18f93cd..7f467f0 100644
--- a/core/java/android/app/WallpaperManager.java
+++ b/core/java/android/app/WallpaperManager.java
@@ -1576,8 +1576,11 @@
         final String whichProp;
         final int defaultResId;
         if (which == FLAG_LOCK) {
+            /* Factory-default lock wallpapers are not yet supported
             whichProp = PROP_LOCK_WALLPAPER;
             defaultResId = com.android.internal.R.drawable.default_lock_wallpaper;
+            */
+            return null;
         } else {
             whichProp = PROP_WALLPAPER;
             defaultResId = com.android.internal.R.drawable.default_wallpaper;
diff --git a/core/java/android/content/pm/PackageItemInfo.java b/core/java/android/content/pm/PackageItemInfo.java
index 30da03c..bc79f41 100644
--- a/core/java/android/content/pm/PackageItemInfo.java
+++ b/core/java/android/content/pm/PackageItemInfo.java
@@ -29,7 +29,9 @@
 import android.text.TextPaint;
 import android.text.TextUtils;
 import android.util.Printer;
-
+import android.text.BidiFormatter;
+import android.text.TextPaint;
+import android.text.Html;
 import java.text.Collator;
 import java.util.Comparator;
 
@@ -44,7 +46,6 @@
  */
 public class PackageItemInfo {
     private static final float MAX_LABEL_SIZE_PX = 500f;
-
     /**
      * Public name of this item. From the "android:name" attribute.
      */
@@ -145,7 +146,7 @@
         }
         return packageName;
     }
-
+ 
     /**
      * Same as {@link #loadLabel(PackageManager)} with the addition that
      * the returned label is safe for being presented in the UI since it
diff --git a/core/java/android/content/res/Resources.java b/core/java/android/content/res/Resources.java
index 93fe73b..54a5968 100644
--- a/core/java/android/content/res/Resources.java
+++ b/core/java/android/content/res/Resources.java
@@ -126,9 +126,9 @@
      * Returns the most appropriate default theme for the specified target SDK version.
      * <ul>
      * <li>Below API 11: Gingerbread
-     * <li>APIs 11 thru 14: Holo
-     * <li>APIs 14 thru XX: Device default dark
-     * <li>API XX and above: Device default light with dark action bar
+     * <li>APIs 12 thru 14: Holo
+     * <li>APIs 15 thru 23: Device default dark
+     * <li>APIs 24 and above: Device default light with dark action bar
      * </ul>
      *
      * @param curTheme The current theme, or 0 if not specified.
@@ -156,7 +156,7 @@
         if (targetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
             return holo;
         }
-        if (targetSdkVersion < Build.VERSION_CODES.CUR_DEVELOPMENT) {
+        if (targetSdkVersion < Build.VERSION_CODES.N) {
             return dark;
         }
         return deviceDefault;
diff --git a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
index 5743b4d..0cee114 100644
--- a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
@@ -1610,41 +1610,6 @@
     }
 
     public class CameraDeviceCallbacks extends ICameraDeviceCallbacks.Stub {
-        //
-        // Constants below need to be kept up-to-date with
-        // frameworks/av/include/camera/camera2/ICameraDeviceCallbacks.h
-        //
-
-        //
-        // Error codes for onCameraError
-        //
-
-        /**
-         * Camera has been disconnected
-         */
-        public static final int ERROR_CAMERA_DISCONNECTED = 0;
-        /**
-         * Camera has encountered a device-level error
-         * Matches CameraDevice.StateCallback#ERROR_CAMERA_DEVICE
-         */
-        public static final int ERROR_CAMERA_DEVICE = 1;
-        /**
-         * Camera has encountered a service-level error
-         * Matches CameraDevice.StateCallback#ERROR_CAMERA_SERVICE
-         */
-        public static final int ERROR_CAMERA_SERVICE = 2;
-        /**
-         * Camera has encountered an error processing a single request.
-         */
-        public static final int ERROR_CAMERA_REQUEST = 3;
-        /**
-         * Camera has encountered an error producing metadata for a single capture
-         */
-        public static final int ERROR_CAMERA_RESULT = 4;
-        /**
-         * Camera has encountered an error producing an image buffer for a single capture
-         */
-        public static final int ERROR_CAMERA_BUFFER = 5;
 
         @Override
         public IBinder asBinder() {
@@ -1675,11 +1640,14 @@
                     case ERROR_CAMERA_DEVICE:
                     case ERROR_CAMERA_SERVICE:
                         mInError = true;
+                        final int publicErrorCode = (errorCode == ERROR_CAMERA_DEVICE) ?
+                                StateCallback.ERROR_CAMERA_DEVICE :
+                                StateCallback.ERROR_CAMERA_SERVICE;
                         Runnable r = new Runnable() {
                             @Override
                             public void run() {
                                 if (!CameraDeviceImpl.this.isClosed()) {
-                                    mDeviceCallback.onError(CameraDeviceImpl.this, errorCode);
+                                    mDeviceCallback.onError(CameraDeviceImpl.this, publicErrorCode);
                                 }
                             }
                         };
@@ -2050,7 +2018,7 @@
             public void run() {
                 if (!isClosed()) {
                     mDeviceCallback.onError(CameraDeviceImpl.this,
-                            CameraDeviceCallbacks.ERROR_CAMERA_SERVICE);
+                            StateCallback.ERROR_CAMERA_SERVICE);
                 }
             }
         };
diff --git a/core/java/android/hardware/camera2/marshal/MarshalRegistry.java b/core/java/android/hardware/camera2/marshal/MarshalRegistry.java
index ba821e4..1565087 100644
--- a/core/java/android/hardware/camera2/marshal/MarshalRegistry.java
+++ b/core/java/android/hardware/camera2/marshal/MarshalRegistry.java
@@ -37,7 +37,9 @@
      * @param queryable a non-{@code null} marshal queryable that supports marshaling {@code T}
      */
     public static <T> void registerMarshalQueryable(MarshalQueryable<T> queryable) {
-        sRegisteredMarshalQueryables.add(queryable);
+        synchronized(sMarshalLock) {
+            sRegisteredMarshalQueryables.add(queryable);
+        }
     }
 
     /**
@@ -54,47 +56,50 @@
      */
     @SuppressWarnings("unchecked")
     public static <T> Marshaler<T> getMarshaler(TypeReference<T> typeToken, int nativeType) {
-        // TODO: can avoid making a new token each time by code-genning
-        // the list of type tokens and native types from the keys (at the call sites)
-        MarshalToken<T> marshalToken = new MarshalToken<T>(typeToken, nativeType);
+        synchronized(sMarshalLock) {
+            // TODO: can avoid making a new token each time by code-genning
+            // the list of type tokens and native types from the keys (at the call sites)
+            MarshalToken<T> marshalToken = new MarshalToken<T>(typeToken, nativeType);
 
-        /*
-         * Marshalers are instantiated lazily once they are looked up; successive lookups
-         * will not instantiate new marshalers.
-         */
-        Marshaler<T> marshaler =
-                (Marshaler<T>) sMarshalerMap.get(marshalToken);
-
-        if (sRegisteredMarshalQueryables.size() == 0) {
-            throw new AssertionError("No available query marshalers registered");
-        }
-
-        if (marshaler == null) {
-            // Query each marshaler to see if they support the native/managed type combination
-            for (MarshalQueryable<?> potentialMarshaler : sRegisteredMarshalQueryables) {
-
-                MarshalQueryable<T> castedPotential =
-                        (MarshalQueryable<T>)potentialMarshaler;
-
-                if (castedPotential.isTypeMappingSupported(typeToken, nativeType)) {
-                    marshaler = castedPotential.createMarshaler(typeToken, nativeType);
-                    break;
-                }
-            }
+            /*
+             * Marshalers are instantiated lazily once they are looked up; successive lookups
+             * will not instantiate new marshalers.
+             */
+            Marshaler<T> marshaler =
+                    (Marshaler<T>) sMarshalerMap.get(marshalToken);
 
             if (marshaler == null) {
-                throw new UnsupportedOperationException(
+
+                if (sRegisteredMarshalQueryables.size() == 0) {
+                    throw new AssertionError("No available query marshalers registered");
+                }
+
+                // Query each marshaler to see if they support the native/managed type combination
+                for (MarshalQueryable<?> potentialMarshaler : sRegisteredMarshalQueryables) {
+
+                    MarshalQueryable<T> castedPotential =
+                            (MarshalQueryable<T>)potentialMarshaler;
+
+                    if (castedPotential.isTypeMappingSupported(typeToken, nativeType)) {
+                        marshaler = castedPotential.createMarshaler(typeToken, nativeType);
+                        break;
+                    }
+                }
+
+                if (marshaler == null) {
+                    throw new UnsupportedOperationException(
                         "Could not find marshaler that matches the requested " +
-                                "combination of type reference " +
-                                typeToken + " and native type " +
-                                MarshalHelpers.toStringNativeType(nativeType));
+                        "combination of type reference " +
+                        typeToken + " and native type " +
+                        MarshalHelpers.toStringNativeType(nativeType));
+                }
+
+                // Only put when no cached version exists to avoid +0.5ms lookup per call.
+                sMarshalerMap.put(marshalToken, marshaler);
             }
 
-            // Only put when no cached version exists to avoid +0.5ms lookup per call.
-            sMarshalerMap.put(marshalToken, marshaler);
+            return marshaler;
         }
-
-        return marshaler;
     }
 
     private static class MarshalToken<T> {
@@ -125,9 +130,12 @@
         }
     }
 
-    private static List<MarshalQueryable<?>> sRegisteredMarshalQueryables =
+    // Control access to the static data structures below
+    private static final Object sMarshalLock = new Object();
+
+    private static final List<MarshalQueryable<?>> sRegisteredMarshalQueryables =
             new ArrayList<MarshalQueryable<?>>();
-    private static HashMap<MarshalToken<?>, Marshaler<?>> sMarshalerMap =
+    private static final HashMap<MarshalToken<?>, Marshaler<?>> sMarshalerMap =
             new HashMap<MarshalToken<?>, Marshaler<?>>();
 
     private MarshalRegistry() {
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index ea5ae32..f4bf3ea 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -176,7 +176,7 @@
     /**
      * Current version of checkin data format.
      */
-    static final String CHECKIN_VERSION = "17";
+    static final String CHECKIN_VERSION = "18";
 
     /**
      * Old version, we hit 9 and ran out of room, need to remove.
@@ -2371,6 +2371,20 @@
     };
 
     /**
+     * Return the counter keeping track of the amount of battery discharge while the screen was off,
+     * measured in micro-Ampere-hours. This will be non-zero only if the device's battery has
+     * a coulomb counter.
+     */
+    public abstract LongCounter getDischargeScreenOffCoulombCounter();
+
+    /**
+     * Return the counter keeping track of the amount of battery discharge measured in
+     * micro-Ampere-hours. This will be non-zero only if the device's battery has
+     * a coulomb counter.
+     */
+    public abstract LongCounter getDischargeCoulombCounter();
+
+    /**
      * Return the array of discharge step durations.
      */
     public abstract LevelStepTracker getDischargeLevelStepTracker();
@@ -2805,6 +2819,9 @@
                 rawRealtime, which);
         final int connChanges = getNumConnectivityChange(which);
         final long phoneOnTime = getPhoneOnTime(rawRealtime, which);
+        final long dischargeCount = getDischargeCoulombCounter().getCountLocked(which);
+        final long dischargeScreenOffCount = getDischargeScreenOffCoulombCounter()
+                .getCountLocked(which);
 
         final StringBuilder sb = new StringBuilder(128);
         
@@ -2820,6 +2837,7 @@
                 totalRealtime / 1000, totalUptime / 1000,
                 getStartClockTime(),
                 whichBatteryScreenOffRealtime / 1000, whichBatteryScreenOffUptime / 1000);
+
         
         // Calculate wakelock times across all uids.
         long fullWakeLockTimeTotal = 0;
@@ -2969,12 +2987,14 @@
             dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA,
                     getDischargeStartLevel()-getDischargeCurrentLevel(),
                     getDischargeStartLevel()-getDischargeCurrentLevel(),
-                    getDischargeAmountScreenOn(), getDischargeAmountScreenOff());
+                    getDischargeAmountScreenOn(), getDischargeAmountScreenOff(),
+                    dischargeCount / 1000, dischargeScreenOffCount / 1000);
         } else {
             dumpLine(pw, 0 /* uid */, category, BATTERY_DISCHARGE_DATA,
                     getLowDischargeAmountSinceCharge(), getHighDischargeAmountSinceCharge(),
                     getDischargeAmountScreenOnSinceCharge(),
-                    getDischargeAmountScreenOffSinceCharge());
+                    getDischargeAmountScreenOffSinceCharge(),
+                    dischargeCount / 1000, dischargeScreenOffCount / 1000);
         }
         
         if (reqUid < 0) {
@@ -3371,6 +3391,39 @@
                     formatTimeMs(sb, chargeTimeRemaining / 1000);
             pw.println(sb.toString());
         }
+
+        final LongCounter dischargeCounter = getDischargeCoulombCounter();
+        final long dischargeCount = dischargeCounter.getCountLocked(which);
+        if (dischargeCount >= 0) {
+            sb.setLength(0);
+            sb.append(prefix);
+                sb.append("  Discharge: ");
+                sb.append(BatteryStatsHelper.makemAh(dischargeCount / 1000.0));
+                sb.append(" mAh");
+            pw.println(sb.toString());
+        }
+
+        final LongCounter dischargeScreenOffCounter = getDischargeScreenOffCoulombCounter();
+        final long dischargeScreenOffCount = dischargeScreenOffCounter.getCountLocked(which);
+        if (dischargeScreenOffCount >= 0) {
+            sb.setLength(0);
+            sb.append(prefix);
+                sb.append("  Screen off discharge: ");
+                sb.append(BatteryStatsHelper.makemAh(dischargeScreenOffCount / 1000.0));
+                sb.append(" mAh");
+            pw.println(sb.toString());
+        }
+
+        final long dischargeScreenOnCount = dischargeCount - dischargeScreenOffCount;
+        if (dischargeScreenOnCount >= 0) {
+            sb.setLength(0);
+            sb.append(prefix);
+                sb.append("  Screen on discharge: ");
+                sb.append(BatteryStatsHelper.makemAh(dischargeScreenOnCount / 1000.0));
+                sb.append(" mAh");
+            pw.println(sb.toString());
+        }
+
         pw.print("  Start clock time: ");
         pw.println(DateFormat.format("yyyy-MM-dd-HH-mm-ss", getStartClockTime()).toString());
 
diff --git a/core/java/android/os/RecoverySystem.java b/core/java/android/os/RecoverySystem.java
index 4abbf0e..7ff01da 100644
--- a/core/java/android/os/RecoverySystem.java
+++ b/core/java/android/os/RecoverySystem.java
@@ -687,13 +687,15 @@
         }
     }
 
-    // Read last_install; then report time for update and I/O to tron.
+    // Read last_install; then report time (in seconds) and I/O (in MiB) for
+    // this update to tron.
     // Only report on the reboots immediately after an OTA update.
     private static void parseLastInstallLog(Context context) {
         try (BufferedReader in = new BufferedReader(new FileReader(LAST_INSTALL_FILE))) {
             String line = null;
-            int bytesWritten = -1, bytesStashed = -1;
+            int bytesWrittenInMiB = -1, bytesStashedInMiB = -1;
             int timeTotal = -1;
+            int sourceVersion = -1;
             while ((line = in.readLine()) != null) {
                 // Here is an example of lines in last_install:
                 // ...
@@ -705,20 +707,37 @@
                     continue;
                 }
                 String numString = line.substring(numIndex + 1).trim();
-                int parsedNum;
+                long parsedNum;
                 try {
-                    parsedNum = Integer.parseInt(numString);
+                    parsedNum = Long.parseLong(numString);
                 } catch (NumberFormatException ignored) {
                     Log.e(TAG, "Failed to parse numbers in " + line);
                     continue;
                 }
 
+                final int MiB = 1024 * 1024;
+                int scaled;
+                try {
+                    if (line.startsWith("bytes")) {
+                        scaled = Math.toIntExact(parsedNum / MiB);
+                    } else {
+                        scaled = Math.toIntExact(parsedNum);
+                    }
+                } catch (ArithmeticException ignored) {
+                    Log.e(TAG, "Number overflows in " + line);
+                    continue;
+                }
+
                 if (line.startsWith("time")) {
-                    timeTotal = parsedNum;
+                    timeTotal = scaled;
+                } else if (line.startsWith("source_version")) {
+                    sourceVersion = scaled;
                 } else if (line.startsWith("bytes_written")) {
-                    bytesWritten = (bytesWritten == -1) ? parsedNum : bytesWritten + parsedNum;
+                    bytesWrittenInMiB = (bytesWrittenInMiB == -1) ? scaled :
+                            bytesWrittenInMiB + scaled;
                 } else if (line.startsWith("bytes_stashed")) {
-                    bytesStashed = (bytesStashed == -1) ? parsedNum : bytesStashed + parsedNum;
+                    bytesStashedInMiB = (bytesStashedInMiB == -1) ? scaled :
+                            bytesStashedInMiB + scaled;
                 }
             }
 
@@ -726,15 +745,18 @@
             if (timeTotal != -1) {
                 MetricsLogger.histogram(context, "ota_time_total", timeTotal);
             }
-            if (bytesWritten != -1) {
-                MetricsLogger.histogram(context, "ota_bytes_written", bytesWritten);
+            if (sourceVersion != -1) {
+                MetricsLogger.histogram(context, "ota_source_version", sourceVersion);
             }
-            if (bytesStashed != -1) {
-                MetricsLogger.histogram(context, "ota_bytes_stashed", bytesStashed);
+            if (bytesWrittenInMiB != -1) {
+                MetricsLogger.histogram(context, "ota_written_in_MiBs", bytesWrittenInMiB);
+            }
+            if (bytesStashedInMiB != -1) {
+                MetricsLogger.histogram(context, "ota_stashed_in_MiBs", bytesStashedInMiB);
             }
 
-        } catch (IOException ignored) {
-            Log.e(TAG, "Failed to read lines in last_install", ignored);
+        } catch (IOException e) {
+            Log.e(TAG, "Failed to read lines in last_install", e);
         }
     }
 
diff --git a/core/java/android/security/net/config/ManifestConfigSource.java b/core/java/android/security/net/config/ManifestConfigSource.java
index d59b5e3..92bddb7 100644
--- a/core/java/android/security/net/config/ManifestConfigSource.java
+++ b/core/java/android/security/net/config/ManifestConfigSource.java
@@ -29,13 +29,19 @@
 
     private final Object mLock = new Object();
     private final Context mContext;
-    private final ApplicationInfo mInfo;
+    private final int mApplicationInfoFlags;
+    private final int mTargetSdkVersion;
+    private final int mConfigResourceId;
 
     private ConfigSource mConfigSource;
 
-    public ManifestConfigSource(Context context, ApplicationInfo info) {
+    public ManifestConfigSource(Context context) {
         mContext = context;
-        mInfo = info;
+        // Cache values because ApplicationInfo is mutable and apps do modify it :(
+        ApplicationInfo info = context.getApplicationInfo();
+        mApplicationInfoFlags = info.flags;
+        mTargetSdkVersion = info.targetSdkVersion;
+        mConfigResourceId = info.networkSecurityConfigRes;
     }
 
     @Override
@@ -53,29 +59,24 @@
             if (mConfigSource != null) {
                 return mConfigSource;
             }
-            int targetSdkVersion = mInfo.targetSdkVersion;
-            int configResourceId = 0;
-            if (mInfo != null) {
-                configResourceId = mInfo.networkSecurityConfigRes;
-            }
 
             ConfigSource source;
-            if (configResourceId != 0) {
-                boolean debugBuild = (mInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
+            if (mConfigResourceId != 0) {
+                boolean debugBuild = (mApplicationInfoFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
                 if (DBG) {
                     Log.d(LOG_TAG, "Using Network Security Config from resource "
-                            + mContext.getResources().getResourceEntryName(configResourceId)
+                            + mContext.getResources().getResourceEntryName(mConfigResourceId)
                             + " debugBuild: " + debugBuild);
                 }
-                source = new XmlConfigSource(mContext, configResourceId, debugBuild,
-                        targetSdkVersion);
+                source = new XmlConfigSource(mContext, mConfigResourceId, debugBuild,
+                        mTargetSdkVersion);
             } else {
                 if (DBG) {
                     Log.d(LOG_TAG, "No Network Security Config specified, using platform default");
                 }
                 boolean usesCleartextTraffic =
-                        (mInfo.flags & ApplicationInfo.FLAG_USES_CLEARTEXT_TRAFFIC) != 0;
-                source = new DefaultConfigSource(usesCleartextTraffic, targetSdkVersion);
+                        (mApplicationInfoFlags & ApplicationInfo.FLAG_USES_CLEARTEXT_TRAFFIC) != 0;
+                source = new DefaultConfigSource(usesCleartextTraffic, mTargetSdkVersion);
             }
             mConfigSource = source;
             return mConfigSource;
diff --git a/core/java/android/security/net/config/NetworkSecurityConfigProvider.java b/core/java/android/security/net/config/NetworkSecurityConfigProvider.java
index 4c51cc3..0f66873 100644
--- a/core/java/android/security/net/config/NetworkSecurityConfigProvider.java
+++ b/core/java/android/security/net/config/NetworkSecurityConfigProvider.java
@@ -17,7 +17,6 @@
 package android.security.net.config;
 
 import android.content.Context;
-import android.content.pm.ApplicationInfo;
 import java.security.Security;
 import java.security.Provider;
 
@@ -33,8 +32,8 @@
         put("Alg.Alias.TrustManagerFactory.X509", "PKIX");
     }
 
-    public static void install(Context context, ApplicationInfo info) {
-        ApplicationConfig config = new ApplicationConfig(new ManifestConfigSource(context, info));
+    public static void install(Context context) {
+        ApplicationConfig config = new ApplicationConfig(new ManifestConfigSource(context));
         ApplicationConfig.setDefaultInstance(config);
         int pos = Security.insertProviderAt(new NetworkSecurityConfigProvider(), 1);
         if (pos != 1) {
diff --git a/core/java/android/view/SurfaceControl.java b/core/java/android/view/SurfaceControl.java
index b4131b4..415e70c 100644
--- a/core/java/android/view/SurfaceControl.java
+++ b/core/java/android/view/SurfaceControl.java
@@ -51,6 +51,7 @@
 
     private static native void nativeSetLayer(long nativeObject, int zorder);
     private static native void nativeSetPosition(long nativeObject, float x, float y);
+    private static native void nativeSetPositionAppliesWithResize(long nativeObject);
     private static native void nativeSetSize(long nativeObject, int w, int h);
     private static native void nativeSetTransparentRegionHint(long nativeObject, Region region);
     private static native void nativeSetAlpha(long nativeObject, float alpha);
@@ -407,6 +408,16 @@
         nativeSetPosition(mNativeObject, x, y);
     }
 
+    /**
+     * If the size changes in this transaction, position updates specified
+     * in this transaction will not complete until a buffer of the new size
+     * arrives.
+     */
+    public void setPositionAppliesWithResize() {
+        checkNotReleased();
+        nativeSetPositionAppliesWithResize(mNativeObject);
+    }
+
     public void setSize(int w, int h) {
         checkNotReleased();
         nativeSetSize(mNativeObject, w, h);
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 4742818..19b1cf3 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -1938,7 +1938,7 @@
                 mSurfaceHolder.setSurfaceFrameSize(mWidth, mHeight);
                 mSurfaceHolder.mSurfaceLock.unlock();
                 if (mSurface.isValid()) {
-                    if (!hadSurface || surfaceGenerationId != mSurface.getGenerationId()) {
+                    if (!hadSurface) {
                         mSurfaceHolder.ungetCallbacks();
 
                         mIsCreating = true;
@@ -1951,7 +1951,7 @@
                         }
                         surfaceChanged = true;
                     }
-                    if (surfaceChanged) {
+                    if (surfaceChanged || surfaceGenerationId != mSurface.getGenerationId()) {
                         mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
                                 lp.format, mWidth, mHeight);
                         SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
diff --git a/core/java/android/view/accessibility/AccessibilityWindowInfo.java b/core/java/android/view/accessibility/AccessibilityWindowInfo.java
index d0d4507..52f35de 100644
--- a/core/java/android/view/accessibility/AccessibilityWindowInfo.java
+++ b/core/java/android/view/accessibility/AccessibilityWindowInfo.java
@@ -16,6 +16,7 @@
 
 package android.view.accessibility;
 
+import android.annotation.Nullable;
 import android.graphics.Rect;
 import android.os.Parcel;
 import android.os.Parcelable;
@@ -101,8 +102,9 @@
     /**
      * Gets the title of the window.
      *
-     * @return The title.
+     * @return The title of the window, or {@code null} if none is available.
      */
+    @Nullable
     public CharSequence getTitle() {
         return mTitle;
     }
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 8b02352..07d38d7 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -108,7 +108,7 @@
     private static final int MAGIC = 0xBA757475; // 'BATSTATS'
 
     // Current on-disk Parcel version
-    private static final int VERSION = 144 + (USE_OLD_HISTORY ? 1000 : 0);
+    private static final int VERSION = 146 + (USE_OLD_HISTORY ? 1000 : 0);
 
     // Maximum number of items we will record in the history.
     private static final int MAX_HISTORY_ITEMS = 2000;
@@ -509,6 +509,9 @@
     int mDischargeAmountScreenOff;
     int mDischargeAmountScreenOffSinceCharge;
 
+    private LongSamplingCounter mDischargeScreenOffCounter;
+    private LongSamplingCounter mDischargeCounter;
+
     static final int MAX_LEVEL_STEPS = 200;
 
     int mInitStepMode = 0;
@@ -565,6 +568,16 @@
         return mWakeupReasonStats;
     }
 
+    @Override
+    public LongCounter getDischargeScreenOffCoulombCounter() {
+        return mDischargeScreenOffCounter;
+    }
+
+    @Override
+    public LongCounter getDischargeCoulombCounter() {
+        return mDischargeCounter;
+    }
+
     public BatteryStatsImpl() {
         this(new SystemClocks());
     }
@@ -912,7 +925,6 @@
         final TimeBase mTimeBase;
         long mCount;
         long mLoadedCount;
-        long mLastCount;
         long mUnpluggedCount;
         long mPluggedCount;
 
@@ -921,7 +933,6 @@
             mPluggedCount = in.readLong();
             mCount = mPluggedCount;
             mLoadedCount = in.readLong();
-            mLastCount = 0;
             mUnpluggedCount = in.readLong();
             timeBase.add(this);
         }
@@ -949,20 +960,19 @@
         }
 
         public long getCountLocked(int which) {
-            long val = mCount;
+            long val = mTimeBase.isRunning() ? mCount : mPluggedCount;
             if (which == STATS_SINCE_UNPLUGGED) {
                 val -= mUnpluggedCount;
             } else if (which != STATS_SINCE_CHARGED) {
                 val -= mLoadedCount;
             }
-
             return val;
         }
 
         @Override
         public void logState(Printer pw, String prefix) {
             pw.println(prefix + "mCount=" + mCount
-                    + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
+                    + " mLoadedCount=" + mLoadedCount
                     + " mUnpluggedCount=" + mUnpluggedCount
                     + " mPluggedCount=" + mPluggedCount);
         }
@@ -976,7 +986,7 @@
          */
         void reset(boolean detachIfReset) {
             mCount = 0;
-            mLoadedCount = mLastCount = mPluggedCount = mUnpluggedCount = 0;
+            mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
             if (detachIfReset) {
                 detach();
             }
@@ -993,7 +1003,6 @@
         void readSummaryFromParcelLocked(Parcel in) {
             mLoadedCount = in.readLong();
             mCount = mLoadedCount;
-            mLastCount = 0;
             mUnpluggedCount = mPluggedCount = mLoadedCount;
         }
     }
@@ -7566,6 +7575,8 @@
         mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
         mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
         mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
+        mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
+        mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
         mOnBattery = mOnBatteryInternal = false;
         long uptime = mClocks.uptimeMillis() * 1000;
         long realtime = mClocks.elapsedRealtime() * 1000;
@@ -8123,6 +8134,8 @@
         mDischargeAmountScreenOffSinceCharge = 0;
         mDischargeStepTracker.init();
         mChargeStepTracker.init();
+        mDischargeScreenOffCounter.reset(false);
+        mDischargeCounter.reset(false);
     }
 
     public void resetAllStatsCmdLocked() {
@@ -9327,6 +9340,7 @@
             mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
             mHistoryCur.batteryStatus = (byte)status;
             mHistoryCur.batteryLevel = (byte)level;
+            mHistoryCur.batteryChargeUAh = chargeUAh;
             mMaxChargeStepLevel = mMinDischargeStepLevel =
                     mLastChargeStepLevel = mLastDischargeStepLevel = level;
             mLastChargingStateLevel = level;
@@ -9358,6 +9372,12 @@
             mHistoryCur.batteryPlugType = (byte)plugType;
             mHistoryCur.batteryTemperature = (short)temp;
             mHistoryCur.batteryVoltage = (char)volt;
+            if (chargeUAh < mHistoryCur.batteryChargeUAh) {
+                // Only record discharges
+                final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
+                mDischargeCounter.addCountLocked(chargeDiff);
+                mDischargeScreenOffCounter.addCountLocked(chargeDiff);
+            }
             mHistoryCur.batteryChargeUAh = chargeUAh;
             setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level);
         } else {
@@ -9394,6 +9414,12 @@
             }
             if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
                     || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
+                if (chargeUAh < mHistoryCur.batteryChargeUAh) {
+                    // Only record discharges
+                    final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
+                    mDischargeCounter.addCountLocked(chargeDiff);
+                    mDischargeScreenOffCounter.addCountLocked(chargeDiff);
+                }
                 mHistoryCur.batteryChargeUAh = chargeUAh;
                 changed = true;
             }
@@ -10075,6 +10101,8 @@
         mChargeStepTracker.readFromParcel(in);
         mDailyDischargeStepTracker.readFromParcel(in);
         mDailyChargeStepTracker.readFromParcel(in);
+        mDischargeCounter.readSummaryFromParcelLocked(in);
+        mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
         int NPKG = in.readInt();
         if (NPKG > 0) {
             mDailyPackageChanges = new ArrayList<>(NPKG);
@@ -10425,6 +10453,8 @@
         mChargeStepTracker.writeToParcel(out);
         mDailyDischargeStepTracker.writeToParcel(out);
         mDailyChargeStepTracker.writeToParcel(out);
+        mDischargeCounter.writeSummaryFromParcelLocked(out);
+        mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
         if (mDailyPackageChanges != null) {
             final int NPKG = mDailyPackageChanges.size();
             out.writeInt(NPKG);
@@ -10880,6 +10910,8 @@
         mDischargeAmountScreenOffSinceCharge = in.readInt();
         mDischargeStepTracker.readFromParcel(in);
         mChargeStepTracker.readFromParcel(in);
+        mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
+        mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
         mLastWriteTime = in.readLong();
 
         mKernelWakelockStats.clear();
@@ -11028,6 +11060,8 @@
         out.writeInt(mDischargeAmountScreenOffSinceCharge);
         mDischargeStepTracker.writeToParcel(out);
         mChargeStepTracker.writeToParcel(out);
+        mDischargeCounter.writeToParcel(out);
+        mDischargeScreenOffCounter.writeToParcel(out);
         out.writeLong(mLastWriteTime);
 
         if (inclUids) {
diff --git a/core/java/com/android/internal/os/KernelUidCpuTimeReader.java b/core/java/com/android/internal/os/KernelUidCpuTimeReader.java
index 5d3043c..c828d11 100644
--- a/core/java/com/android/internal/os/KernelUidCpuTimeReader.java
+++ b/core/java/com/android/internal/os/KernelUidCpuTimeReader.java
@@ -84,7 +84,8 @@
                     powerMaUs = 0;
                 }
 
-                if (callback != null) {
+                // Only report if there is a callback and if this is not the first read.
+                if (callback != null && mLastTimeReadUs != 0) {
                     long userTimeDeltaUs = userTimeUs;
                     long systemTimeDeltaUs = systemTimeUs;
                     long powerDeltaMaUs = powerMaUs;
diff --git a/core/java/com/android/internal/policy/PhoneWindow.java b/core/java/com/android/internal/policy/PhoneWindow.java
index 18408aa..9ad750d 100644
--- a/core/java/com/android/internal/policy/PhoneWindow.java
+++ b/core/java/com/android/internal/policy/PhoneWindow.java
@@ -528,16 +528,22 @@
 
     @Override
     public void setTitle(CharSequence title) {
+        setTitle(title, true);
+    }
+
+    public void setTitle(CharSequence title, boolean updateAccessibilityTitle) {
         if (mTitleView != null) {
             mTitleView.setText(title);
         } else if (mDecorContentParent != null) {
             mDecorContentParent.setWindowTitle(title);
         }
         mTitle = title;
-        WindowManager.LayoutParams params = getAttributes();
-        if (!TextUtils.equals(title, params.accessibilityTitle)) {
-            params.accessibilityTitle = TextUtils.stringOrSpannedString(title);
-            dispatchWindowAttributesChanged(getAttributes());
+        if (updateAccessibilityTitle) {
+            WindowManager.LayoutParams params = getAttributes();
+            if (!TextUtils.equals(title, params.accessibilityTitle)) {
+                params.accessibilityTitle = TextUtils.stringOrSpannedString(title);
+                dispatchWindowAttributesChanged(getAttributes());
+            }
         }
     }
 
diff --git a/core/jni/android_view_SurfaceControl.cpp b/core/jni/android_view_SurfaceControl.cpp
index a9ed9dc..ff75677 100644
--- a/core/jni/android_view_SurfaceControl.cpp
+++ b/core/jni/android_view_SurfaceControl.cpp
@@ -248,6 +248,15 @@
     }
 }
 
+static void nativeSetPositionAppliesWithResize(JNIEnv* env, jclass clazz,
+        jlong nativeObject) {
+    SurfaceControl* const ctrl = reinterpret_cast<SurfaceControl *>(nativeObject);
+    status_t err = ctrl->setPositionAppliesWithResize();
+    if (err < 0 && err != NO_INIT) {
+        doThrowIAE(env);
+    }
+}
+
 static void nativeSetSize(JNIEnv* env, jclass clazz, jlong nativeObject, jint w, jint h) {
     SurfaceControl* const ctrl = reinterpret_cast<SurfaceControl *>(nativeObject);
     status_t err = ctrl->setSize(w, h);
@@ -658,6 +667,8 @@
             (void*)nativeSetLayer },
     {"nativeSetPosition", "(JFF)V",
             (void*)nativeSetPosition },
+    {"nativeSetPositionAppliesWithResize", "(J)V",
+            (void*)nativeSetPositionAppliesWithResize },
     {"nativeSetSize", "(JII)V",
             (void*)nativeSetSize },
     {"nativeSetTransparentRegionHint", "(JLandroid/graphics/Region;)V",
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 6c289dc..2ef1fcf 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -360,6 +360,7 @@
     <!-- Added in N -->
     <protected-broadcast android:name="android.intent.action.ANR" />
     <protected-broadcast android:name="android.intent.action.CALL" />
+    <protected-broadcast android:name="android.intent.action.CALL_PRIVILEGED" />
     <protected-broadcast android:name="android.intent.action.DROPBOX_ENTRY_ADDED" />
     <protected-broadcast android:name="android.intent.action.INPUT_METHOD_CHANGED" />
     <protected-broadcast android:name="android.intent.action.internal_sim_state_changed" />
@@ -1416,6 +1417,11 @@
     <permission android:name="android.permission.DVB_DEVICE"
         android:protectionLevel="signature|privileged" />
 
+    <!-- @SystemApi Allows reading the OEM unlock state
+         @hide <p>Not for use by third-party applications. -->
+    <permission android:name="android.permission.READ_OEM_UNLOCK_STATE"
+        android:protectionLevel="signature|privileged" />
+
     <!-- @hide Allows enabling/disabling OEM unlock
    <p>Not for use by third-party applications. -->
     <permission android:name="android.permission.OEM_UNLOCK_STATE"
@@ -1616,6 +1622,14 @@
     <permission android:name="android.permission.MANAGE_USERS"
         android:protectionLevel="signature|privileged" />
 
+    <!-- @hide Allows an application to create, remove users and get the list of
+         users on the device. Applications holding this permission can only create restricted,
+         guest, managed, and ephemeral users. For creating other kind of users,
+         {@link android.Manifest.permission#MANAGE_USERS} is needed.
+         This permission is not available to third party applications. -->
+    <permission android:name="android.permission.CREATE_USERS"
+        android:protectionLevel="signature" />
+
     <!-- @hide Allows an application to set the profile owners and the device owner.
          This permission is not available to third party applications.-->
     <permission android:name="android.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS"
diff --git a/core/res/res/values-az-rAZ/strings.xml b/core/res/res/values-az-rAZ/strings.xml
index aa84ed0a..17712b0 100644
--- a/core/res/res/values-az-rAZ/strings.xml
+++ b/core/res/res/values-az-rAZ/strings.xml
@@ -860,32 +860,32 @@
     </plurals>
     <string name="now_string_shortest" msgid="8912796667087856402">"indi"</string>
     <plurals name="duration_minutes_shortest" formatted="false" msgid="3957499975064245495">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>dəq</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>dəq</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>d</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>d</item>
     </plurals>
     <plurals name="duration_hours_shortest" formatted="false" msgid="3552182110578602356">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>saat</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>saat</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>st</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>st</item>
     </plurals>
     <plurals name="duration_days_shortest" formatted="false" msgid="5213655532597081640">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>gün</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>gün</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>g</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>g</item>
     </plurals>
     <plurals name="duration_years_shortest" formatted="false" msgid="7848711145196397042">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>il</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>il</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>i</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>i</item>
     </plurals>
     <plurals name="duration_minutes_shortest_future" formatted="false" msgid="3277614521231489951">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>dəqiqədə</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>dəqiqədə</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>d-də</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>d-də</item>
     </plurals>
     <plurals name="duration_hours_shortest_future" formatted="false" msgid="2152452368397489370">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>saata</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>saata</item>
+      <item quantity="other"> <xliff:g id="COUNT_1">%d</xliff:g>s-da</item>
+      <item quantity="one"> <xliff:g id="COUNT_0">%d</xliff:g>s-da</item>
     </plurals>
     <plurals name="duration_days_shortest_future" formatted="false" msgid="8088331502820295701">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>gündə</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>gündə</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>g-də</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g>g-də</item>
     </plurals>
     <plurals name="duration_years_shortest_future" formatted="false" msgid="2317006667145250301">
       <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g>ildə</item>
diff --git a/core/res/res/values-de/strings.xml b/core/res/res/values-de/strings.xml
index 92541f2..616d2b8 100644
--- a/core/res/res/values-de/strings.xml
+++ b/core/res/res/values-de/strings.xml
@@ -860,20 +860,20 @@
     </plurals>
     <string name="now_string_shortest" msgid="8912796667087856402">"jetzt"</string>
     <plurals name="duration_minutes_shortest" formatted="false" msgid="3957499975064245495">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> min</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> min</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> min</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> min</item>
     </plurals>
     <plurals name="duration_hours_shortest" formatted="false" msgid="3552182110578602356">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> h</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> h</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> h</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> h</item>
     </plurals>
     <plurals name="duration_days_shortest" formatted="false" msgid="5213655532597081640">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> d</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> d</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> T.</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> T.</item>
     </plurals>
     <plurals name="duration_years_shortest" formatted="false" msgid="7848711145196397042">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> a</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> a</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> J.</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> J.</item>
     </plurals>
     <plurals name="duration_minutes_shortest_future" formatted="false" msgid="3277614521231489951">
       <item quantity="other">in <xliff:g id="COUNT_1">%d</xliff:g> min</item>
@@ -884,12 +884,12 @@
       <item quantity="one">in <xliff:g id="COUNT_0">%d</xliff:g> h</item>
     </plurals>
     <plurals name="duration_days_shortest_future" formatted="false" msgid="8088331502820295701">
-      <item quantity="other">in <xliff:g id="COUNT_1">%d</xliff:g> d</item>
-      <item quantity="one">in <xliff:g id="COUNT_0">%d</xliff:g> d</item>
+      <item quantity="other">in <xliff:g id="COUNT_1">%d</xliff:g> T.</item>
+      <item quantity="one">in <xliff:g id="COUNT_0">%d</xliff:g> T.</item>
     </plurals>
     <plurals name="duration_years_shortest_future" formatted="false" msgid="2317006667145250301">
-      <item quantity="other">in <xliff:g id="COUNT_1">%d</xliff:g> a</item>
-      <item quantity="one">in <xliff:g id="COUNT_0">%d</xliff:g> a</item>
+      <item quantity="other">in <xliff:g id="COUNT_1">%d</xliff:g> J.</item>
+      <item quantity="one">in <xliff:g id="COUNT_0">%d</xliff:g> J.</item>
     </plurals>
     <plurals name="duration_minutes_relative" formatted="false" msgid="3178131706192980192">
       <item quantity="other">vor <xliff:g id="COUNT_1">%d</xliff:g> Minuten</item>
diff --git a/core/res/res/values-es-rUS/strings.xml b/core/res/res/values-es-rUS/strings.xml
index 393b8ff..2f76a33 100644
--- a/core/res/res/values-es-rUS/strings.xml
+++ b/core/res/res/values-es-rUS/strings.xml
@@ -868,12 +868,12 @@
       <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> h</item>
     </plurals>
     <plurals name="duration_days_shortest" formatted="false" msgid="5213655532597081640">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> días</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> día</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> d</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> d</item>
     </plurals>
     <plurals name="duration_years_shortest" formatted="false" msgid="7848711145196397042">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> años</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> año</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> a</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> a</item>
     </plurals>
     <plurals name="duration_minutes_shortest_future" formatted="false" msgid="3277614521231489951">
       <item quantity="other">en <xliff:g id="COUNT_1">%d</xliff:g> min</item>
@@ -884,8 +884,8 @@
       <item quantity="one">en <xliff:g id="COUNT_0">%d</xliff:g> h</item>
     </plurals>
     <plurals name="duration_days_shortest_future" formatted="false" msgid="8088331502820295701">
-      <item quantity="other">en <xliff:g id="COUNT_1">%d</xliff:g> días</item>
-      <item quantity="one">en <xliff:g id="COUNT_0">%d</xliff:g> día</item>
+      <item quantity="other">en <xliff:g id="COUNT_1">%d</xliff:g> d</item>
+      <item quantity="one">en <xliff:g id="COUNT_0">%d</xliff:g> d</item>
     </plurals>
     <plurals name="duration_years_shortest_future" formatted="false" msgid="2317006667145250301">
       <item quantity="other">en <xliff:g id="COUNT_1">%d</xliff:g> años</item>
diff --git a/core/res/res/values-gl-rES/strings.xml b/core/res/res/values-gl-rES/strings.xml
index 0626546..fcccc55 100644
--- a/core/res/res/values-gl-rES/strings.xml
+++ b/core/res/res/values-gl-rES/strings.xml
@@ -860,8 +860,8 @@
     </plurals>
     <string name="now_string_shortest" msgid="8912796667087856402">"agora"</string>
     <plurals name="duration_minutes_shortest" formatted="false" msgid="3957499975064245495">
-      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> min</item>
-      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> min</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> m</item>
+      <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> m</item>
     </plurals>
     <plurals name="duration_hours_shortest" formatted="false" msgid="3552182110578602356">
       <item quantity="other"><xliff:g id="COUNT_1">%d</xliff:g> h</item>
@@ -876,8 +876,8 @@
       <item quantity="one"><xliff:g id="COUNT_0">%d</xliff:g> a</item>
     </plurals>
     <plurals name="duration_minutes_shortest_future" formatted="false" msgid="3277614521231489951">
-      <item quantity="other">en <xliff:g id="COUNT_1">%d</xliff:g> min</item>
-      <item quantity="one">en <xliff:g id="COUNT_0">%d</xliff:g> min</item>
+      <item quantity="other">en <xliff:g id="COUNT_1">%d</xliff:g> m</item>
+      <item quantity="one">en <xliff:g id="COUNT_0">%d</xliff:g> m</item>
     </plurals>
     <plurals name="duration_hours_shortest_future" formatted="false" msgid="2152452368397489370">
       <item quantity="other">en <xliff:g id="COUNT_1">%d</xliff:g> h</item>
diff --git a/core/res/res/values-hy-rAM/strings.xml b/core/res/res/values-hy-rAM/strings.xml
index 993cd7e..ee89493 100644
--- a/core/res/res/values-hy-rAM/strings.xml
+++ b/core/res/res/values-hy-rAM/strings.xml
@@ -21,7 +21,7 @@
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
     <string name="byteShort" msgid="8340973892742019101">"Բ"</string>
-    <string name="kilobyteShort" msgid="5973789783504771878">"ԿԲ"</string>
+    <string name="kilobyteShort" msgid="5973789783504771878">"կԲ"</string>
     <string name="megabyteShort" msgid="6355851576770428922">"ՄԲ"</string>
     <string name="gigabyteShort" msgid="3259882455212193214">"ԳԲ"</string>
     <string name="terabyteShort" msgid="231613018159186962">"ՏԲ"</string>
@@ -973,7 +973,7 @@
     <string name="whichEditApplicationNamed" msgid="1775815530156447790">"Խմբագրել հետևյալով՝ %1$s"</string>
     <string name="whichEditApplicationLabel" msgid="7183524181625290300">"Փոփոխել"</string>
     <string name="whichSendApplication" msgid="6902512414057341668">"Կիսվել"</string>
-    <string name="whichSendApplicationNamed" msgid="2799370240005424391">"Տարածել ըստ %1$s"</string>
+    <string name="whichSendApplicationNamed" msgid="2799370240005424391">"Կիսվել %1$s-ի միջոցով"</string>
     <string name="whichSendApplicationLabel" msgid="4579076294675975354">"Տրամադրել"</string>
     <string name="whichSendToApplication" msgid="8272422260066642057">"Ուղարկել այս հավելվածով"</string>
     <string name="whichSendToApplicationNamed" msgid="7768387871529295325">"Ուղարկել %1$s հավելվածով"</string>
@@ -995,7 +995,7 @@
     <string name="aerr_application_repeated" msgid="3146328699537439573">"<xliff:g id="APPLICATION">%1$s</xliff:g> հավելվածի աշխատանքը շարունակաբար ընդհատվում է"</string>
     <string name="aerr_process_repeated" msgid="6235302956890402259">"<xliff:g id="PROCESS">%1$s</xliff:g> գործընթացը շարունակաբար ընդհատվում է"</string>
     <string name="aerr_restart" msgid="7581308074153624475">"Կրկին բացել հավելվածը"</string>
-    <string name="aerr_report" msgid="5371800241488400617">"Ուղարկել կարծիք"</string>
+    <string name="aerr_report" msgid="5371800241488400617">"Կարծիք հայտնել"</string>
     <string name="aerr_close" msgid="2991640326563991340">"Փակել"</string>
     <string name="aerr_mute" msgid="1974781923723235953">"Անջատել ձայնը մինչև սարքի վերագործարկումը"</string>
     <string name="aerr_wait" msgid="3199956902437040261">"Սպասել"</string>
diff --git a/core/res/res/values-nb/strings.xml b/core/res/res/values-nb/strings.xml
index ee3c606..860ff12 100644
--- a/core/res/res/values-nb/strings.xml
+++ b/core/res/res/values-nb/strings.xml
@@ -253,7 +253,7 @@
     <string name="permgrouplab_storage" msgid="1971118770546336966">"Lagring"</string>
     <string name="permgroupdesc_storage" msgid="637758554581589203">"åpne bilder, medieinnhold og filer på enheten din"</string>
     <string name="permgrouplab_microphone" msgid="171539900250043464">"Mikrofon"</string>
-    <string name="permgroupdesc_microphone" msgid="4988812113943554584">"spill inn lyd"</string>
+    <string name="permgroupdesc_microphone" msgid="4988812113943554584">"ta opp lyd"</string>
     <string name="permgrouplab_camera" msgid="4820372495894586615">"Kamera"</string>
     <string name="permgroupdesc_camera" msgid="3250611594678347720">"ta bilder og ta opp video"</string>
     <string name="permgrouplab_phone" msgid="5229115638567440675">"Telefon"</string>
diff --git a/core/res/res/values-pa-rIN/strings.xml b/core/res/res/values-pa-rIN/strings.xml
index 12f2ba7..d9156b5 100644
--- a/core/res/res/values-pa-rIN/strings.xml
+++ b/core/res/res/values-pa-rIN/strings.xml
@@ -243,23 +243,23 @@
     <string name="user_owner_label" msgid="1119010402169916617">"ਨਿੱਜੀ \'ਤੇ ਸਵਿੱਚ ਕਰੋ"</string>
     <string name="managed_profile_label" msgid="5289992269827577857">"ਕੰਮ \'ਤੇ ਸਵਿੱਚ ਕਰੋ"</string>
     <string name="permgrouplab_contacts" msgid="3657758145679177612">"ਸੰਪਰਕ"</string>
-    <string name="permgroupdesc_contacts" msgid="6951499528303668046">"ਆਪਣੇ ਸੰਪਰਕਾਂ ਨੂੰ ਐਕਸੈਸ ਕਰੋ"</string>
+    <string name="permgroupdesc_contacts" msgid="6951499528303668046">"ਆਪਣੇ ਸੰਪਰਕਾਂ ਤੱਕ ਪਹੁੰਚ ਕਰਨ"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"ਟਿਕਾਣਾ"</string>
-    <string name="permgroupdesc_location" msgid="1346617465127855033">"ਇਸ ਡੀਵਾਈਸ ਦੇ ਨਿਰਧਾਰਿਤ ਸਥਾਨ ਤੱਕ ਪਹੁੰਚੋ"</string>
+    <string name="permgroupdesc_location" msgid="1346617465127855033">"ਇਸ ਡੀਵਾਈਸ ਦੇ ਟਿਕਾਣੇ ਤੱਕ ਪਹੁੰਚ ਕਰਨ"</string>
     <string name="permgrouplab_calendar" msgid="5863508437783683902">"ਕੈਲੰਡਰ"</string>
-    <string name="permgroupdesc_calendar" msgid="3889615280211184106">"ਆਪਣੇ ਕੈਲੰਡਰ ਦੀ ਐਕਸੈਸ ਕਰੋ"</string>
+    <string name="permgroupdesc_calendar" msgid="3889615280211184106">"ਤੁਹਾਡੇ ਕੈਲੰਡਰ ਤੱਕ ਪਹੁੰਚ ਕਰਨ"</string>
     <string name="permgrouplab_sms" msgid="228308803364967808">"SMS"</string>
-    <string name="permgroupdesc_sms" msgid="4656988620100940350">"SMS ਸੁਨੇਹੇ ਭੇਜੋ ਅਤੇ ਦਿਖਾਓ"</string>
+    <string name="permgroupdesc_sms" msgid="4656988620100940350">"SMS ਸੁਨੇਹੇ ਭੇਜਣ ਅਤੇ ਦੇਖਣ"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"ਸਟੋਰੇਜ"</string>
-    <string name="permgroupdesc_storage" msgid="637758554581589203">"ਆਪਣੀ ਡੀਵਾਈਸ ’ਤੇ ਫੋਟੋਆਂ, ਮੀਡੀਆ ਅਤੇ ਫਾਈਲਾਂ ਤੱਕ ਪਹੁੰਚ ਕਰਨ ਦੇਣ"</string>
+    <string name="permgroupdesc_storage" msgid="637758554581589203">"ਆਪਣੀ ਡੀਵਾਈਸ ’ਤੇ ਫੋਟੋਆਂ, ਮੀਡੀਆ ਅਤੇ ਫਾਈਲਾਂ ਤੱਕ ਪਹੁੰਚ ਕਰਨ"</string>
     <string name="permgrouplab_microphone" msgid="171539900250043464">"ਮਾਈਕ੍ਰੋਫੋਨ"</string>
-    <string name="permgroupdesc_microphone" msgid="4988812113943554584">"ਔਡੀਓ ਰਿਕਾਰਡ ਕਰੋ"</string>
+    <string name="permgroupdesc_microphone" msgid="4988812113943554584">"ਔਡੀਓ ਰਿਕਾਰਡ ਕਰਨ"</string>
     <string name="permgrouplab_camera" msgid="4820372495894586615">"ਕੈਮਰਾ"</string>
-    <string name="permgroupdesc_camera" msgid="3250611594678347720">"ਤਸਵੀਰਾਂ ਖਿੱਚੋ ਅਤੇ ਵੀਡੀਓ ਰਿਕਾਰਡ ਕਰੋ"</string>
+    <string name="permgroupdesc_camera" msgid="3250611594678347720">"ਤਸਵੀਰਾਂ ਲੈਣ ਅਤੇ ਵੀਡੀਓ ਰਿਕਾਰਡ ਕਰਨ"</string>
     <string name="permgrouplab_phone" msgid="5229115638567440675">"ਫੋਨ"</string>
-    <string name="permgroupdesc_phone" msgid="6234224354060641055">"ਫ਼ੋਨ ਕਾਲਾਂ ਕਰੋ ਅਤੇ ਉਹਨਾਂ ਨੂੰ ਪ੍ਰਬੰਧਿਤ ਕਰੋ"</string>
+    <string name="permgroupdesc_phone" msgid="6234224354060641055">"ਫ਼ੋਨ ਕਾਲਾਂ ਕਰਨ ਅਤੇ ਉਹਨਾਂ ਦਾ ਪ੍ਰਬੰਧਨ ਕਰਨ"</string>
     <string name="permgrouplab_sensors" msgid="416037179223226722">"ਸਰੀਰ ਸੰਵੇਦਕ"</string>
-    <string name="permgroupdesc_sensors" msgid="7147968539346634043">"ਆਪਣੇ ਮਹੱਤਵਪੂਰਣ ਲੱਛਣਾਂ ਬਾਰੇ ਸੰਵੇਦਕ ਡੈਟਾ ਤੱਕ ਪਹੁੰਚ"</string>
+    <string name="permgroupdesc_sensors" msgid="7147968539346634043">"ਆਪਣੇ ਸਰੀਰ ਦੇ ਅਹਿਮ ਚਿੰਨ੍ਹਾਂ ਬਾਰੇ ਸੰਵੇਦਕ ਡੈਟੇ ਤੱਕ ਪਹੁੰਚ ਕਰਨ"</string>
     <string name="capability_title_canRetrieveWindowContent" msgid="3901717936930170320">"ਵਿੰਡੋ ਸਮੱਗਰੀ ਮੁੜ ਪ੍ਰਾਪਤ ਕਰੋ"</string>
     <string name="capability_desc_canRetrieveWindowContent" msgid="3772225008605310672">"ਇੱਕ ਵਿੰਡੋ ਦੀ ਸਮੱਗਰੀ ਦੀ ਜਾਂਚ ਕਰੋ, ਜਿਸ ਨਾਲ ਤੁਸੀਂ ਇੰਟਰੈਕਟ ਕਰ ਰਹੇ ਹੋ।"</string>
     <string name="capability_title_canRequestTouchExploration" msgid="3108723364676667320">"ਐਕਸਪਲੋਰ ਬਾਇ ਟਚ ਚਾਲੂ ਕਰੋ"</string>
@@ -292,7 +292,7 @@
     <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"ਐਪ ਨੂੰ ਤੁਹਾਡੀ ਡੀਵਾਈਸ ਵੱਲੋਂ ਪ੍ਰਾਪਤ ਕੀਤੇ ਸੈਲ ਪ੍ਰਸਾਰਨ ਸੁਨੇਹੇ ਪੜ੍ਹਨ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ। ਸੈਲ ਪ੍ਰਸਾਰਨ ਚਿਤਾਵਨੀਆਂ ਤੁਹਾਨੂੰ ਐਮਰਜੈਂਸੀ ਸਥਿਤੀਆਂ ਦੀ ਚਿਤਾਵਨੀ ਦੇਣ ਲਈ ਕੁਝ ਨਿਰਧਾਰਿਤ ਸਥਾਨਾਂ ਤੇ ਪ੍ਰਦਾਨ ਕੀਤੀਆਂ ਜਾਂਦੀਆਂ ਹਨ। ਖ਼ਰਾਬ ਐਪਸ ਤੁਹਾਡੀ ਡੀਵਾਈਸ ਦੇ ਪ੍ਰਦਰਸ਼ਨ ਜਾਂ ਓਪਰੇਸ਼ਨ ਵਿੱਚ ਵਿਘਨ ਪਾ ਸਕਦੇ ਹਨ ਜਦੋਂ ਇੱਕ ਐਮਰਜੈਂਸੀ ਸੈਲ ਪ੍ਰਸਾਰਨ ਪ੍ਰਾਪਤ ਕੀਤਾ ਜਾਂਦਾ ਹੈ।"</string>
     <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"ਸਬਸਕ੍ਰਾਈਬ ਕੀਤੇ ਫੀਡਸ ਪੜ੍ਹੋ"</string>
     <string name="permdesc_subscribedFeedsRead" msgid="5557058907906144505">"ਐਪ ਨੂੰ ਵਰਤਮਾਨ ਵਿੱਚ ਸਿੰਕ ਕੀਤੇ ਫੀਡਸ ਬਾਰੇ ਵੇਰਵੇ ਪ੍ਰਾਪਤ ਕਰਨ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ।"</string>
-    <string name="permlab_sendSms" msgid="7544599214260982981">"SMS ਸੁਨੇਹੇ ਭੇਜੋ ਅਤੇ ਦਿਖਾਓ"</string>
+    <string name="permlab_sendSms" msgid="7544599214260982981">"SMS ਸੁਨੇਹੇ ਭੇਜਣ ਅਤੇ ਦੇਖਣ"</string>
     <string name="permdesc_sendSms" msgid="7094729298204937667">"ਐਪ ਨੂੰ SMS ਸੁਨੇਹੇ ਭੇਜਣ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ। ਇਸਦੇ ਸਿੱਟੇ ਵਜੋਂ ਅਕਲਪਿਤ ਖ਼ਰਚੇ ਪੈ ਸਕਦੇ ਹਨ। ਖ਼ਰਾਬ ਐਪਸ ਤੁਹਾਡੀ ਪੁਸ਼ਟੀ ਤੋਂ ਬਿਨਾਂ ਸੁਨੇਹੇ ਭੇਜ ਕੇ ਤੁਹਾਨੂੰ ਖ਼ਰਚੇ ਪਾ ਸਕਦੇ ਹਨ।"</string>
     <string name="permlab_readSms" msgid="8745086572213270480">"ਤੁਹਾਡੇ ਟੈਕਸਟ ਸੁਨੇਹੇ (SMS ਜਾਂ MMS) ਪੜ੍ਹੋ"</string>
     <string name="permdesc_readSms" product="tablet" msgid="2467981548684735522">"ਐਪ ਨੂੰ ਤੁਹਾਡੀ ਟੈਬਲੇਟ ਜਾਂ SIM ਕਾਰਡ ਤੇ ਸਟੋਰ ਕੀਤੇ SMS ਸੁਨੇਹੇ ਪੜ੍ਹਨ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ। ਇਹ ਐਪ ਨੂੰ ਸਾਰੇ SMS ਸੁਨੇਹੇ ਪੜ੍ਹਨ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ, ਸਮੱਗਰੀ ਜਾਂ ਗੁਪਤਤਾ ਤੇ ਧਿਆਨ ਦਿੱਤੇ ਬਿਨਾਂ।"</string>
diff --git a/core/res/res/values/themes.xml b/core/res/res/values/themes.xml
index aecda44..998eea5 100644
--- a/core/res/res/values/themes.xml
+++ b/core/res/res/values/themes.xml
@@ -174,6 +174,7 @@
 
         <!-- Window attributes -->
         <item name="windowBackground">@drawable/screen_background_selector_dark</item>
+        <item name="windowBackgroundFallback">?attr/colorBackground</item>
         <item name="windowClipToOutline">false</item>
         <item name="windowFrame">@null</item>
         <item name="windowNoTitle">false</item>
diff --git a/docs/html/_redirects.yaml b/docs/html/_redirects.yaml
index f287f51..ae858fe 100644
--- a/docs/html/_redirects.yaml
+++ b/docs/html/_redirects.yaml
@@ -843,6 +843,8 @@
   to: http://tools.android.com/tech-docs/test-recorder
 - from: /r/studio-ui/export-licenses.html
   to: http://tools.android.com/tech-docs/new-build-system/license
+- from: /r/studio-ui/experimental-to-stable-gradle.html
+  to: http://tools.android.com/tech-docs/new-build-system/gradle-experimental/experimental-to-stable-gradle
 - from: /reference/org/apache/http/...
   to: /about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client
 - from: /shareables/...
diff --git a/docs/html/guide/practices/screens_support.jd b/docs/html/guide/practices/screens_support.jd
index 1335790..4d93c835 100644
--- a/docs/html/guide/practices/screens_support.jd
+++ b/docs/html/guide/practices/screens_support.jd
@@ -677,7 +677,7 @@
   <li>48x48 (1.0x baseline) for medium-density</li>
   <li>72x72 (1.5x) for high-density</li>
   <li>96x96 (2.0x) for extra-high-density</li>
-  <li>180x180 (3.0x) for extra-extra-high-density</li>
+  <li>144x144 (3.0x) for extra-extra-high-density</li>
   <li>192x192 (4.0x) for extra-extra-extra-high-density (launcher icon only; see
     <a href="#xxxhdpi-note">note</a> above)</li>
 </ul>
diff --git a/docs/html/topic/libraries/support-library/features.jd b/docs/html/topic/libraries/support-library/features.jd
index d9616d9..584bef8 100755
--- a/docs/html/topic/libraries/support-library/features.jd
+++ b/docs/html/topic/libraries/support-library/features.jd
@@ -619,7 +619,7 @@
 <a href="{@docRoot}reference/android/support/customtabs/CustomTabsService.html">Custom Tabs
 Service</a>
 and
-<a href="{@docRoot}reference/android/support/customtabs/CustomTabsSCallback.html">Custom Tabs
+<a href="{@docRoot}reference/android/support/customtabs/CustomTabsCallback.html">Custom Tabs
 Callback</a>.  </p>
 
 
diff --git a/docs/html/topic/libraries/testing-support-library/index.jd b/docs/html/topic/libraries/testing-support-library/index.jd
index 8b23f73..941f5c3 100644
--- a/docs/html/topic/libraries/testing-support-library/index.jd
+++ b/docs/html/topic/libraries/testing-support-library/index.jd
@@ -523,7 +523,7 @@
 mDevice = UiDevice.getInstance(getInstrumentation());
 
 // Perform a short press on the HOME button
-mDevice().pressHome();
+mDevice.pressHome();
 
 // Bring up the default launcher by searching for
 // a UI component that matches the content-description for the launcher button
diff --git a/docs/html/training/appbar/setting-up.jd b/docs/html/training/appbar/setting-up.jd
index cc963c6..cf564d0 100644
--- a/docs/html/training/appbar/setting-up.jd
+++ b/docs/html/training/appbar/setting-up.jd
@@ -68,7 +68,7 @@
 as your activity's app bar:
 
 <ol>
-  <li>Add the the
+  <li>Add the
   <a href="{@docRoot}tools/support-library/features.html#v7-appcompat">v7
   appcompat</a> support library to your project, as described in <a href=
   "{@docRoot}tools/support-library/setup.html">Support Library Setup</a>.
diff --git a/docs/html/training/auto/audio/index.jd b/docs/html/training/auto/audio/index.jd
index 9144900..aa20e3a 100644
--- a/docs/html/training/auto/audio/index.jd
+++ b/docs/html/training/auto/audio/index.jd
@@ -20,6 +20,7 @@
       <li><a href="#overview">Provide Audio Services</a></li>
       <li><a href="#config_manifest">Configure Your Manifest</a></li>
       <li><a href="#isconnected">Determine if Your App is Connected</a></li>
+      <li><a href="#alarm">Handle Alarms</a></li>
       <li><a href="#implement_browser">Build a Browser Service</a></li>
       <li><a href="#implement_callback">Implement Play Controls</a></li>
       <li><a href="#support_voice">Support Voice Actions</a></li>
@@ -239,6 +240,44 @@
 registerReceiver(receiver, filter);
 </pre>
 
+<h2 id="alarm">Handle Alarms</h2>
+<p>
+To prevent user distraction, Android Auto media apps must not start playing audio
+ through the car speakers unless a user consciously starts playback (such as
+ when the user presses play in your app). Even a user-scheduled alarm from the
+ media app must not start playing music through the car speakers.
+ If your media app has an alarm feature, the app should determine if the phone
+ is in
+<a href="{@docRoot}reference/android/content/res/Configuration.html#UI_MODE_TYPE_CAR">car mode</a>
+before playing any audio. Your app can do this by calling
+<a href="{@docRoot}reference/android/app/UiModeManager.html">UiModeManager.getCurrentModeType()</a>,
+ which checks whether the device is running in car mode.
+</p>
+
+<p>
+If the device is in car mode, media apps that support alarms must do one of the
+following things:
+
+<ul>
+<li>Disable the alarm.</li>
+<li>Play the alarm over
+<a href="{@docRoot}reference/android/media/AudioManager.html">STREAM_ALARM</a>,
+ and provide a UI on the phone screen to disable the alarm.</li>
+</ul>
+
+The following code snippet checks whether an app is running in car mode:
+<pre>
+ public static boolean isCarUiMode(Context c) {
+      UiModeManager uiModeManager = (UiModeManager) c.getSystemService(Context.UI_MODE_SERVICE);
+      if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_CAR) {
+            LogHelper.d(TAG, "Running in Car mode");
+            return true;
+      } else {
+          LogHelper.d(TAG, "Running on a non-Car mode");
+          return false;
+        }
+  }
+</pre>
 
 <h2 id="implement_browser">Build a Browser Service</h2>
 
diff --git a/docs/html/training/testing/performance.jd b/docs/html/training/testing/performance.jd
index 8592c0f..0c0ab7f 100644
--- a/docs/html/training/testing/performance.jd
+++ b/docs/html/training/testing/performance.jd
@@ -437,15 +437,25 @@
 </p>
 
 <ul>
-  <li>Rendering Performance 101
+  <li>
+    <a class="external-link" href="https://www.youtube.com/watch?v=HXQhu6qfTVU">
+      Rendering Performance 101</a>
   </li>
-  <li>Why 60fps?
+  <li>
+    <a class="external-link" href="https://www.youtube.com/watch?v=CaMTIgxCSqU">
+      Why 60fps?</a>
   </li>
-  <li>Android UI and the GPU
+  <li>
+    <a class="external-link" href="https://www.youtube.com/watch?v=WH9AFhgwmDw">
+      Android, UI, and the GPU</a>
   </li>
-  <li>Invalidations Layouts and performance
+  <li>
+    <a class="external-link" href="https://www.youtube.com/watch?v=we6poP0kw6E">
+      Invalidations, Layouts, and Performance</a>
   </li>
-  <li>Analyzing UI Performance with Systrace
+  <li>
+    <a href="{@docRoot}studio/profile/systrace.html">
+      Analyzing UI Performance with Systrace</a>
   </li>
 </ul>
 
diff --git a/libs/hwui/Android.mk b/libs/hwui/Android.mk
index faf6a52..c9d4af6 100644
--- a/libs/hwui/Android.mk
+++ b/libs/hwui/Android.mk
@@ -256,6 +256,7 @@
     tests/unit/MatrixTests.cpp \
     tests/unit/OffscreenBufferPoolTests.cpp \
     tests/unit/RenderNodeTests.cpp \
+    tests/unit/RenderPropertiesTests.cpp \
     tests/unit/SkiaBehaviorTests.cpp \
     tests/unit/SnapshotTests.cpp \
     tests/unit/StringUtilsTests.cpp \
diff --git a/libs/hwui/BakedOpRenderer.cpp b/libs/hwui/BakedOpRenderer.cpp
index ea2e15b..6db345a 100644
--- a/libs/hwui/BakedOpRenderer.cpp
+++ b/libs/hwui/BakedOpRenderer.cpp
@@ -66,8 +66,13 @@
             offscreenBuffer->texture.id(), 0);
     GL_CHECKPOINT(LOW);
 
-    LOG_ALWAYS_FATAL_IF(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE,
-            "framebuffer incomplete!");
+    int status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
+    LOG_ALWAYS_FATAL_IF(status != GL_FRAMEBUFFER_COMPLETE,
+            "framebuffer incomplete, status %d, textureId %d, size %dx%d",
+            status,
+            offscreenBuffer->texture.id(),
+            offscreenBuffer->texture.width(),
+            offscreenBuffer->texture.height());
 
     // Change the viewport & ortho projection
     setViewport(offscreenBuffer->viewportWidth, offscreenBuffer->viewportHeight);
diff --git a/libs/hwui/FrameBuilder.cpp b/libs/hwui/FrameBuilder.cpp
index cb8e55f..b8a5ce6 100644
--- a/libs/hwui/FrameBuilder.cpp
+++ b/libs/hwui/FrameBuilder.cpp
@@ -86,7 +86,9 @@
             ATRACE_FORMAT("Optimize HW Layer DisplayList %s %ux%u",
                     layerNode->getName(), layerNode->getWidth(), layerNode->getHeight());
 
-            const Rect& layerDamage = layers.entries()[i].damage;
+            Rect layerDamage = layers.entries()[i].damage;
+            // TODO: ensure layer damage can't be larger than layer
+            layerDamage.doIntersect(0, 0, layer->viewportWidth, layer->viewportHeight);
             layerNode->computeOrdering();
 
             // map current light center into RenderNode's coordinate space
diff --git a/libs/hwui/RenderNode.cpp b/libs/hwui/RenderNode.cpp
index 6e848fd..be2dab9 100644
--- a/libs/hwui/RenderNode.cpp
+++ b/libs/hwui/RenderNode.cpp
@@ -319,6 +319,8 @@
         transformUpdateNeeded = true;
     } else if (!layerMatchesWidthAndHeight(mLayer, getWidth(), getHeight())) {
 #if HWUI_NEW_OPS
+        // TODO: remove now irrelevant, currently enqueued damage (respecting damage ordering)
+        // Or, ideally, maintain damage between frames on node/layer so ordering is always correct
         RenderState& renderState = mLayer->renderState;
         if (properties().fitsOnLayer()) {
             mLayer = renderState.layerPool().resize(mLayer, getWidth(), getHeight());
diff --git a/libs/hwui/RenderProperties.h b/libs/hwui/RenderProperties.h
index 3952798..696cc29 100644
--- a/libs/hwui/RenderProperties.h
+++ b/libs/hwui/RenderProperties.h
@@ -611,7 +611,9 @@
     bool fitsOnLayer() const {
         const DeviceInfo* deviceInfo = DeviceInfo::get();
         return mPrimitiveFields.mWidth <= deviceInfo->maxTextureSize()
-                        && mPrimitiveFields.mHeight <= deviceInfo->maxTextureSize();
+                        && mPrimitiveFields.mHeight <= deviceInfo->maxTextureSize()
+                        && mPrimitiveFields.mWidth > 0
+                        && mPrimitiveFields.mHeight > 0;
     }
 
     bool promotedToLayer() const {
diff --git a/libs/hwui/tests/unit/RenderPropertiesTests.cpp b/libs/hwui/tests/unit/RenderPropertiesTests.cpp
new file mode 100644
index 0000000..9001098
--- /dev/null
+++ b/libs/hwui/tests/unit/RenderPropertiesTests.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#include <gtest/gtest.h>
+
+#include <RenderProperties.h>
+
+using namespace android;
+using namespace android::uirenderer;
+
+TEST(RenderProperties, layerValidity) {
+    DeviceInfo::initialize();
+
+    const int maxTextureSize = DeviceInfo::get()->maxTextureSize();
+    ASSERT_LE(2048, maxTextureSize);
+    ASSERT_GT(100000, maxTextureSize);
+
+    RenderProperties props;
+
+    // simple cases that all should fit on layers
+    props.setLeftTopRightBottom(0, 0, 100, 100);
+    ASSERT_TRUE(props.fitsOnLayer());
+    props.setLeftTopRightBottom(100, 2000, 300, 4000);
+    ASSERT_TRUE(props.fitsOnLayer());
+    props.setLeftTopRightBottom(-10, -10, 510, 512);
+    ASSERT_TRUE(props.fitsOnLayer());
+
+    // Too big - can't have layer bigger than max texture size
+    props.setLeftTopRightBottom(0, 0, maxTextureSize + 1, maxTextureSize + 1);
+    ASSERT_FALSE(props.fitsOnLayer());
+
+    // Too small - can't have 0 dimen layer
+    props.setLeftTopRightBottom(0, 0, 100, 0);
+    ASSERT_FALSE(props.fitsOnLayer());
+}
diff --git a/packages/DocumentsUI/src/com/android/documentsui/OpenExternalDirectoryActivity.java b/packages/DocumentsUI/src/com/android/documentsui/OpenExternalDirectoryActivity.java
index b0e5e4e..6588ee1 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/OpenExternalDirectoryActivity.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/OpenExternalDirectoryActivity.java
@@ -20,6 +20,7 @@
 import static android.os.Environment.STANDARD_DIRECTORIES;
 import static android.os.storage.StorageVolume.EXTRA_DIRECTORY_NAME;
 import static android.os.storage.StorageVolume.EXTRA_STORAGE_VOLUME;
+
 import static com.android.documentsui.LocalPreferences.getScopedAccessPermissionStatus;
 import static com.android.documentsui.LocalPreferences.PERMISSION_ASK;
 import static com.android.documentsui.LocalPreferences.PERMISSION_ASK_AGAIN;
@@ -201,14 +202,23 @@
         final List<VolumeInfo> volumes = sm.getVolumes();
         if (DEBUG) Log.d(TAG, "Number of volumes: " + volumes.size());
         File internalRoot = null;
+        boolean found = true;
         for (VolumeInfo volume : volumes) {
             if (isRightVolume(volume, root, userId)) {
+                found = true;
                 internalRoot = volume.getInternalPathForUser(userId);
                 // Must convert path before calling getDocIdForFileCreateNewDir()
                 if (DEBUG) Log.d(TAG, "Converting " + root + " to " + internalRoot);
                 file = isRoot ? internalRoot : new File(internalRoot, directory);
+                volumeUuid = storageVolume.getUuid();
                 volumeLabel = sm.getBestVolumeDescription(volume);
-                volumeUuid = volume.getFsUuid();
+                if (TextUtils.isEmpty(volumeLabel)) {
+                    volumeLabel = storageVolume.getDescription(activity);
+                }
+                if (TextUtils.isEmpty(volumeLabel)) {
+                    volumeLabel = activity.getString(android.R.string.unknownName);
+                    Log.w(TAG, "No volume description  for " + volume + "; using " + volumeLabel);
+                }
                 break;
             }
         }
@@ -229,7 +239,7 @@
             return true;
         }
 
-        if (volumeLabel == null) {
+        if (!found) {
             Log.e(TAG, "Could not get volume for " + file);
             logInvalidScopedAccessRequest(activity, SCOPED_DIRECTORY_ACCESS_ERROR);
             return false;
@@ -277,15 +287,16 @@
     private static boolean isRightVolume(VolumeInfo volume, String root, int userId) {
         final File userPath = volume.getPathForUser(userId);
         final String path = userPath == null ? null : volume.getPathForUser(userId).getPath();
-        final boolean isVisible = volume.isVisibleForWrite(userId);
+        final boolean isMounted = volume.isMountedReadable();
         if (DEBUG)
-            Log.d(TAG, "Volume: " + volume + " userId: " + userId + " root: " + root
-                    + " volumePath: " + volume.getPath().getPath()
-                    + " pathForUser: " + path
-                    + " internalPathForUser: " + volume.getInternalPath()
-                    + " isVisible: " + isVisible);
+            Log.d(TAG, "Volume: " + volume
+                    + "\n\tuserId: " + userId
+                    + "\n\tuserPath: " + userPath
+                    + "\n\troot: " + root
+                    + "\n\tpath: " + path
+                    + "\n\tisMounted: " + isMounted);
 
-        return volume.isVisibleForWrite(userId) && root.equals(path);
+        return isMounted && root.equals(path);
     }
 
     private static Uri getGrantedUriPermission(Context context, ContentProviderClient provider,
@@ -455,7 +466,7 @@
                 message = TextUtils.expandTemplate(
                         getText(mIsPrimary ? R.string.open_external_dialog_request_primary_volume
                                 : R.string.open_external_dialog_request),
-                        mAppLabel, directory, mVolumeLabel);
+                                mAppLabel, directory, mVolumeLabel);
             }
             final TextView messageField = (TextView) view.findViewById(R.id.message);
             messageField.setText(message);
diff --git a/packages/PrintRecommendationService/res/values/strings.xml b/packages/PrintRecommendationService/res/values/strings.xml
index 348fcac..b6c45b7 100644
--- a/packages/PrintRecommendationService/res/values/strings.xml
+++ b/packages/PrintRecommendationService/res/values/strings.xml
@@ -26,6 +26,6 @@
     <string name="plugin_vendor_samsung">Samsung</string>
     <string name="plugin_vendor_epson">Epson</string>
     <string name="plugin_vendor_konica_minolta">Konica Minolta</string>
-    <string name="plugin_vendor_fuji">Fuji</string>
+    <string name="plugin_vendor_fuji_xerox">Fuji Xerox</string>
     <string name="plugin_vendor_morpia">Mopria</string>
 </resources>
diff --git a/packages/PrintRecommendationService/res/xml/vendorconfigs.xml b/packages/PrintRecommendationService/res/xml/vendorconfigs.xml
index 52889ce..703cf6f 100644
--- a/packages/PrintRecommendationService/res/xml/vendorconfigs.xml
+++ b/packages/PrintRecommendationService/res/xml/vendorconfigs.xml
@@ -60,7 +60,7 @@
     </vendor>
 
     <vendor>
-        <name>@string/plugin_vendor_fuji</name>
+        <name>@string/plugin_vendor_fuji_xerox</name>
         <package>jp.co.fujixerox.prt.PrintUtil.PCL</package>
         <mdns-names>
             <mdns-name>FUJI XEROX</mdns-name>
diff --git a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/xerox/MDnsUtils.java b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/xerox/MDnsUtils.java
index 7a2d0d8..b0da08b 100755
--- a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/xerox/MDnsUtils.java
+++ b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/xerox/MDnsUtils.java
@@ -39,8 +39,10 @@
         String usbMfg = getString(attributes.get(ATTRIBUTE__USB_MFG));
         String usbMdl = getString(attributes.get(ATTRIBUTE__USB_MDL));
         String mfg = getString(attributes.get(ATTRIBUTE__MFG));
-        return containsVendor(product, vendorValues) || containsVendor(ty, vendorValues) || containsVendor(usbMfg, vendorValues) || containsVendor(mfg, vendorValues) && !(containsString(ty, EXCLUDE_FUJI) || containsString(product, EXCLUDE_FUJI) || containsString(usbMdl, EXCLUDE_FUJI));
-
+        return (containsVendor(product, vendorValues) || containsVendor(ty, vendorValues) ||
+                containsVendor(usbMfg, vendorValues) || containsVendor(mfg, vendorValues)) &&
+                !(containsString(ty, EXCLUDE_FUJI) || containsString(product, EXCLUDE_FUJI) ||
+                        containsString(usbMdl, EXCLUDE_FUJI));
     }
 
     public static String getVendor(NsdServiceInfo networkDevice) {
diff --git a/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java b/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java
index be3df54..c318275 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/ui/PrintActivity.java
@@ -614,6 +614,9 @@
     @Override
     public void onConfigurationChanged(Configuration newConfig) {
         super.onConfigurationChanged(newConfig);
+
+        mMediaSizeComparator.onConfigurationChanged(newConfig);
+
         if (mPrintPreviewController != null) {
             mPrintPreviewController.onOrientationChanged();
         }
diff --git a/packages/PrintSpooler/src/com/android/printspooler/util/MediaSizeUtils.java b/packages/PrintSpooler/src/com/android/printspooler/util/MediaSizeUtils.java
index 912ee1d..7289301 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/util/MediaSizeUtils.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/util/MediaSizeUtils.java
@@ -16,13 +16,16 @@
 
 package com.android.printspooler.util;
 
+import android.annotation.NonNull;
 import android.content.Context;
+import android.content.pm.ActivityInfo;
+import android.content.res.Configuration;
 import android.print.PrintAttributes.MediaSize;
-import android.util.ArrayMap;
 
 import com.android.printspooler.R;
 
 import java.util.Comparator;
+import java.util.HashMap;
 import java.util.Map;
 
 /**
@@ -30,7 +33,10 @@
  */
 public final class MediaSizeUtils {
 
-    private static Map<MediaSize, String> sMediaSizeToStandardMap;
+    private static Map<MediaSize, Integer> sMediaSizeToStandardMap;
+
+    /** The media size standard for all media sizes no standard is defined for */
+    private static int sMediaSizeStandardIso;
 
     private MediaSizeUtils() {
         /* do nothing - hide constructor */
@@ -47,22 +53,32 @@
         return MediaSize.getStandardMediaSizeById(mediaSizeId);
     }
 
-    private static String getStandardForMediaSize(Context context, MediaSize mediaSize) {
+    /**
+     * Get the standard the {@link MediaSize} belongs to.
+     *
+     * @param context   The context of the caller
+     * @param mediaSize The {@link MediaSize} to be resolved
+     *
+     * @return The standard the {@link MediaSize} belongs to
+     */
+    private static int getStandardForMediaSize(Context context, MediaSize mediaSize) {
         if (sMediaSizeToStandardMap == null) {
-            sMediaSizeToStandardMap = new ArrayMap<MediaSize, String>();
+            sMediaSizeStandardIso = Integer.parseInt(context.getString(
+                    R.string.mediasize_standard_iso));
+
+            sMediaSizeToStandardMap = new HashMap<>();
             String[] mediaSizeToStandardMapValues = context.getResources()
                     .getStringArray(R.array.mediasize_to_standard_map);
             final int mediaSizeToStandardCount = mediaSizeToStandardMapValues.length;
             for (int i = 0; i < mediaSizeToStandardCount; i += 2) {
                 String mediaSizeId = mediaSizeToStandardMapValues[i];
                 MediaSize key = MediaSize.getStandardMediaSizeById(mediaSizeId);
-                String value = mediaSizeToStandardMapValues[i + 1];
+                int value = Integer.parseInt(mediaSizeToStandardMapValues[i + 1]);
                 sMediaSizeToStandardMap.put(key, value);
             }
         }
-        String standard = sMediaSizeToStandardMap.get(mediaSize);
-        return (standard != null) ? standard : context.getString(
-                R.string.mediasize_standard_iso);
+        Integer standard = sMediaSizeToStandardMap.get(mediaSize);
+        return (standard != null) ? standard : sMediaSizeStandardIso;
     }
 
     /**
@@ -73,32 +89,76 @@
     public static final class MediaSizeComparator implements Comparator<MediaSize> {
         private final Context mContext;
 
+        /** Current configuration */
+        private Configuration mCurrentConfig;
+
+        /** The standard to use for the current locale */
+        private int mCurrentStandard;
+
+        /** Mapping from media size to label */
+        private final @NonNull Map<MediaSize, String> mMediaSizeToLabel;
+
         public MediaSizeComparator(Context context) {
             mContext = context;
+            mMediaSizeToLabel = new HashMap<>();
+            mCurrentStandard = Integer.parseInt(mContext.getString(R.string.mediasize_standard));
+        }
+
+        /**
+         * Handle a configuration change by reloading all resources.
+         *
+         * @param newConfig The new configuration that will be applied.
+         */
+        public void onConfigurationChanged(@NonNull Configuration newConfig) {
+            if (mCurrentConfig == null ||
+                    (newConfig.diff(mCurrentConfig) & ActivityInfo.CONFIG_LOCALE) != 0) {
+                mCurrentStandard = Integer
+                        .parseInt(mContext.getString(R.string.mediasize_standard));
+                mMediaSizeToLabel.clear();
+
+                mCurrentConfig = newConfig;
+            }
+        }
+
+        /**
+         * Get the label for a {@link MediaSize}.
+         *
+         * @param context   The context the label should be loaded for
+         * @param mediaSize The {@link MediaSize} to resolve
+         *
+         * @return The label for the media size
+         */
+        public @NonNull String getLabel(@NonNull Context context, @NonNull MediaSize mediaSize) {
+            String label = mMediaSizeToLabel.get(mediaSize);
+
+            if (label == null) {
+                label = mediaSize.getLabel(context.getPackageManager());
+                mMediaSizeToLabel.put(mediaSize, label);
+            }
+
+            return label;
         }
 
         @Override
         public int compare(MediaSize lhs, MediaSize rhs) {
-            String currentStandard = mContext.getString(R.string.mediasize_standard);
-            String lhsStandard = getStandardForMediaSize(mContext, lhs);
-            String rhsStandard = getStandardForMediaSize(mContext, rhs);
+            int lhsStandard = getStandardForMediaSize(mContext, lhs);
+            int rhsStandard = getStandardForMediaSize(mContext, rhs);
 
             // The current standard always wins.
-            if (lhsStandard.equals(currentStandard)) {
-                if (!rhsStandard.equals(currentStandard)) {
+            if (lhsStandard == mCurrentStandard) {
+                if (rhsStandard != mCurrentStandard) {
                     return -1;
                 }
-            } else if (rhsStandard.equals(currentStandard)) {
+            } else if (rhsStandard == mCurrentStandard) {
                 return 1;
             }
 
-            if (!lhsStandard.equals(rhsStandard)) {
+            if (lhsStandard != rhsStandard) {
                 // Different standards - use the standard ordering.
-                return lhsStandard.compareTo(rhsStandard);
+                return Integer.valueOf(lhsStandard).compareTo(rhsStandard);
             } else {
                 // Same standard - sort alphabetically by label.
-                return lhs.getLabel(mContext.getPackageManager()).
-                        compareTo(rhs.getLabel(mContext.getPackageManager()));
+                return getLabel(mContext, lhs).compareTo(getLabel(mContext, rhs));
             }
         }
     }
diff --git a/packages/SettingsLib/res/values-tl/strings.xml b/packages/SettingsLib/res/values-tl/strings.xml
index 08dbb01..2cd6813 100644
--- a/packages/SettingsLib/res/values-tl/strings.xml
+++ b/packages/SettingsLib/res/values-tl/strings.xml
@@ -242,7 +242,7 @@
     <string name="transition_animation_scale_title" msgid="387527540523595875">"Scale ng transition animation"</string>
     <string name="animator_duration_scale_title" msgid="3406722410819934083">"Scale ng tagal ng animator"</string>
     <string name="overlay_display_devices_title" msgid="5364176287998398539">"I-simulate, ika-2 display"</string>
-    <string name="debug_applications_category" msgid="4206913653849771549">"Apps"</string>
+    <string name="debug_applications_category" msgid="4206913653849771549">"Mga App"</string>
     <string name="immediately_destroy_activities" msgid="1579659389568133959">"Huwag magtago ng mga aktibidad"</string>
     <string name="immediately_destroy_activities_summary" msgid="3592221124808773368">"Sirain ang bawat aktibidad sa sandaling iwan ito ng user"</string>
     <string name="app_process_limit_title" msgid="4280600650253107163">"Limitasyon ng proseso sa background"</string>
diff --git a/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java b/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java
index bf75046..ce916cb 100644
--- a/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java
+++ b/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java
@@ -20,14 +20,17 @@
 import android.app.Activity;
 import android.content.ActivityNotFoundException;
 import android.content.BroadcastReceiver;
+import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.pm.PackageManager;
 import android.content.res.TypedArray;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.provider.Settings;
 import android.support.v4.widget.DrawerLayout;
+import android.util.ArraySet;
 import android.util.Log;
 import android.util.Pair;
 import android.view.Gravity;
@@ -56,6 +59,9 @@
 
     private static List<DashboardCategory> sDashboardCategories;
     private static HashMap<Pair<String, String>, Tile> sTileCache;
+    // Serves as a temporary list of tiles to ignore until we heard back from the PM that they
+    // are disabled.
+    private static ArraySet<ComponentName> sTileBlacklist = new ArraySet<>();
     private static InterestingConfigChanges sConfigTracker;
 
     private final PackageReceiver mPackageReceiver = new PackageReceiver();
@@ -270,6 +276,24 @@
         finish();
     }
 
+    public void setTileEnabled(ComponentName component, boolean enabled) {
+        PackageManager pm = getPackageManager();
+        int state = pm.getComponentEnabledSetting(component);
+        boolean isEnabled = state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
+        if (isEnabled != enabled || state == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
+            if (enabled) {
+                sTileBlacklist.remove(component);
+            } else {
+                sTileBlacklist.add(component);
+            }
+            pm.setComponentEnabledSetting(component, enabled
+                    ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
+                    : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
+                    PackageManager.DONT_KILL_APP);
+            new CategoriesUpdater().execute();
+        }
+    }
+
     public interface CategoryListener {
         void onCategoriesChanged();
     }
@@ -285,6 +309,15 @@
 
         @Override
         protected void onPostExecute(List<DashboardCategory> dashboardCategories) {
+            for (int i = 0; i < dashboardCategories.size(); i++) {
+                DashboardCategory category = dashboardCategories.get(i);
+                for (int j = 0; j < category.tiles.size(); j++) {
+                    Tile tile = category.tiles.get(j);
+                    if (sTileBlacklist.contains(tile.intent.getComponent())) {
+                        category.tiles.remove(j--);
+                    }
+                }
+            }
             sDashboardCategories = dashboardCategories;
             onCategoriesChanged();
         }
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index 9c0aa35d..2efefb3 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -90,7 +90,7 @@
     <uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
     <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
     <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
-    <uses-permission android:name="android.permission.MANAGE_USERS" />
+    <uses-permission android:name="android.permission.CREATE_USERS" />
     <uses-permission android:name="android.permission.MANAGE_DEVICE_ADMINS" />
     <uses-permission android:name="android.permission.BLUETOOTH_STACK" />
     <uses-permission android:name="android.permission.GET_ACCOUNTS" />
diff --git a/packages/SystemUI/res/layout-sw410dp/status_bar_alarm_group.xml b/packages/SystemUI/res/layout-sw410dp/status_bar_alarm_group.xml
new file mode 100644
index 0000000..ba5c0aa
--- /dev/null
+++ b/packages/SystemUI/res/layout-sw410dp/status_bar_alarm_group.xml
@@ -0,0 +1,75 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2016 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.
+-->
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:systemui="http://schemas.android.com/apk/res-auto"
+    android:id="@+id/date_time_alarm_group"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:layout_marginTop="8dp"
+    android:layout_marginStart="16dp"
+    android:gravity="start"
+    android:orientation="vertical">
+    <LinearLayout
+        android:id="@+id/date_time_group"
+        android:layout_width="wrap_content"
+        android:layout_height="19dp"
+        android:orientation="horizontal"
+        android:focusable="true" >
+
+        <include layout="@layout/split_clock_view"
+            android:layout_width="wrap_content"
+            android:layout_height="match_parent"
+            android:id="@+id/clock" />
+
+        <com.android.systemui.statusbar.policy.DateView
+            android:id="@+id/date"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginStart="6dp"
+            android:drawableStart="@drawable/header_dot"
+            android:drawablePadding="6dp"
+            android:singleLine="true"
+            android:textAppearance="@style/TextAppearance.StatusBar.Expanded.Clock"
+            android:textSize="@dimen/qs_time_collapsed_size"
+            android:gravity="top"
+            systemui:datePattern="@string/abbrev_wday_month_day_no_year_alarm" />
+
+        <com.android.systemui.statusbar.AlphaOptimizedImageView
+            android:id="@+id/alarm_status_collapsed"
+            android:layout_width="wrap_content"
+            android:layout_height="match_parent"
+            android:src="@drawable/ic_access_alarms_small"
+            android:paddingStart="6dp"
+            android:gravity="center"
+            android:visibility="gone" />
+    </LinearLayout>
+
+    <com.android.systemui.statusbar.AlphaOptimizedButton
+        android:id="@+id/alarm_status"
+        android:layout_width="wrap_content"
+        android:layout_height="20dp"
+        android:paddingTop="3dp"
+        android:drawablePadding="8dp"
+        android:drawableStart="@drawable/ic_access_alarms_small"
+        android:textColor="#64ffffff"
+        android:textAppearance="@style/TextAppearance.StatusBar.Expanded.Date"
+        android:gravity="top"
+        android:background="?android:attr/selectableItemBackground"
+        android:visibility="gone" />
+
+</LinearLayout>
diff --git a/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml b/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
index 5d62940..f65a667 100644
--- a/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
+++ b/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
@@ -106,64 +106,11 @@
         android:gravity="center_vertical"
         android:focusable="true" />
 
-    <LinearLayout
+    <include
         android:id="@+id/date_time_alarm_group"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
+        layout="@layout/status_bar_alarm_group"
         android:layout_alignParentStart="true"
-        android:layout_alignParentTop="true"
-        android:layout_marginTop="8dp"
-        android:layout_marginStart="16dp"
-        android:gravity="start"
-        android:orientation="vertical">
-        <LinearLayout
-            android:id="@+id/date_time_group"
-            android:layout_width="wrap_content"
-            android:layout_height="19dp"
-            android:orientation="horizontal"
-            android:focusable="true" >
-
-            <include layout="@layout/split_clock_view"
-                android:layout_width="wrap_content"
-                android:layout_height="match_parent"
-                android:id="@+id/clock" />
-
-            <com.android.systemui.statusbar.policy.DateView
-                android:id="@+id/date"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_marginStart="6dp"
-                android:drawableStart="@drawable/header_dot"
-                android:drawablePadding="6dp"
-                android:singleLine="true"
-                android:textAppearance="@style/TextAppearance.StatusBar.Expanded.Clock"
-                android:textSize="@dimen/qs_time_collapsed_size"
-                android:gravity="top"
-                systemui:datePattern="@string/abbrev_wday_month_day_no_year_alarm" />
-
-            <com.android.systemui.statusbar.AlphaOptimizedImageView
-                android:id="@+id/alarm_status_collapsed"
-                android:layout_width="wrap_content"
-                android:layout_height="match_parent"
-                android:src="@drawable/ic_access_alarms_small"
-                android:paddingStart="6dp"
-                android:gravity="center"
-                android:visibility="gone" />
-        </LinearLayout>
-
-        <com.android.systemui.statusbar.AlphaOptimizedButton
-            android:id="@+id/alarm_status"
-            android:layout_width="wrap_content"
-            android:layout_height="20dp"
-            android:paddingTop="3dp"
-            android:drawablePadding="8dp"
-            android:drawableStart="@drawable/ic_access_alarms_small"
-            android:textColor="#64ffffff"
-            android:textAppearance="@style/TextAppearance.StatusBar.Expanded.Date"
-            android:gravity="top"
-            android:background="?android:attr/selectableItemBackground"
-            android:visibility="gone" />
-    </LinearLayout>
+        android:layout_alignParentTop="true" />
 
     <com.android.systemui.qs.QuickQSPanel
         android:id="@+id/quick_qs_panel"
@@ -177,7 +124,7 @@
         android:clipToPadding="false"
         android:importantForAccessibility="yes"
         android:focusable="true"
-        android:accessibilityTraversalAfter="@id/date_time_group"
+        android:accessibilityTraversalAfter="@+id/date_time_group"
         android:accessibilityTraversalBefore="@id/expand_indicator" />
 
     <com.android.systemui.statusbar.AlphaOptimizedImageView
diff --git a/packages/SystemUI/res/layout/remote_input.xml b/packages/SystemUI/res/layout/remote_input.xml
index 2db97a6..0c8cc9b 100644
--- a/packages/SystemUI/res/layout/remote_input.xml
+++ b/packages/SystemUI/res/layout/remote_input.xml
@@ -43,7 +43,7 @@
             android:ellipsize="start"
             android:inputType="textShortMessage|textAutoCorrect|textCapSentences"
             android:textIsSelectable="true"
-            android:imeOptions="actionSend|flagNoExtractUi" />
+            android:imeOptions="actionNone|flagNoExtractUi" />
 
     <FrameLayout
             android:layout_width="wrap_content"
diff --git a/packages/SystemUI/res/layout/status_bar_alarm_group.xml b/packages/SystemUI/res/layout/status_bar_alarm_group.xml
new file mode 100644
index 0000000..f94b727
--- /dev/null
+++ b/packages/SystemUI/res/layout/status_bar_alarm_group.xml
@@ -0,0 +1,73 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2016 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.
+-->
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:systemui="http://schemas.android.com/apk/res-auto"
+    android:id="@+id/date_time_alarm_group"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:layout_marginTop="8dp"
+    android:layout_marginStart="16dp"
+    android:gravity="start"
+    android:orientation="vertical">
+    <LinearLayout
+        android:id="@+id/date_time_group"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal"
+        android:focusable="true" >
+
+        <include layout="@layout/split_clock_view"
+            android:layout_width="wrap_content"
+            android:layout_height="match_parent"
+            android:id="@+id/clock" />
+
+        <com.android.systemui.statusbar.AlphaOptimizedImageView
+            android:id="@+id/alarm_status_collapsed"
+            android:layout_width="wrap_content"
+            android:layout_height="match_parent"
+            android:src="@drawable/ic_access_alarms_small"
+            android:paddingStart="6dp"
+            android:gravity="center"
+            android:visibility="gone" />
+    </LinearLayout>
+
+    <com.android.systemui.statusbar.policy.DateView
+        android:id="@+id/date"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:singleLine="true"
+        android:layout_marginTop="-4dp"
+        android:textAppearance="@style/TextAppearance.StatusBar.Expanded.Clock"
+        android:textSize="@dimen/qs_time_collapsed_size"
+        android:gravity="top"
+        systemui:datePattern="@string/abbrev_wday_month_day_no_year_alarm" />
+
+    <com.android.systemui.statusbar.AlphaOptimizedButton
+        android:id="@+id/alarm_status"
+        android:layout_width="wrap_content"
+        android:layout_height="20dp"
+        android:paddingTop="3dp"
+        android:drawablePadding="8dp"
+        android:drawableStart="@drawable/ic_access_alarms_small"
+        android:textColor="#64ffffff"
+        android:textAppearance="@style/TextAppearance.StatusBar.Expanded.Date"
+        android:gravity="top"
+        android:background="?android:attr/selectableItemBackground"
+        android:visibility="gone" />
+
+</LinearLayout>
diff --git a/packages/SystemUI/res/values-sw410dp/config.xml b/packages/SystemUI/res/values-sw410dp/config.xml
index 049a535..b04b28c 100644
--- a/packages/SystemUI/res/values-sw410dp/config.xml
+++ b/packages/SystemUI/res/values-sw410dp/config.xml
@@ -22,5 +22,5 @@
 <resources>
     <integer name="quick_settings_num_rows">2</integer>
 
-    <bool name="quick_settings_show_date">true</bool>
+    <bool name="quick_settings_show_full_alarm">true</bool>
 </resources>
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index e98309e..02b1b50 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -262,7 +262,7 @@
     <!-- Nav bar button default ordering/layout -->
     <string name="config_navBarLayout" translatable="false">space,back;home;recent,menu_ime</string>
 
-    <bool name="quick_settings_show_date">false</bool>
+    <bool name="quick_settings_show_full_alarm">false</bool>
 
 </resources>
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java b/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
index cf96457..71bd798 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
@@ -109,18 +109,18 @@
         if (mListening) {
             if (mPosition != position) {
                 // Clear out the last pages from listening.
-                mPages.get(mPosition).setListening(false);
+                setPageListening(mPosition, false);
                 if (mOffPage) {
-                    mPages.get(mPosition + 1).setListening(false);
+                    setPageListening(mPosition + 1, false);
                 }
                 // Set the new pages to listening
-                mPages.get(position).setListening(true);
+                setPageListening(position, true);
                 if (offPage) {
-                    mPages.get(position + 1).setListening(true);
+                    setPageListening(position + 1, true);
                 }
             } else if (mOffPage != offPage) {
                 // Whether we are showing position + 1 has changed.
-                mPages.get(mPosition + 1).setListening(offPage);
+                setPageListening(mPosition + 1, offPage);
             }
         }
         // Save the current state.
@@ -128,6 +128,11 @@
         mOffPage = offPage;
     }
 
+    private void setPageListening(int position, boolean listening) {
+        if (position >= mPages.size()) return;
+        mPages.get(position).setListening(listening);
+    }
+
     @Override
     public boolean hasOverlappingRendering() {
         return false;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSAnimator.java b/packages/SystemUI/src/com/android/systemui/qs/QSAnimator.java
index f92c51f..2dcb5f4 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSAnimator.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSAnimator.java
@@ -20,6 +20,7 @@
 import android.view.View.OnAttachStateChangeListener;
 import android.view.View.OnLayoutChangeListener;
 import android.widget.TextView;
+
 import com.android.systemui.qs.PagedTileLayout.PageListener;
 import com.android.systemui.qs.QSPanel.QSTileLayout;
 import com.android.systemui.qs.QSTile.Host.Callback;
@@ -65,6 +66,7 @@
     private boolean mFullRows;
     private int mNumQuickTiles;
     private float mLastPosition;
+    private QSTileHost mHost;
 
     public QSAnimator(QSContainer container, QuickQSPanel quickPanel, QSPanel panel) {
         mQsContainer = container;
@@ -94,6 +96,7 @@
     }
 
     public void setHost(QSTileHost qsh) {
+        mHost = qsh;
         qsh.addCallback(this);
         updateAnimators();
     }
@@ -106,6 +109,9 @@
 
     @Override
     public void onViewDetachedFromWindow(View v) {
+        if (mHost != null) {
+            mHost.removeCallback(this);
+        }
         TunerService.get(mQsContainer.getContext()).removeTunable(this);
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSContainer.java b/packages/SystemUI/src/com/android/systemui/qs/QSContainer.java
index 8d6e17e..d5fb8f2 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSContainer.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSContainer.java
@@ -178,6 +178,7 @@
     private void updateQsState() {
         boolean expandVisually = mQsExpanded || mStackScrollerOverscrolling || mHeaderAnimating;
         mQSPanel.setExpanded(mQsExpanded);
+        mQSDetail.setExpanded(mQsExpanded);
         mHeader.setVisibility((mQsExpanded || !mKeyguardShowing || mHeaderAnimating)
                 ? View.VISIBLE
                 : View.INVISIBLE);
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSDetail.java b/packages/SystemUI/src/com/android/systemui/qs/QSDetail.java
index 0cf7e479..a40e5b7 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSDetail.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSDetail.java
@@ -31,6 +31,7 @@
 import android.widget.LinearLayout;
 import android.widget.Switch;
 import android.widget.TextView;
+
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.FontSizeUtils;
 import com.android.systemui.R;
@@ -64,6 +65,9 @@
     private boolean mFullyExpanded;
     private View mQsDetailHeaderBack;
     private BaseStatusBarHeader mHeader;
+    private boolean mTriggeredExpand;
+    private int mOpenX;
+    private int mOpenY;
 
     public QSDetail(Context context, @Nullable AttributeSet attrs) {
         super(context, attrs);
@@ -112,6 +116,7 @@
     public void setQsPanel(QSPanel panel, BaseStatusBarHeader header) {
         mQsPanel = panel;
         mHeader = header;
+        mHeader.setCallback(mQsPanelCallback);
         mQsPanel.setCallback(mQsPanelCallback);
     }
 
@@ -126,6 +131,12 @@
         mFullyExpanded = fullyExpanded;
     }
 
+    public void setExpanded(boolean qsExpanded) {
+        if (!qsExpanded) {
+            mTriggeredExpand = false;
+        }
+    }
+
     private void updateDetailText() {
         mDetailDoneButton.setText(R.string.quick_settings_done);
         mDetailSettingsButton.setText(R.string.quick_settings_more_settings);
@@ -161,6 +172,22 @@
                     }
                 });
             }
+            if (!mFullyExpanded) {
+                mTriggeredExpand = true;
+                mHost.animateToggleQSExpansion();
+            } else {
+                mTriggeredExpand = false;
+            }
+            mOpenX = x;
+            mOpenY = y;
+        } else {
+            // Ensure we collapse into the same point we opened from.
+            x = mOpenX;
+            y = mOpenY;
+            if (mTriggeredExpand) {
+                mHost.animateToggleQSExpansion();
+                mTriggeredExpand = false;
+            }
         }
 
         boolean visibleDiff = (mDetailAdapter != null) != (adapter != null);
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
index 6945176..2c874e5 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
@@ -23,6 +23,7 @@
 import android.os.Handler;
 import android.os.Message;
 import android.util.AttributeSet;
+import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.widget.ImageView;
@@ -56,7 +57,7 @@
 
     private int mPanelPaddingBottom;
     private int mBrightnessPaddingTop;
-    private boolean mExpanded;
+    protected boolean mExpanded;
     protected boolean mListening;
 
     private Callback mCallback;
@@ -70,7 +71,6 @@
 
     private QSCustomizer mCustomizePanel;
     private Record mDetailRecord;
-    private boolean mTriggeredExpand;
 
     public QSPanel(Context context) {
         this(context, null);
@@ -221,7 +221,6 @@
         }
         MetricsLogger.visibility(mContext, MetricsEvent.QS_PANEL, mExpanded);
         if (!mExpanded) {
-            mTriggeredExpand = false;
             closeDetail();
         } else {
             logTiles();
@@ -279,6 +278,7 @@
     public void setTiles(Collection<QSTile<?>> tiles, boolean collapsedView) {
         for (TileRecord record : mRecords) {
             mTileLayout.removeTile(record);
+            record.tile.removeCallback(record.callback);
         }
         mRecords.clear();
         for (QSTile<?> tile : tiles) {
@@ -294,6 +294,10 @@
         return new QSTileView(mContext, tile.createTileView(mContext), collapsedView);
     }
 
+    protected boolean shouldShowDetail() {
+        return mExpanded;
+    }
+
     protected void addTile(final QSTile<?> tile, boolean collapsedView) {
         final TileRecord r = new TileRecord();
         r.tile = tile;
@@ -306,7 +310,11 @@
 
             @Override
             public void onShowDetail(boolean show) {
-                QSPanel.this.showDetail(show, r);
+                // Both the collapsed and full QS panels get this callback, this check determines
+                // which one should handle showing the detail.
+                if (shouldShowDetail()) {
+                    QSPanel.this.showDetail(show, r);
+                }
             }
 
             @Override
@@ -330,6 +338,7 @@
             }
         };
         r.tile.addCallback(callback);
+        r.callback = callback;
         final View.OnClickListener click = new View.OnClickListener() {
             @Override
             public void onClick(View v) {
@@ -390,17 +399,6 @@
     }
 
     protected void handleShowDetail(Record r, boolean show) {
-        if (show) {
-            if (!mExpanded) {
-                mTriggeredExpand = true;
-                mHost.animateToggleQSExpansion();
-            } else {
-                mTriggeredExpand = false;
-            }
-        } else if (mTriggeredExpand) {
-            mHost.animateToggleQSExpansion();
-            mTriggeredExpand = false;
-        }
         if (r instanceof TileRecord) {
             handleShowDetailTile((TileRecord) r, show);
         } else {
@@ -520,6 +518,7 @@
         public QSTile<?> tile;
         public QSTileBaseView tileView;
         public boolean scanState;
+        public QSTile.Callback callback;
     }
 
     public interface Callback {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSTile.java b/packages/SystemUI/src/com/android/systemui/qs/QSTile.java
index 8d9f23f..974de08 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSTile.java
@@ -161,6 +161,10 @@
         mHandler.obtainMessage(H.ADD_CALLBACK, callback).sendToTarget();
     }
 
+    public void removeCallback(Callback callback) {
+        mHandler.obtainMessage(H.REMOVE_CALLBACK, callback).sendToTarget();
+    }
+
     public void removeCallbacks() {
         mHandler.sendEmptyMessage(H.REMOVE_CALLBACKS);
     }
@@ -224,6 +228,10 @@
         handleRefreshState(null);
     }
 
+    private void handleRemoveCallback(Callback callback) {
+        mCallbacks.remove(callback);
+    }
+
     private void handleRemoveCallbacks() {
         mCallbacks.clear();
     }
@@ -334,7 +342,8 @@
         private static final int DESTROY = 10;
         private static final int CLEAR_STATE = 11;
         private static final int REMOVE_CALLBACKS = 12;
-        private static final int SET_LISTENING = 13;
+        private static final int REMOVE_CALLBACK = 13;
+        private static final int SET_LISTENING = 14;
 
         private H(Looper looper) {
             super(looper);
@@ -350,6 +359,9 @@
                 } else if (msg.what == REMOVE_CALLBACKS) {
                     name = "handleRemoveCallbacks";
                     handleRemoveCallbacks();
+                } else if (msg.what == REMOVE_CALLBACK) {
+                    name = "handleRemoveCallback";
+                    handleRemoveCallback((QSTile.Callback) msg.obj);
                 } else if (msg.what == CLICK) {
                     name = "handleClick";
                     if (mState.disabledByPolicy) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
index b28d0f2..c984abe 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickQSPanel.java
@@ -77,6 +77,11 @@
     }
 
     @Override
+    protected boolean shouldShowDetail() {
+        return !mExpanded;
+    }
+
+    @Override
     protected void drawTile(TileRecord r, State state) {
         if (state instanceof SignalState) {
             State copy = r.tile.newTileState();
@@ -90,11 +95,6 @@
     }
 
     @Override
-    protected void showDetail(boolean show, Record r) {
-        // Do nothing, will be handled by the QSPanel.
-    }
-
-    @Override
     protected QSTileBaseView createTileView(QSTile<?> tile, boolean collapsedView) {
         return new QSTileBaseView(mContext, tile.createTileView(mContext), collapsedView);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java b/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
index 4bf85c7..8a0079d 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
@@ -42,6 +42,7 @@
 import com.android.systemui.statusbar.phone.NotificationsQuickSettingsContainer;
 import com.android.systemui.statusbar.phone.PhoneStatusBar;
 import com.android.systemui.statusbar.phone.QSTileHost;
+import com.android.systemui.statusbar.policy.KeyguardMonitor.Callback;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -141,6 +142,7 @@
             mNotifQsContainer.setCustomizerShowing(true);
             announceForAccessibility(mContext.getString(
                     R.string.accessibility_desc_quick_settings_edit));
+            mHost.getKeyguardMonitor().addCallback(mKeyguardCallback);
         }
     }
 
@@ -156,6 +158,7 @@
             mNotifQsContainer.setCustomizerShowing(false);
             announceForAccessibility(mContext.getString(
                     R.string.accessibility_desc_quick_settings));
+            mHost.getKeyguardMonitor().removeCallback(mKeyguardCallback);
         }
     }
 
@@ -201,6 +204,15 @@
         mTileAdapter.saveSpecs(mHost);
     }
 
+    private final Callback mKeyguardCallback = new Callback() {
+        @Override
+        public void onKeyguardChanged() {
+            if (mHost.getKeyguardMonitor().isShowing()) {
+                hide(0, 0);
+            }
+        }
+    };
+
     private final AnimatorListener mExpandAnimationListener = new AnimatorListenerAdapter() {
         @Override
         public void onAnimationEnd(Animator animation) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/external/TileLifecycleManager.java b/packages/SystemUI/src/com/android/systemui/qs/external/TileLifecycleManager.java
index 16b1158..87d6307 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/external/TileLifecycleManager.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/external/TileLifecycleManager.java
@@ -134,9 +134,14 @@
             }
             if (DEBUG) Log.d(TAG, "Binding service " + mIntent + " " + mUser);
             mBindTryCount++;
-            mIsBound = mContext.bindServiceAsUser(mIntent, this,
-                    Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE,
-                    mUser);
+            try {
+                mIsBound = mContext.bindServiceAsUser(mIntent, this,
+                        Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE,
+                        mUser);
+            } catch (SecurityException e) {
+                Log.e(TAG, "Failed to bind to service", e);
+                mIsBound = false;
+            }
         } else {
             if (DEBUG) Log.d(TAG, "Unbinding service " + mIntent + " " + mUser);
             // Give it another chance next time it needs to be bound, out of kindness.
diff --git a/packages/SystemUI/src/com/android/systemui/qs/external/TileServiceManager.java b/packages/SystemUI/src/com/android/systemui/qs/external/TileServiceManager.java
index 82a5622..ce9bbf4 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/external/TileServiceManager.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/external/TileServiceManager.java
@@ -21,13 +21,20 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
 import android.net.Uri;
 import android.os.Handler;
 import android.os.UserHandle;
 import android.service.quicksettings.IQSTileService;
+import android.service.quicksettings.TileService;
 import android.support.annotation.VisibleForTesting;
 import android.util.Log;
+
 import com.android.systemui.qs.external.TileLifecycleManager.TileChangeListener;
+
+import java.util.List;
+
 import libcore.util.Objects;
 
 /**
@@ -222,15 +229,29 @@
             if (!Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
                 return;
             }
-            if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
-                return;
-            }
+
             Uri data = intent.getData();
             String pkgName = data.getEncodedSchemeSpecificPart();
             final ComponentName component = mStateManager.getComponent();
             if (!Objects.equal(pkgName, component.getPackageName())) {
                 return;
             }
+
+            // If the package is being updated, verify the component still exists.
+            if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
+                Intent queryIntent = new Intent(TileService.ACTION_QS_TILE);
+                queryIntent.setPackage(pkgName);
+                PackageManager pm = context.getPackageManager();
+                List<ResolveInfo> services = pm.queryIntentServicesAsUser(
+                        queryIntent, 0, ActivityManager.getCurrentUser());
+                for (ResolveInfo info : services) {
+                    if (Objects.equal(info.serviceInfo.packageName, component.getPackageName())
+                            && Objects.equal(info.serviceInfo.name, component.getClassName())) {
+                        return;
+                    }
+                }
+            }
+
             mServices.getHost().removeTile(component);
         }
     };
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskCardView.java b/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskCardView.java
index 72a589f..e757560 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskCardView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskCardView.java
@@ -56,6 +56,7 @@
     private ImageView mBadgeView;
     private Task mTask;
     private boolean mDismissState;
+    private boolean mTouchExplorationEnabled;
     private int mCornerRadius;
 
     private ViewFocusAnimator mViewFocusAnimator;
@@ -90,7 +91,8 @@
                 R.dimen.recents_task_view_rounded_corners_radius);
         mRecentsRowFocusAnimationHolder = new RecentsRowFocusAnimationHolder(this, mInfoFieldView);
         SystemServicesProxy ssp = Recents.getSystemServices();
-        if (!ssp.isTouchExplorationEnabled()) {
+        mTouchExplorationEnabled = ssp.isTouchExplorationEnabled();
+        if (!mTouchExplorationEnabled) {
             mDismissIconView.setVisibility(VISIBLE);
         } else {
             mDismissIconView.setVisibility(GONE);
@@ -237,10 +239,15 @@
     private void setDismissState(boolean dismissState) {
         if (mDismissState != dismissState) {
             mDismissState = dismissState;
-            if (dismissState) {
-                mDismissAnimationsHolder.startEnterAnimation();
-            } else {
-                mDismissAnimationsHolder.startExitAnimation();
+            // Check for touch exploration to ensure dismiss icon/text do not
+            // get animated. This should be removed based on decision from
+            // b/29208918
+            if (!mTouchExplorationEnabled) {
+                if (dismissState) {
+                    mDismissAnimationsHolder.startEnterAnimation();
+                } else {
+                    mDismissAnimationsHolder.startExitAnimation();
+                }
             }
         }
     }
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskViewHeader.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskViewHeader.java
index 7b372ec..691e599 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskViewHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskViewHeader.java
@@ -31,6 +31,7 @@
 import android.graphics.PorterDuff;
 import android.graphics.Rect;
 import android.graphics.drawable.Drawable;
+import android.graphics.drawable.RippleDrawable;
 import android.os.CountDownTimer;
 import android.support.v4.graphics.ColorUtils;
 import android.util.AttributeSet;
@@ -460,6 +461,7 @@
         mDismissButton.setContentDescription(t.dismissDescription);
         mDismissButton.setOnClickListener(this);
         mDismissButton.setClickable(false);
+        ((RippleDrawable) mDismissButton.getBackground()).setForceSoftware(true);
 
         // When freeform workspaces are enabled, then update the move-task button depending on the
         // current task
@@ -477,6 +479,7 @@
             }
             mMoveTaskButton.setOnClickListener(this);
             mMoveTaskButton.setClickable(false);
+            ((RippleDrawable) mMoveTaskButton.getBackground()).setForceSoftware(true);
         }
 
         if (Recents.getDebugFlags().isFastToggleRecentsEnabled()) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/BaseStatusBarHeader.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/BaseStatusBarHeader.java
index 6e1c862..79eef43 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/BaseStatusBarHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/BaseStatusBarHeader.java
@@ -20,6 +20,7 @@
 import android.util.AttributeSet;
 import android.widget.RelativeLayout;
 import com.android.systemui.qs.QSPanel;
+import com.android.systemui.qs.QSPanel.Callback;
 import com.android.systemui.statusbar.policy.BatteryController;
 import com.android.systemui.statusbar.policy.NetworkControllerImpl;
 import com.android.systemui.statusbar.policy.NextAlarmController;
@@ -44,4 +45,5 @@
     public abstract void setBatteryController(BatteryController batteryController);
     public abstract void setNextAlarmController(NextAlarmController nextAlarmController);
     public abstract void setUserInfoController(UserInfoController userInfoController);
+    public abstract void setCallback(Callback qsPanelCallback);
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
index 8bb1f24..e091d6dc 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
@@ -38,6 +38,7 @@
 import com.android.systemui.R;
 import com.android.systemui.qs.QSAnimator;
 import com.android.systemui.qs.QSPanel;
+import com.android.systemui.qs.QSPanel.Callback;
 import com.android.systemui.qs.QuickQSPanel;
 import com.android.systemui.qs.TouchAnimator;
 import com.android.systemui.statusbar.policy.BatteryController;
@@ -93,6 +94,7 @@
     protected TouchAnimator mSettingsAlpha;
     private float mExpansionAmount;
     private QSTileHost mHost;
+    private boolean mShowFullAlarm;
 
     public QuickStatusBarHeader(Context context, AttributeSet attrs) {
         super(context, attrs);
@@ -109,8 +111,7 @@
         mDateTimeGroup = (ViewGroup) findViewById(R.id.date_time_group);
         mDateTimeGroup.setPivotX(0);
         mDateTimeGroup.setPivotY(0);
-        boolean showDate = getResources().getBoolean(R.bool.quick_settings_show_date);
-        findViewById(R.id.date).setVisibility(showDate ? View.VISIBLE : View.GONE);
+        mShowFullAlarm = getResources().getBoolean(R.bool.quick_settings_show_full_alarm);
 
         mExpandIndicator = (ExpandableIndicator) findViewById(R.id.expand_indicator);
 
@@ -165,14 +166,16 @@
         updateDateTimePosition();
 
         mSecondHalfAnimator = new TouchAnimator.Builder()
-                .addFloat(mAlarmStatus, "alpha", 0, 1)
+                .addFloat(mShowFullAlarm ? mAlarmStatus : findViewById(R.id.date), "alpha", 0, 1)
                 .addFloat(mEmergencyOnly, "alpha", 0, 1)
                 .setStartDelay(.5f)
                 .build();
-        mFirstHalfAnimator = new TouchAnimator.Builder()
-                .addFloat(mAlarmStatusCollapsed, "alpha", 1, 0)
-                .setEndDelay(.5f)
-                .build();
+        if (mShowFullAlarm) {
+            mFirstHalfAnimator = new TouchAnimator.Builder()
+                    .addFloat(mAlarmStatusCollapsed, "alpha", 1, 0)
+                    .setEndDelay(.5f)
+                    .build();
+        }
         mDateSizeAnimator = new TouchAnimator.Builder()
                 .addFloat(mDateTimeGroup, "scaleX", 1, mDateScaleFactor)
                 .addFloat(mDateTimeGroup, "scaleY", 1, mDateScaleFactor)
@@ -220,6 +223,7 @@
     @Override
     public void setExpanded(boolean expanded) {
         mExpanded = expanded;
+        mHeaderQsPanel.setExpanded(expanded);
         updateEverything();
     }
 
@@ -244,7 +248,9 @@
     public void setExpansion(float headerExpansionFraction) {
         mExpansionAmount = headerExpansionFraction;
         mSecondHalfAnimator.setPosition(headerExpansionFraction);
-        mFirstHalfAnimator.setPosition(headerExpansionFraction);
+        if (mShowFullAlarm) {
+            mFirstHalfAnimator.setPosition(headerExpansionFraction);
+        }
         mDateSizeAnimator.setPosition(headerExpansionFraction);
         mAlarmTranslation.setPosition(headerExpansionFraction);
         mSettingsAlpha.setPosition(headerExpansionFraction);
@@ -263,7 +269,7 @@
     }
 
     private void updateAlarmVisibilities() {
-        mAlarmStatus.setVisibility(mAlarmShowing ? View.VISIBLE : View.INVISIBLE);
+        mAlarmStatus.setVisibility(mAlarmShowing && mShowFullAlarm ? View.VISIBLE : View.INVISIBLE);
         mAlarmStatusCollapsed.setVisibility(mAlarmShowing ? View.VISIBLE : View.INVISIBLE);
     }
 
@@ -389,6 +395,11 @@
     }
 
     @Override
+    public void setCallback(Callback qsPanelCallback) {
+        mHeaderQsPanel.setCallback(qsPanelCallback);
+    }
+
+    @Override
     public void setEmergencyCallsOnly(boolean show) {
         boolean changed = show != mShowEmergencyCallsOnly;
         if (changed) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeaderView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeaderView.java
index a051973..72eafd8 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeaderView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeaderView.java
@@ -44,6 +44,7 @@
 import com.android.systemui.FontSizeUtils;
 import com.android.systemui.R;
 import com.android.systemui.qs.QSPanel;
+import com.android.systemui.qs.QSPanel.Callback;
 import com.android.systemui.qs.QSTile;
 import com.android.systemui.qs.QSTile.DetailAdapter;
 import com.android.systemui.statusbar.policy.BatteryController;
@@ -511,6 +512,10 @@
     }
 
     @Override
+    public void setCallback(Callback qsPanelCallback) {
+    }
+
+    @Override
     public void onClick(View v) {
         if (v == mSettingsButton) {
             if (mSettingsButton.isTunerClick()) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
index d5f1707..7c391fb 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
@@ -873,7 +873,8 @@
             ExpandableNotificationRow row = (ExpandableNotificationRow) child;
             ExpandableNotificationRow parent = row.getNotificationParent();
             if (parent != null && parent.areChildrenExpanded()
-                    && (mGearExposedView == parent
+                    && (parent.areGutsExposed()
+                        || mGearExposedView == parent
                         || (parent.getNotificationChildren().size() == 1
                                 && parent.isClearable()))) {
                 // In this case the group is expanded and showing the gear for the
@@ -961,6 +962,7 @@
     public boolean canChildBeExpanded(View v) {
         return v instanceof ExpandableNotificationRow
                 && ((ExpandableNotificationRow) v).isExpandable()
+                && !((ExpandableNotificationRow) v).areGutsExposed()
                 && (mIsExpanded || !((ExpandableNotificationRow) v).isPinned());
     }
 
@@ -2097,7 +2099,9 @@
         final ExpandableView firstChild = getFirstChildNotGone();
         int firstChildMinHeight = firstChild != null
                 ? firstChild.getIntrinsicHeight()
-                : mCollapsedSize;
+                : mEmptyShadeView != null
+                        ? mEmptyShadeView.getMinHeight()
+                        : mCollapsedSize;
         if (mOwnScrollY > 0) {
             firstChildMinHeight = Math.max(firstChildMinHeight - mOwnScrollY, mCollapsedSize);
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/stack/StackScrollAlgorithm.java b/packages/SystemUI/src/com/android/systemui/statusbar/stack/StackScrollAlgorithm.java
index 5d26988..c8c7d3d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/StackScrollAlgorithm.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/StackScrollAlgorithm.java
@@ -171,6 +171,12 @@
     }
 
     public static boolean canChildBeDismissed(View v) {
+        if (v instanceof ExpandableNotificationRow) {
+            ExpandableNotificationRow row = (ExpandableNotificationRow) v;
+            if (row.areGutsExposed()) {
+                return false;
+            }
+        }
         final View veto = v.findViewById(R.id.veto);
         return (veto != null && veto.getVisibility() != View.GONE);
     }
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index acc2ec3..334b228 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -9849,7 +9849,11 @@
 
         synchronized(this) {
             if (mActiveRestoreSession != null) {
-                Slog.d(TAG, "Restore session requested but one already active");
+                Slog.i(TAG, "Restore session requested but one already active");
+                return null;
+            }
+            if (mBackupRunning) {
+                Slog.i(TAG, "Restore session requested but currently running backups");
                 return null;
             }
             mActiveRestoreSession = new ActiveRestoreSession(packageName, transport);
diff --git a/services/core/java/com/android/server/BluetoothManagerService.java b/services/core/java/com/android/server/BluetoothManagerService.java
index 3eadb5c..9154b8e 100644
--- a/services/core/java/com/android/server/BluetoothManagerService.java
+++ b/services/core/java/com/android/server/BluetoothManagerService.java
@@ -222,7 +222,7 @@
                             } catch (RemoteException e) {
                                 Slog.e(TAG,"Unable to call onBrEdrDown", e);
                             } finally {
-                                mBluetoothLock.readLock().lock();
+                                mBluetoothLock.readLock().unlock();
                             }
                         } else if (st == BluetoothAdapter.STATE_ON){
                             // disable without persisting the setting
diff --git a/services/core/java/com/android/server/LocationManagerService.java b/services/core/java/com/android/server/LocationManagerService.java
index e0b4960..36ec2eb 100644
--- a/services/core/java/com/android/server/LocationManagerService.java
+++ b/services/core/java/com/android/server/LocationManagerService.java
@@ -1431,6 +1431,13 @@
                 for (UpdateRecord record : records) {
                     if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
                         LocationRequest locationRequest = record.mRequest;
+
+                        // Don't assign battery blame for update records whose
+                        // client has no permission to receive location data.
+                        if (!providerRequest.locationRequests.contains(locationRequest)) {
+                            continue;
+                        }
+
                         if (locationRequest.getInterval() <= thresholdInterval) {
                             if (record.mReceiver.mWorkSource != null
                                     && record.mReceiver.mWorkSource.size() > 0
diff --git a/services/core/java/com/android/server/MountService.java b/services/core/java/com/android/server/MountService.java
index c89b6ea..9c75a00 100644
--- a/services/core/java/com/android/server/MountService.java
+++ b/services/core/java/com/android/server/MountService.java
@@ -3031,7 +3031,8 @@
                 if (forWrite) {
                     match = vol.isVisibleForWrite(userId);
                 } else {
-                    match = vol.isVisibleForRead(userId) || includeInvisible;
+                    match = vol.isVisibleForRead(userId)
+                            || (includeInvisible && vol.getPath() != null);
                 }
                 if (!match) continue;
 
diff --git a/services/core/java/com/android/server/PersistentDataBlockService.java b/services/core/java/com/android/server/PersistentDataBlockService.java
index 2085f32..680547a 100644
--- a/services/core/java/com/android/server/PersistentDataBlockService.java
+++ b/services/core/java/com/android/server/PersistentDataBlockService.java
@@ -125,10 +125,20 @@
         SystemProperties.set(OEM_UNLOCK_PROP, enabled ? "1" : "0");
     }
 
-    private void enforceOemUnlockPermission() {
+    private void enforceOemUnlockReadPermission() {
+        if (mContext.checkCallingOrSelfPermission(Manifest.permission.READ_OEM_UNLOCK_STATE)
+                == PackageManager.PERMISSION_DENIED
+                && mContext.checkCallingOrSelfPermission(Manifest.permission.OEM_UNLOCK_STATE)
+                == PackageManager.PERMISSION_DENIED) {
+            throw new SecurityException("Can't access OEM unlock state. Requires "
+                    + "READ_OEM_UNLOCK_STATE or OEM_UNLOCK_STATE permission.");
+        }
+    }
+
+    private void enforceOemUnlockWritePermission() {
         mContext.enforceCallingOrSelfPermission(
                 Manifest.permission.OEM_UNLOCK_STATE,
-                "Can't access OEM unlock state");
+                "Can't modify OEM unlock state");
     }
 
     private void enforceUid(int callingUid) {
@@ -425,7 +435,7 @@
 
         @Override
         public void wipe() {
-            enforceOemUnlockPermission();
+            enforceOemUnlockWritePermission();
 
             synchronized (mLock) {
                 int ret = nativeWipe(mDataBlockFile);
@@ -442,7 +452,7 @@
             if (ActivityManager.isUserAMonkey()) {
                 return;
             }
-            enforceOemUnlockPermission();
+            enforceOemUnlockWritePermission();
             enforceIsAdmin();
 
             synchronized (mLock) {
@@ -453,13 +463,13 @@
 
         @Override
         public boolean getOemUnlockEnabled() {
-            enforceOemUnlockPermission();
+            enforceOemUnlockReadPermission();
             return doGetOemUnlockEnabled();
         }
 
         @Override
         public int getFlashLockState() {
-            enforceOemUnlockPermission();
+            enforceOemUnlockReadPermission();
             String locked = SystemProperties.get(FLASH_LOCK_PROP);
             switch (locked) {
                 case FLASH_LOCK_LOCKED:
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 32aeea8..3fd78fde 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -267,6 +267,7 @@
 import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
 import static android.content.pm.PackageManager.GET_PROVIDERS;
 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
+import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
@@ -6035,7 +6036,7 @@
         if (appId < 0 && packageName != null) {
             try {
                 appId = UserHandle.getAppId(AppGlobals.getPackageManager()
-                        .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId));
+                        .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0));
             } catch (RemoteException e) {
             }
         }
@@ -7820,7 +7821,7 @@
         return ActivityManager.APP_START_MODE_NORMAL;
     }
 
-    private ProviderInfo getProviderInfoLocked(String authority, int userHandle) {
+    private ProviderInfo getProviderInfoLocked(String authority, int userHandle, int pmFlags) {
         ProviderInfo pi = null;
         ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle);
         if (cpr != null) {
@@ -7828,7 +7829,8 @@
         } else {
             try {
                 pi = AppGlobals.getPackageManager().resolveContentProvider(
-                        authority, PackageManager.GET_URI_PERMISSION_PATTERNS, userHandle);
+                        authority, PackageManager.GET_URI_PERMISSION_PATTERNS | pmFlags,
+                        userHandle);
             } catch (RemoteException ex) {
             }
         }
@@ -7951,7 +7953,8 @@
         }
 
         final String authority = grantUri.uri.getAuthority();
-        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
+        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId,
+                MATCH_DEBUG_TRIAGED_MISSING);
         if (pi == null) {
             Slog.w(TAG, "No content provider found for permission check: " +
                     grantUri.uri.toSafeString());
@@ -8078,7 +8081,8 @@
                 "Granting " + targetPkg + "/" + targetUid + " permission to " + grantUri);
 
         final String authority = grantUri.uri.getAuthority();
-        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
+        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId,
+                MATCH_DEBUG_TRIAGED_MISSING);
         if (pi == null) {
             Slog.w(TAG, "No content provider found for grant: " + grantUri.toSafeString());
             return;
@@ -8293,7 +8297,8 @@
 
         final IPackageManager pm = AppGlobals.getPackageManager();
         final String authority = grantUri.uri.getAuthority();
-        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
+        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId,
+                MATCH_DEBUG_TRIAGED_MISSING);
         if (pi == null) {
             Slog.w(TAG, "No content provider found for permission revoke: "
                     + grantUri.toSafeString());
@@ -8390,7 +8395,8 @@
             }
 
             final String authority = uri.getAuthority();
-            final ProviderInfo pi = getProviderInfoLocked(authority, userId);
+            final ProviderInfo pi = getProviderInfoLocked(authority, userId,
+                    MATCH_DEBUG_TRIAGED_MISSING);
             if (pi == null) {
                 Slog.w(TAG, "No content provider found for permission revoke: "
                         + uri.toSafeString());
@@ -8624,8 +8630,11 @@
                         final long createdTime = readLongAttribute(in, ATTR_CREATED_TIME, now);
 
                         // Sanity check that provider still belongs to source package
+                        // Both direct boot aware and unaware packages are fine as we
+                        // will do filtering at query time to avoid multiple parsing.
                         final ProviderInfo pi = getProviderInfoLocked(
-                                uri.getAuthority(), sourceUserId);
+                                uri.getAuthority(), sourceUserId, MATCH_DIRECT_BOOT_AWARE
+                                        | MATCH_DIRECT_BOOT_UNAWARE);
                         if (pi != null && sourcePkg.equals(pi.packageName)) {
                             int targetUid = -1;
                             try {
@@ -8804,8 +8813,30 @@
                 if (perms == null) {
                     Slog.w(TAG, "No permission grants found for " + packageName);
                 } else {
+                    final int userId = UserHandle.getUserId(callingUid);
+                    Set<String> existingAuthorities = null;
+
                     for (UriPermission perm : perms.values()) {
                         if (packageName.equals(perm.targetPkg) && perm.persistedModeFlags != 0) {
+                            // Is this provider available in the current boot state? If the user
+                            // is not running and unlocked we check if the provider package exists.
+                            if (!mUserController.isUserRunningLocked(userId,
+                                    ActivityManager.FLAG_AND_UNLOCKED)) {
+                                String authority = perm.uri.uri.getAuthority();
+                                if (existingAuthorities == null
+                                        || !existingAuthorities.contains(authority)) {
+                                    ProviderInfo providerInfo = getProviderInfoLocked(authority,
+                                            userId, MATCH_DEBUG_TRIAGED_MISSING);
+                                    if (providerInfo != null) {
+                                        if (existingAuthorities == null) {
+                                            existingAuthorities = new ArraySet<>();
+                                        }
+                                        existingAuthorities.add(authority);
+                                    } else {
+                                        continue;
+                                    }
+                                }
+                            }
                             result.add(perm.buildPersistedPublicApiObject());
                         }
                     }
@@ -13850,7 +13881,12 @@
                             args.length - opti);
                 }
                 synchronized (this) {
-                    dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage);
+                    if (dumpCheckinFormat) {
+                        dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin,
+                                dumpPackage);
+                    } else {
+                        dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage);
+                    }
                 }
             } else if ("intents".equals(cmd) || "i".equals(cmd)) {
                 String[] newArgs;
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index 0e4c9a4..52c002d 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -1097,21 +1097,7 @@
             // Don't debug things in the system process
             if (!aInfo.processName.equals("system")) {
                 if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
-                    final ProcessRecord app = mService.getProcessRecordLocked(
-                            aInfo.processName, aInfo.applicationInfo.uid, true);
-                    // If the process already started, we can't wait for debugger and shouldn't
-                    // modify the debug settings.
-                    // For non-persistent debug, normally we set the debug app here, and restores
-                    // to the original at attachApplication time. However, if the app process
-                    // already exists, we won't get another attachApplication, and the debug setting
-                    // never gets restored. Furthermore, if we get two such calls back-to-back,
-                    // both mOrigDebugApp and mDebugApp will become the same app, and it won't be
-                    // cleared even if we get attachApplication after the app process is killed.
-                    if (app == null || app.thread == null) {
-                        mService.setDebugApp(aInfo.processName, true, false);
-                    } else {
-                        Slog.w(TAG, "Ignoring waitForDebugger because process already exists");
-                    }
+                    mService.setDebugApp(aInfo.processName, true, false);
                 }
 
                 if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
diff --git a/services/core/java/com/android/server/am/ActivityStarter.java b/services/core/java/com/android/server/am/ActivityStarter.java
index 61b1317..522e42b 100644
--- a/services/core/java/com/android/server/am/ActivityStarter.java
+++ b/services/core/java/com/android/server/am/ActivityStarter.java
@@ -166,8 +166,9 @@
     private Intent mNewTaskIntent;
     private ActivityStack mSourceStack;
     private ActivityStack mTargetStack;
-    // TODO: Is the mMoveHome flag really needed?
-    private boolean mMovedHome;
+    // Indicates that we moved other task and are going to put something on top soon, so
+    // we don't want to show it redundantly or accidentally change what's shown below.
+    private boolean mMovedOtherTask;
     private boolean mMovedToFront;
     private boolean mNoAnimation;
     private boolean mKeepCurTransition;
@@ -204,7 +205,7 @@
         mSourceStack = null;
 
         mTargetStack = null;
-        mMovedHome = false;
+        mMovedOtherTask = false;
         mMovedToFront = false;
         mNoAnimation = false;
         mKeepCurTransition = false;
@@ -1013,7 +1014,6 @@
                 resumeTargetStackIfNeeded();
                 return START_RETURN_INTENT_TO_CALLER;
             }
-
             setTaskFromIntentActivity(mReusedActivity);
 
             if (!mAddingToTask && mReuseTask == null) {
@@ -1082,7 +1082,7 @@
                 Slog.e(TAG, "Attempted Lock Task Mode violation mStartActivity=" + mStartActivity);
                 return START_RETURN_LOCK_TASK_MODE_VIOLATION;
             }
-            if (!mMovedHome) {
+            if (!mMovedOtherTask) {
                 updateTaskReturnToType(mStartActivity.task, mLaunchFlags, topStack);
             }
         } else if (mSourceRecord != null) {
@@ -1443,7 +1443,7 @@
                 if (mLaunchTaskBehind && mSourceRecord != null) {
                     intentActivity.setTaskToAffiliateWith(mSourceRecord.task);
                 }
-                mMovedHome = true;
+                mMovedOtherTask = true;
 
                 // If the launch flags carry both NEW_TASK and CLEAR_TASK, the task's activities
                 // will be cleared soon by ActivityStarter in setTaskFromIntentActivity().
@@ -1521,6 +1521,10 @@
             mReuseTask = intentActivity.task;
             mReuseTask.performClearTaskLocked();
             mReuseTask.setIntent(mStartActivity);
+            // When we clear the task - focus will be adjusted, which will bring another task
+            // to top before we launch the activity we need. This will temporary swap their
+            // mTaskToReturnTo values and we don't want to overwrite them accidentally.
+            mMovedOtherTask = true;
         } else if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
                 || mLaunchSingleInstance || mLaunchSingleTask) {
             ActivityRecord top = intentActivity.task.performClearTaskLocked(mStartActivity,
diff --git a/services/core/java/com/android/server/fingerprint/FingerprintService.java b/services/core/java/com/android/server/fingerprint/FingerprintService.java
index 142426d..cc556c7 100644
--- a/services/core/java/com/android/server/fingerprint/FingerprintService.java
+++ b/services/core/java/com/android/server/fingerprint/FingerprintService.java
@@ -96,7 +96,7 @@
 
     private static final long FAIL_LOCKOUT_TIMEOUT_MS = 30*1000;
     private static final int MAX_FAILED_ATTEMPTS = 5;
-    private static final long CANCEL_TIMEOUT_LIMIT = 300; // max wait for onCancel() from HAL,in ms
+    private static final long CANCEL_TIMEOUT_LIMIT = 3000; // max wait for onCancel() from HAL,in ms
     private final String mKeyguardPackage;
     private int mCurrentUserId = UserHandle.USER_CURRENT;
     private final FingerprintUtils mFingerprintUtils = FingerprintUtils.getInstance();
diff --git a/services/core/java/com/android/server/notification/ScheduleCalendar.java b/services/core/java/com/android/server/notification/ScheduleCalendar.java
index 9267d82..22ca702 100644
--- a/services/core/java/com/android/server/notification/ScheduleCalendar.java
+++ b/services/core/java/com/android/server/notification/ScheduleCalendar.java
@@ -58,11 +58,7 @@
         final long nextEnd = getNextTime(now, mSchedule.endHour, mSchedule.endMinute);
         long nextScheduleTime = Math.min(nextStart, nextEnd);
 
-        if (mSchedule.exitAtAlarm && mSchedule.nextAlarm > now) {
-            return Math.min(nextScheduleTime, mSchedule.nextAlarm);
-        } else {
-            return nextScheduleTime;
-        }
+        return nextScheduleTime;
     }
 
     private long getNextTime(long now, int hr, int min) {
@@ -124,4 +120,4 @@
         mCalendar.add(Calendar.DATE, days);
         return mCalendar.getTimeInMillis();
     }
-}
\ No newline at end of file
+}
diff --git a/services/core/java/com/android/server/notification/ScheduleConditionProvider.java b/services/core/java/com/android/server/notification/ScheduleConditionProvider.java
index e3dcf14..8197544 100644
--- a/services/core/java/com/android/server/notification/ScheduleConditionProvider.java
+++ b/services/core/java/com/android/server/notification/ScheduleConditionProvider.java
@@ -43,8 +43,8 @@
  * Built-in zen condition provider for daily scheduled time-based conditions.
  */
 public class ScheduleConditionProvider extends SystemConditionProviderService {
-    private static final String TAG = "ConditionProviders.SCP";
-    private static final boolean DEBUG = true || Log.isLoggable("ConditionProviders", Log.DEBUG);
+    static final String TAG = "ConditionProviders.SCP";
+    static final boolean DEBUG = true || Log.isLoggable("ConditionProviders", Log.DEBUG);
 
     public static final ComponentName COMPONENT =
             new ComponentName("android", ScheduleConditionProvider.class.getName());
@@ -154,6 +154,9 @@
                 cal.maybeSetNextAlarm(now, nextUserAlarmTime);
             } else {
                 notifyCondition(conditionId, Condition.STATE_FALSE, "!meetsSchedule");
+                if (nextUserAlarmTime == 0) {
+                    cal.maybeSetNextAlarm(now, nextUserAlarmTime);
+                }
             }
             if (cal != null) {
                 final long nextChangeTime = cal.getNextChangeTime(now);
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index a7bd4ab..1906da7 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -7520,9 +7520,11 @@
                 throw new IllegalArgumentException("Unknown package: " + packageName);
             }
         }
-        /* Only the shell or the app user should be able to dump profiles. */
+        /* Only the shell, root, or the app user should be able to dump profiles. */
         int callingUid = Binder.getCallingUid();
-        if (callingUid != Process.SHELL_UID && callingUid != pkg.applicationInfo.uid) {
+        if (callingUid != Process.SHELL_UID &&
+            callingUid != Process.ROOT_UID &&
+            callingUid != pkg.applicationInfo.uid) {
             throw new SecurityException("dumpProfiles");
         }
 
@@ -7530,16 +7532,7 @@
             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
             final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
             try {
-                final File codeFile = new File(pkg.applicationInfo.getCodePath());
-                List<String> allCodePaths = Collections.EMPTY_LIST;
-                if (codeFile != null && codeFile.exists()) {
-                    try {
-                        final PackageLite codePkg = PackageParser.parsePackageLite(codeFile, 0);
-                        allCodePaths = codePkg.getAllCodePaths();
-                    } catch (PackageParserException e) {
-                        // Well, we tried.
-                    }
-                }
+                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
                 String gid = Integer.toString(sharedGid);
                 String codePaths = TextUtils.join(";", allCodePaths);
                 mInstaller.dumpProfiles(gid, packageName, codePaths);
@@ -8620,7 +8613,11 @@
             // We don't expect installation to fail beyond this point
 
             if (pkgSetting.pkg != null) {
-                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, user);
+                // Note that |user| might be null during the initial boot scan. If a codePath
+                // for an app has changed during a boot scan, it's due to an app update that's
+                // part of the system partition and marker changes must be applied to all users.
+                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
+                    (user != null) ? user : UserHandle.ALL);
             }
 
             // Add the new setting to mSettings
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index b916790..e7518e7 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -167,6 +167,12 @@
     private static final String RESTRICTIONS_FILE_PREFIX = "res_";
     private static final String XML_SUFFIX = ".xml";
 
+    private static final int ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION =
+            UserInfo.FLAG_MANAGED_PROFILE
+            | UserInfo.FLAG_EPHEMERAL
+            | UserInfo.FLAG_RESTRICTED
+            | UserInfo.FLAG_GUEST;
+
     private static final int MIN_USER_ID = 10;
     // We need to keep process uid within Integer.MAX_VALUE.
     private static final int MAX_USER_ID = Integer.MAX_VALUE / UserHandle.PER_USER_RANGE;
@@ -465,7 +471,7 @@
 
     @Override
     public @NonNull List<UserInfo> getUsers(boolean excludeDying) {
-        checkManageUsersPermission("query users");
+        checkManageOrCreateUsersPermission("query users");
         synchronized (mUsersLock) {
             ArrayList<UserInfo> users = new ArrayList<UserInfo>(mUsers.size());
             final int userSize = mUsers.size();
@@ -1407,6 +1413,41 @@
     }
 
     /**
+     * Enforces that only the system UID or root's UID or apps that have the
+     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
+     * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}
+     * can make certain calls to the UserManager.
+     *
+     * @param message used as message if SecurityException is thrown
+     * @throws SecurityException if the caller is not system or root
+     * @see #hasManageOrCreateUsersPermission()
+     */
+    private static final void checkManageOrCreateUsersPermission(String message) {
+        if (!hasManageOrCreateUsersPermission()) {
+            throw new SecurityException(
+                    "You either need MANAGE_USERS or CREATE_USERS permission to: " + message);
+        }
+    }
+
+    /**
+     * Similar to {@link #checkManageOrCreateUsersPermission(String)} but when the caller is tries
+     * to create user/profiles other than what is allowed for
+     * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS} permission, then it will only
+     * allow callers with {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} permission.
+     */
+    private static final void checkManageOrCreateUsersPermission(int creationFlags) {
+        if ((creationFlags & ~ALLOWED_FLAGS_FOR_CREATE_USERS_PERMISSION) == 0) {
+            if (!hasManageOrCreateUsersPermission()) {
+                throw new SecurityException("You either need MANAGE_USERS or CREATE_USERS "
+                        + "permission to create an user with flags: " + creationFlags);
+            }
+        } else if (!hasManageUsersPermission()) {
+            throw new SecurityException("You need MANAGE_USERS permission to create an user "
+                    + " with flags: " + creationFlags);
+        }
+    }
+
+    /**
      * @return whether the calling UID is system UID or root's UID or the calling app has the
      * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS}.
      */
@@ -1420,6 +1461,23 @@
     }
 
     /**
+     * @return whether the calling UID is system UID or root's UID or the calling app has the
+     * {@link android.Manifest.permission#MANAGE_USERS MANAGE_USERS} or
+     * {@link android.Manifest.permission#CREATE_USERS CREATE_USERS}.
+     */
+    private static final boolean hasManageOrCreateUsersPermission() {
+        final int callingUid = Binder.getCallingUid();
+        return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
+                || callingUid == Process.ROOT_UID
+                || ActivityManager.checkComponentPermission(
+                        android.Manifest.permission.MANAGE_USERS,
+                        callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
+                || ActivityManager.checkComponentPermission(
+                        android.Manifest.permission.CREATE_USERS,
+                        callingUid, -1, true) == PackageManager.PERMISSION_GRANTED;
+    }
+
+    /**
      * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
      * UserManager.
      *
@@ -2005,13 +2063,13 @@
 
     @Override
     public UserInfo createProfileForUser(String name, int flags, int userId) {
-        checkManageUsersPermission("Only the system can create users");
+        checkManageOrCreateUsersPermission(flags);
         return createUserInternal(name, flags, userId);
     }
 
     @Override
     public UserInfo createUser(String name, int flags) {
-        checkManageUsersPermission("Only the system can create users");
+        checkManageOrCreateUsersPermission(flags);
         return createUserInternal(name, flags, UserHandle.USER_NULL);
     }
 
@@ -2255,7 +2313,7 @@
      */
     @Override
     public boolean removeUser(int userHandle) {
-        checkManageUsersPermission("Only the system can remove users");
+        checkManageOrCreateUsersPermission("Only the system can remove users");
         if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(
                 UserManager.DISALLOW_REMOVE_USER, false)) {
             Log.w(LOG_TAG, "Cannot remove user. DISALLOW_REMOVE_USER is enabled.");
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 6987744..568f94c 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -2589,8 +2589,13 @@
             final PhoneWindow win = new PhoneWindow(context);
             win.setIsStartingWindow(true);
 
-            final Resources r = context.getResources();
-            win.setTitle(r.getText(labelRes, nonLocalizedLabel));
+            CharSequence label = context.getResources().getText(labelRes, null);
+            // Only change the accessibility title if the label is localized
+            if (label != null) {
+                win.setTitle(label, true);
+            } else {
+                win.setTitle(nonLocalizedLabel, false);
+            }
 
             win.setType(
                 WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
diff --git a/services/core/java/com/android/server/wm/AccessibilityController.java b/services/core/java/com/android/server/wm/AccessibilityController.java
index 101f56f..8be5dfb 100644
--- a/services/core/java/com/android/server/wm/AccessibilityController.java
+++ b/services/core/java/com/android/server/wm/AccessibilityController.java
@@ -1203,9 +1203,6 @@
             window.layer = windowState.mLayer;
             window.token = windowState.mClient.asBinder();
             window.title = windowState.mAttrs.accessibilityTitle;
-            if (window.title == null) {
-                window.title = windowState.mAttrs.getTitle();
-            }
             window.accessibilityIdOfAnchor = windowState.mAttrs.accessibilityIdOfAnchor;
 
             WindowState attachedWindow = windowState.mAttachedWindow;
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 3f4c1d5..a882607 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -5346,7 +5346,13 @@
         // If this isn't coming from the system then don't allow disabling the lockscreen
         // to bypass security.
         if (Binder.getCallingUid() != Process.SYSTEM_UID && isKeyguardSecure()) {
-            Log.d(TAG_WM, "current mode is SecurityMode, ignore hide keyguard");
+            Log.d(TAG_WM, "current mode is SecurityMode, ignore disableKeyguard");
+            return;
+        }
+
+        // If this isn't coming from the current user, ignore it.
+        if (Binder.getCallingUserHandle().getIdentifier() != mCurrentUserId) {
+            Log.d(TAG_WM, "non-current user, ignore disableKeyguard");
             return;
         }
 
@@ -5661,6 +5667,11 @@
             mAppTransition.setCurrentUser(newUserId);
             mPolicy.setCurrentUserLw(newUserId);
 
+            // If keyguard was disabled, re-enable it
+            // TODO: Keep track of keyguardEnabled state per user and use here...
+            // e.g. enabled = mKeyguardDisableHandler.getEnabledStateForUser(newUserId);
+            mPolicy.enableKeyguard(true);
+
             // Hide windows that should not be seen by the new user.
             final int numDisplays = mDisplayContents.size();
             for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
@@ -10022,6 +10033,7 @@
         }
     }
 
+    @Override
     public void createWallpaperInputConsumer(InputChannel inputChannel) {
         synchronized (mWindowMap) {
             mWallpaperInputConsumer = new InputConsumerImpl(this, "wallpaper input", inputChannel);
@@ -10030,6 +10042,7 @@
         }
     }
 
+    @Override
     public void removeWallpaperInputConsumer() {
         synchronized (mWindowMap) {
             if (mWallpaperInputConsumer != null) {
@@ -11125,6 +11138,7 @@
         }
     }
 
+    @Override
     public void registerShortcutKey(long shortcutCode, IShortcutService shortcutKeyReceiver)
             throws RemoteException {
         if (!checkCallingPermission(Manifest.permission.REGISTER_WINDOW_MANAGER_LISTENERS,
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index 3b4c3cf..46b6976 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -230,6 +230,14 @@
 
     boolean mForceScaleUntilResize;
 
+    // WindowState.mHScale and WindowState.mVScale contain the
+    // scale according to client specified layout parameters (e.g.
+    // one layout size, with another surface size, creates such scaling).
+    // Here we track an additional scaling factor used to follow stack
+    // scaling (as in the case of the Pinned stack animation).
+    float mExtraHScale = (float) 1.0;
+    float mExtraVScale = (float) 1.0;
+
     private final Rect mTmpSize = new Rect();
 
     WindowStateAnimator(final WindowState win) {
@@ -816,22 +824,11 @@
             mTmpSize.bottom = mTmpSize.top + 1;
         }
 
-        final int displayId = w.getDisplayId();
-        float scale = 1.0f;
-        // Magnification is supported only for the default display.
-        if (mService.mAccessibilityController != null && displayId == DEFAULT_DISPLAY) {
-            final MagnificationSpec spec =
-                    mService.mAccessibilityController.getMagnificationSpecForWindowLocked(w);
-            if (spec != null && !spec.isNop()) {
-                scale = spec.scale;
-            }
-        }
-
         // Adjust for surface insets.
-        mTmpSize.left -= scale * attrs.surfaceInsets.left;
-        mTmpSize.top -= scale * attrs.surfaceInsets.top;
-        mTmpSize.right += scale * attrs.surfaceInsets.right;
-        mTmpSize.bottom += scale * attrs.surfaceInsets.bottom;
+        mTmpSize.left -= attrs.surfaceInsets.left;
+        mTmpSize.top -= attrs.surfaceInsets.top;
+        mTmpSize.right += attrs.surfaceInsets.right;
+        mTmpSize.bottom += attrs.surfaceInsets.bottom;
     }
 
     boolean hasSurface() {
@@ -1306,7 +1303,6 @@
     }
 
     private int resolveStackClip() {
-
         // App animation overrides window animation stack clip mode.
         if (mAppAnimator != null && mAppAnimator.animation != null) {
             return mAppAnimator.getStackClip();
@@ -1397,8 +1393,8 @@
         mTmpSize.set(w.mShownPosition.x, w.mShownPosition.y, 0, 0);
         calculateSurfaceBounds(w, w.getAttrs());
 
-        float extraHScale = (float) 1.0;
-        float extraVScale = (float) 1.0;
+        mExtraHScale = (float) 1.0;
+        mExtraVScale = (float) 1.0;
 
         // Once relayout has been called at least once, we need to make sure
         // we only resize the client surface during calls to relayout. For
@@ -1412,6 +1408,9 @@
         // aren't observing known issues here outside of PiP resizing. (Typically
         // the other windows that use -1 are PopupWindows which aren't likely
         // to be rendering while we resize).
+
+        boolean wasForceScaled = mForceScaleUntilResize;
+
         if (!w.inPinnedWorkspace() || (!w.mRelayoutCalled || w.mInRelayout)) {
             mSurfaceResized = mSurfaceController.setSizeInTransaction(
                     mTmpSize.width(), mTmpSize.height(), recoveringMemory);
@@ -1420,34 +1419,39 @@
         }
         mForceScaleUntilResize = mForceScaleUntilResize && !mSurfaceResized;
 
-
         calculateSurfaceWindowCrop(mTmpClipRect, mTmpFinalClipRect);
+
+        float surfaceWidth = mSurfaceController.getWidth();
+        float surfaceHeight = mSurfaceController.getHeight();
+
         if ((task != null && task.mStack.getForceScaleToCrop()) || mForceScaleUntilResize) {
             int hInsets = w.getAttrs().surfaceInsets.left + w.getAttrs().surfaceInsets.right;
             int vInsets = w.getAttrs().surfaceInsets.top + w.getAttrs().surfaceInsets.bottom;
-            float surfaceWidth = mSurfaceController.getWidth();
-            float surfaceHeight = mSurfaceController.getHeight();
+            if (!mForceScaleUntilResize) {
+                mSurfaceController.forceScaleableInTransaction(true);
+            }
             // We want to calculate the scaling based on the content area, not based on
             // the entire surface, so that we scale in sync with windows that don't have insets.
-            extraHScale = (mTmpClipRect.width() - hInsets) / (float)(surfaceWidth - hInsets);
-            extraVScale = (mTmpClipRect.height() - vInsets) / (float)(surfaceHeight - vInsets);
+            mExtraHScale = (mTmpClipRect.width() - hInsets) / (float)(surfaceWidth - hInsets);
+            mExtraVScale = (mTmpClipRect.height() - vInsets) / (float)(surfaceHeight - vInsets);
 
             // In the case of ForceScaleToCrop we scale entire tasks together,
             // and so we need to scale our offsets relative to the task bounds
             // or parent and child windows would fall out of alignment.
-            int posX = (int) (mTmpSize.left - w.mAttrs.x * (1 - extraHScale));
-            int posY = (int) (mTmpSize.top - w.mAttrs.y * (1 - extraVScale));
+            int posX = (int) (mTmpSize.left - w.mAttrs.x * (1 - mExtraHScale));
+            int posY = (int) (mTmpSize.top - w.mAttrs.y * (1 - mExtraVScale));
             // Imagine we are scaling down. As we scale the buffer down, we decrease the
             // distance between the surface top left, and the start of the surface contents
             // (previously it was surfaceInsets.left pixels in screen space but now it
-            // will be surfaceInsets.left*extraHScale). This means in order to keep the
+            // will be surfaceInsets.left*mExtraHScale). This means in order to keep the
             // non inset content at the same position, we have to shift the whole window
             // forward. Likewise for scaling up, we've increased this distance, and we need
             // to shift by a negative number to compensate.
-            posX += w.getAttrs().surfaceInsets.left * (1 - extraHScale);
-            posY += w.getAttrs().surfaceInsets.top * (1 - extraVScale);
+            posX += w.getAttrs().surfaceInsets.left * (1 - mExtraHScale);
+            posY += w.getAttrs().surfaceInsets.top * (1 - mExtraVScale);
 
-            mSurfaceController.setPositionInTransaction(posX, posY, recoveringMemory);
+            mSurfaceController.setPositionInTransaction((float)Math.floor(posX),
+                    (float)Math.floor(posY), recoveringMemory);
 
             // Since we are scaled to fit in our previously desired crop, we can now
             // expose the whole window in buffer space, and not risk extending
@@ -1459,7 +1463,7 @@
             // We need to ensure for each surface, that we disable transformation matrix
             // scaling in the same transaction which we resize the surface in.
             // As we are in SCALING_MODE_SCALE_TO_WINDOW, SurfaceFlinger will
-            // then take over the scaling until the new buffer arrives, and things 
+            // then take over the scaling until the new buffer arrives, and things
             // will be seamless.
             mForceScaleUntilResize = true;
         } else {
@@ -1467,12 +1471,28 @@
                     recoveringMemory);
         }
 
+        // If we are ending the scaling mode. We switch to SCALING_MODE_FREEZE
+        // to prevent further updates until buffer latch. Normally position
+        // would continue to apply immediately. But we need a different position
+        // before and after resize (since we have scaled the shadows, as discussed
+        // above).
+        if (wasForceScaled && !mForceScaleUntilResize) {
+            mSurfaceController.setPositionAppliesWithResizeInTransaction(true);
+            mSurfaceController.forceScaleableInTransaction(false);
+        }
+        if (w.inPinnedWorkspace()) {
+            mTmpClipRect.set(0, 0, -1, -1);
+            task.mStack.getDimBounds(mTmpFinalClipRect);
+            mTmpFinalClipRect.inset(-w.mAttrs.surfaceInsets.left, -w.mAttrs.surfaceInsets.top,
+                    -w.mAttrs.surfaceInsets.right, -w.mAttrs.surfaceInsets.bottom);
+        }
+
         updateSurfaceWindowCrop(mTmpClipRect, mTmpFinalClipRect, recoveringMemory);
 
-        mSurfaceController.setMatrixInTransaction(mDsDx * w.mHScale * extraHScale,
-                mDtDx * w.mVScale * extraVScale,
-                mDsDy * w.mHScale * extraHScale,
-                mDtDy * w.mVScale * extraVScale, recoveringMemory);
+        mSurfaceController.setMatrixInTransaction(mDsDx * w.mHScale * mExtraHScale,
+                mDtDx * w.mVScale * mExtraVScale,
+                mDsDy * w.mHScale * mExtraHScale,
+                mDtDy * w.mVScale * mExtraVScale, recoveringMemory);
 
         if (mSurfaceResized) {
             mReportSurfaceResized = true;
@@ -1558,8 +1578,10 @@
 
             boolean prepared =
                 mSurfaceController.prepareToShowInTransaction(mShownAlpha, mAnimLayer,
-                        mDsDx * w.mHScale, mDtDx * w.mVScale,
-                        mDsDy * w.mHScale, mDtDy * w.mVScale,
+                        mDsDx * w.mHScale * mExtraHScale,
+                        mDtDx * w.mVScale * mExtraVScale,
+                        mDsDy * w.mHScale * mExtraHScale,
+                        mDtDy * w.mVScale * mExtraVScale,
                         recoveringMemory);
 
             if (prepared && mLastHidden && mDrawState == HAS_DRAWN) {
diff --git a/services/core/java/com/android/server/wm/WindowSurfaceController.java b/services/core/java/com/android/server/wm/WindowSurfaceController.java
index 9646a49..c30da14 100644
--- a/services/core/java/com/android/server/wm/WindowSurfaceController.java
+++ b/services/core/java/com/android/server/wm/WindowSurfaceController.java
@@ -176,7 +176,7 @@
         if (SHOW_TRANSACTIONS) logSurface(
                 "CROP " + clipRect.toShortString(), null);
         try {
-            if (clipRect.width() > 0 && clipRect.height() > 0) {
+            if (clipRect.width() != 0 && clipRect.height() != 0) {
                 mSurfaceControl.setWindowCrop(clipRect);
                 mHiddenForCrop = false;
                 updateVisibility();
@@ -236,6 +236,10 @@
         }
     }
 
+    void setPositionAppliesWithResizeInTransaction(boolean recoveringMemory) {
+        mSurfaceControl.setPositionAppliesWithResize();
+    }
+
     void setMatrixInTransaction(float dsdx, float dtdx, float dsdy, float dtdy,
             boolean recoveringMemory) {
         try {
@@ -554,6 +558,13 @@
         }
 
         @Override
+        public void setPositionAppliesWithResize() {
+            if (LOG_SURFACE_TRACE) Slog.v(SURFACE_TAG, "setPositionAppliesWithResize(): OLD: "
+                    + this + ". Called by" + Debug.getCallers(9));
+            super.setPositionAppliesWithResize();
+        }
+
+        @Override
         public void setSize(int w, int h) {
             if (w != mSize.x || h != mSize.y) {
                 if (LOG_SURFACE_TRACE) Slog.v(SURFACE_TAG, "setSize(" + w + "," + h + "): OLD:"