Merge "Relocate common Calendar classes"
diff --git a/api/current.txt b/api/current.txt
index 559672f..2923805 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -22740,7 +22740,7 @@
     method public void requestDisallowInterceptTouchEvent(boolean);
     method public boolean requestSendAccessibilityEvent(android.view.View, android.view.accessibility.AccessibilityEvent);
     method public void requestTransparentRegion(android.view.View);
-    method protected void resetLayoutDirectionResolution();
+    method protected void resetResolvedLayoutDirection();
     method public void scheduleLayoutAnimation();
     method public void setAddStatesFromChildren(boolean);
     method public void setAlwaysDrawnWithCacheEnabled(boolean);
@@ -26417,7 +26417,7 @@
     method protected void onTextChanged(java.lang.CharSequence, int, int, int);
     method public boolean onTextContextMenuItem(int);
     method public void removeTextChangedListener(android.text.TextWatcher);
-    method protected void resetLayoutDirectionResolution();
+    method protected void resetResolvedLayoutDirection();
     method public void setAllCaps(boolean);
     method public final void setAutoLinkMask(int);
     method public void setCompoundDrawablePadding(int);
diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java
index 8a678d6..76534ef 100644
--- a/core/java/android/net/NetworkUtils.java
+++ b/core/java/android/net/NetworkUtils.java
@@ -38,8 +38,22 @@
     /** Bring the named network interface down. */
     public native static int disableInterface(String interfaceName);
 
-    /** Reset any sockets that are connected via the named interface. */
-    public native static int resetConnections(String interfaceName);
+    /** Setting bit 0 indicates reseting of IPv4 addresses required */
+    public static final int RESET_IPV4_ADDRESSES = 0x01;
+
+    /** Setting bit 1 indicates reseting of IPv4 addresses required */
+    public static final int RESET_IPV6_ADDRESSES = 0x02;
+
+    /** Reset all addresses */
+    public static final int RESET_ALL_ADDRESSES = RESET_IPV4_ADDRESSES | RESET_IPV6_ADDRESSES;
+
+    /**
+     * Reset IPv6 or IPv4 sockets that are connected via the named interface.
+     *
+     * @param interfaceName is the interface to reset
+     * @param mask {@see #RESET_IPV4_ADDRESSES} and {@see #RESET_IPV6_ADDRESSES}
+     */
+    public native static int resetConnections(String interfaceName, int mask);
 
     /**
      * Start the DHCP client daemon, in order to have it request addresses
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index 673b187..dbefb1f 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -266,7 +266,8 @@
      * @param uid The user-id under which the process will run.
      * @param gid The group-id under which the process will run.
      * @param gids Additional group-ids associated with the process.
-     * @param enableDebugger True if debugging should be enabled for this process.
+     * @param debugFlags Additional flags.
+     * @param targetSdkVersion The target SDK version for the app.
      * @param zygoteArgs Additional arguments to supply to the zygote process.
      * 
      * @return int If > 0 the pid of the new process; if 0 the process is
@@ -278,13 +279,13 @@
     public static final int start(final String processClass,
                                   final String niceName,
                                   int uid, int gid, int[] gids,
-                                  int debugFlags,
+                                  int debugFlags, int targetSdkVersion,
                                   String[] zygoteArgs)
     {
         if (supportsProcesses()) {
             try {
                 return startViaZygote(processClass, niceName, uid, gid, gids,
-                        debugFlags, zygoteArgs);
+                        debugFlags, targetSdkVersion, zygoteArgs);
             } catch (ZygoteStartFailedEx ex) {
                 Log.e(LOG_TAG,
                         "Starting VM process through Zygote failed");
@@ -316,9 +317,10 @@
      * {@hide}
      */
     public static final int start(String processClass, int uid, int gid,
-            int[] gids, int debugFlags, String[] zygoteArgs) {
+            int[] gids, int debugFlags, int targetSdkVersion,
+            String[] zygoteArgs) {
         return start(processClass, "", uid, gid, gids, 
-                debugFlags, zygoteArgs);
+                debugFlags, targetSdkVersion, zygoteArgs);
     }
 
     private static void invokeStaticMain(String className) {
@@ -500,7 +502,8 @@
      * @param gid a POSIX gid that the new process shuold setgid() to
      * @param gids null-ok; a list of supplementary group IDs that the
      * new process should setgroup() to.
-     * @param enableDebugger True if debugging should be enabled for this process.
+     * @param debugFlags Additional flags.
+     * @param targetSdkVersion The target SDK version for the app.
      * @param extraArgs Additional arguments to supply to the zygote process.
      * @return PID
      * @throws ZygoteStartFailedEx if process start failed for any reason
@@ -509,7 +512,7 @@
                                   final String niceName,
                                   final int uid, final int gid,
                                   final int[] gids,
-                                  int debugFlags,
+                                  int debugFlags, int targetSdkVersion,
                                   String[] extraArgs)
                                   throws ZygoteStartFailedEx {
         int pid;
@@ -537,6 +540,7 @@
             if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
                 argsForZygote.add("--enable-assert");
             }
+            argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
 
             //TODO optionally enable debuger
             //argsForZygote.add("--enable-debugger");
diff --git a/core/java/android/os/storage/StorageVolume.java b/core/java/android/os/storage/StorageVolume.java
index 792e4c1..60900e1 100644
--- a/core/java/android/os/storage/StorageVolume.java
+++ b/core/java/android/os/storage/StorageVolume.java
@@ -34,6 +34,8 @@
     private final int mMtpReserveSpace;
     private final boolean mAllowMassStorage;
     private int mStorageId;
+    // maximum file size for the storage, or zero for no limit
+    private final long mMaxFileSize;
 
     // StorageVolume extra for ACTION_MEDIA_REMOVED, ACTION_MEDIA_UNMOUNTED, ACTION_MEDIA_CHECKING,
     // ACTION_MEDIA_NOFS, ACTION_MEDIA_MOUNTED, ACTION_MEDIA_SHARED, ACTION_MEDIA_UNSHARED,
@@ -41,18 +43,20 @@
     public static final String EXTRA_STORAGE_VOLUME = "storage_volume";
 
     public StorageVolume(String path, String description, boolean removable,
-            boolean emulated, int mtpReserveSpace, boolean allowMassStorage) {
+            boolean emulated, int mtpReserveSpace, boolean allowMassStorage, long maxFileSize) {
         mPath = path;
         mDescription = description;
         mRemovable = removable;
         mEmulated = emulated;
         mMtpReserveSpace = mtpReserveSpace;
         mAllowMassStorage = allowMassStorage;
+        mMaxFileSize = maxFileSize;
     }
 
     // for parcelling only
     private StorageVolume(String path, String description, boolean removable,
-            boolean emulated, int mtpReserveSpace, int storageId, boolean allowMassStorage) {
+            boolean emulated, int mtpReserveSpace, int storageId,
+            boolean allowMassStorage, long maxFileSize) {
         mPath = path;
         mDescription = description;
         mRemovable = removable;
@@ -60,6 +64,7 @@
         mMtpReserveSpace = mtpReserveSpace;
         mAllowMassStorage = allowMassStorage;
         mStorageId = storageId;
+        mMaxFileSize = maxFileSize;
     }
 
     /**
@@ -142,6 +147,15 @@
         return mAllowMassStorage;
     }
 
+    /**
+     * Returns maximum file size for the volume, or zero if it is unbounded.
+     *
+     * @return maximum file size
+     */
+    public long getMaxFileSize() {
+        return mMaxFileSize;
+    }
+
     @Override
     public boolean equals(Object obj) {
         if (obj instanceof StorageVolume && mPath != null) {
@@ -171,9 +185,10 @@
             int storageId = in.readInt();
             int mtpReserveSpace = in.readInt();
             int allowMassStorage = in.readInt();
+            long maxFileSize = in.readLong();
             return new StorageVolume(path, description,
-                    removable == 1, emulated == 1,
-                    mtpReserveSpace, storageId, allowMassStorage == 1);
+                    removable == 1, emulated == 1, mtpReserveSpace,
+                    storageId, allowMassStorage == 1, maxFileSize);
         }
 
         public StorageVolume[] newArray(int size) {
@@ -193,5 +208,6 @@
         parcel.writeInt(mStorageId);
         parcel.writeInt(mMtpReserveSpace);
         parcel.writeInt(mAllowMassStorage ? 1 : 0);
+        parcel.writeLong(mMaxFileSize);
     }
 }
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 65babc2..23b53ae 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -3833,6 +3833,11 @@
         /** {@hide} */
         public static final String NETSTATS_TAG_MAX_HISTORY = "netstats_tag_max_history";
 
+        /** Preferred NTP server. {@hide} */
+        public static final String NTP_SERVER = "ntp_server";
+        /** Timeout in milliseconds to wait for NTP server. {@hide} */
+        public static final String NTP_TIMEOUT = "ntp_timeout";
+
         /**
          * @hide
          */
diff --git a/core/java/android/text/style/SuggestionSpan.java b/core/java/android/text/style/SuggestionSpan.java
index 240ad9b..555aac5 100644
--- a/core/java/android/text/style/SuggestionSpan.java
+++ b/core/java/android/text/style/SuggestionSpan.java
@@ -22,12 +22,22 @@
 import android.os.SystemClock;
 import android.text.ParcelableSpan;
 import android.text.TextUtils;
+import android.widget.TextView;
 
 import java.util.Arrays;
 import java.util.Locale;
 
 /**
- * Holds suggestion candidates of words under this span.
+ * Holds suggestion candidates for the text enclosed in this span.
+ *
+ * When such a span is edited in an EditText, double tapping on the text enclosed in this span will
+ * display a popup dialog listing suggestion replacement for that text. The user can then replace
+ * the original text by one of the suggestions.
+ *
+ * These spans should typically be created by the input method to privide correction and alternates
+ * for the text.
+ *
+ * @see TextView#setSuggestionsEnabled(boolean)
  */
 public class SuggestionSpan implements ParcelableSpan {
     /**
@@ -115,14 +125,14 @@
     }
 
     /**
-     * @return suggestions
+     * @return an array of suggestion texts for this span
      */
     public String[] getSuggestions() {
         return mSuggestions;
     }
 
     /**
-     * @return locale of suggestions
+     * @return the locale of the suggestions
      */
     public String getLocale() {
         return mLocaleString;
diff --git a/core/java/android/util/NtpTrustedTime.java b/core/java/android/util/NtpTrustedTime.java
index 5b19ecd..2179ff3 100644
--- a/core/java/android/util/NtpTrustedTime.java
+++ b/core/java/android/util/NtpTrustedTime.java
@@ -16,41 +16,71 @@
 
 package android.util;
 
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.res.Resources;
 import android.net.SntpClient;
 import android.os.SystemClock;
+import android.provider.Settings;
 
 /**
- * {@link TrustedTime} that connects with a remote NTP server as its remote
- * trusted time source.
+ * {@link TrustedTime} that connects with a remote NTP server as its trusted
+ * time source.
  *
  * @hide
  */
 public class NtpTrustedTime implements TrustedTime {
-    private String mNtpServer;
-    private long mNtpTimeout;
+    private static final String TAG = "NtpTrustedTime";
+    private static final boolean LOGD = false;
+
+    private static NtpTrustedTime sSingleton;
+
+    private final String mServer;
+    private final long mTimeout;
 
     private boolean mHasCache;
     private long mCachedNtpTime;
     private long mCachedNtpElapsedRealtime;
     private long mCachedNtpCertainty;
 
-    public NtpTrustedTime() {
+    private NtpTrustedTime(String server, long timeout) {
+        if (LOGD) Log.d(TAG, "creating NtpTrustedTime using " + server);
+        mServer = server;
+        mTimeout = timeout;
     }
 
-    public void setNtpServer(String server, long timeout) {
-        mNtpServer = server;
-        mNtpTimeout = timeout;
+    public static synchronized NtpTrustedTime getInstance(Context context) {
+        if (sSingleton == null) {
+            final Resources res = context.getResources();
+            final ContentResolver resolver = context.getContentResolver();
+
+            final String defaultServer = res.getString(
+                    com.android.internal.R.string.config_ntpServer);
+            final long defaultTimeout = res.getInteger(
+                    com.android.internal.R.integer.config_ntpTimeout);
+
+            final String secureServer = Settings.Secure.getString(
+                    resolver, Settings.Secure.NTP_SERVER);
+            final long timeout = Settings.Secure.getLong(
+                    resolver, Settings.Secure.NTP_TIMEOUT, defaultTimeout);
+
+            final String server = secureServer != null ? secureServer : defaultServer;
+            sSingleton = new NtpTrustedTime(server, timeout);
+        }
+
+        return sSingleton;
     }
 
     /** {@inheritDoc} */
     public boolean forceRefresh() {
-        if (mNtpServer == null) {
+        if (mServer == null) {
             // missing server, so no trusted time available
             return false;
         }
 
+        if (LOGD) Log.d(TAG, "forceRefresh() from cache miss");
         final SntpClient client = new SntpClient();
-        if (client.requestTime(mNtpServer, (int) mNtpTimeout)) {
+        if (client.requestTime(mServer, (int) mTimeout)) {
             mHasCache = true;
             mCachedNtpTime = client.getNtpTime();
             mCachedNtpElapsedRealtime = client.getNtpTimeReference();
@@ -89,9 +119,19 @@
         if (!mHasCache) {
             throw new IllegalStateException("Missing authoritative time source");
         }
+        if (LOGD) Log.d(TAG, "currentTimeMillis() cache hit");
 
         // current time is age after the last ntp cache; callers who
         // want fresh values will hit makeAuthoritative() first.
         return mCachedNtpTime + getCacheAge();
     }
+
+    public long getCachedNtpTime() {
+        if (LOGD) Log.d(TAG, "getCachedNtpTime() cache hit");
+        return mCachedNtpTime;
+    }
+
+    public long getCachedNtpTimeReference() {
+        return mCachedNtpElapsedRealtime;
+    }
 }
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 1245898..74dc100 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -4474,7 +4474,7 @@
     @RemotableViewMethod
     public void setLayoutDirection(int layoutDirection) {
         if (getLayoutDirection() != layoutDirection) {
-            resetLayoutDirectionResolution();
+            resetResolvedLayoutDirection();
             // Setting the flag will also request a layout.
             setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
         }
@@ -9043,10 +9043,8 @@
             mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
         }
         jumpDrawablesToCurrentState();
-        resetLayoutDirectionResolution();
         resolveLayoutDirectionIfNeeded();
         resolvePadding();
-        resetResolvedTextDirection();
         resolveTextDirection();
         if (isFocused()) {
             InputMethodManager imm = InputMethodManager.peekInstance();
@@ -9143,7 +9141,7 @@
      *
      * @hide
      */
-    protected void resetLayoutDirectionResolution() {
+    protected void resetResolvedLayoutDirection() {
         // Reset the current View resolution
         mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
     }
@@ -9190,6 +9188,9 @@
         }
 
         mCurrentAnimation = null;
+
+        resetResolvedLayoutDirection();
+        resetResolvedTextDirection();
     }
 
     /**
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index e6fdb17..752fd5a 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -4999,15 +4999,15 @@
     }
 
     @Override
-    protected void resetLayoutDirectionResolution() {
-        super.resetLayoutDirectionResolution();
+    protected void resetResolvedLayoutDirection() {
+        super.resetResolvedLayoutDirection();
 
         // Take care of resetting the children resolution too
         final int count = getChildCount();
         for (int i = 0; i < count; i++) {
             final View child = getChildAt(i);
             if (child.getLayoutDirection() == LAYOUT_DIRECTION_INHERIT) {
-                child.resetLayoutDirectionResolution();
+                child.resetResolvedLayoutDirection();
             }
         }
     }
diff --git a/core/java/android/webkit/ZoomManager.java b/core/java/android/webkit/ZoomManager.java
index 252fc8f..7d3f313 100644
--- a/core/java/android/webkit/ZoomManager.java
+++ b/core/java/android/webkit/ZoomManager.java
@@ -300,7 +300,7 @@
     }
 
     public final float getDefaultScale() {
-        return mDefaultScale;
+        return mInitialScale > 0 ? mInitialScale : mDefaultScale;
     }
 
     public final float getReadingLevelScale() {
@@ -1087,6 +1087,7 @@
             float scale;
             if (mInitialScale > 0) {
                 scale = mInitialScale;
+                mTextWrapScale = scale;
             } else if (viewState.mViewScale > 0) {
                 mTextWrapScale = viewState.mTextWrapScale;
                 scale = viewState.mViewScale;
@@ -1105,7 +1106,7 @@
             }
             boolean reflowText = false;
             if (!viewState.mIsRestored) {
-                if (settings.getUseFixedViewport()) {
+                if (settings.getUseFixedViewport() && mInitialScale == 0) {
                     // Override the scale only in case of fixed viewport.
                     scale = Math.max(scale, overviewScale);
                     mTextWrapScale = Math.max(mTextWrapScale, overviewScale);
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 1e63e26..e350ec4 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -5571,8 +5571,8 @@
     }
 
     @Override
-    protected void resetLayoutDirectionResolution() {
-        super.resetLayoutDirectionResolution();
+    protected void resetResolvedLayoutDirection() {
+        super.resetResolvedLayoutDirection();
 
         if (mLayoutAlignment != null &&
                 (mTextAlign == TextAlign.VIEW_START ||
diff --git a/core/java/com/android/internal/os/RuntimeInit.java b/core/java/com/android/internal/os/RuntimeInit.java
index f13e770..53516c0 100644
--- a/core/java/com/android/internal/os/RuntimeInit.java
+++ b/core/java/com/android/internal/os/RuntimeInit.java
@@ -252,9 +252,10 @@
      *   <li> <code> [--] &lt;start class name&gt;  &lt;args&gt;
      * </ul>
      *
+     * @param targetSdkVersion target SDK version
      * @param argv arg strings
      */
-    public static final void zygoteInit(String[] argv)
+    public static final void zygoteInit(int targetSdkVersion, String[] argv)
             throws ZygoteInit.MethodAndArgsCaller {
         if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");
 
@@ -263,7 +264,7 @@
         commonInit();
         zygoteInitNative();
 
-        applicationInit(argv);
+        applicationInit(targetSdkVersion, argv);
     }
 
     /**
@@ -274,20 +275,22 @@
      * which calls {@link WrapperInit#main} which then calls this method.
      * So we don't need to call commonInit() here.
      *
+     * @param targetSdkVersion target SDK version
      * @param argv arg strings
      */
-    public static void wrapperInit(String[] argv)
+    public static void wrapperInit(int targetSdkVersion, String[] argv)
             throws ZygoteInit.MethodAndArgsCaller {
         if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from wrapper");
 
-        applicationInit(argv);
+        applicationInit(targetSdkVersion, argv);
     }
 
-    private static void applicationInit(String[] argv)
+    private static void applicationInit(int targetSdkVersion, String[] argv)
             throws ZygoteInit.MethodAndArgsCaller {
         // We want to be fairly aggressive about heap utilization, to avoid
         // holding on to a lot of memory that isn't needed.
         VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
+        VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
 
         final Arguments args;
         try {
diff --git a/core/java/com/android/internal/os/WrapperInit.java b/core/java/com/android/internal/os/WrapperInit.java
index 860a08c..c6b3e7c 100644
--- a/core/java/com/android/internal/os/WrapperInit.java
+++ b/core/java/com/android/internal/os/WrapperInit.java
@@ -47,16 +47,22 @@
      * wrapper process instead of by forking Zygote.
      *
      * The first argument specifies the file descriptor for a pipe that should receive
-     * the pid of this process, or 0 if none.  The remaining arguments are passed to
-     * the runtime.
+     * the pid of this process, or 0 if none.
+     *
+     * The second argument is the target SDK version for the app.
+     *
+     * The remaining arguments are passed to the runtime.
      *
      * @param args The command-line arguments.
      */
     public static void main(String[] args) {
         try {
+            // Parse our mandatory arguments.
+            int fdNum = Integer.parseInt(args[0], 10);
+            int targetSdkVersion = Integer.parseInt(args[1], 10);
+
             // Tell the Zygote what our actual PID is (since it only knows about the
             // wrapper that it directly forked).
-            int fdNum = Integer.parseInt(args[0], 10);
             if (fdNum != 0) {
                 try {
                     FileDescriptor fd = ZygoteInit.createFileDescriptor(fdNum);
@@ -73,9 +79,9 @@
             ZygoteInit.preload();
 
             // Launch the application.
-            String[] runtimeArgs = new String[args.length - 1];
-            System.arraycopy(args, 1, runtimeArgs, 0, runtimeArgs.length);
-            RuntimeInit.wrapperInit(runtimeArgs);
+            String[] runtimeArgs = new String[args.length - 2];
+            System.arraycopy(args, 2, runtimeArgs, 0, runtimeArgs.length);
+            RuntimeInit.wrapperInit(targetSdkVersion, runtimeArgs);
         } catch (ZygoteInit.MethodAndArgsCaller caller) {
             caller.run();
         }
@@ -87,11 +93,12 @@
      *
      * @param invokeWith The wrapper command.
      * @param niceName The nice name for the application, or null if none.
+     * @param targetSdkVersion The target SDK version for the app.
      * @param pipeFd The pipe to which the application's pid should be written, or null if none.
      * @param args Arguments for {@link RuntimeInit.main}.
      */
     public static void execApplication(String invokeWith, String niceName,
-            FileDescriptor pipeFd, String[] args) {
+            int targetSdkVersion, FileDescriptor pipeFd, String[] args) {
         StringBuilder command = new StringBuilder(invokeWith);
         command.append(" /system/bin/app_process /system/bin --application");
         if (niceName != null) {
@@ -99,6 +106,8 @@
         }
         command.append(" com.android.internal.os.WrapperInit ");
         command.append(pipeFd != null ? pipeFd.getInt$() : 0);
+        command.append(' ');
+        command.append(targetSdkVersion);
         Zygote.appendQuotedShellArgs(command, args);
         Zygote.execShell(command.toString());
     }
diff --git a/core/java/com/android/internal/os/ZygoteConnection.java b/core/java/com/android/internal/os/ZygoteConnection.java
index 7cb002c..fcac2ac 100644
--- a/core/java/com/android/internal/os/ZygoteConnection.java
+++ b/core/java/com/android/internal/os/ZygoteConnection.java
@@ -18,6 +18,7 @@
 
 import android.net.Credentials;
 import android.net.LocalSocket;
+import android.os.Build;
 import android.os.Process;
 import android.os.SystemProperties;
 import android.util.Log;
@@ -333,6 +334,10 @@
          */
         int debugFlags;
 
+        /** from --target-sdk-version. */
+        int targetSdkVersion;
+        boolean targetSdkVersionSpecified;
+
         /** from --classpath */
         String classpath;
 
@@ -402,6 +407,14 @@
                     gidSpecified = true;
                     gid = Integer.parseInt(
                             arg.substring(arg.indexOf('=') + 1));
+                } else if (arg.startsWith("--target-sdk-version=")) {
+                    if (targetSdkVersionSpecified) {
+                        throw new IllegalArgumentException(
+                                "Duplicate target-sdk-version specified");
+                    }
+                    targetSdkVersionSpecified = true;
+                    targetSdkVersion = Integer.parseInt(
+                            arg.substring(arg.indexOf('=') + 1));
                 } else if (arg.equals("--enable-debugger")) {
                     debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
                 } else if (arg.equals("--enable-safemode")) {
@@ -505,6 +518,10 @@
                         "--runtime-init and -classpath are incompatible");
             }
 
+            if (!targetSdkVersionSpecified) {
+                targetSdkVersion = Build.VERSION.SDK_INT;
+            }
+
             remainingArgs = new String[args.length - curArg];
 
             System.arraycopy(args, curArg, remainingArgs, 0,
@@ -821,9 +838,11 @@
         if (parsedArgs.runtimeInit) {
             if (parsedArgs.invokeWith != null) {
                 WrapperInit.execApplication(parsedArgs.invokeWith,
-                        parsedArgs.niceName, pipeFd, parsedArgs.remainingArgs);
+                        parsedArgs.niceName, parsedArgs.targetSdkVersion,
+                        pipeFd, parsedArgs.remainingArgs);
             } else {
-                RuntimeInit.zygoteInit(parsedArgs.remainingArgs);
+                RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion,
+                        parsedArgs.remainingArgs);
             }
         } else {
             String className;
diff --git a/core/java/com/android/internal/os/ZygoteInit.java b/core/java/com/android/internal/os/ZygoteInit.java
index b4a7e52..6ec186d 100644
--- a/core/java/com/android/internal/os/ZygoteInit.java
+++ b/core/java/com/android/internal/os/ZygoteInit.java
@@ -48,7 +48,7 @@
  * Startup class for the zygote process.
  *
  * Pre-initializes some classes, and then waits for commands on a UNIX domain
- * socket. Based on these commands, forks of child processes that inherit
+ * socket. Based on these commands, forks off child processes that inherit
  * the initial state of the VM.
  *
  * Please see {@link ZygoteConnection.Arguments} for documentation on the
@@ -453,12 +453,13 @@
 
         if (parsedArgs.invokeWith != null) {
             WrapperInit.execApplication(parsedArgs.invokeWith,
-                    parsedArgs.niceName, null, parsedArgs.remainingArgs);
+                    parsedArgs.niceName, parsedArgs.targetSdkVersion,
+                    null, parsedArgs.remainingArgs);
         } else {
             /*
              * Pass the remaining arguments to SystemServer.
              */
-            RuntimeInit.zygoteInit(parsedArgs.remainingArgs);
+            RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs);
         }
 
         /* should never reach here */
@@ -491,7 +492,9 @@
             /* Request to fork the system server process */
             pid = Zygote.forkSystemServer(
                     parsedArgs.uid, parsedArgs.gid,
-                    parsedArgs.gids, parsedArgs.debugFlags, null,
+                    parsedArgs.gids,
+                    parsedArgs.debugFlags,
+                    null,
                     parsedArgs.permittedCapabilities,
                     parsedArgs.effectiveCapabilities);
         } catch (IllegalArgumentException ex) {
diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp
index ddae505..d9bd50e 100644
--- a/core/jni/android_net_NetUtils.cpp
+++ b/core/jni/android_net_NetUtils.cpp
@@ -26,7 +26,7 @@
 extern "C" {
 int ifc_enable(const char *ifname);
 int ifc_disable(const char *ifname);
-int ifc_reset_connections(const char *ifname);
+int ifc_reset_connections(const char *ifname, int reset_mask);
 
 int dhcp_do_request(const char *ifname,
                     const char *ipaddr,
@@ -90,12 +90,17 @@
     return (jint)result;
 }
 
-static jint android_net_utils_resetConnections(JNIEnv* env, jobject clazz, jstring ifname)
+static jint android_net_utils_resetConnections(JNIEnv* env, jobject clazz,
+      jstring ifname, jint mask)
 {
     int result;
 
     const char *nameStr = env->GetStringUTFChars(ifname, NULL);
-    result = ::ifc_reset_connections(nameStr);
+
+    LOGD("android_net_utils_resetConnections in env=%p clazz=%p iface=%s mask=0x%x\n",
+          env, clazz, nameStr, mask);
+
+    result = ::ifc_reset_connections(nameStr, mask);
     env->ReleaseStringUTFChars(ifname, nameStr);
     return (jint)result;
 }
@@ -206,7 +211,7 @@
 
     { "enableInterface", "(Ljava/lang/String;)I",  (void *)android_net_utils_enableInterface },
     { "disableInterface", "(Ljava/lang/String;)I",  (void *)android_net_utils_disableInterface },
-    { "resetConnections", "(Ljava/lang/String;)I",  (void *)android_net_utils_resetConnections },
+    { "resetConnections", "(Ljava/lang/String;I)I",  (void *)android_net_utils_resetConnections },
     { "runDhcp", "(Ljava/lang/String;Landroid/net/DhcpInfoInternal;)Z",  (void *)android_net_utils_runDhcp },
     { "runDhcpRenew", "(Ljava/lang/String;Landroid/net/DhcpInfoInternal;)Z",  (void *)android_net_utils_runDhcpRenew },
     { "stopDhcp", "(Ljava/lang/String;)Z",  (void *)android_net_utils_stopDhcp },
diff --git a/core/res/res/drawable-hdpi/ic_btn_back.png b/core/res/res/drawable-hdpi/ic_btn_back.png
deleted file mode 100644
index f8b3285..0000000
--- a/core/res/res/drawable-hdpi/ic_btn_back.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_btn_next.png b/core/res/res/drawable-hdpi/ic_btn_next.png
deleted file mode 100644
index b2c6e1b..0000000
--- a/core/res/res/drawable-hdpi/ic_btn_next.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_btn_back.png b/core/res/res/drawable-mdpi/ic_btn_back.png
deleted file mode 100644
index c9bff4c..0000000
--- a/core/res/res/drawable-mdpi/ic_btn_back.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_btn_next.png b/core/res/res/drawable-mdpi/ic_btn_next.png
deleted file mode 100755
index c6cf436..0000000
--- a/core/res/res/drawable-mdpi/ic_btn_next.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/layout-sw600dp/preference_list_content.xml b/core/res/res/layout-sw600dp/preference_list_content.xml
index 5a345c6..a5320a7 100644
--- a/core/res/res/layout-sw600dp/preference_list_content.xml
+++ b/core/res/res/layout-sw600dp/preference_list_content.xml
@@ -87,7 +87,6 @@
         android:layout_height="wrap_content"
         android:layout_width="match_parent"
         android:layout_weight="0"
-        android:background="@android:drawable/bottom_bar"
         android:visibility="gone">
 
         <Button android:id="@+id/back_button"
@@ -95,8 +94,6 @@
             android:layout_height="wrap_content"
             android:layout_margin="5dip"
             android:layout_alignParentLeft="true"
-            android:drawableLeft="@drawable/ic_btn_back"
-            android:drawablePadding="3dip"
             android:text="@string/back_button_label"
         />
         <LinearLayout
@@ -117,8 +114,6 @@
                 android:layout_width="150dip"
                 android:layout_height="wrap_content"
                 android:layout_margin="5dip"
-                android:drawableRight="@drawable/ic_btn_next"
-                android:drawablePadding="3dip"
                 android:text="@string/next_button_label"
             />
         </LinearLayout>
diff --git a/core/res/res/layout-w600dp/preference_list_content_single.xml b/core/res/res/layout-w600dp/preference_list_content_single.xml
index 6725996..bbad296 100644
--- a/core/res/res/layout-w600dp/preference_list_content_single.xml
+++ b/core/res/res/layout-w600dp/preference_list_content_single.xml
@@ -61,7 +61,6 @@
         android:layout_height="wrap_content"
         android:layout_width="match_parent"
         android:layout_weight="0"
-        android:background="@android:drawable/bottom_bar"
         android:visibility="gone">
 
         <Button android:id="@+id/back_button"
@@ -69,8 +68,6 @@
             android:layout_height="wrap_content"
             android:layout_margin="5dip"
             android:layout_alignParentLeft="true"
-            android:drawableLeft="@drawable/ic_btn_back"
-            android:drawablePadding="3dip"
             android:text="@string/back_button_label"
         />
         <LinearLayout
@@ -91,8 +88,6 @@
                 android:layout_width="150dip"
                 android:layout_height="wrap_content"
                 android:layout_margin="5dip"
-                android:drawableRight="@drawable/ic_btn_next"
-                android:drawablePadding="3dip"
                 android:text="@string/next_button_label"
             />
         </LinearLayout>
diff --git a/core/res/res/layout/preference_list_content.xml b/core/res/res/layout/preference_list_content.xml
index 82b3a4c..fb898ee 100644
--- a/core/res/res/layout/preference_list_content.xml
+++ b/core/res/res/layout/preference_list_content.xml
@@ -85,7 +85,6 @@
         android:layout_height="wrap_content"
         android:layout_width="match_parent"
         android:layout_weight="0"
-        android:background="@android:drawable/bottom_bar"
         android:visibility="gone">
 
         <Button android:id="@+id/back_button"
@@ -93,8 +92,6 @@
             android:layout_height="wrap_content"
             android:layout_margin="5dip"
             android:layout_alignParentLeft="true"
-            android:drawableLeft="@drawable/ic_btn_back"
-            android:drawablePadding="3dip"
             android:text="@string/back_button_label"
         />
         <LinearLayout
@@ -115,8 +112,6 @@
                 android:layout_width="150dip"
                 android:layout_height="wrap_content"
                 android:layout_margin="5dip"
-                android:drawableRight="@drawable/ic_btn_next"
-                android:drawablePadding="3dip"
                 android:text="@string/next_button_label"
             />
         </LinearLayout>
diff --git a/core/res/res/layout/preference_list_content_single.xml b/core/res/res/layout/preference_list_content_single.xml
index a015761..6902ffd 100644
--- a/core/res/res/layout/preference_list_content_single.xml
+++ b/core/res/res/layout/preference_list_content_single.xml
@@ -56,7 +56,6 @@
         android:layout_height="wrap_content"
         android:layout_width="match_parent"
         android:layout_weight="0"
-        android:background="@android:drawable/bottom_bar"
         android:visibility="gone">
 
         <Button android:id="@+id/back_button"
@@ -64,8 +63,6 @@
             android:layout_height="wrap_content"
             android:layout_margin="5dip"
             android:layout_alignParentLeft="true"
-            android:drawableLeft="@drawable/ic_btn_back"
-            android:drawablePadding="3dip"
             android:text="@string/back_button_label"
         />
         <LinearLayout
@@ -86,8 +83,6 @@
                 android:layout_width="150dip"
                 android:layout_height="wrap_content"
                 android:layout_margin="5dip"
-                android:drawableRight="@drawable/ic_btn_next"
-                android:drawablePadding="3dip"
                 android:text="@string/next_button_label"
             />
         </LinearLayout>
diff --git a/core/res/res/layout/preference_list_fragment.xml b/core/res/res/layout/preference_list_fragment.xml
index 986536e..315f708 100644
--- a/core/res/res/layout/preference_list_fragment.xml
+++ b/core/res/res/layout/preference_list_fragment.xml
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!--
-/* 
+/*
 ** Copyright 2010, The Android Open Source Project
 **
 ** Licensed under the Apache License, Version 2.0 (the "License");
@@ -41,7 +41,6 @@
         android:layout_height="wrap_content"
         android:layout_width="match_parent"
         android:layout_weight="0"
-        android:background="@android:drawable/bottom_bar"
         android:visibility="gone">
 
         <Button android:id="@+id/back_button"
@@ -49,8 +48,6 @@
             android:layout_height="wrap_content"
             android:layout_margin="5dip"
             android:layout_alignParentLeft="true"
-            android:drawableLeft="@drawable/ic_btn_back"
-            android:drawablePadding="3dip"
             android:text="@string/back_button_label"
         />
         <LinearLayout
@@ -71,8 +68,6 @@
                 android:layout_width="150dip"
                 android:layout_height="wrap_content"
                 android:layout_margin="5dip"
-                android:drawableRight="@drawable/ic_btn_next"
-                android:drawablePadding="3dip"
                 android:text="@string/next_button_label"
             />
         </LinearLayout>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 4bc59e4..9c2133f 100755
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -5318,6 +5318,8 @@
         <attr name="mtpReserve" format="integer" />
         <!-- true if the storage can be shared via USB mass storage -->
         <attr name="allowMassStorage" format="boolean" />
+        <!-- maximum file size for the volume in megabytes, zero or unspecified if it is unbounded -->
+        <attr name="maxFileSize" format="integer" />
     </declare-styleable>
 
     <declare-styleable name="SwitchPreference">
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 9f05cbc..1f2b7fb 100755
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -660,4 +660,9 @@
          extremely limited. -->
     <bool name="config_allowActionMenuItemTextWithIcon">false</bool>
 
+    <!-- Remote server that can provide NTP responses. -->
+    <string translatable="false" name="config_ntpServer">pool.ntp.org</string>
+    <!-- Timeout to wait for NTP server response. -->
+    <integer name="config_ntpTimeout">20000</integer>
+
 </resources>
diff --git a/core/tests/coretests/AndroidManifest.xml b/core/tests/coretests/AndroidManifest.xml
index 8e2d925..40fa552 100644
--- a/core/tests/coretests/AndroidManifest.xml
+++ b/core/tests/coretests/AndroidManifest.xml
@@ -1051,6 +1051,13 @@
             </intent-filter>
         </activity>
 
+        <activity android:name="android.widget.TextViewTestActivity" android:label="TextViewTestActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
+            </intent-filter>
+        </activity>
+
 
 
         <!-- Activity-level metadata -->
diff --git a/core/tests/coretests/res/layout/textview_test.xml b/core/tests/coretests/res/layout/textview_test.xml
new file mode 100644
index 0000000..f0c7b9e
--- /dev/null
+++ b/core/tests/coretests/res/layout/textview_test.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 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"
+              android:id="@+id/textviewtest_layout"
+              android:layout_width="fill_parent"
+              android:layout_height="fill_parent">
+
+    <TextView android:id="@+id/textviewtest_textview"
+              android:layout_height="wrap_content"
+              android:layout_width="wrap_content"
+              android:text="@string/textview_hebrew_text"/>
+
+</LinearLayout>
\ No newline at end of file
diff --git a/core/tests/coretests/res/values/strings.xml b/core/tests/coretests/res/values/strings.xml
index f51b08e..71f3520 100644
--- a/core/tests/coretests/res/values/strings.xml
+++ b/core/tests/coretests/res/values/strings.xml
@@ -129,4 +129,6 @@
     <string name="button8">Button8</string>
     <string name="button9">Button9</string>
 
+    <string name="textview_hebrew_text">&#x05DD;&#x05DE;ab?!</string>
+
 </resources>
diff --git a/core/tests/coretests/src/android/widget/TextViewTest.java b/core/tests/coretests/src/android/widget/TextViewTest.java
index 6db67c0..c54e4a1 100644
--- a/core/tests/coretests/src/android/widget/TextViewTest.java
+++ b/core/tests/coretests/src/android/widget/TextViewTest.java
@@ -16,23 +16,25 @@
 
 package android.widget;
 
-import com.google.android.collect.Lists;
-import com.google.android.collect.Maps;
+import com.android.frameworks.coretests.R;
 
-import android.test.AndroidTestCase;
+import android.test.ActivityInstrumentationTestCase2;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.text.GetChars;
 import android.view.View;
-import android.widget.TextView;
 
 /**
  * TextViewTest tests {@link TextView}.
  */
-public class TextViewTest extends AndroidTestCase {
+public class TextViewTest extends ActivityInstrumentationTestCase2<TextViewTestActivity> {
+
+    public TextViewTest() {
+        super(TextViewTestActivity.class);
+    }
 
     @SmallTest
     public void testArray() throws Exception {
-        TextView tv = new TextView(mContext);
+        TextView tv = new TextView(getActivity());
 
         char[] c = new char[] { 'H', 'e', 'l', 'l', 'o', ' ',
                                 'W', 'o', 'r', 'l', 'd', '!' };
@@ -62,13 +64,13 @@
 
     @SmallTest
     public void testTextDirectionDefault() {
-        TextView tv = new TextView(mContext);
+        TextView tv = new TextView(getActivity());
         assertEquals(View.TEXT_DIRECTION_INHERIT, tv.getTextDirection());
     }
 
     @SmallTest
     public void testSetGetTextDirection() {
-        TextView tv = new TextView(mContext);
+        TextView tv = new TextView(getActivity());
 
         tv.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG);
         assertEquals(View.TEXT_DIRECTION_FIRST_STRONG, tv.getTextDirection());
@@ -88,7 +90,7 @@
 
     @SmallTest
     public void testGetResolvedTextDirectionLtr() {
-        TextView tv = new TextView(mContext);
+        TextView tv = new TextView(getActivity());
         tv.setText("this is a test");
 
         tv.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG);
@@ -109,10 +111,10 @@
 
     @SmallTest
     public void testGetResolvedTextDirectionLtrWithInheritance() {
-        LinearLayout ll = new LinearLayout(mContext);
+        LinearLayout ll = new LinearLayout(getActivity());
         ll.setTextDirection(View.TEXT_DIRECTION_RTL);
 
-        TextView tv = new TextView(mContext);
+        TextView tv = new TextView(getActivity());
         tv.setText("this is a test");
         ll.addView(tv);
 
@@ -134,7 +136,7 @@
 
     @SmallTest
     public void testGetResolvedTextDirectionRtl() {
-        TextView tv = new TextView(mContext);
+        TextView tv = new TextView(getActivity());
         tv.setText("\u05DD\u05DE"); // hebrew
 
         tv.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG);
@@ -155,10 +157,9 @@
 
     @SmallTest
     public void testGetResolvedTextDirectionRtlWithInheritance() {
-        LinearLayout ll = new LinearLayout(mContext);
-        ll.setTextDirection(View.TEXT_DIRECTION_RTL);
+        LinearLayout ll = new LinearLayout(getActivity());
 
-        TextView tv = new TextView(mContext);
+        TextView tv = new TextView(getActivity());
         tv.setText("\u05DD\u05DE"); // hebrew
         ll.addView(tv);
 
@@ -169,6 +170,24 @@
         assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection());
 
         tv.setTextDirection(View.TEXT_DIRECTION_INHERIT);
+        assertEquals(View.TEXT_DIRECTION_FIRST_STRONG, tv.getResolvedTextDirection());
+
+        tv.setTextDirection(View.TEXT_DIRECTION_LTR);
+        assertEquals(View.TEXT_DIRECTION_LTR, tv.getResolvedTextDirection());
+
+        tv.setTextDirection(View.TEXT_DIRECTION_RTL);
+        assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection());
+
+        // Force to RTL text direction on the layout
+        ll.setTextDirection(View.TEXT_DIRECTION_RTL);
+
+        tv.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG);
+        assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection());
+
+        tv.setTextDirection(View.TEXT_DIRECTION_ANY_RTL);
+        assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection());
+
+        tv.setTextDirection(View.TEXT_DIRECTION_INHERIT);
         assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection());
 
         tv.setTextDirection(View.TEXT_DIRECTION_LTR);
@@ -180,10 +199,10 @@
 
     @SmallTest
     public void testCharCountHeuristic() {
-        LinearLayout ll = new LinearLayout(mContext);
+        LinearLayout ll = new LinearLayout(getActivity());
         ll.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
 
-        TextView tv = new TextView(mContext);
+        TextView tv = new TextView(getActivity());
         ll.addView(tv);
 
         tv.setTextDirection(View.TEXT_DIRECTION_CHAR_COUNT);
@@ -211,4 +230,23 @@
         tv.setText("ab \u05DD\u05DE"); // latin + hebrew at 50% each
         assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection());
     }
+
+    @SmallTest
+    public void testResetTextDirection() {
+        final TextViewTestActivity activity = getActivity();
+
+        final LinearLayout ll = (LinearLayout) activity.findViewById(R.id.textviewtest_layout);
+        final TextView tv = (TextView) activity.findViewById(R.id.textviewtest_textview);
+
+        getActivity().runOnUiThread(new Runnable() {
+            public void run() {
+                tv.setTextDirection(View.TEXT_DIRECTION_FIRST_STRONG);
+                assertEquals(View.TEXT_DIRECTION_RTL, tv.getResolvedTextDirection());
+                assertEquals(true, tv.isResolvedTextDirection());
+
+                ll.removeView(tv);
+                assertEquals(false, tv.isResolvedTextDirection());
+            }
+        });
+    }
 }
diff --git a/core/tests/coretests/src/android/widget/TextViewTestActivity.java b/core/tests/coretests/src/android/widget/TextViewTestActivity.java
new file mode 100644
index 0000000..1bb4d24
--- /dev/null
+++ b/core/tests/coretests/src/android/widget/TextViewTestActivity.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.widget;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+import com.android.frameworks.coretests.R;
+
+public class TextViewTestActivity extends Activity {
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.textview_test);
+    }
+}
diff --git a/docs/html/index.jd b/docs/html/index.jd
index eeeedd0..dce46f9 100644
--- a/docs/html/index.jd
+++ b/docs/html/index.jd
@@ -148,19 +148,18 @@
 
     'tv': {
       'layout':"imgLeft",
-      'icon':"tv_s.png",
+      'icon':"GTV_icon_small.png",
       'name':"Google TV",
-      'img':"tv_l.png",
-      'title':"Announcing Google TV!",
-      'desc': "<p><a href='http://www.google.com/tv/'>Google TV</a> is a new platform "
-               + "for television built on Android. Google "
-               + "has partnered with Sony and Logitech to integrate "
-               + "this platform into TVs, blu-ray players, and companion "
-               + "boxes. </p>"
-               + "<p><a href='http://www.google.com/tv/'>Learn more about "
-               + "Google TV &raquo;</a></p>"
+      'img':"GTV_icon_large.png",
+      'title':"Google TV!",
+      'desc': "<p>Build something big. By big, we mean <em>worthy-of-the-living-room</em> big.</p>"
+	        +  " <p>Use <a href='http://code.google.com/tv'>Google TV</a> to bring the power of Android" 
+	        +  " and Google Chrome to television."
+			+  " The average American watches five hours of TV per day. Give them the web and apps"
+			+  " to update their status, listen to music, watch web videos, and much more...</p>"
     },
 
+
     'devphone': {
       'layout':"imgLeft",
       'icon':"devphone-small.png",
diff --git a/docs/html/sdk/eclipse-adt.jd b/docs/html/sdk/eclipse-adt.jd
index b4f1b27..18f47a6 100644
--- a/docs/html/sdk/eclipse-adt.jd
+++ b/docs/html/sdk/eclipse-adt.jd
@@ -99,7 +99,7 @@
   <a href="#" onclick="return toggleDiv(this)">
         <img src="{@docRoot}assets/images/triangle-opened.png" class="toggle-img" height="9px"
 width="9px" />
-ADT 12.0.0</a> <em>(June 2011)</em>
+ADT 12.0.0</a> <em>(July 2011)</em>
   <div class="toggleme">
 <dl>
 
diff --git a/docs/html/sdk/tools-notes.jd b/docs/html/sdk/tools-notes.jd
index d4ebf8a..8c4d037 100644
--- a/docs/html/sdk/tools-notes.jd
+++ b/docs/html/sdk/tools-notes.jd
@@ -66,7 +66,7 @@
 <div class="toggleable opened">
   <a href="#" onclick="return toggleDiv(this)">
         <img src="{@docRoot}assets/images/triangle-opened.png" class="toggle-img" height="9px" width="9px" />
-SDK Tools, Revision 12</a> <em>(June 2011)</em>
+SDK Tools, Revision 12</a> <em>(July 2011)</em>
   <div class="toggleme">
   <dl>
 <dt>Dependencies:</dt>
diff --git a/graphics/java/android/graphics/Path.java b/graphics/java/android/graphics/Path.java
index 1324431..c5d7500 100644
--- a/graphics/java/android/graphics/Path.java
+++ b/graphics/java/android/graphics/Path.java
@@ -40,6 +40,7 @@
      */
     public Region rects;
     private boolean mDetectSimplePaths;
+    private Direction mLastDirection = null;
 
     /**
      * Create an empty path
@@ -70,6 +71,7 @@
     public void reset() {
         isSimplePath = true;
         if (mDetectSimplePaths) {
+            mLastDirection = null;
             if (rects != null) rects.setEmpty();
         }
         native_reset(mNativePath);
@@ -82,6 +84,7 @@
     public void rewind() {
         isSimplePath = true;
         if (mDetectSimplePaths) {
+            mLastDirection = null;
             if (rects != null) rects.setEmpty();
         }
         native_rewind(mNativePath);
@@ -378,6 +381,20 @@
         final int nativeInt;
     }
     
+    private void detectSimplePath(float left, float top, float right, float bottom, Direction dir) {
+        if (mDetectSimplePaths) {
+            if (mLastDirection == null) {
+                mLastDirection = dir;
+            }
+            if (mLastDirection != dir) {
+                isSimplePath = false;
+            } else {
+                if (rects == null) rects = new Region();
+                rects.op((int) left, (int) top, (int) right, (int) bottom, Region.Op.UNION);
+            }
+        }
+    }
+
     /**
      * Add a closed rectangle contour to the path
      *
@@ -388,11 +405,7 @@
         if (rect == null) {
             throw new NullPointerException("need rect parameter");
         }
-        if (mDetectSimplePaths) {
-            if (rects == null) rects = new Region();
-            rects.op((int) rect.left, (int) rect.top, (int) rect.right, (int) rect.bottom,
-                    Region.Op.UNION);
-        }
+        detectSimplePath(rect.left, rect.top, rect.right, rect.bottom, dir);
         native_addRect(mNativePath, rect, dir.nativeInt);
     }
 
@@ -406,10 +419,7 @@
      * @param dir    The direction to wind the rectangle's contour
      */
     public void addRect(float left, float top, float right, float bottom, Direction dir) {
-        if (mDetectSimplePaths) {
-            if (rects == null) rects = new Region();
-            rects.op((int) left, (int) top, (int) right, (int) bottom, Region.Op.UNION);
-        }
+        detectSimplePath(left, top, right, bottom, dir);
         native_addRect(mNativePath, left, top, right, bottom, dir.nativeInt);
     }
 
diff --git a/graphics/java/android/renderscript/ScriptC.java b/graphics/java/android/renderscript/ScriptC.java
index f865753..90f959f 100644
--- a/graphics/java/android/renderscript/ScriptC.java
+++ b/graphics/java/android/renderscript/ScriptC.java
@@ -95,7 +95,7 @@
         // E.g, /system/apps/Fountain.apk
         //String packageName = rs.getApplicationContext().getPackageResourcePath();
         // For res/raw/fountain.bc, it wil be /com.android.fountain:raw/fountain
-        String resName = resources.getResourceName(resourceID);
+        String resName = resources.getResourceEntryName(resourceID);
         String cacheDir = rs.getApplicationContext().getCacheDir().toString();
 
         Log.v(TAG, "Create script for resource = " + resName);
diff --git a/libs/hwui/ShapeCache.h b/libs/hwui/ShapeCache.h
index b048469..f4d9686 100644
--- a/libs/hwui/ShapeCache.h
+++ b/libs/hwui/ShapeCache.h
@@ -537,7 +537,7 @@
     const float pathWidth = fmax(bounds.width(), 1.0f);
     const float pathHeight = fmax(bounds.height(), 1.0f);
 
-    const float offset = fmax(paint->getStrokeWidth(), 1.0f) * 1.5f;
+    const float offset = (int) floorf(fmax(paint->getStrokeWidth(), 1.0f) * 1.5f + 0.5f);
 
     const uint32_t width = uint32_t(pathWidth + offset * 2.0 + 0.5);
     const uint32_t height = uint32_t(pathHeight + offset * 2.0 + 0.5);
diff --git a/libs/rs/driver/rsdBcc.cpp b/libs/rs/driver/rsdBcc.cpp
index 8120864..62eb24e 100644
--- a/libs/rs/driver/rsdBcc.cpp
+++ b/libs/rs/driver/rsdBcc.cpp
@@ -66,65 +66,6 @@
 }
 
 
-// Input: cacheDir
-// Input: resName
-// Input: extName
-//
-// Note: cacheFile = resName + extName
-//
-// Output: Returns cachePath == cacheDir + cacheFile
-static char *genCacheFileName(const char *cacheDir,
-                              const char *resName,
-                              const char *extName) {
-    char cachePath[512];
-    char cacheFile[sizeof(cachePath)];
-    const size_t kBufLen = sizeof(cachePath) - 1;
-
-    cacheFile[0] = '\0';
-    // Note: resName today is usually something like
-    //       "/com.android.fountain:raw/fountain"
-    if (resName[0] != '/') {
-        // Get the absolute path of the raw/***.bc file.
-
-        // Generate the absolute path.  This doesn't do everything it
-        // should, e.g. if resName is "./out/whatever" it doesn't crunch
-        // the leading "./" out because this if-block is not triggered,
-        // but it'll make do.
-        //
-        if (getcwd(cacheFile, kBufLen) == NULL) {
-            LOGE("Can't get CWD while opening raw/***.bc file\n");
-            return NULL;
-        }
-        // Append "/" at the end of cacheFile so far.
-        strncat(cacheFile, "/", kBufLen);
-    }
-
-    // cacheFile = resName + extName
-    //
-    strncat(cacheFile, resName, kBufLen);
-    if (extName != NULL) {
-        // TODO(srhines): strncat() is a bit dangerous
-        strncat(cacheFile, extName, kBufLen);
-    }
-
-    // Turn the path into a flat filename by replacing
-    // any slashes after the first one with '@' characters.
-    char *cp = cacheFile + 1;
-    while (*cp != '\0') {
-        if (*cp == '/') {
-            *cp = '@';
-        }
-        cp++;
-    }
-
-    // Tack on the file name for the actual cache file path.
-    strncpy(cachePath, cacheDir, kBufLen);
-    strncat(cachePath, cacheFile, kBufLen);
-
-    LOGV("Cache file for '%s' '%s' is '%s'\n", resName, extName, cachePath);
-    return strdup(cachePath);
-}
-
 bool rsdScriptInit(const Context *rsc,
                      ScriptC *script,
                      char const *resName,
@@ -164,15 +105,12 @@
         goto error;
     }
 
-#if 1
     if (bccLinkFile(drv->mBccScript, "/system/lib/libclcore.bc", 0) != 0) {
         LOGE("bcc: FAILS to link bitcode");
         goto error;
     }
-#endif
-    cachePath = genCacheFileName(cacheDir, resName, ".oBCC");
 
-    if (bccPrepareExecutable(drv->mBccScript, cachePath, 0) != 0) {
+    if (bccPrepareExecutableEx(drv->mBccScript, cacheDir, resName, 0) != 0) {
         LOGE("bcc: FAILS to prepare executable");
         goto error;
     }
@@ -214,14 +152,13 @@
     const char ** mPragmaKeys;
     const char ** mPragmaValues;
 
-    const static int pragmaMax = 16;
     drv->mPragmaCount = bccGetPragmaCount(drv->mBccScript);
     if (drv->mPragmaCount <= 0) {
         drv->mPragmaKeys = NULL;
         drv->mPragmaValues = NULL;
     } else {
-        drv->mPragmaKeys = (const char **) calloc(drv->mFieldCount, sizeof(const char *));
-        drv->mPragmaValues = (const char **) calloc(drv->mFieldCount, sizeof(const char *));
+        drv->mPragmaKeys = (const char **) calloc(drv->mPragmaCount, sizeof(const char *));
+        drv->mPragmaValues = (const char **) calloc(drv->mPragmaCount, sizeof(const char *));
         bccGetPragmaList(drv->mBccScript, drv->mPragmaCount, drv->mPragmaKeys, drv->mPragmaValues);
     }
 
diff --git a/media/java/android/media/MediaFile.java b/media/java/android/media/MediaFile.java
index 6df2f73..816d215 100644
--- a/media/java/android/media/MediaFile.java
+++ b/media/java/android/media/MediaFile.java
@@ -104,10 +104,9 @@
     public static final int FILE_TYPE_MS_POWERPOINT = 106;
     public static final int FILE_TYPE_ZIP           = 107;
     
-    static class MediaFileType {
-    
-        int fileType;
-        String mimeType;
+    public static class MediaFileType {
+        public final int fileType;
+        public final String mimeType;
         
         MediaFileType(int fileType, String mimeType) {
             this.fileType = fileType;
diff --git a/media/java/android/media/MediaScanner.java b/media/java/android/media/MediaScanner.java
index c55338a..18742ea 100644
--- a/media/java/android/media/MediaScanner.java
+++ b/media/java/android/media/MediaScanner.java
@@ -368,6 +368,34 @@
         }
     }
 
+    private class FileInserter {
+
+        ContentValues[] mValues = new ContentValues[1000];
+        int mIndex = 0;
+
+        public Uri insert(ContentValues values) {
+            if (mIndex == mValues.length) {
+                flush();
+            }
+            mValues[mIndex++] = values;
+            // URI not needed when doing bulk inserts
+            return null;
+        }
+
+        public void flush() {
+            while (mIndex < mValues.length) {
+                mValues[mIndex++] = null;
+            }
+            try {
+                mMediaProvider.bulkInsert(mFilesUri, mValues);
+            } catch (RemoteException e) {
+                Log.e(TAG, "RemoteException in FileInserter.flush()", e);
+            }
+            mIndex = 0;
+        }
+    }
+    private FileInserter mFileInserter;
+
     // hashes file path to FileCacheEntry.
     // path should be lower case if mCaseInsensitivePaths is true
     private HashMap<String, FileCacheEntry> mFileCache;
@@ -805,37 +833,31 @@
                 }
             }
 
-            Uri tableUri = mFilesUri;
-            if (!mNoMedia) {
-                if (MediaFile.isVideoFileType(mFileType)) {
-                    tableUri = mVideoUri;
-                } else if (MediaFile.isImageFileType(mFileType)) {
-                    tableUri = mImagesUri;
-                } else if (MediaFile.isAudioFileType(mFileType)) {
-                    tableUri = mAudioUri;
-                }
-            }
             Uri result = null;
             if (rowId == 0) {
                 if (mMtpObjectHandle != 0) {
                     values.put(MediaStore.MediaColumns.MEDIA_SCANNER_NEW_OBJECT_ID, mMtpObjectHandle);
                 }
-                if (tableUri == mFilesUri) {
-                    int format = entry.mFormat;
-                    if (format == 0) {
-                        format = MediaFile.getFormatCode(entry.mPath, mMimeType);
-                    }
-                    values.put(Files.FileColumns.FORMAT, format);
+                int format = entry.mFormat;
+                if (format == 0) {
+                    format = MediaFile.getFormatCode(entry.mPath, mMimeType);
                 }
+                values.put(Files.FileColumns.FORMAT, format);
+
                 // new file, insert it
-                result = mMediaProvider.insert(tableUri, values);
+                if (mFileInserter != null) {
+                    result = mFileInserter.insert(values);
+                } else {
+                    result = mMediaProvider.insert(mFilesUri, values);
+                }
+
                 if (result != null) {
                     rowId = ContentUris.parseId(result);
                     entry.mRowId = rowId;
                 }
             } else {
                 // updated file
-                result = ContentUris.withAppendedId(tableUri, rowId);
+                result = ContentUris.withAppendedId(mFilesUri, rowId);
                 // path should never change, and we want to avoid replacing mixed cased paths
                 // with squashed lower case paths
                 values.remove(MediaStore.MediaColumns.DATA);
@@ -854,7 +876,7 @@
                                         new String[] { genre }, null);
                         if (cursor == null || cursor.getCount() == 0) {
                             // genre does not exist, so create the genre in the genre table
-                            values.clear();
+                            values = new ContentValues();
                             values.put(MediaStore.Audio.Genres.NAME, genre);
                             uri = mMediaProvider.insert(mGenresUri, values);
                         } else {
@@ -876,7 +898,7 @@
 
                 if (uri != null) {
                     // add entry to audio_genre_map
-                    values.clear();
+                    values = new ContentValues();
                     values.put(MediaStore.Audio.Genres.Members.AUDIO_ID, Long.valueOf(rowId));
                     mMediaProvider.insert(uri, values);
                 }
@@ -885,19 +907,19 @@
             if (notifications && !mDefaultNotificationSet) {
                 if (TextUtils.isEmpty(mDefaultNotificationFilename) ||
                         doesPathHaveFilename(entry.mPath, mDefaultNotificationFilename)) {
-                    setSettingIfNotSet(Settings.System.NOTIFICATION_SOUND, tableUri, rowId);
+                    setSettingIfNotSet(Settings.System.NOTIFICATION_SOUND, mFilesUri, rowId);
                     mDefaultNotificationSet = true;
                 }
             } else if (ringtones && !mDefaultRingtoneSet) {
                 if (TextUtils.isEmpty(mDefaultRingtoneFilename) ||
                         doesPathHaveFilename(entry.mPath, mDefaultRingtoneFilename)) {
-                    setSettingIfNotSet(Settings.System.RINGTONE, tableUri, rowId);
+                    setSettingIfNotSet(Settings.System.RINGTONE, mFilesUri, rowId);
                     mDefaultRingtoneSet = true;
                 }
             } else if (alarms && !mDefaultAlarmSet) {
                 if (TextUtils.isEmpty(mDefaultAlarmAlertFilename) ||
                         doesPathHaveFilename(entry.mPath, mDefaultAlarmAlertFilename)) {
-                    setSettingIfNotSet(Settings.System.ALARM_ALERT, tableUri, rowId);
+                    setSettingIfNotSet(Settings.System.ALARM_ALERT, mFilesUri, rowId);
                     mDefaultAlarmSet = true;
                 }
             }
@@ -1165,10 +1187,14 @@
             initialize(volumeName);
             prescan(null, true);
             long prescan = System.currentTimeMillis();
+            mFileInserter = new FileInserter();
 
             for (int i = 0; i < directories.length; i++) {
                 processDirectory(directories[i], mClient);
             }
+            mFileInserter.flush();
+            mFileInserter = null;
+
             long scan = System.currentTimeMillis();
             postscan(directories);
             long end = System.currentTimeMillis();
diff --git a/media/java/android/mtp/MtpPropertyGroup.java b/media/java/android/mtp/MtpPropertyGroup.java
index b75b11a..76c8569 100644
--- a/media/java/android/mtp/MtpPropertyGroup.java
+++ b/media/java/android/mtp/MtpPropertyGroup.java
@@ -330,7 +330,6 @@
             }
 
             int count = (c == null ? 1 : c.getCount());
-            Log.d(TAG, "count: " + count);
             MtpPropertyList result = new MtpPropertyList(count * mProperties.length,
                     MtpConstants.RESPONSE_OK);
 
diff --git a/media/java/android/mtp/MtpStorage.java b/media/java/android/mtp/MtpStorage.java
index 7932d34..da190a6 100644
--- a/media/java/android/mtp/MtpStorage.java
+++ b/media/java/android/mtp/MtpStorage.java
@@ -32,6 +32,7 @@
     private final String mDescription;
     private final long mReserveSpace;
     private final boolean mRemovable;
+    private final long mMaxFileSize;
 
     public MtpStorage(StorageVolume volume) {
         mStorageId = volume.getStorageId();
@@ -39,6 +40,7 @@
         mDescription = volume.getDescription();
         mReserveSpace = volume.getMtpReserveSpace();
         mRemovable = volume.isRemovable();
+        mMaxFileSize = volume.getMaxFileSize();
     }
 
     /**
@@ -98,4 +100,13 @@
     public final boolean isRemovable() {
         return mRemovable;
     }
+
+   /**
+     * Returns maximum file size for the storage, or zero if it is unbounded.
+     *
+     * @return maximum file size
+     */
+    public long getMaxFileSize() {
+        return mMaxFileSize;
+    }
 }
diff --git a/media/jni/android_mtp_MtpServer.cpp b/media/jni/android_mtp_MtpServer.cpp
index aaf85c3..446b630 100644
--- a/media/jni/android_mtp_MtpServer.cpp
+++ b/media/jni/android_mtp_MtpServer.cpp
@@ -48,6 +48,7 @@
 static jfieldID field_MtpStorage_description;
 static jfieldID field_MtpStorage_reserveSpace;
 static jfieldID field_MtpStorage_removable;
+static jfieldID field_MtpStorage_maxFileSize;
 
 static Mutex sMutex;
 
@@ -228,12 +229,14 @@
         jstring description = (jstring)env->GetObjectField(jstorage, field_MtpStorage_description);
         jlong reserveSpace = env->GetLongField(jstorage, field_MtpStorage_reserveSpace);
         jboolean removable = env->GetBooleanField(jstorage, field_MtpStorage_removable);
+        jlong maxFileSize = env->GetLongField(jstorage, field_MtpStorage_maxFileSize);
 
         const char *pathStr = env->GetStringUTFChars(path, NULL);
         if (pathStr != NULL) {
             const char *descriptionStr = env->GetStringUTFChars(description, NULL);
             if (descriptionStr != NULL) {
-                MtpStorage* storage = new MtpStorage(storageID, pathStr, descriptionStr, reserveSpace, removable);
+                MtpStorage* storage = new MtpStorage(storageID, pathStr, descriptionStr,
+                        reserveSpace, removable, maxFileSize);
                 thread->addStorage(storage);
                 env->ReleaseStringUTFChars(path, pathStr);
                 env->ReleaseStringUTFChars(description, descriptionStr);
@@ -312,6 +315,11 @@
         LOGE("Can't find MtpStorage.mRemovable");
         return -1;
     }
+    field_MtpStorage_maxFileSize = env->GetFieldID(clazz, "mMaxFileSize", "J");
+    if (field_MtpStorage_maxFileSize == NULL) {
+        LOGE("Can't find MtpStorage.mMaxFileSize");
+        return -1;
+    }
     clazz_MtpStorage = (jclass)env->NewGlobalRef(clazz);
 
     clazz = env->FindClass("android/mtp/MtpServer");
diff --git a/media/mtp/MtpServer.cpp b/media/mtp/MtpServer.cpp
index bc04e8c..9085f10 100644
--- a/media/mtp/MtpServer.cpp
+++ b/media/mtp/MtpServer.cpp
@@ -871,6 +871,14 @@
     // check space first
     if (mSendObjectFileSize > storage->getFreeSpace())
         return MTP_RESPONSE_STORAGE_FULL;
+    uint64_t maxFileSize = storage->getMaxFileSize();
+    // check storage max file size
+    if (maxFileSize != 0) {
+        // if mSendObjectFileSize is 0xFFFFFFFF, then all we know is the file size
+        // is >= 0xFFFFFFFF
+        if (mSendObjectFileSize > maxFileSize || mSendObjectFileSize == 0xFFFFFFFF)
+            return MTP_RESPONSE_OBJECT_TOO_LARGE;
+    }
 
 LOGD("path: %s parent: %d storageID: %08X", (const char*)path, parent, storageID);
     MtpObjectHandle handle = mDatabase->beginSendObject((const char*)path,
diff --git a/media/mtp/MtpStorage.cpp b/media/mtp/MtpStorage.cpp
index fef8066..941e303 100644
--- a/media/mtp/MtpStorage.cpp
+++ b/media/mtp/MtpStorage.cpp
@@ -33,11 +33,13 @@
 namespace android {
 
 MtpStorage::MtpStorage(MtpStorageID id, const char* filePath,
-        const char* description, uint64_t reserveSpace, bool removable)
+        const char* description, uint64_t reserveSpace,
+        bool removable, uint64_t maxFileSize)
     :   mStorageID(id),
         mFilePath(filePath),
         mDescription(description),
         mMaxCapacity(0),
+        mMaxFileSize(maxFileSize),
         mReserveSpace(reserveSpace),
         mRemovable(removable)
 {
diff --git a/media/mtp/MtpStorage.h b/media/mtp/MtpStorage.h
index 3e4f40d..e5a2e57 100644
--- a/media/mtp/MtpStorage.h
+++ b/media/mtp/MtpStorage.h
@@ -31,6 +31,7 @@
     MtpString               mFilePath;
     MtpString               mDescription;
     uint64_t                mMaxCapacity;
+    uint64_t                mMaxFileSize;
     // amount of free space to leave unallocated
     uint64_t                mReserveSpace;
     bool                    mRemovable;
@@ -38,7 +39,7 @@
 public:
                             MtpStorage(MtpStorageID id, const char* filePath,
                                     const char* description, uint64_t reserveSpace,
-                                    bool removable);
+                                    bool removable, uint64_t maxFileSize);
     virtual                 ~MtpStorage();
 
     inline MtpStorageID     getStorageID() const { return mStorageID; }
@@ -50,6 +51,7 @@
     const char*             getDescription() const;
     inline const char*      getPath() const { return (const char *)mFilePath; }
     inline bool             isRemovable() const { return mRemovable; }
+    inline uint64_t         getMaxFileSize() const { return mMaxFileSize; }
 };
 
 }; // namespace android
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/VideoEditorAPITest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/VideoEditorAPITest.java
index 5120694..afe2001 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/VideoEditorAPITest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/VideoEditorAPITest.java
@@ -1335,16 +1335,19 @@
     @LargeTest
     public void testEffectKenBurn() throws Exception {
         // Test ken burn effect using a JPEG file.
-        testEffectKenBurn(INPUT_FILE_PATH + "IMG_640x480.jpg");
+        testEffectKenBurn(INPUT_FILE_PATH + "IMG_640x480.jpg",
+         "mediaImageItem1");
 
         // Test ken burn effect using a PNG file
-        testEffectKenBurn(INPUT_FILE_PATH + "IMG_640x480.png");
+        testEffectKenBurn(INPUT_FILE_PATH + "IMG_640x480.png",
+         "mediaImageItem2");
     }
 
-    private void testEffectKenBurn(final String imageItemFileName) throws Exception {
+    private void testEffectKenBurn(final String imageItemFileName,
+     final String MediaId) throws Exception {
         final int imageItemRenderingMode =MediaItem.RENDERING_MODE_BLACK_BORDER;
         final MediaImageItem mediaImageItem =
-            mVideoEditorHelper.createMediaItem(mVideoEditor, "mediaImageItem1",
+            mVideoEditorHelper.createMediaItem(mVideoEditor, MediaId,
             imageItemFileName, 5000, imageItemRenderingMode);
         mVideoEditor.addMediaItem(mediaImageItem);
 
diff --git a/packages/SystemUI/res/layout-port/status_bar_recent_panel.xml b/packages/SystemUI/res/layout-port/status_bar_recent_panel.xml
index 386182d..28ef239 100644
--- a/packages/SystemUI/res/layout-port/status_bar_recent_panel.xml
+++ b/packages/SystemUI/res/layout-port/status_bar_recent_panel.xml
@@ -29,21 +29,17 @@
         android:background="@drawable/status_bar_recents_background"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
-        android:layout_alignParentBottom="true"
-        android:paddingBottom="@*android:dimen/status_bar_height"
-        android:clipToPadding="false"
-        android:clipChildren="false">
+        android:layout_alignParentBottom="true">
 
         <LinearLayout android:id="@+id/recents_glow"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
-            android:layout_marginBottom="0dp"
             android:layout_gravity="bottom"
             android:orientation="horizontal"
-            android:clipToPadding="false"
             android:clipChildren="false"
-            >
-            <com.android.systemui.recent.RecentsVerticalScrollView android:id="@+id/recents_container"
+            android:layout_marginTop="@*android:dimen/status_bar_height">
+            <com.android.systemui.recent.RecentsVerticalScrollView
+                android:id="@+id/recents_container"
                 android:layout_width="@dimen/status_bar_recents_width"
                 android:layout_height="wrap_content"
                 android:layout_marginRight="0dp"
@@ -51,7 +47,7 @@
                 android:stackFromBottom="true"
                 android:fadingEdge="vertical"
                 android:scrollbars="none"
-                android:fadingEdgeLength="20dip"
+                android:fadingEdgeLength="@*android:dimen/status_bar_height"
                 android:listSelector="@drawable/recents_thumbnail_bg_selector"
                 android:layout_gravity="bottom|left"
                 android:clipToPadding="false"
diff --git a/packages/SystemUI/src/com/android/systemui/recent/Constants.java b/packages/SystemUI/src/com/android/systemui/recent/Constants.java
index 66f9292..8252a9f8 100644
--- a/packages/SystemUI/src/com/android/systemui/recent/Constants.java
+++ b/packages/SystemUI/src/com/android/systemui/recent/Constants.java
@@ -18,7 +18,8 @@
 
 public class Constants {
     static final int MAX_ESCAPE_ANIMATION_DURATION = 500; // in ms
-    static final float FADE_CONSTANT = 0.5f; // unitless
     static final int SNAP_BACK_DURATION = 250; // in ms
     static final int ESCAPE_VELOCITY = 100; // speed of item required to "curate" it in dp/s
+    public static float ALPHA_FADE_START = 0.8f; // fraction of thumbnail width where fade starts
+    static final float ALPHA_FADE_END = 0.5f; // fraction of thumbnail width beyond which alpha->0
 }
diff --git a/packages/SystemUI/src/com/android/systemui/recent/RecentsHorizontalScrollView.java b/packages/SystemUI/src/com/android/systemui/recent/RecentsHorizontalScrollView.java
index fb7a0a7..f984aac 100644
--- a/packages/SystemUI/src/com/android/systemui/recent/RecentsHorizontalScrollView.java
+++ b/packages/SystemUI/src/com/android/systemui/recent/RecentsHorizontalScrollView.java
@@ -118,12 +118,12 @@
     }
 
     private float getAlphaForOffset(View view, float thumbHeight) {
-        final float fadeHeight = Constants.FADE_CONSTANT * thumbHeight;
+        final float fadeHeight = Constants.ALPHA_FADE_END * thumbHeight;
         float result = 1.0f;
-        if (view.getY() >= thumbHeight) {
-            result = 1.0f - (view.getY() - thumbHeight) / fadeHeight;
-        } else if (view.getY() < 0.0f) {
-            result = 1.0f + (thumbHeight + view.getY()) / fadeHeight;
+        if (view.getY() >= thumbHeight * Constants.ALPHA_FADE_START) {
+            result = 1.0f - (view.getY() - thumbHeight * Constants.ALPHA_FADE_START) / fadeHeight;
+        } else if (view.getY() < thumbHeight * (1.0f - Constants.ALPHA_FADE_START)) {
+            result = 1.0f + (thumbHeight * Constants.ALPHA_FADE_START + view.getY()) / fadeHeight;
         }
         if (DEBUG) Log.v(TAG, "FADE AMOUNT: " + result);
         return result;
@@ -269,7 +269,7 @@
         // This has to happen post-layout, so run it "in the future"
         post(new Runnable() {
             public void run() {
-                scrollTo(0, mLastScrollPosition);
+                scrollTo(mLastScrollPosition, 0);
             }
         });
     }
diff --git a/packages/SystemUI/src/com/android/systemui/recent/RecentsVerticalScrollView.java b/packages/SystemUI/src/com/android/systemui/recent/RecentsVerticalScrollView.java
index 711ffa3..27bb0b5 100644
--- a/packages/SystemUI/src/com/android/systemui/recent/RecentsVerticalScrollView.java
+++ b/packages/SystemUI/src/com/android/systemui/recent/RecentsVerticalScrollView.java
@@ -118,12 +118,12 @@
     }
 
     private float getAlphaForOffset(View view, float thumbWidth) {
-        final float fadeWidth = Constants.FADE_CONSTANT * thumbWidth;
+        final float fadeWidth = Constants.ALPHA_FADE_END * thumbWidth;
         float result = 1.0f;
-        if (view.getX() >= thumbWidth) {
-            result = 1.0f - (view.getX() - thumbWidth) / fadeWidth;
-        } else if (view.getX() < 0.0f) {
-            result = 1.0f + (thumbWidth + view.getX()) / fadeWidth;
+        if (view.getX() >= thumbWidth*Constants.ALPHA_FADE_START) {
+            result = 1.0f - (view.getX() - thumbWidth*Constants.ALPHA_FADE_START) / fadeWidth;
+        } else if (view.getX() < thumbWidth* (1.0f - Constants.ALPHA_FADE_START)) {
+            result = 1.0f + (thumbWidth*Constants.ALPHA_FADE_START + view.getX()) / fadeWidth;
         }
         if (DEBUG) Log.v(TAG, "FADE AMOUNT: " + result);
         return result;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
index 5eacad7..b50fd81 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -307,7 +307,7 @@
         mDateView.setVisibility(View.INVISIBLE);
 
         // Recents Panel
-        initializeRecentsPanel();
+        updateRecentsPanel();
 
         // receive broadcasts
         IntentFilter filter = new IntentFilter();
@@ -338,7 +338,7 @@
         return lp;
     }
 
-    protected void initializeRecentsPanel() {
+    protected void updateRecentsPanel() {
         // Recents Panel
         boolean visible = false;
         if (mRecentsPanel != null) {
@@ -385,9 +385,9 @@
     // For small-screen devices (read: phones) that lack hardware navigation buttons
     private void addNavigationBar() {
         if (mNavigationBarView == null) return;
-        
+
         mNavigationBarView.reorient();
- 
+
         mNavigationBarView.getRecentsButton().setOnClickListener(mRecentsClickListener);
 
         WindowManagerImpl.getDefault().addView(
@@ -396,7 +396,7 @@
 
     private void repositionNavigationBar() {
         if (mNavigationBarView == null) return;
-        
+
         mNavigationBarView.reorient();
 
         mNavigationBarView.getRecentsButton().setOnClickListener(mRecentsClickListener);
@@ -656,7 +656,7 @@
 
     @Override
     protected void onConfigurationChanged(Configuration newConfig) {
-        initializeRecentsPanel();
+        updateRecentsPanel();
     }
 
 
diff --git a/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java b/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
index f862d01..75e799c 100644
--- a/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
+++ b/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
@@ -29,7 +29,9 @@
 import android.os.SystemClock;
 import android.security.KeyStore;
 import android.telephony.TelephonyManager;
+import android.text.Editable;
 import android.text.InputType;
+import android.text.TextWatcher;
 import android.text.method.DigitsKeyListener;
 import android.text.method.TextKeyListener;
 import android.util.Log;
@@ -120,15 +122,6 @@
             }
         });
 
-        // We don't currently use the IME for PIN mode, but this will make it work if we ever do...
-        if (!mIsAlpha) {
-            mPasswordEntry.setInputType(InputType.TYPE_CLASS_NUMBER
-                    | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
-        } else {
-            mPasswordEntry.setInputType(InputType.TYPE_CLASS_TEXT
-                    | InputType.TYPE_TEXT_VARIATION_PASSWORD);
-        }
-
         mEmergencyCallButton = (Button) findViewById(R.id.emergencyCallButton);
         mEmergencyCallButton.setOnClickListener(this);
         mLockPatternUtils.updateEmergencyCallButtonState(mEmergencyCallButton);
@@ -151,14 +144,17 @@
 
         mPasswordEntry.requestFocus();
 
-        // This allows keyboards with overlapping qwerty/numeric keys to choose just the
-        // numeric keys.
+        // This allows keyboards with overlapping qwerty/numeric keys to choose just numeric keys.
         if (mIsAlpha) {
             mPasswordEntry.setKeyListener(TextKeyListener.getInstance());
+            mPasswordEntry.setInputType(InputType.TYPE_CLASS_TEXT
+                    | InputType.TYPE_TEXT_VARIATION_PASSWORD);
             // mStatusView.setHelpMessage(R.string.keyguard_password_enter_password_code,
             //      StatusView.LOCK_ICON);
         } else {
             mPasswordEntry.setKeyListener(DigitsKeyListener.getInstance());
+            mPasswordEntry.setInputType(InputType.TYPE_CLASS_NUMBER
+                    | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
             //mStatusView.setHelpMessage(R.string.keyguard_password_enter_pin_code,
             //      StatusView.LOCK_ICON);
         }
@@ -179,6 +175,19 @@
         //mUpdateMonitor.registerSimStateCallback(this);
 
         resetStatusInfo();
+
+        // Poke the wakelock any time the text is modified
+        mPasswordEntry.addTextChangedListener(new TextWatcher() {
+            public void onTextChanged(CharSequence s, int start, int before, int count) {
+            }
+
+            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+            }
+
+            public void afterTextChanged(Editable s) {
+                mCallback.pokeWakelock();
+            }
+        });
     }
 
     @Override
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index b98d2a2..41450d2 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -1602,8 +1602,10 @@
             if (linkProperties != null) {
                 String iface = linkProperties.getInterfaceName();
                 if (TextUtils.isEmpty(iface) == false) {
-                    if (DBG) log("resetConnections(" + iface + ")");
-                    NetworkUtils.resetConnections(iface);
+                    if (DBG) {
+                        log("resetConnections(" + iface + ", NetworkUtils.RESET_ALL_ADDRESSES)");
+                    }
+                    NetworkUtils.resetConnections(iface, NetworkUtils.RESET_ALL_ADDRESSES);
                 }
             }
         }
diff --git a/services/java/com/android/server/MountService.java b/services/java/com/android/server/MountService.java
index 54e5432..2e54c99 100644
--- a/services/java/com/android/server/MountService.java
+++ b/services/java/com/android/server/MountService.java
@@ -1075,18 +1075,22 @@
                             com.android.internal.R.styleable.Storage_mtpReserve, 0);
                     boolean allowMassStorage = a.getBoolean(
                             com.android.internal.R.styleable.Storage_allowMassStorage, false);
+                    // resource parser does not support longs, so XML value is in megabytes
+                    long maxFileSize = a.getInt(
+                            com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L;
 
                     Slog.d(TAG, "got storage path: " + path + " description: " + description +
                             " primary: " + primary + " removable: " + removable +
                             " emulated: " + emulated +  " mtpReserve: " + mtpReserve +
-                            " allowMassStorage: " + allowMassStorage);
+                            " allowMassStorage: " + allowMassStorage +
+                            " maxFileSize: " + maxFileSize);
                     if (path == null || description == null) {
                         Slog.e(TAG, "path or description is null in readStorageList");
                     } else {
                         String pathString = path.toString();
                         StorageVolume volume = new StorageVolume(pathString,
                                 description.toString(), removable, emulated,
-                                mtpReserve, allowMassStorage);
+                                mtpReserve, allowMassStorage, maxFileSize);
                         if (primary) {
                             if (mPrimaryVolume == null) {
                                 mPrimaryVolume = volume;
diff --git a/services/java/com/android/server/NetworkTimeUpdateService.java b/services/java/com/android/server/NetworkTimeUpdateService.java
index 15f22c0..f7fe39e 100644
--- a/services/java/com/android/server/NetworkTimeUpdateService.java
+++ b/services/java/com/android/server/NetworkTimeUpdateService.java
@@ -16,8 +16,6 @@
 
 package com.android.server;
 
-import com.android.internal.telephony.TelephonyIntents;
-
 import android.app.AlarmManager;
 import android.app.PendingIntent;
 import android.content.BroadcastReceiver;
@@ -28,7 +26,6 @@
 import android.database.ContentObserver;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
-import android.net.SntpClient;
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.Looper;
@@ -36,12 +33,10 @@
 import android.os.SystemClock;
 import android.provider.Settings;
 import android.util.Log;
-import android.util.Slog;
+import android.util.NtpTrustedTime;
+import android.util.TrustedTime;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.util.Properties;
+import com.android.internal.telephony.TelephonyIntents;
 
 /**
  * Monitors the network time and updates the system time if it is out of sync
@@ -68,14 +63,11 @@
     private static final long POLLING_INTERVAL_SHORTER_MS = 60 * 1000L; // 60 seconds
     /** Number of times to try again */
     private static final int TRY_AGAIN_TIMES_MAX = 3;
-    /** How long to wait for the NTP server to respond. */
-    private static final int MAX_NTP_FETCH_WAIT_MS = 20 * 1000;
     /** If the time difference is greater than this threshold, then update the time. */
     private static final int TIME_ERROR_THRESHOLD_MS = 5 * 1000;
 
     private static final String ACTION_POLL =
             "com.android.server.NetworkTimeUpdateService.action.POLL";
-    private static final String PROPERTIES_FILE = "/etc/gps.conf";
     private static int POLL_REQUEST = 0;
 
     private static final long NOT_SET = -1;
@@ -84,14 +76,14 @@
     private long mNitzZoneSetTime = NOT_SET;
 
     private Context mContext;
+    private TrustedTime mTime;
+
     // NTP lookup is done on this thread and handler
     private Handler mHandler;
     private HandlerThread mThread;
     private AlarmManager mAlarmManager;
     private PendingIntent mPendingPollIntent;
     private SettingsObserver mSettingsObserver;
-    // Address of the NTP server
-    private String mNtpServer;
     // The last time that we successfully fetched the NTP time.
     private long mLastNtpFetchTime = NOT_SET;
     // Keeps track of how many quick attempts were made to fetch NTP time.
@@ -101,6 +93,7 @@
 
     public NetworkTimeUpdateService(Context context) {
         mContext = context;
+        mTime = NtpTrustedTime.getInstance(context);
         mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
         Intent pollIntent = new Intent(ACTION_POLL, null);
         mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0);
@@ -108,12 +101,6 @@
 
     /** Initialize the receivers and initiate the first NTP request */
     public void systemReady() {
-        mNtpServer = getNtpServerAddress();
-        if (mNtpServer == null) {
-            Slog.e(TAG, "NTP server address not found, not syncing to NTP time");
-            return;
-        }
-
         registerForTelephonyIntents();
         registerForAlarms();
         registerForConnectivityIntents();
@@ -128,27 +115,6 @@
         mSettingsObserver.observe(mContext);
     }
 
-    private String getNtpServerAddress() {
-        String serverAddress = null;
-        FileInputStream stream = null;
-        try {
-            Properties properties = new Properties();
-            File file = new File(PROPERTIES_FILE);
-            stream = new FileInputStream(file);
-            properties.load(stream);
-            serverAddress = properties.getProperty("NTP_SERVER", null);
-        } catch (IOException e) {
-            Slog.e(TAG, "Could not open GPS configuration file " + PROPERTIES_FILE);
-        } finally {
-            if (stream != null) {
-                try {
-                    stream.close();
-                } catch (Exception e) {}
-            }
-        }
-        return serverAddress;
-    }
-
     private void registerForTelephonyIntents() {
         IntentFilter intentFilter = new IntentFilter();
         intentFilter.addAction(TelephonyIntents.ACTION_NETWORK_SET_TIME);
@@ -189,9 +155,15 @@
         if (mLastNtpFetchTime == NOT_SET || refTime >= mLastNtpFetchTime + POLLING_INTERVAL_MS
                 || event == EVENT_AUTO_TIME_CHANGED) {
             if (DBG) Log.d(TAG, "Before Ntp fetch");
-            long ntp = getNtpTime();
-            if (DBG) Log.d(TAG, "Ntp = " + ntp);
-            if (ntp > 0) {
+
+            // force refresh NTP cache when outdated
+            if (mTime.getCacheAge() >= POLLING_INTERVAL_MS) {
+                mTime.forceRefresh();
+            }
+
+            // only update when NTP time is fresh
+            if (mTime.getCacheAge() < POLLING_INTERVAL_MS) {
+                final long ntp = mTime.currentTimeMillis();
                 mTryAgainCounter = 0;
                 mLastNtpFetchTime = SystemClock.elapsedRealtime();
                 if (Math.abs(ntp - currentTime) > TIME_ERROR_THRESHOLD_MS) {
@@ -232,15 +204,6 @@
         mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, next, mPendingPollIntent);
     }
 
-    private long getNtpTime() {
-        SntpClient client = new SntpClient();
-        if (client.requestTime(mNtpServer, MAX_NTP_FETCH_WAIT_MS)) {
-            return client.getNtpTime();
-        } else {
-            return 0;
-        }
-    }
-
     /**
      * Checks if the user prefers to automatically set the time.
      */
diff --git a/services/java/com/android/server/ThrottleService.java b/services/java/com/android/server/ThrottleService.java
index d81dfdb..24d4dd3 100644
--- a/services/java/com/android/server/ThrottleService.java
+++ b/services/java/com/android/server/ThrottleService.java
@@ -16,9 +16,6 @@
 
 package com.android.server;
 
-import com.android.internal.R;
-import com.android.internal.telephony.TelephonyProperties;
-
 import android.app.AlarmManager;
 import android.app.Notification;
 import android.app.NotificationManager;
@@ -54,6 +51,9 @@
 import android.util.Slog;
 import android.util.TrustedTime;
 
+import com.android.internal.R;
+import com.android.internal.telephony.TelephonyProperties;
+
 import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileDescriptor;
@@ -63,7 +63,6 @@
 import java.io.PrintWriter;
 import java.util.Calendar;
 import java.util.GregorianCalendar;
-import java.util.Properties;
 import java.util.Random;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicLong;
@@ -87,7 +86,6 @@
     private static final long TESTING_THRESHOLD = 1 * 1024 * 1024;
 
     private static final long MAX_NTP_CACHE_AGE = 24 * 60 * 60 * 1000;
-    private static final long MAX_NTP_FETCH_WAIT = 20 * 1000;
 
     private long mMaxNtpCacheAge = MAX_NTP_CACHE_AGE;
 
@@ -127,8 +125,6 @@
     private static final int THROTTLE_INDEX_UNINITIALIZED = -1;
     private static final int THROTTLE_INDEX_UNTHROTTLED   =  0;
 
-    private static final String PROPERTIES_FILE = "/etc/gps.conf";
-
     private Intent mPollStickyBroadcast;
 
     private TrustedTime mTime;
@@ -139,8 +135,7 @@
     }
 
     public ThrottleService(Context context) {
-        // TODO: move to using cached NtpTrustedTime
-        this(context, getNetworkManagementService(), new NtpTrustedTime(),
+        this(context, getNetworkManagementService(), NtpTrustedTime.getInstance(context),
                 context.getResources().getString(R.string.config_datause_iface));
     }
 
@@ -341,26 +336,6 @@
                 }
             }, new IntentFilter(ACTION_RESET));
 
-        FileInputStream stream = null;
-        try {
-            Properties properties = new Properties();
-            File file = new File(PROPERTIES_FILE);
-            stream = new FileInputStream(file);
-            properties.load(stream);
-            final String ntpServer = properties.getProperty("NTP_SERVER", null);
-            if (mTime instanceof NtpTrustedTime) {
-                ((NtpTrustedTime) mTime).setNtpServer(ntpServer, MAX_NTP_FETCH_WAIT);
-            }
-        } catch (IOException e) {
-            Slog.e(TAG, "Could not open GPS configuration file " + PROPERTIES_FILE);
-        } finally {
-            if (stream != null) {
-                try {
-                    stream.close();
-                } catch (Exception e) {}
-            }
-        }
-
         // use a new thread as we don't want to stall the system for file writes
         mThread = new HandlerThread(TAG);
         mThread.start();
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index 29cccb6..62f0fea 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -1960,7 +1960,8 @@
                 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
             }
             int pid = Process.start("android.app.ActivityThread",
-                    app.processName, uid, uid, gids, debugFlags, null);
+                    app.processName, uid, uid, gids, debugFlags,
+                    app.info.targetSdkVersion, null);
             BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
             synchronized (bs) {
                 if (bs.isOnBattery()) {
diff --git a/services/java/com/android/server/location/GpsLocationProvider.java b/services/java/com/android/server/location/GpsLocationProvider.java
index 4fa3bda..c813d37 100755
--- a/services/java/com/android/server/location/GpsLocationProvider.java
+++ b/services/java/com/android/server/location/GpsLocationProvider.java
@@ -32,7 +32,6 @@
 import android.location.LocationProvider;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
-import android.net.SntpClient;
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.Handler;
@@ -51,6 +50,7 @@
 import android.telephony.TelephonyManager;
 import android.telephony.gsm.GsmCellLocation;
 import android.util.Log;
+import android.util.NtpTrustedTime;
 import android.util.SparseIntArray;
 
 import com.android.internal.app.IBatteryStats;
@@ -61,7 +61,7 @@
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
-import java.io.StringBufferInputStream;
+import java.io.StringReader;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.Map.Entry;
@@ -235,13 +235,13 @@
 
     // properties loaded from PROPERTIES_FILE
     private Properties mProperties;
-    private String mNtpServer;
     private String mSuplServerHost;
     private int mSuplServerPort;
     private String mC2KServerHost;
     private int mC2KServerPort;
 
     private final Context mContext;
+    private final NtpTrustedTime mNtpTime;
     private final ILocationManager mLocationManager;
     private Location mLocation = new Location(LocationManager.GPS_PROVIDER);
     private Bundle mLocationExtras = new Bundle();
@@ -286,10 +286,6 @@
     // current setting - 5 minutes
     private static final long RETRY_INTERVAL = 5*60*1000;
 
-    // to avoid injecting bad NTP time, we reject any time fixes that differ from system time
-    // by more than 5 minutes.
-    private static final long MAX_NTP_SYSTEM_TIME_OFFSET = 5*60*1000;
-
     private final IGpsStatusProvider mGpsStatusProvider = new IGpsStatusProvider.Stub() {
         public void addGpsStatusListener(IGpsStatusListener listener) throws RemoteException {
             if (listener == null) {
@@ -378,6 +374,7 @@
 
     public GpsLocationProvider(Context context, ILocationManager locationManager) {
         mContext = context;
+        mNtpTime = NtpTrustedTime.getInstance(context);
         mLocationManager = locationManager;
         mNIHandler = new GpsNetInitiatedHandler(context);
 
@@ -418,7 +415,6 @@
             FileInputStream stream = new FileInputStream(file);
             mProperties.load(stream);
             stream.close();
-            mNtpServer = mProperties.getProperty("NTP_SERVER", null);
 
             mSuplServerHost = mProperties.getProperty("SUPL_HOST");
             String portString = mProperties.getProperty("SUPL_PORT");
@@ -530,13 +526,18 @@
         }
         mInjectNtpTimePending = false;
 
-        SntpClient client = new SntpClient();
         long delay;
 
-        if (client.requestTime(mNtpServer, 10000)) {
-            long time = client.getNtpTime();
-            long timeReference = client.getNtpTimeReference();
-            int certainty = (int)(client.getRoundTripTime()/2);
+        // force refresh NTP cache when outdated
+        if (mNtpTime.getCacheAge() >= NTP_INTERVAL) {
+            mNtpTime.forceRefresh();
+        }
+
+        // only update when NTP time is fresh
+        if (mNtpTime.getCacheAge() < NTP_INTERVAL) {
+            long time = mNtpTime.getCachedNtpTime();
+            long timeReference = mNtpTime.getCachedNtpTimeReference();
+            long certainty = mNtpTime.getCacheCertainty();
             long now = System.currentTimeMillis();
 
             Log.d(TAG, "NTP server returned: "
@@ -545,7 +546,7 @@
                     + " certainty: " + certainty
                     + " system time offset: " + (time - now));
 
-            native_inject_time(time, timeReference, certainty);
+            native_inject_time(time, timeReference, (int) certainty);
             delay = NTP_INTERVAL;
         } else {
             if (DEBUG) Log.d(TAG, "requestTime failed");
@@ -1395,7 +1396,7 @@
         Properties extraProp = new Properties();
 
         try {
-            extraProp.load(new StringBufferInputStream(extras));
+            extraProp.load(new StringReader(extras));
         }
         catch (IOException e)
         {
diff --git a/services/java/com/android/server/net/NetworkPolicyManagerService.java b/services/java/com/android/server/net/NetworkPolicyManagerService.java
index 2a17cbe..d23d0f4 100644
--- a/services/java/com/android/server/net/NetworkPolicyManagerService.java
+++ b/services/java/com/android/server/net/NetworkPolicyManagerService.java
@@ -204,9 +204,8 @@
     public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
             IPowerManager powerManager, INetworkStatsService networkStats,
             INetworkManagementService networkManagement) {
-        // TODO: move to using cached NtpTrustedTime
         this(context, activityManager, powerManager, networkStats, networkManagement,
-                new NtpTrustedTime(), getSystemDir());
+                NtpTrustedTime.getInstance(context), getSystemDir());
     }
 
     private static File getSystemDir() {
diff --git a/services/java/com/android/server/net/NetworkStatsService.java b/services/java/com/android/server/net/NetworkStatsService.java
index b4bd176..b6834f6 100644
--- a/services/java/com/android/server/net/NetworkStatsService.java
+++ b/services/java/com/android/server/net/NetworkStatsService.java
@@ -27,7 +27,6 @@
 import static android.net.NetworkStats.TAG_NONE;
 import static android.net.NetworkStats.UID_ALL;
 import static android.net.TrafficStats.UID_REMOVED;
-import static android.provider.Settings.Secure.NETSTATS_ENABLED;
 import static android.provider.Settings.Secure.NETSTATS_NETWORK_BUCKET_DURATION;
 import static android.provider.Settings.Secure.NETSTATS_NETWORK_MAX_HISTORY;
 import static android.provider.Settings.Secure.NETSTATS_PERSIST_THRESHOLD;
@@ -71,7 +70,6 @@
 import android.util.TrustedTime;
 
 import com.android.internal.os.AtomicFile;
-import com.android.server.NativeDaemonConnectorException;
 import com.google.android.collect.Maps;
 import com.google.android.collect.Sets;
 
@@ -175,9 +173,8 @@
 
     public NetworkStatsService(
             Context context, INetworkManagementService networkManager, IAlarmManager alarmManager) {
-        // TODO: move to using cached NtpTrustedTime
-        this(context, networkManager, alarmManager, new NtpTrustedTime(), getSystemDir(),
-                new DefaultNetworkStatsSettings(context));
+        this(context, networkManager, alarmManager, NtpTrustedTime.getInstance(context),
+                getSystemDir(), new DefaultNetworkStatsSettings(context));
     }
 
     private static File getSystemDir() {
diff --git a/services/java/com/android/server/usb/UsbDeviceManager.java b/services/java/com/android/server/usb/UsbDeviceManager.java
index d645160..1ab570a 100644
--- a/services/java/com/android/server/usb/UsbDeviceManager.java
+++ b/services/java/com/android/server/usb/UsbDeviceManager.java
@@ -630,20 +630,20 @@
     }
 
     /* opens the currently attached USB accessory */
-        public ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
-            UsbAccessory currentAccessory = mHandler.getCurrentAccessory();
-            if (currentAccessory == null) {
-                throw new IllegalArgumentException("no accessory attached");
-            }
-            if (!currentAccessory.equals(accessory)) {
-                String error = accessory.toString()
-                        + " does not match current accessory "
-                        + currentAccessory;
-                throw new IllegalArgumentException(error);
-            }
-            mSettingsManager.checkPermission(accessory);
-            return nativeOpenAccessory();
+    public ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
+        UsbAccessory currentAccessory = mHandler.getCurrentAccessory();
+        if (currentAccessory == null) {
+            throw new IllegalArgumentException("no accessory attached");
         }
+        if (!currentAccessory.equals(accessory)) {
+            String error = accessory.toString()
+                    + " does not match current accessory "
+                    + currentAccessory;
+            throw new IllegalArgumentException(error);
+        }
+        mSettingsManager.checkPermission(accessory);
+        return nativeOpenAccessory();
+    }
 
     public void setCurrentFunction(String function, boolean makeDefault) {
         if (DEBUG) Slog.d(TAG, "setCurrentFunction(" + function + ") default: " + makeDefault);
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
index fe57d0d..df5898b 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
@@ -1055,10 +1055,16 @@
                     }
                 }
                 if (!found) {
-                    // ApnContext does not have dcan reorted in data call list.
+                    // ApnContext does not have dcac reported in data call list.
+                    // Fetch all the ApnContexts that map to this dcac which are in
+                    // INITING state too.
                     if (DBG) log("onDataStateChanged(ar): Connected apn not found in the list (" +
                                  apnContext.toString() + ")");
-                    list.add(apnContext);
+                    if (apnContext.getDataConnectionAc() != null) {
+                        list.addAll(apnContext.getDataConnectionAc().getApnListSync());
+                    } else {
+                        list.add(apnContext);
+                    }
                 }
             }
         }
@@ -1110,10 +1116,12 @@
 
             Collection<ApnContext> apns = dcac.getApnListSync();
 
-            // filter out ApnContext with "Connected" state.
+            // filter out ApnContext with "Connected/Connecting" state.
             ArrayList<ApnContext> connectedApns = new ArrayList<ApnContext>();
             for (ApnContext apnContext : apns) {
-                if (apnContext.getState() == State.CONNECTED) {
+                if (apnContext.getState() == State.CONNECTED ||
+                       apnContext.getState() == State.CONNECTING ||
+                       apnContext.getState() == State.INITING) {
                     connectedApns.add(apnContext);
                 }
             }