Merge "Fix a variable name reference in Activity docs."
diff --git a/Android.mk b/Android.mk
index 35ee3fd..95f38c5 100644
--- a/Android.mk
+++ b/Android.mk
@@ -120,6 +120,7 @@
 	core/java/android/os/IMessenger.aidl \
 	core/java/android/os/storage/IMountService.aidl \
 	core/java/android/os/storage/IMountServiceListener.aidl \
+	core/java/android/os/storage/IMountShutdownObserver.aidl \
 	core/java/android/os/INetworkManagementService.aidl \
 	core/java/android/os/INetStatService.aidl \
 	core/java/android/os/IPermissionController.aidl \
diff --git a/api/current.xml b/api/current.xml
index e273cd2..d792a41 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -5971,6 +5971,28 @@
  visibility="public"
 >
 </field>
+<field name="overscrollFooter"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="16843456"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="overscrollHeader"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="16843455"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="overscrollMode"
  type="int"
  transient="false"
@@ -44348,7 +44370,7 @@
  synchronized="false"
  static="false"
  final="false"
- deprecated="not deprecated"
+ deprecated="deprecated"
  visibility="public"
 >
 <parameter name="filter" type="android.content.IntentFilter">
@@ -45243,6 +45265,17 @@
  visibility="public"
 >
 </field>
+<field name="FEATURE_BLUETOOTH"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.bluetooth&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="FEATURE_CAMERA"
  type="java.lang.String"
  transient="false"
@@ -45287,6 +45320,72 @@
  visibility="public"
 >
 </field>
+<field name="FEATURE_LOCATION"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.location&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_LOCATION_GPS"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.location.gps&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_LOCATION_NETWORK"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.location.network&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_MICROPHONE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.microphone&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_SENSOR_ACCELEROMETER"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.sensor.accelerometer&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_SENSOR_COMPASS"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.hardware.sensor.compass&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
 <field name="FEATURE_SENSOR_LIGHT"
  type="java.lang.String"
  transient="false"
@@ -45364,61 +45463,6 @@
  visibility="public"
 >
 </field>
-<field name="FEATURE_BLUETOOTH"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.bluetooth&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="FEATURE_LOCATION"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.location&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="FEATURE_LOCATION_GPS"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.location.gps&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="FEATURE_LOCATION_NETWORK"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.location.network&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="FEATURE_MICROPHONE"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.microphone&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
 <field name="FEATURE_WIFI"
  type="java.lang.String"
  transient="false"
@@ -45430,28 +45474,6 @@
  visibility="public"
 >
 </field>
-<field name="FEATURE_SENSOR_ACCELEROMETER"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.sensor.accelerometer&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="FEATURE_SENSOR_COMPASS"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value="&quot;android.hardware.sensor.compass&quot;"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
 <field name="GET_ACTIVITIES"
  type="int"
  transient="false"
@@ -71563,6 +71585,19 @@
  deprecated="not deprecated"
  visibility="public"
 >
+<method name="addCallbackBuffer"
+ return="void"
+ abstract="false"
+ native="true"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callbackBuffer" type="byte[]">
+</parameter>
+</method>
 <method name="autoFocus"
  return="void"
  abstract="false"
@@ -71709,6 +71744,19 @@
 <parameter name="cb" type="android.hardware.Camera.PreviewCallback">
 </parameter>
 </method>
+<method name="setPreviewCallbackWithBuffer"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="cb" type="android.hardware.Camera.PreviewCallback">
+</parameter>
+</method>
 <method name="setPreviewDisplay"
  return="void"
  abstract="false"
@@ -174575,6 +174623,19 @@
  visibility="public"
 >
 </method>
+<method name="getXVelocity"
+ return="float"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="id" type="int">
+</parameter>
+</method>
 <method name="getYVelocity"
  return="float"
  abstract="false"
@@ -174586,6 +174647,19 @@
  visibility="public"
 >
 </method>
+<method name="getYVelocity"
+ return="float"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="id" type="int">
+</parameter>
+</method>
 <method name="obtain"
  return="android.view.VelocityTracker"
  abstract="false"
@@ -179364,6 +179438,17 @@
  visibility="public"
 >
 </method>
+<method name="getScaledPagingTouchSlop"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="getScaledScrollBarSize"
  return="int"
  abstract="false"
@@ -193424,6 +193509,17 @@
  visibility="public"
 >
 </method>
+<method name="getUseSystemOverscrollBackground"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="getUseWideViewPort"
  return="boolean"
  abstract="false"
@@ -194003,6 +194099,19 @@
 <parameter name="use" type="boolean">
 </parameter>
 </method>
+<method name="setUseSystemOverscrollBackground"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="system" type="boolean">
+</parameter>
+</method>
 <method name="setUseWideViewPort"
  return="void"
  abstract="false"
@@ -204470,6 +204579,28 @@
  visibility="public"
 >
 </method>
+<method name="getOverscrollFooter"
+ return="android.graphics.drawable.Drawable"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getOverscrollHeader"
+ return="android.graphics.drawable.Drawable"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="isItemChecked"
  return="boolean"
  abstract="false"
@@ -204615,6 +204746,32 @@
 <parameter name="itemsCanFocus" type="boolean">
 </parameter>
 </method>
+<method name="setOverscrollFooter"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="footer" type="android.graphics.drawable.Drawable">
+</parameter>
+</method>
+<method name="setOverscrollHeader"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="header" type="android.graphics.drawable.Drawable">
+</parameter>
+</method>
 <method name="setSelection"
  return="void"
  abstract="false"
diff --git a/cmds/installd/commands.c b/cmds/installd/commands.c
index c8d1397..654ee68 100644
--- a/cmds/installd/commands.c
+++ b/cmds/installd/commands.c
@@ -404,6 +404,15 @@
         }
     }
 
+        /* count the source apk as code -- but only if it's not
+         * installed on the sdcard
+         */
+    if (strncmp(apkpath, SDCARD_DIR_PREFIX, 7) != 0) {
+        if (stat(apkpath, &s) == 0) {
+            codesize += stat_size(&s);
+        }
+    }
+
 
         /* count the cached dexfile as code */
     if (!create_cache_path(path, apkpath)) {
diff --git a/cmds/servicemanager/Android.mk b/cmds/servicemanager/Android.mk
index 25266a2..fe5929b 100644
--- a/cmds/servicemanager/Android.mk
+++ b/cmds/servicemanager/Android.mk
@@ -10,5 +10,8 @@
 LOCAL_SHARED_LIBRARIES := liblog
 LOCAL_SRC_FILES := service_manager.c binder.c
 LOCAL_MODULE := servicemanager
+ifeq ($(BOARD_USE_LVMX),true)
+    LOCAL_CFLAGS += -DLVMX
+endif
 include $(BUILD_EXECUTABLE)
 endif
diff --git a/cmds/servicemanager/service_manager.c b/cmds/servicemanager/service_manager.c
index f3a4713..a2006c1 100644
--- a/cmds/servicemanager/service_manager.c
+++ b/cmds/servicemanager/service_manager.c
@@ -27,6 +27,9 @@
     unsigned uid;
     const char *name;
 } allowed[] = {
+#ifdef LVMX
+    { AID_MEDIA, "com.lifevibes.mx.ipc" },
+#endif
     { AID_MEDIA, "media.audio_flinger" },
     { AID_MEDIA, "media.player" },
     { AID_MEDIA, "media.camera" },
diff --git a/cmds/stagefright/stagefright.cpp b/cmds/stagefright/stagefright.cpp
index 942a303..5e2c61e 100644
--- a/cmds/stagefright/stagefright.cpp
+++ b/cmds/stagefright/stagefright.cpp
@@ -232,7 +232,7 @@
     fprintf(stderr, "       -m max-number-of-frames-to-decode in each pass\n");
     fprintf(stderr, "       -b bug to reproduce\n");
     fprintf(stderr, "       -p(rofiles) dump decoder profiles supported\n");
-    fprintf(stderr, "       -t(humbnail) extract video thumbnail\n");
+    fprintf(stderr, "       -t(humbnail) extract video thumbnail or album art\n");
     fprintf(stderr, "       -s(oftware) prefer software codec\n");
 }
 
@@ -334,12 +334,24 @@
             const char *filename = argv[k];
 
             CHECK_EQ(retriever->setDataSource(filename), OK);
-            CHECK_EQ(retriever->setMode(METADATA_MODE_FRAME_CAPTURE_ONLY), OK);
+            CHECK_EQ(retriever->setMode(
+                        METADATA_MODE_FRAME_CAPTURE_AND_METADATA_RETRIEVAL),
+                     OK);
 
             sp<IMemory> mem = retriever->captureFrame();
 
-            printf("captureFrame(%s) => %s\n",
-                   filename, mem != NULL ? "OK" : "FAILED");
+            if (mem != NULL) {
+                printf("captureFrame(%s) => OK\n", filename);
+            } else {
+                mem = retriever->extractAlbumArt();
+
+                if (mem != NULL) {
+                    printf("extractAlbumArt(%s) => OK\n", filename);
+                } else {
+                    printf("both captureFrame and extractAlbumArt "
+                           "failed on file '%s'.\n", filename);
+                }
+            }
         }
 
         return 0;
diff --git a/core/java/android/accounts/AccountManagerService.java b/core/java/android/accounts/AccountManagerService.java
index 2aaf5b0..6d0a266 100644
--- a/core/java/android/accounts/AccountManagerService.java
+++ b/core/java/android/accounts/AccountManagerService.java
@@ -1071,8 +1071,20 @@
                 return;
             }
 
+            final IAccountAuthenticator accountAuthenticator = mAuthenticator;
+            if (accountAuthenticator == null) {
+                // It is possible that the authenticator has died, which is indicated by
+                // mAuthenticator being set to null. If this happens then just abort.
+                // There is no need to send back a result or error in this case since
+                // that already happened when mAuthenticator was cleared.
+                if (Log.isLoggable(TAG, Log.VERBOSE)) {
+                    Log.v(TAG, "checkAccount: aborting session since we are no longer"
+                            + " connected to the authenticator, " + toDebugString());
+                }
+                return;
+            }
             try {
-                mAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
+                accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
             } catch (RemoteException e) {
                 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
             }
diff --git a/core/java/android/app/SearchDialog.java b/core/java/android/app/SearchDialog.java
index 3e426f5..bf9b021 100644
--- a/core/java/android/app/SearchDialog.java
+++ b/core/java/android/app/SearchDialog.java
@@ -668,7 +668,10 @@
                 // The user changed the query, remember it.
                 mUserQuery = s == null ? "" : s.toString();
             }
-            updateVoiceButton(mSearchAutoComplete.isEmpty());
+            // Always want to show the microphone if the context is voice.
+            updateVoiceButton(mSearchAutoComplete.isEmpty()
+                    || (mAppSearchData != null && mAppSearchData.getBoolean(
+                    SearchManager.CONTEXT_IS_VOICE)));
         }
 
         public void afterTextChanged(Editable s) {
diff --git a/core/java/android/app/SearchManager.java b/core/java/android/app/SearchManager.java
index 0ed572a..625b120 100644
--- a/core/java/android/app/SearchManager.java
+++ b/core/java/android/app/SearchManager.java
@@ -1544,6 +1544,15 @@
     public final static String INTENT_ACTION_NONE = "android.search.action.ZILCH";
 
     /**
+     * This means that context is voice, and therefore the SearchDialog should
+     * continue showing the microphone until the user indicates that he/she does
+     * not want to re-speak (e.g. by typing).
+     *
+     * @hide
+     */
+    public final static String CONTEXT_IS_VOICE = "android.search.CONTEXT_IS_VOICE";
+
+    /**
      * Reference to the shared system search service.
      */
     private static ISearchManager mService;
diff --git a/core/java/android/content/ContentProviderNative.java b/core/java/android/content/ContentProviderNative.java
index de52e65..fdb3d20 100644
--- a/core/java/android/content/ContentProviderNative.java
+++ b/core/java/android/content/ContentProviderNative.java
@@ -73,7 +73,10 @@
                 case QUERY_TRANSACTION:
                 {
                     data.enforceInterface(IContentProvider.descriptor);
+
                     Uri url = Uri.CREATOR.createFromParcel(data);
+
+                    // String[] projection
                     int num = data.readInt();
                     String[] projection = null;
                     if (num > 0) {
@@ -82,6 +85,8 @@
                             projection[i] = data.readString();
                         }
                     }
+
+                    // String selection, String[] selectionArgs...
                     String selection = data.readString();
                     num = data.readInt();
                     String[] selectionArgs = null;
@@ -91,19 +96,33 @@
                             selectionArgs[i] = data.readString();
                         }
                     }
+
                     String sortOrder = data.readString();
                     IContentObserver observer = IContentObserver.Stub.
                         asInterface(data.readStrongBinder());
                     CursorWindow window = CursorWindow.CREATOR.createFromParcel(data);
 
+                    // Flag for whether caller wants the number of
+                    // rows in the cursor and the position of the
+                    // "_id" column index (or -1 if non-existent)
+                    // Only to be returned if binder != null.
+                    boolean wantsCursorMetadata = data.readInt() != 0;
+
                     IBulkCursor bulkCursor = bulkQuery(url, projection, selection,
                             selectionArgs, sortOrder, observer, window);
                     reply.writeNoException();
                     if (bulkCursor != null) {
                         reply.writeStrongBinder(bulkCursor.asBinder());
+
+                        if (wantsCursorMetadata) {
+                            reply.writeInt(bulkCursor.count());
+                            reply.writeInt(BulkCursorToCursorAdaptor.findRowIdColumnIndex(
+                                bulkCursor.getColumnNames()));
+                        }
                     } else {
                         reply.writeStrongBinder(null);
                     }
+
                     return true;
                 }
 
@@ -266,9 +285,12 @@
         return mRemote;
     }
 
-    public IBulkCursor bulkQuery(Uri url, String[] projection,
-            String selection, String[] selectionArgs, String sortOrder, IContentObserver observer,
-            CursorWindow window) throws RemoteException {
+    // Like bulkQuery() but sets up provided 'adaptor' if not null.
+    private IBulkCursor bulkQueryInternal(
+        Uri url, String[] projection,
+        String selection, String[] selectionArgs, String sortOrder,
+        IContentObserver observer, CursorWindow window,
+        BulkCursorToCursorAdaptor adaptor) throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
 
@@ -297,6 +319,12 @@
         data.writeStrongBinder(observer.asBinder());
         window.writeToParcel(data, 0);
 
+        // Flag for whether or not we want the number of rows in the
+        // cursor and the position of the "_id" column index (or -1 if
+        // non-existent).  Only to be returned if binder != null.
+        final boolean wantsCursorMetadata = (adaptor != null);
+        data.writeInt(wantsCursorMetadata ? 1 : 0);
+
         mRemote.transact(IContentProvider.QUERY_TRANSACTION, data, reply, 0);
 
         DatabaseUtils.readExceptionFromParcel(reply);
@@ -305,26 +333,43 @@
         IBinder bulkCursorBinder = reply.readStrongBinder();
         if (bulkCursorBinder != null) {
             bulkCursor = BulkCursorNative.asInterface(bulkCursorBinder);
+
+            if (wantsCursorMetadata) {
+                int rowCount = reply.readInt();
+                int idColumnPosition = reply.readInt();
+                if (bulkCursor != null) {
+                    adaptor.set(bulkCursor, rowCount, idColumnPosition);
+                }
+            }
         }
-        
+
         data.recycle();
         reply.recycle();
-        
+
         return bulkCursor;
     }
 
+    public IBulkCursor bulkQuery(Uri url, String[] projection,
+            String selection, String[] selectionArgs, String sortOrder, IContentObserver observer,
+            CursorWindow window) throws RemoteException {
+        return bulkQueryInternal(
+            url, projection, selection, selectionArgs, sortOrder,
+            observer, window,
+            null /* BulkCursorToCursorAdaptor */);
+    }
+
     public Cursor query(Uri url, String[] projection, String selection,
             String[] selectionArgs, String sortOrder) throws RemoteException {
         //TODO make a pool of windows so we can reuse memory dealers
         CursorWindow window = new CursorWindow(false /* window will be used remotely */);
         BulkCursorToCursorAdaptor adaptor = new BulkCursorToCursorAdaptor();
-        IBulkCursor bulkCursor = bulkQuery(url, projection, selection, selectionArgs, sortOrder,
-                adaptor.getObserver(), window);
-
+        IBulkCursor bulkCursor = bulkQueryInternal(
+            url, projection, selection, selectionArgs, sortOrder,
+            adaptor.getObserver(), window,
+            adaptor);
         if (bulkCursor == null) {
             return null;
         }
-        adaptor.set(bulkCursor);
         return adaptor;
     }
 
diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java
index bcef75e..d3cc4df 100644
--- a/core/java/android/content/ContentResolver.java
+++ b/core/java/android/content/ContentResolver.java
@@ -689,7 +689,7 @@
      * @param uri The URI to modify.
      * @param values The new field values. The key is the column name for the field.
                      A null value will remove an existing field value.
-     * @param where A filter to apply to rows before deleting, formatted as an SQL WHERE clause
+     * @param where A filter to apply to rows before updating, formatted as an SQL WHERE clause
                     (excluding the WHERE itself).
      * @return The number of rows updated.
      * @throws NullPointerException if uri or values are null
diff --git a/core/java/android/content/SyncManager.java b/core/java/android/content/SyncManager.java
index 211a2ae..85769a6 100644
--- a/core/java/android/content/SyncManager.java
+++ b/core/java/android/content/SyncManager.java
@@ -124,6 +124,8 @@
      */
     private static final long ERROR_NOTIFICATION_DELAY_MS = 1000 * 60 * 10; // 10 minutes
 
+    private static final int INITIALIZATION_UNBIND_DELAY_MS = 5000;
+
     private static final String SYNC_WAKE_LOCK = "SyncManagerSyncWakeLock";
     private static final String HANDLE_SYNC_ALARM_WAKE_LOCK = "SyncManagerHandleSyncAlarmWakeLock";
 
@@ -283,6 +285,7 @@
 
     private static final String ACTION_SYNC_ALARM = "android.content.syncmanager.SYNC_ALARM";
     private final SyncHandler mSyncHandler;
+    private final Handler mMainHandler;
 
     private volatile boolean mBootCompleted = false;
 
@@ -309,6 +312,7 @@
                 Process.THREAD_PRIORITY_BACKGROUND);
         syncThread.start();
         mSyncHandler = new SyncHandler(syncThread.getLooper());
+        mMainHandler = new Handler(mContext.getMainLooper());
 
         mSyncAdapters = new SyncAdaptersCache(mContext);
         mSyncAdapters.setListener(new RegisteredServicesCacheListener<SyncAdapterType>() {
@@ -423,32 +427,56 @@
         Intent intent = new Intent();
         intent.setAction("android.content.SyncAdapter");
         intent.setComponent(syncAdapterInfo.componentName);
-        mContext.bindService(intent, new InitializerServiceConnection(account, authority),
+        mContext.bindService(intent, new InitializerServiceConnection(account, authority, mContext,
+                mMainHandler),
                 Context.BIND_AUTO_CREATE | Context.BIND_NOT_FOREGROUND);
     }
 
-    private class InitializerServiceConnection implements ServiceConnection {
+    private static class InitializerServiceConnection implements ServiceConnection {
         private final Account mAccount;
         private final String mAuthority;
+        private final Handler mHandler;
+        private volatile Context mContext;
+        private volatile boolean mInitialized;
 
-        public InitializerServiceConnection(Account account, String authority) {
+        public InitializerServiceConnection(Account account, String authority, Context context,
+                Handler handler) {
             mAccount = account;
             mAuthority = authority;
+            mContext = context;
+            mHandler = handler;
+            mInitialized = false;
         }
 
         public void onServiceConnected(ComponentName name, IBinder service) {
             try {
-                ISyncAdapter.Stub.asInterface(service).initialize(mAccount, mAuthority);
+                if (!mInitialized) {
+                    mInitialized = true;
+                    ISyncAdapter.Stub.asInterface(service).initialize(mAccount, mAuthority);
+                }
             } catch (RemoteException e) {
                 // doesn't matter, we will retry again later
             } finally {
-                mContext.unbindService(this);
+                // give the sync adapter time to initialize before unbinding from it
+                // TODO: change this API to not rely on this timing, http://b/2500805
+                mHandler.postDelayed(new Runnable() {
+                    public void run() {
+                        if (mContext != null) {
+                            mContext.unbindService(InitializerServiceConnection.this);
+                            mContext = null;
+                        }
+                    }
+                }, INITIALIZATION_UNBIND_DELAY_MS);
             }
         }
 
         public void onServiceDisconnected(ComponentName name) {
-            mContext.unbindService(this);
+            if (mContext != null) {
+                mContext.unbindService(InitializerServiceConnection.this);
+                mContext = null;
+            }
         }
+
     }
 
     /**
@@ -841,6 +869,7 @@
         ISyncAdapter mSyncAdapter;
         final long mStartTime;
         long mTimeoutStartTime;
+        boolean mBound;
 
         public ActiveSyncContext(SyncOperation syncOperation,
                 long historyRowId) {
@@ -895,15 +924,23 @@
                     com.android.internal.R.string.sync_binding_label);
             intent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
                     mContext, 0, new Intent(Settings.ACTION_SYNC_SETTINGS), 0));
-            return mContext.bindService(intent, this,
+            mBound = true;
+            final boolean bindResult = mContext.bindService(intent, this,
                     Context.BIND_AUTO_CREATE | Context.BIND_NOT_FOREGROUND);
+            if (!bindResult) {
+                mBound = false;
+            }
+            return bindResult;
         }
 
-        void unBindFromSyncAdapter() {
+        protected void close() {
             if (Log.isLoggable(TAG, Log.VERBOSE)) {
                 Log.d(TAG, "unBindFromSyncAdapter: connection " + this);
             }
-            mContext.unbindService(this);
+            if (mBound) {
+                mBound = false;
+                mContext.unbindService(this);
+            }
         }
 
         @Override
@@ -1580,6 +1617,7 @@
             mSyncStorageEngine.setActiveSync(mActiveSyncContext);
             if (!activeSyncContext.bindToSyncAdapter(syncAdapterInfo)) {
                 Log.e(TAG, "Bind attempt failed to " + syncAdapterInfo);
+                mActiveSyncContext.close();
                 mActiveSyncContext = null;
                 mSyncStorageEngine.setActiveSync(mActiveSyncContext);
                 runStateIdle();
@@ -1669,13 +1707,13 @@
                         syncOperation.account, syncOperation.extras);
             } catch (RemoteException remoteExc) {
                 Log.d(TAG, "runStateIdle: caught a RemoteException, rescheduling", remoteExc);
-                mActiveSyncContext.unBindFromSyncAdapter();
+                mActiveSyncContext.close();
                 mActiveSyncContext = null;
                 mSyncStorageEngine.setActiveSync(mActiveSyncContext);
                 increaseBackoffSetting(syncOperation);
                 scheduleSyncOperation(new SyncOperation(syncOperation));
             } catch (RuntimeException exc) {
-                mActiveSyncContext.unBindFromSyncAdapter();
+                mActiveSyncContext.close();
                 mActiveSyncContext = null;
                 mSyncStorageEngine.setActiveSync(mActiveSyncContext);
                 Log.e(TAG, "Caught RuntimeException while starting the sync " + syncOperation, exc);
@@ -1741,7 +1779,7 @@
             stopSyncEvent(activeSyncContext.mHistoryRowId, syncOperation, historyMessage,
                     upstreamActivity, downstreamActivity, elapsedTime);
 
-            activeSyncContext.unBindFromSyncAdapter();
+            activeSyncContext.close();
 
             if (syncResult != null && syncResult.tooManyDeletions) {
                 installHandleTooManyDeletesNotification(syncOperation.account,
diff --git a/core/java/android/content/pm/ApplicationInfo.java b/core/java/android/content/pm/ApplicationInfo.java
index 8773f59..423f4bc 100644
--- a/core/java/android/content/pm/ApplicationInfo.java
+++ b/core/java/android/content/pm/ApplicationInfo.java
@@ -237,7 +237,7 @@
      *
      * {@hide}
      */
-    public static final int FLAG_ON_SDCARD = 1<<20;
+    public static final int FLAG_EXTERNAL_STORAGE = 1<<20;
 
     /**
      * Value for {@link #flags}: Set to true if the application is
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index efd7bbc..271f477 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -1896,6 +1896,10 @@
     public abstract List<PackageInfo> getPreferredPackages(int flags);
 
     /**
+     * @deprecated This is a protected API that should not have been available
+     * to third party applications.  It is the platform's responsibility for
+     * assigning preferred activities and this can not be directly modified.
+     * 
      * Add a new preferred activity mapping to the system.  This will be used
      * to automatically select the given activity component when
      * {@link Context#startActivity(Intent) Context.startActivity()} finds
@@ -1910,10 +1914,15 @@
      * @param activity The component name of the activity that is to be
      * preferred.
      */
+    @Deprecated
     public abstract void addPreferredActivity(IntentFilter filter, int match,
             ComponentName[] set, ComponentName activity);
 
     /**
+     * @deprecated This is a protected API that should not have been available
+     * to third party applications.  It is the platform's responsibility for
+     * assigning preferred activities and this can not be directly modified.
+     * 
      * Replaces an existing preferred activity mapping to the system, and if that were not present
      * adds a new preferred activity.  This will be used
      * to automatically select the given activity component when
@@ -1930,6 +1939,7 @@
      * preferred.
      * @hide
      */
+    @Deprecated
     public abstract void replacePreferredActivity(IntentFilter filter, int match,
             ComponentName[] set, ComponentName activity);
 
@@ -1937,6 +1947,7 @@
      * Remove all preferred activity mappings, previously added with
      * {@link #addPreferredActivity}, from the
      * system whose activities are implemented in the given package name.
+     * An application can only clear its own package(s).
      *
      * @param packageName The name of the package whose preferred activity
      * mappings are to be removed.
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 5da7fd1..9736b01 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -755,14 +755,14 @@
                 com.android.internal.R.styleable.AndroidManifest);
         pkg.mVersionCode = sa.getInteger(
                 com.android.internal.R.styleable.AndroidManifest_versionCode, 0);
-        pkg.mVersionName = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifest_versionName);
+        pkg.mVersionName = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifest_versionName, 0);
         if (pkg.mVersionName != null) {
             pkg.mVersionName = pkg.mVersionName.intern();
         }
-        String str = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifest_sharedUserId);
-        if (str != null) {
+        String str = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifest_sharedUserId, 0);
+        if (str != null && str.length() > 0) {
             String nameError = validateName(str, true);
             if (nameError != null && !"android".equals(pkgName)) {
                 outError[0] = "<manifest> specifies bad sharedUserId name \""
@@ -828,6 +828,8 @@
                 sa = res.obtainAttributes(attrs,
                         com.android.internal.R.styleable.AndroidManifestUsesPermission);
 
+                // Note: don't allow this value to be a reference to a resource
+                // that may change.
                 String name = sa.getNonResourceString(
                         com.android.internal.R.styleable.AndroidManifestUsesPermission_name);
 
@@ -871,6 +873,8 @@
                 FeatureInfo fi = new FeatureInfo();
                 sa = res.obtainAttributes(attrs,
                         com.android.internal.R.styleable.AndroidManifestUsesFeature);
+                // Note: don't allow this value to be a reference to a resource
+                // that may change.
                 fi.name = sa.getNonResourceString(
                         com.android.internal.R.styleable.AndroidManifestUsesFeature_name);
                 if (fi.name == null) {
@@ -1002,6 +1006,8 @@
                 sa = res.obtainAttributes(attrs,
                         com.android.internal.R.styleable.AndroidManifestProtectedBroadcast);
 
+                // Note: don't allow this value to be a reference to a resource
+                // that may change.
                 String name = sa.getNonResourceString(
                         com.android.internal.R.styleable.AndroidManifestProtectedBroadcast_name);
 
@@ -1027,8 +1033,8 @@
                 sa = res.obtainAttributes(attrs,
                         com.android.internal.R.styleable.AndroidManifestOriginalPackage);
 
-                String orig =sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestOriginalPackage_name);
+                String orig =sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestOriginalPackage_name, 0);
                 if (!pkg.packageName.equals(orig)) {
                     if (pkg.mOriginalPackages == null) {
                         pkg.mOriginalPackages = new ArrayList<String>();
@@ -1045,8 +1051,8 @@
                 sa = res.obtainAttributes(attrs,
                         com.android.internal.R.styleable.AndroidManifestOriginalPackage);
 
-                String name = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestOriginalPackage_name);
+                String name = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestOriginalPackage_name, 0);
 
                 sa.recycle();
 
@@ -1271,6 +1277,8 @@
             return null;
         }
 
+        // Note: don't allow this value to be a reference to a resource
+        // that may change.
         perm.info.group = sa.getNonResourceString(
                 com.android.internal.R.styleable.AndroidManifestPermission_permissionGroup);
         if (perm.info.group != null) {
@@ -1375,6 +1383,8 @@
         }
 
         String str;
+        // Note: don't allow this value to be a reference to a resource
+        // that may change.
         str = sa.getNonResourceString(
                 com.android.internal.R.styleable.AndroidManifestInstrumentation_targetPackage);
         a.info.targetPackage = str != null ? str.intern() : null;
@@ -1415,8 +1425,8 @@
         TypedArray sa = res.obtainAttributes(attrs,
                 com.android.internal.R.styleable.AndroidManifestApplication);
 
-        String name = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestApplication_name);
+        String name = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestApplication_name, 0);
         if (name != null) {
             ai.className = buildClassName(pkgName, name, outError);
             if (ai.className == null) {
@@ -1426,8 +1436,8 @@
             }
         }
 
-        String manageSpaceActivity = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestApplication_manageSpaceActivity);
+        String manageSpaceActivity = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestApplication_manageSpaceActivity, 0);
         if (manageSpaceActivity != null) {
             ai.manageSpaceActivityName = buildClassName(pkgName, manageSpaceActivity,
                     outError);
@@ -1440,8 +1450,8 @@
 
             // backupAgent, killAfterRestore, restoreNeedsApplication, and restoreAnyVersion
             // are only relevant if backup is possible for the given application.
-            String backupAgent = sa.getNonResourceString(
-                    com.android.internal.R.styleable.AndroidManifestApplication_backupAgent);
+            String backupAgent = sa.getNonConfigurationString(
+                    com.android.internal.R.styleable.AndroidManifestApplication_backupAgent, 0);
             if (backupAgent != null) {
                 ai.backupAgentName = buildClassName(pkgName, backupAgent, outError);
                 if (false) {
@@ -1493,7 +1503,7 @@
         }
 
         if ((flags & PARSE_ON_SDCARD) != 0) {
-            ai.flags |= ApplicationInfo.FLAG_ON_SDCARD;
+            ai.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
         }
 
         if (sa.getBoolean(
@@ -1539,21 +1549,22 @@
         }
 
         String str;
-        str = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestApplication_permission);
+        str = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestApplication_permission, 0);
         ai.permission = (str != null && str.length() > 0) ? str.intern() : null;
 
-        str = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestApplication_taskAffinity);
+        str = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestApplication_taskAffinity, 0);
         ai.taskAffinity = buildTaskAffinityName(ai.packageName, ai.packageName,
                 str, outError);
 
         if (outError[0] == null) {
-            ai.processName = buildProcessName(ai.packageName, null, sa.getNonResourceString(
-                    com.android.internal.R.styleable.AndroidManifestApplication_process),
+            ai.processName = buildProcessName(ai.packageName, null, sa.getNonConfigurationString(
+                    com.android.internal.R.styleable.AndroidManifestApplication_process, 0),
                     flags, mSeparateProcesses, outError);
     
-            ai.enabled = sa.getBoolean(com.android.internal.R.styleable.AndroidManifestApplication_enabled, true);
+            ai.enabled = sa.getBoolean(
+                    com.android.internal.R.styleable.AndroidManifestApplication_enabled, true);
         }
 
         sa.recycle();
@@ -1632,6 +1643,8 @@
                 sa = res.obtainAttributes(attrs,
                         com.android.internal.R.styleable.AndroidManifestUsesLibrary);
 
+                // Note: don't allow this value to be a reference to a resource
+                // that may change.
                 String lname = sa.getNonResourceString(
                         com.android.internal.R.styleable.AndroidManifestUsesLibrary_name);
                 boolean req = sa.getBoolean(
@@ -1681,7 +1694,7 @@
     private boolean parsePackageItemInfo(Package owner, PackageItemInfo outInfo,
             String[] outError, String tag, TypedArray sa,
             int nameRes, int labelRes, int iconRes) {
-        String name = sa.getNonResourceString(nameRes);
+        String name = sa.getNonConfigurationString(nameRes, 0);
         if (name == null) {
             outError[0] = tag + " does not specify android:name";
             return false;
@@ -1747,16 +1760,16 @@
                 com.android.internal.R.styleable.AndroidManifestActivity_theme, 0);
 
         String str;
-        str = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestActivity_permission);
+        str = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestActivity_permission, 0);
         if (str == null) {
             a.info.permission = owner.applicationInfo.permission;
         } else {
             a.info.permission = str.length() > 0 ? str.toString().intern() : null;
         }
 
-        str = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestActivity_taskAffinity);
+        str = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestActivity_taskAffinity, 0);
         a.info.taskAffinity = buildTaskAffinityName(owner.applicationInfo.packageName,
                 owner.applicationInfo.taskAffinity, str, outError);
 
@@ -1902,8 +1915,8 @@
         TypedArray sa = res.obtainAttributes(attrs,
                 com.android.internal.R.styleable.AndroidManifestActivityAlias);
 
-        String targetActivity = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestActivityAlias_targetActivity);
+        String targetActivity = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestActivityAlias_targetActivity, 0);
         if (targetActivity == null) {
             outError[0] = "<activity-alias> does not specify android:targetActivity";
             sa.recycle();
@@ -1980,8 +1993,8 @@
         }
 
         String str;
-        str = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestActivityAlias_permission);
+        str = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestActivityAlias_permission, 0);
         if (str != null) {
             a.info.permission = str.length() > 0 ? str.toString().intern() : null;
         }
@@ -2068,17 +2081,17 @@
         p.info.exported = sa.getBoolean(
                 com.android.internal.R.styleable.AndroidManifestProvider_exported, true);
 
-        String cpname = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestProvider_authorities);
+        String cpname = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestProvider_authorities, 0);
 
         p.info.isSyncable = sa.getBoolean(
                 com.android.internal.R.styleable.AndroidManifestProvider_syncable,
                 false);
 
-        String permission = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestProvider_permission);
-        String str = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestProvider_readPermission);
+        String permission = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestProvider_permission, 0);
+        String str = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestProvider_readPermission, 0);
         if (str == null) {
             str = permission;
         }
@@ -2088,8 +2101,8 @@
             p.info.readPermission =
                 str.length() > 0 ? str.toString().intern() : null;
         }
-        str = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestProvider_writePermission);
+        str = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestProvider_writePermission, 0);
         if (str == null) {
             str = permission;
         }
@@ -2152,20 +2165,20 @@
 
                 PatternMatcher pa = null;
 
-                String str = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_path);
+                String str = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_path, 0);
                 if (str != null) {
                     pa = new PatternMatcher(str, PatternMatcher.PATTERN_LITERAL);
                 }
 
-                str = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPrefix);
+                str = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPrefix, 0);
                 if (str != null) {
                     pa = new PatternMatcher(str, PatternMatcher.PATTERN_PREFIX);
                 }
 
-                str = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPattern);
+                str = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestGrantUriPermission_pathPattern, 0);
                 if (str != null) {
                     pa = new PatternMatcher(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
                 }
@@ -2203,15 +2216,15 @@
 
                 PathPermission pa = null;
 
-                String permission = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestPathPermission_permission);
-                String readPermission = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestPathPermission_readPermission);
+                String permission = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestPathPermission_permission, 0);
+                String readPermission = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestPathPermission_readPermission, 0);
                 if (readPermission == null) {
                     readPermission = permission;
                 }
-                String writePermission = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestPathPermission_writePermission);
+                String writePermission = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestPathPermission_writePermission, 0);
                 if (writePermission == null) {
                     writePermission = permission;
                 }
@@ -2238,22 +2251,22 @@
                     return false;
                 }
                 
-                String path = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestPathPermission_path);
+                String path = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestPathPermission_path, 0);
                 if (path != null) {
                     pa = new PathPermission(path,
                             PatternMatcher.PATTERN_LITERAL, readPermission, writePermission);
                 }
 
-                path = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPrefix);
+                path = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPrefix, 0);
                 if (path != null) {
                     pa = new PathPermission(path,
                             PatternMatcher.PATTERN_PREFIX, readPermission, writePermission);
                 }
 
-                path = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPattern);
+                path = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestPathPermission_pathPattern, 0);
                 if (path != null) {
                     pa = new PathPermission(path,
                             PatternMatcher.PATTERN_SIMPLE_GLOB, readPermission, writePermission);
@@ -2335,8 +2348,8 @@
                     com.android.internal.R.styleable.AndroidManifestService_exported, false);
         }
 
-        String str = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestService_permission);
+        String str = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestService_permission, 0);
         if (str == null) {
             s.info.permission = owner.applicationInfo.permission;
         } else {
@@ -2433,8 +2446,8 @@
             data = new Bundle();
         }
 
-        String name = sa.getNonResourceString(
-                com.android.internal.R.styleable.AndroidManifestMetaData_name);
+        String name = sa.getNonConfigurationString(
+                com.android.internal.R.styleable.AndroidManifestMetaData_name, 0);
         if (name == null) {
             outError[0] = "<meta-data> requires an android:name attribute";
             sa.recycle();
@@ -2552,8 +2565,8 @@
                 sa = res.obtainAttributes(attrs,
                         com.android.internal.R.styleable.AndroidManifestData);
 
-                String str = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestData_mimeType);
+                String str = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestData_mimeType, 0);
                 if (str != null) {
                     try {
                         outInfo.addDataType(str);
@@ -2564,34 +2577,34 @@
                     }
                 }
 
-                str = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestData_scheme);
+                str = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestData_scheme, 0);
                 if (str != null) {
                     outInfo.addDataScheme(str);
                 }
 
-                String host = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestData_host);
-                String port = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestData_port);
+                String host = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestData_host, 0);
+                String port = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestData_port, 0);
                 if (host != null) {
                     outInfo.addDataAuthority(host, port);
                 }
 
-                str = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestData_path);
+                str = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestData_path, 0);
                 if (str != null) {
                     outInfo.addDataPath(str, PatternMatcher.PATTERN_LITERAL);
                 }
 
-                str = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestData_pathPrefix);
+                str = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestData_pathPrefix, 0);
                 if (str != null) {
                     outInfo.addDataPath(str, PatternMatcher.PATTERN_PREFIX);
                 }
 
-                str = sa.getNonResourceString(
-                        com.android.internal.R.styleable.AndroidManifestData_pathPattern);
+                str = sa.getNonConfigurationString(
+                        com.android.internal.R.styleable.AndroidManifestData_pathPattern, 0);
                 if (str != null) {
                     outInfo.addDataPath(str, PatternMatcher.PATTERN_SIMPLE_GLOB);
                 }
@@ -2754,7 +2767,7 @@
         public Component(final ParsePackageItemArgs args, final PackageItemInfo outInfo) {
             owner = args.owner;
             intents = new ArrayList<II>(0);
-            String name = args.sa.getNonResourceString(args.nameRes);
+            String name = args.sa.getNonConfigurationString(args.nameRes, 0);
             if (name == null) {
                 className = null;
                 args.outError[0] = args.tag + " does not specify android:name";
@@ -2793,7 +2806,8 @@
 
             if (args.processRes != 0) {
                 outInfo.processName = buildProcessName(owner.applicationInfo.packageName,
-                        owner.applicationInfo.processName, args.sa.getNonResourceString(args.processRes),
+                        owner.applicationInfo.processName,
+                        args.sa.getNonConfigurationString(args.processRes, 0),
                         args.flags, args.sepProcesses, args.outError);
             }
             
diff --git a/core/java/android/content/res/TypedArray.java b/core/java/android/content/res/TypedArray.java
index a7fb31d..09fdf8d 100644
--- a/core/java/android/content/res/TypedArray.java
+++ b/core/java/android/content/res/TypedArray.java
@@ -148,6 +148,42 @@
     }
     
     /**
+     * @hide
+     * Retrieve the string value for the attribute at <var>index</var> that is
+     * not allowed to change with the given configurations.
+     * 
+     * @param index Index of attribute to retrieve.
+     * @param allowedChangingConfigs Bit mask of configurations from
+     * ActivityInfo that are allowed to change.
+     * 
+     * @return String holding string data.  Any styling information is
+     * removed.  Returns null if the attribute is not defined.
+     */
+    public String getNonConfigurationString(int index, int allowedChangingConfigs) {
+        index *= AssetManager.STYLE_NUM_ENTRIES;
+        final int[] data = mData;
+        final int type = data[index+AssetManager.STYLE_TYPE];
+        if ((data[index+AssetManager.STYLE_CHANGING_CONFIGURATIONS]&~allowedChangingConfigs) != 0) {
+            return null;
+        }
+        if (type == TypedValue.TYPE_NULL) {
+            return null;
+        } else if (type == TypedValue.TYPE_STRING) {
+            return loadStringValueAt(index).toString();
+        }
+
+        TypedValue v = mValue;
+        if (getValueAt(index, v)) {
+            Log.w(Resources.TAG, "Converting to string: " + v);
+            CharSequence cs = v.coerceToString();
+            return cs != null ? cs.toString() : null;
+        }
+        Log.w(Resources.TAG, "getString of bad type: 0x"
+              + Integer.toHexString(type));
+        return null;
+    }
+
+    /**
      * Retrieve the boolean value for the attribute at <var>index</var>.
      * 
      * @param index Index of attribute to retrieve.
diff --git a/core/java/android/database/BulkCursorToCursorAdaptor.java b/core/java/android/database/BulkCursorToCursorAdaptor.java
index cf30dd9..1469ea2 100644
--- a/core/java/android/database/BulkCursorToCursorAdaptor.java
+++ b/core/java/android/database/BulkCursorToCursorAdaptor.java
@@ -43,25 +43,43 @@
         try {
             mCount = mBulkCursor.count();
             mWantsAllOnMoveCalls = mBulkCursor.getWantsAllOnMoveCalls();
-    
+
             // Search for the rowID column index and set it for our parent
             mColumns = mBulkCursor.getColumnNames();
-            int length = mColumns.length;
-            for (int i = 0; i < length; i++) {
-                if (mColumns[i].equals("_id")) {
-                    mRowIdColumnIndex = i;
-                    break;
-                }
-            }
+            mRowIdColumnIndex = findRowIdColumnIndex(mColumns);
         } catch (RemoteException ex) {
             Log.e(TAG, "Setup failed because the remote process is dead");
         }
     }
 
     /**
+     * Version of set() that does fewer Binder calls if the caller
+     * already knows BulkCursorToCursorAdaptor's properties.
+     */
+    public void set(IBulkCursor bulkCursor, int count, int idIndex) {
+        mBulkCursor = bulkCursor;
+        mColumns = null;  // lazily retrieved
+        mCount = count;
+        mRowIdColumnIndex = idIndex;
+    }
+
+    /**
+     * Returns column index of "_id" column, or -1 if not found.
+     */
+    public static int findRowIdColumnIndex(String[] columnNames) {
+        int length = columnNames.length;
+        for (int i = 0; i < length; i++) {
+            if (columnNames[i].equals("_id")) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    /**
      * Gets a SelfDataChangeOberserver that can be sent to a remote
      * process to receive change notifications over IPC.
-     * 
+     *
      * @return A SelfContentObserver hooked up to this Cursor
      */
     public synchronized IContentObserver getObserver() {
@@ -190,6 +208,14 @@
 
     @Override
     public String[] getColumnNames() {
+        if (mColumns == null) {
+            try {
+                mColumns = mBulkCursor.getColumnNames();
+            } catch (RemoteException ex) {
+                Log.e(TAG, "Unable to fetch column names because the remote process is dead");
+                return null;
+            }
+        }
         return mColumns;
     }
 
@@ -255,4 +281,3 @@
         }
     }
 }
-
diff --git a/core/java/android/database/CursorWindow.java b/core/java/android/database/CursorWindow.java
index 99db81b..c756825 100644
--- a/core/java/android/database/CursorWindow.java
+++ b/core/java/android/database/CursorWindow.java
@@ -44,7 +44,7 @@
     /**
      * Returns the starting position of this window within the entire
      * Cursor's result set.
-     * 
+     *
      * @return the starting position of this window within the entire
      * Cursor's result set.
      */
diff --git a/core/java/android/database/IBulkCursor.java b/core/java/android/database/IBulkCursor.java
index 24354fd..46790a3 100644
--- a/core/java/android/database/IBulkCursor.java
+++ b/core/java/android/database/IBulkCursor.java
@@ -27,11 +27,10 @@
  * This interface provides a low-level way to pass bulk cursor data across
  * both process and language boundries. Application code should use the Cursor
  * interface directly.
- * 
+ *
  * {@hide}
  */
-public interface IBulkCursor extends IInterface 
-{
+public interface IBulkCursor extends IInterface  {
     /**
      * Returns a BulkCursorWindow, which either has a reference to a shared
      * memory segment with the rows, or an array of JSON strings.
@@ -60,7 +59,7 @@
     public boolean deleteRow(int position) throws RemoteException;
 
     public void deactivate() throws RemoteException;
-    
+
     public void close() throws RemoteException;
 
     public int requery(IContentObserver observer, CursorWindow window) throws RemoteException;
@@ -87,4 +86,3 @@
     static final int RESPOND_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 10;
     static final int CLOSE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION + 11;
 }
-
diff --git a/core/java/android/database/sqlite/SQLiteClosable.java b/core/java/android/database/sqlite/SQLiteClosable.java
index e589f34..71fa2c2 100644
--- a/core/java/android/database/sqlite/SQLiteClosable.java
+++ b/core/java/android/database/sqlite/SQLiteClosable.java
@@ -19,14 +19,15 @@
 import android.database.CursorWindow;
 
 /**
- * An object create from a SQLiteDatabase that can be closed.
+ * An object created from a SQLiteDatabase that can be closed.
  */
-public abstract class SQLiteClosable {    
+public abstract class SQLiteClosable {
     private int mReferenceCount = 1;
     private Object mLock = new Object();
+
     protected abstract void onAllReferencesReleased();
-    protected void onAllReferencesReleasedFromContainer(){}
-    
+    protected void onAllReferencesReleasedFromContainer() {}
+
     public void acquireReference() {
         synchronized(mLock) {
             if (mReferenceCount <= 0) {
@@ -36,7 +37,7 @@
             mReferenceCount++;
         }
     }
-    
+
     public void releaseReference() {
         synchronized(mLock) {
             mReferenceCount--;
@@ -45,14 +46,14 @@
             }
         }
     }
-    
+
     public void releaseReferenceFromContainer() {
         synchronized(mLock) {
             mReferenceCount--;
             if (mReferenceCount == 0) {
                 onAllReferencesReleasedFromContainer();
             }
-        }        
+        }
     }
 
     private String getObjInfo() {
diff --git a/core/java/android/database/sqlite/SQLiteCompiledSql.java b/core/java/android/database/sqlite/SQLiteCompiledSql.java
index 4ccf6b0..18cc1d5 100644
--- a/core/java/android/database/sqlite/SQLiteCompiledSql.java
+++ b/core/java/android/database/sqlite/SQLiteCompiledSql.java
@@ -23,8 +23,8 @@
  * Once a sql statement is compiled, it is cached in {@link SQLiteDatabase}
  * and it is released in one of the 2 following ways
  * 1. when {@link SQLiteDatabase} object is closed.
- * 2. dalvikVM wants to reclaim some memory and releases it from the cache in
- * {@link SQLiteDatabase}.
+ * 2. if this is not cached in {@link SQLiteDatabase}, {@link android.database.Cursor#close()}
+ * releaases this obj.
  */
 /* package */ class SQLiteCompiledSql {
 
@@ -127,7 +127,7 @@
         try {
             if (nStatement == 0) return;
             // finalizer should NEVER get called
-            Log.w(TAG, "finalizer should never be called. sql: " + mSqlStmt, mStackTrace);
+            Log.w(TAG, "finalizer should never be called on sql: " + mSqlStmt, mStackTrace);
             releaseSqlStatement();
         } finally {
             super.finalize();
diff --git a/core/java/android/database/sqlite/SQLiteProgram.java b/core/java/android/database/sqlite/SQLiteProgram.java
index 6636473..5b4516d 100644
--- a/core/java/android/database/sqlite/SQLiteProgram.java
+++ b/core/java/android/database/sqlite/SQLiteProgram.java
@@ -61,6 +61,7 @@
         // only cache CRUD statements
         String prefixSql = mSql.substring(0, 6);
         if (!prefixSql.equalsIgnoreCase("INSERT") && !prefixSql.equalsIgnoreCase("UPDATE") &&
+                !prefixSql.equalsIgnoreCase("REPLAC") &&
                 !prefixSql.equalsIgnoreCase("DELETE") && !prefixSql.equalsIgnoreCase("SELECT")) {
             mCompiledSql = new SQLiteCompiledSql(db, sql);
             nStatement = mCompiledSql.nStatement;
diff --git a/core/java/android/hardware/Camera.java b/core/java/android/hardware/Camera.java
index 85d52ec..3484d55 100644
--- a/core/java/android/hardware/Camera.java
+++ b/core/java/android/hardware/Camera.java
@@ -261,7 +261,6 @@
      * setPreviewCallback, or to this method with a null callback parameter.
      *
      * @param cb A callback object that receives a copy of the preview frame.  A null value will clear the queue.
-     * @hide
      */
     public final void setPreviewCallbackWithBuffer(PreviewCallback cb) {
         mPreviewCallback = cb;
@@ -271,16 +270,22 @@
     }
 
     /**
-     * Adds a pre-allocated buffer to the callback buffer queue.
+     * Adds a pre-allocated buffer to the callback buffer queue. Applications
+     * can add one or more buffers to the queue. When a preview frame arrives
+     * and there is still available buffer, buffer will be filled and it is
+     * removed from the queue. Then preview callback is invoked with the buffer.
+     * If a frame arrives and there is no buffer left, the frame is discarded.
+     * Applications should add the buffers back when they finish the processing.
+     *
      * Preview width and height can be determined from getPreviewSize, and bitsPerPixel can be
-     * found from from  {@link android.hardware.Camera.Parameters#getPreviewFormat()} and
-     * {@link android.graphics.ImageFormat#getBitsPerPixel(int)}
+     * found from {@link android.hardware.Camera.Parameters#getPreviewFormat()}
+     * and {@link android.graphics.ImageFormat#getBitsPerPixel(int)}.
      *
      * Alternatively, a buffer from a previous callback may be passed in or used
      * to determine the size of new preview frame buffers.
      *
      * @param callbackBuffer The buffer to register. Size should be width * height * bitsPerPixel / 8.
-     * @hide
+     * @see #setPreviewCallbackWithBuffer(PreviewCallback)
      */
     public native final void addCallbackBuffer(byte[] callbackBuffer);
 
diff --git a/core/java/android/net/MobileDataStateTracker.java b/core/java/android/net/MobileDataStateTracker.java
index b59e279..17b0330 100644
--- a/core/java/android/net/MobileDataStateTracker.java
+++ b/core/java/android/net/MobileDataStateTracker.java
@@ -346,7 +346,7 @@
                         ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
                 intent.putExtra(Phone.STATE_KEY, Phone.DataState.CONNECTED.toString());
                 intent.putExtra(Phone.STATE_CHANGE_REASON_KEY, Phone.REASON_APN_CHANGED);
-                intent.putExtra(Phone.DATA_APN_TYPES_KEY, mApnType);
+                intent.putExtra(Phone.DATA_APN_TYPES_KEY, mApnTypeToWatchFor);
                 intent.putExtra(Phone.DATA_APN_KEY, mApnName);
                 intent.putExtra(Phone.DATA_IFACE_NAME_KEY, mInterfaceName);
                 intent.putExtra(Phone.NETWORK_UNAVAILABLE_KEY, false);
diff --git a/core/java/android/os/Power.java b/core/java/android/os/Power.java
index b3df522..5a79215 100644
--- a/core/java/android/os/Power.java
+++ b/core/java/android/os/Power.java
@@ -18,7 +18,6 @@
 
 import java.io.IOException;
 import android.os.ServiceManager;
-import android.os.storage.IMountService;
 
 /**
  * Class that provides access to some of the power management functions.
@@ -101,15 +100,6 @@
      */
     public static void reboot(String reason) throws IOException
     {
-        IMountService mSvc = IMountService.Stub.asInterface(
-                ServiceManager.getService("mount"));
-
-        if (mSvc != null) {
-            try {
-                mSvc.shutdown();
-            } catch (Exception e) {
-            }
-        }
         rebootNative(reason);
     }
 
diff --git a/core/java/android/os/storage/IMountService.aidl b/core/java/android/os/storage/IMountService.aidl
index ad4cb10..75455ab 100644
--- a/core/java/android/os/storage/IMountService.aidl
+++ b/core/java/android/os/storage/IMountService.aidl
@@ -18,6 +18,7 @@
 package android.os.storage;
 
 import android.os.storage.IMountServiceListener;
+import android.os.storage.IMountShutdownObserver;
 
 /** WARNING! Update IMountService.h and IMountService.cpp if you change this file.
  * In particular, the ordering of the methods below must match the 
@@ -142,6 +143,7 @@
 
     /**
      * Shuts down the MountService and gracefully unmounts all external media.
+     * Invokes call back once the shutdown is complete.
      */
-    void shutdown();
+    void shutdown(IMountShutdownObserver observer);
 }
diff --git a/core/java/android/os/storage/IMountShutdownObserver.aidl b/core/java/android/os/storage/IMountShutdownObserver.aidl
new file mode 100644
index 0000000..0aa8a45
--- /dev/null
+++ b/core/java/android/os/storage/IMountShutdownObserver.aidl
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2009 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.os.storage;
+
+/**
+ * Callback class for receiving events related
+ * to shutdown.
+ *
+ * @hide - For internal consumption only.
+ */
+interface IMountShutdownObserver {
+    /**
+     * This method is called when the shutdown
+     * of MountService completed.
+     * @param statusCode indicates success or failure
+     * of the shutdown.
+     */
+    void onShutDownComplete(int statusCode);
+}
diff --git a/core/java/android/provider/Browser.java b/core/java/android/provider/Browser.java
index f32fb5a..a5c85c1 100644
--- a/core/java/android/provider/Browser.java
+++ b/core/java/android/provider/Browser.java
@@ -23,6 +23,7 @@
 import android.database.Cursor;
 import android.database.DatabaseUtils;
 import android.net.Uri;
+import android.os.AsyncTask;
 import android.util.Log;
 import android.webkit.WebIconDatabase;
 
@@ -275,43 +276,71 @@
     public static final void updateVisitedHistory(ContentResolver cr,
                                                   String url, boolean real) {
         long now = new Date().getTime();
-        try {
-            Cursor c = getVisitedLike(cr, url);
-            /* We should only get one answer that is exactly the same. */
-            if (c.moveToFirst()) {
-                ContentValues map = new ContentValues();
-                if (real) {
-                    map.put(BookmarkColumns.VISITS, c
-                            .getInt(HISTORY_PROJECTION_VISITS_INDEX) + 1);
+        new UpdateVisitedHistory(cr, url, real, now).execute();
+    }
+
+    /**
+     * Runnable to perform the update in a separate thread.
+     */
+    private static class UpdateVisitedHistory extends AsyncTask<Void, Void, Void> {
+        private final ContentResolver mContentResolver;
+        private final String mUrl;
+        private final boolean mReal;
+        private final long mNow;
+
+        public UpdateVisitedHistory(ContentResolver cr, String url,
+                boolean real, long now) {
+            mContentResolver = cr;
+            mUrl = url;
+            mReal = real;
+            mNow = now;
+        }
+
+        protected Void doInBackground(Void... unused) {
+            Cursor c = null;
+            try {
+                c = getVisitedLike(mContentResolver, mUrl);
+                /* We should only get one answer that is exactly the same. */
+                if (c.moveToFirst()) {
+                    ContentValues map = new ContentValues();
+                    if (mReal) {
+                        map.put(BookmarkColumns.VISITS, c
+                                .getInt(HISTORY_PROJECTION_VISITS_INDEX) + 1);
+                    } else {
+                        map.put(BookmarkColumns.USER_ENTERED, 1);
+                    }
+                    map.put(BookmarkColumns.DATE, mNow);
+                    String[] projection = new String[]
+                            { Integer.valueOf(c.getInt(0)).toString() };
+                    mContentResolver.update(BOOKMARKS_URI, map, "_id = ?",
+                            projection);
                 } else {
-                    map.put(BookmarkColumns.USER_ENTERED, 1);
+                    truncateHistory(mContentResolver);
+                    ContentValues map = new ContentValues();
+                    int visits;
+                    int user_entered;
+                    if (mReal) {
+                        visits = 1;
+                        user_entered = 0;
+                    } else {
+                        visits = 0;
+                        user_entered = 1;
+                    }
+                    map.put(BookmarkColumns.URL, mUrl);
+                    map.put(BookmarkColumns.VISITS, visits);
+                    map.put(BookmarkColumns.DATE, mNow);
+                    map.put(BookmarkColumns.BOOKMARK, 0);
+                    map.put(BookmarkColumns.TITLE, mUrl);
+                    map.put(BookmarkColumns.CREATED, 0);
+                    map.put(BookmarkColumns.USER_ENTERED, user_entered);
+                    mContentResolver.insert(BOOKMARKS_URI, map);
                 }
-                map.put(BookmarkColumns.DATE, now);
-                cr.update(BOOKMARKS_URI, map, "_id = " + c.getInt(0), null);
-            } else {
-                truncateHistory(cr);
-                ContentValues map = new ContentValues();
-                int visits;
-                int user_entered;
-                if (real) {
-                    visits = 1;
-                    user_entered = 0;
-                } else {
-                    visits = 0;
-                    user_entered = 1;
-                }
-                map.put(BookmarkColumns.URL, url);
-                map.put(BookmarkColumns.VISITS, visits);
-                map.put(BookmarkColumns.DATE, now);
-                map.put(BookmarkColumns.BOOKMARK, 0);
-                map.put(BookmarkColumns.TITLE, url);
-                map.put(BookmarkColumns.CREATED, 0);
-                map.put(BookmarkColumns.USER_ENTERED, user_entered);
-                cr.insert(BOOKMARKS_URI, map);
+            } catch (IllegalStateException e) {
+                Log.e(LOGTAG, "updateVisitedHistory", e);
+            } finally {
+                if (c != null) c.close();
             }
-            c.deactivate();
-        } catch (IllegalStateException e) {
-            return;
+            return null;
         }
     }
 
@@ -579,22 +608,24 @@
      */
     public static final void requestAllIcons(ContentResolver cr, String where,
             WebIconDatabase.IconListener listener) {
+        Cursor c = null;
         try {
-            final Cursor c = cr.query(
+            c = cr.query(
                     BOOKMARKS_URI,
-                    HISTORY_PROJECTION,
+                    new String[] { BookmarkColumns.URL },
                     where, null, null);
             if (c.moveToFirst()) {
                 final WebIconDatabase db = WebIconDatabase.getInstance();
                 do {
-                    db.requestIconForPageUrl(
-                            c.getString(HISTORY_PROJECTION_URL_INDEX), 
-                            listener);
+                    db.requestIconForPageUrl(c.getString(0), listener);
                 } while (c.moveToNext());
             }
-            c.deactivate();
         } catch (IllegalStateException e) {
             Log.e(LOGTAG, "requestAllIcons", e);
+        } finally {
+            if (c != null) {
+                c.close();
+            }
         }
     }
 
diff --git a/core/java/android/provider/Calendar.java b/core/java/android/provider/Calendar.java
index 509317d..4dbeef9 100644
--- a/core/java/android/provider/Calendar.java
+++ b/core/java/android/provider/Calendar.java
@@ -52,8 +52,7 @@
     /**
      * Broadcast Action: An event reminder.
      */
-    public static final String
-            EVENT_REMINDER_ACTION = "android.intent.action.EVENT_REMINDER";
+    public static final String EVENT_REMINDER_ACTION = "android.intent.action.EVENT_REMINDER";
 
     /**
      * These are the symbolic names for the keys used in the extra data
@@ -208,6 +207,9 @@
      */
     public static class Calendars implements BaseColumns, CalendarsColumns
     {
+        private static final String WHERE_DELETE_FOR_ACCOUNT = Calendars._SYNC_ACCOUNT + "=?"
+                + " AND " + Calendars._SYNC_ACCOUNT_TYPE + "=?";
+
         public static final Cursor query(ContentResolver cr, String[] projection,
                                        String where, String orderBy)
         {
@@ -237,16 +239,14 @@
         public static int deleteCalendarsForAccount(ContentResolver cr, Account account) {
             // delete all calendars that match this account
             return Calendar.Calendars.delete(cr,
-                    Calendar.Calendars._SYNC_ACCOUNT + "=? AND "
-                            + Calendar.Calendars._SYNC_ACCOUNT_TYPE + "=?",
-                    new String[] {account.name, account.type});
+                    WHERE_DELETE_FOR_ACCOUNT,
+                    new String[] { account.name, account.type });
         }
 
         /**
          * The content:// style URL for this table
          */
-        public static final Uri CONTENT_URI =
-            Uri.parse("content://" + AUTHORITY + "/calendars");
+        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/calendars");
 
         /**
          * The default sort order for this table
@@ -346,10 +346,8 @@
         public static final int ATTENDEE_STATUS_TENTATIVE = 4;
     }
 
-    public static final class Attendees implements BaseColumns,
-            AttendeesColumns, EventsColumns {
-        public static final Uri CONTENT_URI =
-                Uri.parse("content://" + AUTHORITY + "/attendees");
+    public static final class Attendees implements BaseColumns, AttendeesColumns, EventsColumns {
+        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/attendees");
 
         // TODO: fill out this class when we actually start utilizing attendees
         // in the calendar application.
@@ -641,6 +639,8 @@
             private static final int COLUMN_NAME = 0;
             private static final int COLUMN_VALUE = 1;
 
+            private static final String WHERE_EVENT_ID = "event_id=?";
+
             public EntityIteratorImpl(Cursor cursor, ContentResolver resolver) {
                 super(cursor);
                 mResolver = resolver;
@@ -703,10 +703,14 @@
                 Cursor subCursor;
                 if (mResolver != null) {
                     subCursor = mResolver.query(Reminders.CONTENT_URI, REMINDERS_PROJECTION,
-                            "event_id=" + eventId, null, null);
+                            WHERE_EVENT_ID,
+                            new String[] { Long.toString(eventId) }  /* selectionArgs */,
+                            null /* sortOrder */);
                 } else {
                     subCursor = mProvider.query(Reminders.CONTENT_URI, REMINDERS_PROJECTION,
-                            "event_id=" + eventId, null, null);
+                            WHERE_EVENT_ID,
+                            new String[] { Long.toString(eventId) }  /* selectionArgs */,
+                            null /* sortOrder */);
                 }
                 try {
                     while (subCursor.moveToNext()) {
@@ -721,10 +725,14 @@
 
                 if (mResolver != null) {
                     subCursor = mResolver.query(Attendees.CONTENT_URI, ATTENDEES_PROJECTION,
-                            "event_id=" + eventId, null /* selectionArgs */, null /* sortOrder */);
+                            WHERE_EVENT_ID,
+                            new String[] { Long.toString(eventId) } /* selectionArgs */,
+                            null /* sortOrder */);
                 } else {
                     subCursor = mProvider.query(Attendees.CONTENT_URI, ATTENDEES_PROJECTION,
-                            "event_id=" + eventId, null /* selectionArgs */, null /* sortOrder */);
+                            WHERE_EVENT_ID,
+                            new String[] { Long.toString(eventId) } /* selectionArgs */,
+                            null /* sortOrder */);
                 }
                 try {
                     while (subCursor.moveToNext()) {
@@ -747,10 +755,14 @@
 
                 if (mResolver != null) {
                     subCursor = mResolver.query(ExtendedProperties.CONTENT_URI, EXTENDED_PROJECTION,
-                            "event_id=" + eventId, null /* selectionArgs */, null /* sortOrder */);
+                            WHERE_EVENT_ID,
+                            new String[] { Long.toString(eventId) } /* selectionArgs */,
+                            null /* sortOrder */);
                 } else {
                     subCursor = mProvider.query(ExtendedProperties.CONTENT_URI, EXTENDED_PROJECTION,
-                            "event_id=" + eventId, null /* selectionArgs */, null /* sortOrder */);
+                            WHERE_EVENT_ID,
+                            new String[] { Long.toString(eventId) } /* selectionArgs */,
+                            null /* sortOrder */);
                 }
                 try {
                     while (subCursor.moveToNext()) {
@@ -827,12 +839,14 @@
      */
     public static final class Instances implements BaseColumns, EventsColumns, CalendarsColumns {
 
+        private static final String WHERE_CALENDARS_SELECTED = Calendars.SELECTED + "=1";
+
         public static final Cursor query(ContentResolver cr, String[] projection,
                                          long begin, long end) {
             Uri.Builder builder = CONTENT_URI.buildUpon();
             ContentUris.appendId(builder, begin);
             ContentUris.appendId(builder, end);
-            return cr.query(builder.build(), projection, Calendars.SELECTED + "=1",
+            return cr.query(builder.build(), projection, WHERE_CALENDARS_SELECTED,
                          null, DEFAULT_SORT_ORDER);
         }
 
@@ -842,9 +856,9 @@
             ContentUris.appendId(builder, begin);
             ContentUris.appendId(builder, end);
             if (TextUtils.isEmpty(where)) {
-                where = Calendars.SELECTED + "=1";
+                where = WHERE_CALENDARS_SELECTED;
             } else {
-                where = "(" + where + ") AND " + Calendars.SELECTED + "=1";
+                where = "(" + where + ") AND " + WHERE_CALENDARS_SELECTED;
             }
             return cr.query(builder.build(), projection, where,
                          null, orderBy == null ? DEFAULT_SORT_ORDER : orderBy);
@@ -976,7 +990,7 @@
                 "/instances/groupbyday");
 
         public static final String[] PROJECTION = { STARTDAY, ENDDAY };
-        public static final String SELECTION = "selected==1";
+        public static final String SELECTION = "selected=1";
 
         /**
          * Retrieves the days with events for the Julian days starting at "startDay"
@@ -1107,10 +1121,23 @@
 
     public static final class CalendarAlerts implements BaseColumns,
             CalendarAlertsColumns, EventsColumns, CalendarsColumns {
+
         public static final String TABLE_NAME = "CalendarAlerts";
         public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY +
                 "/calendar_alerts");
 
+        private static final String WHERE_ALARM_EXISTS = EVENT_ID + "=?"
+                + " AND " + BEGIN + "=?"
+                + " AND " + ALARM_TIME + "=?";
+
+        private static final String WHERE_FINDNEXTALARMTIME = ALARM_TIME + ">=?";
+        private static final String SORT_ORDER_ALARMTIME_ASC = ALARM_TIME + " ASC";
+
+        private static final String WHERE_RESCHEDULE_MISSED_ALARMS = STATE + "=" + SCHEDULED
+                + " AND " + ALARM_TIME + "<?"
+                + " AND " + ALARM_TIME + ">?"
+                + " AND " + END + ">=?";
+
         /**
          * This URI is for grouping the query results by event_id and begin
          * time.  This will return one result per instance of an event.  So
@@ -1158,7 +1185,12 @@
             // TODO: construct an explicit SQL query so that we can add
             // "LIMIT 1" to the end and get just one result.
             String[] projection = new String[] { ALARM_TIME };
-            Cursor cursor = query(cr, projection, selection, null, ALARM_TIME + " ASC");
+            Cursor cursor = query(cr, projection,
+                    WHERE_FINDNEXTALARMTIME,
+                    new String[] {
+                        Long.toString(millis)
+                    },
+                    SORT_ORDER_ALARMTIME_ASC);
             long alarmTime = -1;
             try {
                 if (cursor != null && cursor.moveToFirst()) {
@@ -1188,17 +1220,21 @@
             // and should have fired by now and are not too old.
             long now = System.currentTimeMillis();
             long ancient = now - DateUtils.DAY_IN_MILLIS;
-            String selection = CalendarAlerts.STATE + "=" + CalendarAlerts.SCHEDULED
-                    + " AND " + CalendarAlerts.ALARM_TIME + "<" + now
-                    + " AND " + CalendarAlerts.ALARM_TIME + ">" + ancient
-                    + " AND " + CalendarAlerts.END + ">=" + now;
             String[] projection = new String[] {
                     ALARM_TIME,
             };
 
             // TODO: construct an explicit SQL query so that we can add
             // "GROUPBY" instead of doing a sort and de-dup
-            Cursor cursor = CalendarAlerts.query(cr, projection, selection, null, "alarmTime ASC");
+            Cursor cursor = CalendarAlerts.query(cr,
+                    projection,
+                    WHERE_RESCHEDULE_MISSED_ALARMS,
+                    new String[] {
+                        Long.toString(now),
+                        Long.toString(ancient),
+                        Long.toString(now)
+                    },
+                    SORT_ORDER_ALARMTIME_ASC);
             if (cursor == null) {
                 return;
             }
@@ -1237,8 +1273,8 @@
                 manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
             }
 
-            Intent intent = new Intent(android.provider.Calendar.EVENT_REMINDER_ACTION);
-            intent.putExtra(android.provider.Calendar.CalendarAlerts.ALARM_TIME, alarmTime);
+            Intent intent = new Intent(EVENT_REMINDER_ACTION);
+            intent.putExtra(ALARM_TIME, alarmTime);
             PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent,
                     PendingIntent.FLAG_CANCEL_CURRENT);
             manager.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
@@ -1258,13 +1294,18 @@
          */
         public static final boolean alarmExists(ContentResolver cr, long eventId,
                 long begin, long alarmTime) {
-            String selection = CalendarAlerts.EVENT_ID + "=" + eventId
-                    + " AND " + CalendarAlerts.BEGIN + "=" + begin
-                    + " AND " + CalendarAlerts.ALARM_TIME + "=" + alarmTime;
             // TODO: construct an explicit SQL query so that we can add
             // "LIMIT 1" to the end and get just one result.
-            String[] projection = new String[] { CalendarAlerts.ALARM_TIME };
-            Cursor cursor = query(cr, projection, selection, null, null);
+            String[] projection = new String[] { ALARM_TIME };
+            Cursor cursor = query(cr,
+                    projection,
+                    WHERE_ALARM_EXISTS,
+                    new String[] {
+                        Long.toString(eventId),
+                        Long.toString(begin),
+                        Long.toString(alarmTime)
+                    },
+                    null);
             boolean found = false;
             try {
                 if (cursor != null && cursor.getCount() > 0) {
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index fdde591..4995cac 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -29,6 +29,7 @@
 import android.content.Context;
 import android.content.IContentProvider;
 import android.content.Intent;
+import android.content.pm.ActivityInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.content.res.Configuration;
@@ -989,6 +990,11 @@
             return Settings.System.putFloat(cr, FONT_SCALE, config.fontScale);
         }
 
+        /** @hide */
+        public static boolean hasInterestingConfigurationChanges(int changes) {
+            return (changes&ActivityInfo.CONFIG_FONT_SCALE) != 0;
+        }
+        
         public static boolean getShowGTalkServiceStatus(ContentResolver cr) {
             return getInt(cr, SHOW_GTALK_SERVICE_STATUS, 0) != 0;
         }
@@ -1708,6 +1714,7 @@
             VOLUME_ALARM + APPEND_FOR_LAST_AUDIBLE,
             VOLUME_NOTIFICATION + APPEND_FOR_LAST_AUDIBLE,
             VOLUME_BLUETOOTH_SCO + APPEND_FOR_LAST_AUDIBLE,
+            VIBRATE_IN_SILENT,
             TEXT_AUTO_REPLACE,
             TEXT_AUTO_CAPS,
             TEXT_AUTO_PUNCTUATE,
diff --git a/core/java/android/server/BluetoothEventLoop.java b/core/java/android/server/BluetoothEventLoop.java
index f363828..c0e4600 100644
--- a/core/java/android/server/BluetoothEventLoop.java
+++ b/core/java/android/server/BluetoothEventLoop.java
@@ -374,6 +374,11 @@
             Intent intent = null;
             if (propValues[1].equals("true")) {
                 intent = new Intent(BluetoothDevice.ACTION_ACL_CONNECTED);
+                // Set the link timeout to 8000 slots (5 sec timeout)
+                // for bluetooth docks.
+                if (mBluetoothService.isBluetoothDock(address)) {
+                    mBluetoothService.setLinkTimeout(address, 8000);
+                }
             } else {
                 intent = new Intent(BluetoothDevice.ACTION_ACL_DISCONNECTED);
             }
diff --git a/core/java/android/server/BluetoothService.java b/core/java/android/server/BluetoothService.java
index e7d9d5b..2c73416 100644
--- a/core/java/android/server/BluetoothService.java
+++ b/core/java/android/server/BluetoothService.java
@@ -1910,6 +1910,13 @@
         return path;
     }
 
+    /*package */ void setLinkTimeout(String address, int num_slots) {
+        String path = getObjectPathFromAddress(address);
+        boolean result = setLinkTimeoutNative(path, num_slots);
+
+        if (!result) log("Set Link Timeout to:" + num_slots + " slots failed");
+    }
+
     private static void log(String msg) {
         Log.d(TAG, msg);
     }
@@ -1953,4 +1960,5 @@
     private native int addRfcommServiceRecordNative(String name, long uuidMsb, long uuidLsb,
             short channel);
     private native boolean removeServiceRecordNative(int handle);
+    private native boolean setLinkTimeoutNative(String path, int num_slots);
 }
diff --git a/core/java/android/text/StaticLayout.java b/core/java/android/text/StaticLayout.java
index 600ec7e..f02ad2a 100644
--- a/core/java/android/text/StaticLayout.java
+++ b/core/java/android/text/StaticLayout.java
@@ -233,25 +233,25 @@
                 }
             }
 
-            if (!easy) {
-                // Ensure that none of the underlying characters are treated
-                // as viable breakpoints, and that the entire run gets the
-                // same bidi direction.
+            // Ensure that none of the underlying characters are treated
+            // as viable breakpoints, and that the entire run gets the
+            // same bidi direction.
 
-                if (source instanceof Spanned) {
-                    Spanned sp = (Spanned) source;
-                    ReplacementSpan[] spans = sp.getSpans(start, end, ReplacementSpan.class);
+            if (source instanceof Spanned) {
+                Spanned sp = (Spanned) source;
+                ReplacementSpan[] spans = sp.getSpans(start, end, ReplacementSpan.class);
 
-                    for (int y = 0; y < spans.length; y++) {
-                        int a = sp.getSpanStart(spans[y]);
-                        int b = sp.getSpanEnd(spans[y]);
+                for (int y = 0; y < spans.length; y++) {
+                    int a = sp.getSpanStart(spans[y]);
+                    int b = sp.getSpanEnd(spans[y]);
 
-                        for (int x = a; x < b; x++) {
-                            chs[x - start] = '\uFFFC';
-                        }
+                    for (int x = a; x < b; x++) {
+                        chs[x - start] = '\uFFFC';
                     }
                 }
+            }
 
+            if (!easy) {
                 // XXX put override flags, etc. into chdirs
                 dir = bidi(dir, chs, chdirs, n, false);
 
diff --git a/core/java/android/text/util/Rfc822Tokenizer.java b/core/java/android/text/util/Rfc822Tokenizer.java
index 69d745d..952d833 100644
--- a/core/java/android/text/util/Rfc822Tokenizer.java
+++ b/core/java/android/text/util/Rfc822Tokenizer.java
@@ -74,7 +74,7 @@
 
                 name.setLength(0);
                 address.setLength(0);
-                address.setLength(0);
+                comment.setLength(0);
             } else if (c == '"') {
                 i++;
 
diff --git a/core/java/android/view/VelocityTracker.java b/core/java/android/view/VelocityTracker.java
index c17a724..aab76c4 100644
--- a/core/java/android/view/VelocityTracker.java
+++ b/core/java/android/view/VelocityTracker.java
@@ -259,8 +259,6 @@
      * 
      * @param id Which pointer's velocity to return.
      * @return The previously computed X velocity.
-     * 
-     * @hide Pending API approval
      */
     public float getXVelocity(int id) {
         return mXVelocity[id];
@@ -272,8 +270,6 @@
      * 
      * @param id Which pointer's velocity to return.
      * @return The previously computed Y velocity.
-     * 
-     * @hide Pending API approval
      */
     public float getYVelocity(int id) {
         return mYVelocity[id];
diff --git a/core/java/android/view/ViewConfiguration.java b/core/java/android/view/ViewConfiguration.java
index 2344c42..2b78d2d 100644
--- a/core/java/android/view/ViewConfiguration.java
+++ b/core/java/android/view/ViewConfiguration.java
@@ -102,6 +102,12 @@
     private static final int TOUCH_SLOP = 16;
     
     /**
+     * Distance a touch can wander before we think the user is attempting a paged scroll
+     * (in dips)
+     */
+    private static final int PAGING_TOUCH_SLOP = TOUCH_SLOP * 3;
+    
+    /**
      * Distance between the first touch and second touch to still be considered a double tap
      */
     private static final int DOUBLE_TAP_SLOP = 100;
@@ -140,6 +146,7 @@
     private final int mMaximumFlingVelocity;
     private final int mScrollbarSize;
     private final int mTouchSlop;
+    private final int mPagingTouchSlop;
     private final int mDoubleTapSlop;
     private final int mWindowTouchSlop;
     private final int mMaximumDrawingCacheSize;
@@ -158,6 +165,7 @@
         mMaximumFlingVelocity = MAXIMUM_FLING_VELOCITY;
         mScrollbarSize = SCROLL_BAR_SIZE;
         mTouchSlop = TOUCH_SLOP;
+        mPagingTouchSlop = PAGING_TOUCH_SLOP;
         mDoubleTapSlop = DOUBLE_TAP_SLOP;
         mWindowTouchSlop = WINDOW_TOUCH_SLOP;
         //noinspection deprecation
@@ -184,6 +192,7 @@
         mMaximumFlingVelocity = (int) (density * MAXIMUM_FLING_VELOCITY + 0.5f);
         mScrollbarSize = (int) (density * SCROLL_BAR_SIZE + 0.5f);
         mTouchSlop = (int) (density * TOUCH_SLOP + 0.5f);
+        mPagingTouchSlop = (int) (density * PAGING_TOUCH_SLOP + 0.5f);
         mDoubleTapSlop = (int) (density * DOUBLE_TAP_SLOP + 0.5f);
         mWindowTouchSlop = (int) (density * WINDOW_TOUCH_SLOP + 0.5f);
 
@@ -339,6 +348,14 @@
     public int getScaledTouchSlop() {
         return mTouchSlop;
     }
+    
+    /**
+     * @return Distance a touch can wander before we think the user is scrolling a full page
+     *         in dips
+     */
+    public int getScaledPagingTouchSlop() {
+        return mPagingTouchSlop;
+    }
 
     /**
      * @return Distance between the first touch and second touch to still be
diff --git a/core/java/android/view/WindowManagerPolicy.java b/core/java/android/view/WindowManagerPolicy.java
index ab3260e..b39cb9d 100644
--- a/core/java/android/view/WindowManagerPolicy.java
+++ b/core/java/android/view/WindowManagerPolicy.java
@@ -627,8 +627,9 @@
      * returned, all windows given to layoutWindow() <em>must</em> have had a
      * frame assigned.
      *  
-     * @return Return any bit set of {@link #FINISH_LAYOUT_REDO_LAYOUT}
-     * and {@link #FINISH_LAYOUT_REDO_CONFIG}.
+     * @return Return any bit set of {@link #FINISH_LAYOUT_REDO_LAYOUT},
+     * {@link #FINISH_LAYOUT_REDO_CONFIG}, {@link #FINISH_LAYOUT_REDO_WALLPAPER},
+     * or {@link #FINISH_LAYOUT_REDO_ANIM}.
      */
     public int finishLayoutLw();
 
@@ -638,6 +639,8 @@
     static final int FINISH_LAYOUT_REDO_CONFIG = 0x0002;
     /** Wallpaper may need to move */
     static final int FINISH_LAYOUT_REDO_WALLPAPER = 0x0004;
+    /** Need to recompute animations */
+    static final int FINISH_LAYOUT_REDO_ANIM = 0x0008;
     
     /**
      * Called when animation of the windows is about to start.
@@ -661,10 +664,11 @@
      * something that may have modified the animation state of another window, 
      * be sure to return true in order to perform another animation frame. 
      *  
-     * @return Return true if animation state may have changed (so that another 
-     *         frame of animation will be run).
+     * @return Return any bit set of {@link #FINISH_LAYOUT_REDO_LAYOUT},
+     * {@link #FINISH_LAYOUT_REDO_CONFIG}, {@link #FINISH_LAYOUT_REDO_WALLPAPER},
+     * or {@link #FINISH_LAYOUT_REDO_ANIM}.
      */
-    public boolean finishAnimationLw();
+    public int finishAnimationLw();
 
     /**
      * Return true if it is okay to perform animations for an app transition
diff --git a/core/java/android/webkit/LoadListener.java b/core/java/android/webkit/LoadListener.java
index 115499f..7da99ca 100644
--- a/core/java/android/webkit/LoadListener.java
+++ b/core/java/android/webkit/LoadListener.java
@@ -1057,7 +1057,7 @@
                 mCacheLoader != null) ? HTTP_OK : mStatusCode;
         // pass content-type content-length and content-encoding
         final int nativeResponse = nativeCreateResponse(
-                mUrl, statusCode, mStatusText,
+                originalUrl(), statusCode, mStatusText,
                 mMimeType, mContentLength, mEncoding);
         if (mHeaders != null) {
             mHeaders.getHeaders(new Headers.HeaderCallback() {
@@ -1256,9 +1256,6 @@
                 return;
             }
 
-            if (mOriginalUrl == null) {
-                mOriginalUrl = mUrl;
-            }
 
             // Cache the redirect response
             if (getErrorID() == OK) {
@@ -1273,6 +1270,8 @@
                         WebViewWorker.MSG_REMOVE_CACHE, this).sendToTarget();
             }
 
+            // Saving a copy of the unstripped url for the response
+            mOriginalUrl = redirectTo;
             // This will strip the anchor
             setUrl(redirectTo);
 
diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java
index 8981419..fb15f78 100644
--- a/core/java/android/webkit/WebSettings.java
+++ b/core/java/android/webkit/WebSettings.java
@@ -192,6 +192,7 @@
     private boolean         mBuiltInZoomControls = false;
     private boolean         mAllowFileAccess = true;
     private boolean         mLoadWithOverviewMode = false;
+    private boolean         mUseSystemOverscrollBackground = false;
 
     // private WebSettings, not accessible by the host activity
     static private int      mDoubleTapToastCount = 3;
@@ -470,6 +471,23 @@
     }
 
     /**
+     * Set whether the WebView uses system background for over scroll
+     * background. If false, it will use the WebView's background. Default is
+     * false.
+     */
+    public void setUseSystemOverscrollBackground(boolean system) {
+        mUseSystemOverscrollBackground = system;
+    }
+
+    /**
+     * Returns true if this WebView uses system background instead of WebView
+     * background for over scroll background.
+     */
+    public boolean getUseSystemOverscrollBackground() {
+        return mUseSystemOverscrollBackground;
+    }
+
+    /**
      * Store whether the WebView is saving form data.
      */
     public void setSaveFormData(boolean save) {
diff --git a/core/java/android/webkit/WebTextView.java b/core/java/android/webkit/WebTextView.java
index 39edcad..016f016 100644
--- a/core/java/android/webkit/WebTextView.java
+++ b/core/java/android/webkit/WebTextView.java
@@ -377,11 +377,17 @@
             return;
         }
         mPreChange = postChange;
-        // This was simply a delete or a cut, so just delete the selection.
-        if (before > 0 && 0 == count) {
-            mWebView.deleteSelection(start, start + before);
-            // For this and all changes to the text, update our cache
-            updateCachedTextfield();
+        if (0 == count) {
+            if (before > 0) {
+                // This was simply a delete or a cut, so just delete the
+                // selection.
+                mWebView.deleteSelection(start, start + before);
+                // For this and all changes to the text, update our cache
+                updateCachedTextfield();
+            }
+            // before should never be negative, so whether it was a cut
+            // (handled above), or before is 0, in which case nothing has
+            // changed, we should return.
             return;
         }
         // Find the last character being replaced.  If it can be represented by
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index e81fec4..5099cd4 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -68,6 +68,7 @@
 import android.view.inputmethod.InputMethodManager;
 import android.webkit.WebTextView.AutoCompleteAdapter;
 import android.webkit.WebViewCore.EventHub;
+import android.webkit.WebViewCore.TouchEventData;
 import android.widget.AbsoluteLayout;
 import android.widget.Adapter;
 import android.widget.AdapterView;
@@ -375,27 +376,29 @@
     // Whether to forward the touch events to WebCore
     private boolean mForwardTouchEvents = false;
 
-    // Whether to prevent drag during touch. The initial value depends on
-    // mForwardTouchEvents. If WebCore wants touch events, we assume it will
-    // take control of touch events unless it says no for touch down event.
-    private static final int PREVENT_DRAG_NO = 0;
-    private static final int PREVENT_DRAG_MAYBE_YES = 1;
-    private static final int PREVENT_DRAG_YES = 2;
-    private static final int PREVENT_DRAG_CANCEL = 3;
-    private int mPreventDrag = PREVENT_DRAG_NO;
+    // Whether to prevent default during touch. The initial value depends on
+    // mForwardTouchEvents. If WebCore wants all the touch events, it says yes
+    // for touch down. Otherwise UI will wait for the answer of the first
+    // confirmed move before taking over the control.
+    private static final int PREVENT_DEFAULT_NO = 0;
+    private static final int PREVENT_DEFAULT_MAYBE_YES = 1;
+    private static final int PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN = 2;
+    private static final int PREVENT_DEFAULT_YES = 3;
+    private static final int PREVENT_DEFAULT_IGNORE = 4;
+    private int mPreventDefault = PREVENT_DEFAULT_IGNORE;
 
-    // by default mPreventLongPress is false. If it is true, long press event
-    // will be handled by WebKit instead of UI.
-    private boolean mPreventLongPress = false;
-    // by default mPreventDoubleTap is false. If it is true, double tap event
-    // will be handled by WebKit instead of UI.
-    private boolean mPreventDoubleTap = false;
+    // true when the touch movement exceeds the slop
+    private boolean mConfirmMove;
 
-    // this needs to be in sync with the logic in WebKit's
-    // EventHandler::handleTouchEvent()
-    private static final int TOUCH_PREVENT_DRAG         = 0x1;
-    private static final int TOUCH_PREVENT_LONGPRESS    = 0x2;
-    private static final int TOUCH_PREVENT_DOUBLETAP    = 0x4;
+    // if true, touch events will be first processed by WebCore, if prevent
+    // default is not set, the UI will continue handle them.
+    private boolean mDeferTouchProcess;
+
+    // to avoid interfering with the current touch events, track them
+    // separately. Currently no snapping or fling in the deferred process mode
+    private int mDeferTouchMode = TOUCH_DONE_MODE;
+    private float mLastDeferTouchX;
+    private float mLastDeferTouchY;
 
     // To keep track of whether the current drag was initiated by a WebTextView,
     // so that we know not to hide the cursor
@@ -484,7 +487,7 @@
     private int mAnchorX;
     private int mAnchorY;
 
-    /**
+    /*
      * Private message ids
      */
     private static final int REMEMBER_PASSWORD          = 1;
@@ -496,39 +499,49 @@
     private static final int RESUME_WEBCORE_PRIORITY    = 7;
     private static final int DRAG_HELD_MOTIONLESS       = 8;
     private static final int AWAKEN_SCROLL_BARS         = 9;
+    private static final int PREVENT_DEFAULT_TIMEOUT    = 10;
 
+    private static final int FIRST_PRIVATE_MSG_ID = REMEMBER_PASSWORD;
+    private static final int LAST_PRIVATE_MSG_ID = PREVENT_DEFAULT_TIMEOUT;
+
+    /*
+     * Package message ids
+     */
     //! arg1=x, arg2=y
-    static final int SCROLL_TO_MSG_ID                   = 10;
-    static final int SCROLL_BY_MSG_ID                   = 11;
+    static final int SCROLL_TO_MSG_ID                   = 101;
+    static final int SCROLL_BY_MSG_ID                   = 102;
     //! arg1=x, arg2=y
-    static final int SPAWN_SCROLL_TO_MSG_ID             = 12;
+    static final int SPAWN_SCROLL_TO_MSG_ID             = 103;
     //! arg1=x, arg2=y
-    static final int SYNC_SCROLL_TO_MSG_ID              = 13;
-    static final int NEW_PICTURE_MSG_ID                 = 14;
-    static final int UPDATE_TEXT_ENTRY_MSG_ID           = 15;
-    static final int WEBCORE_INITIALIZED_MSG_ID         = 16;
-    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 17;
-    static final int UPDATE_ZOOM_RANGE                  = 18;
-    static final int MOVE_OUT_OF_PLUGIN                 = 19;
-    static final int CLEAR_TEXT_ENTRY                   = 20;
-    static final int UPDATE_TEXT_SELECTION_MSG_ID       = 21;
-    static final int SHOW_RECT_MSG_ID                   = 22;
-    static final int LONG_PRESS_CENTER                  = 23;
-    static final int PREVENT_TOUCH_ID                   = 24;
-    static final int WEBCORE_NEED_TOUCH_EVENTS          = 25;
+    static final int SYNC_SCROLL_TO_MSG_ID              = 104;
+    static final int NEW_PICTURE_MSG_ID                 = 105;
+    static final int UPDATE_TEXT_ENTRY_MSG_ID           = 106;
+    static final int WEBCORE_INITIALIZED_MSG_ID         = 107;
+    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 108;
+    static final int UPDATE_ZOOM_RANGE                  = 109;
+    static final int MOVE_OUT_OF_PLUGIN                 = 110;
+    static final int CLEAR_TEXT_ENTRY                   = 111;
+    static final int UPDATE_TEXT_SELECTION_MSG_ID       = 112;
+    static final int SHOW_RECT_MSG_ID                   = 113;
+    static final int LONG_PRESS_CENTER                  = 114;
+    static final int PREVENT_TOUCH_ID                   = 115;
+    static final int WEBCORE_NEED_TOUCH_EVENTS          = 116;
     // obj=Rect in doc coordinates
-    static final int INVAL_RECT_MSG_ID                  = 26;
-    static final int REQUEST_KEYBOARD                   = 27;
-    static final int DO_MOTION_UP                       = 28;
-    static final int SHOW_FULLSCREEN                    = 29;
-    static final int HIDE_FULLSCREEN                    = 30;
-    static final int DOM_FOCUS_CHANGED                  = 31;
-    static final int IMMEDIATE_REPAINT_MSG_ID           = 32;
-    static final int SET_ROOT_LAYER_MSG_ID              = 33;
-    static final int RETURN_LABEL                       = 34;
-    static final int FIND_AGAIN                         = 35;
+    static final int INVAL_RECT_MSG_ID                  = 117;
+    static final int REQUEST_KEYBOARD                   = 118;
+    static final int DO_MOTION_UP                       = 119;
+    static final int SHOW_FULLSCREEN                    = 120;
+    static final int HIDE_FULLSCREEN                    = 121;
+    static final int DOM_FOCUS_CHANGED                  = 122;
+    static final int IMMEDIATE_REPAINT_MSG_ID           = 123;
+    static final int SET_ROOT_LAYER_MSG_ID              = 124;
+    static final int RETURN_LABEL                       = 125;
+    static final int FIND_AGAIN                         = 126;
 
-    static final String[] HandlerDebugString = {
+    private static final int FIRST_PACKAGE_MSG_ID = SCROLL_TO_MSG_ID;
+    private static final int LAST_PACKAGE_MSG_ID = FIND_AGAIN;
+
+    static final String[] HandlerPrivateDebugString = {
         "REMEMBER_PASSWORD", //              = 1;
         "NEVER_REMEMBER_PASSWORD", //        = 2;
         "SWITCH_TO_SHORTPRESS", //           = 3;
@@ -538,32 +551,36 @@
         "RESUME_WEBCORE_PRIORITY", //        = 7;
         "DRAG_HELD_MOTIONLESS", //           = 8;
         "AWAKEN_SCROLL_BARS", //             = 9;
-        "SCROLL_TO_MSG_ID", //               = 10;
-        "SCROLL_BY_MSG_ID", //               = 11;
-        "SPAWN_SCROLL_TO_MSG_ID", //         = 12;
-        "SYNC_SCROLL_TO_MSG_ID", //          = 13;
-        "NEW_PICTURE_MSG_ID", //             = 14;
-        "UPDATE_TEXT_ENTRY_MSG_ID", //       = 15;
-        "WEBCORE_INITIALIZED_MSG_ID", //     = 16;
-        "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 17;
-        "UPDATE_ZOOM_RANGE", //              = 18;
-        "MOVE_OUT_OF_PLUGIN", //             = 19;
-        "CLEAR_TEXT_ENTRY", //               = 20;
-        "UPDATE_TEXT_SELECTION_MSG_ID", //   = 21;
-        "SHOW_RECT_MSG_ID", //               = 22;
-        "LONG_PRESS_CENTER", //              = 23;
-        "PREVENT_TOUCH_ID", //               = 24;
-        "WEBCORE_NEED_TOUCH_EVENTS", //      = 25;
-        "INVAL_RECT_MSG_ID", //              = 26;
-        "REQUEST_KEYBOARD", //               = 27;
-        "DO_MOTION_UP", //                   = 28;
-        "SHOW_FULLSCREEN", //                = 29;
-        "HIDE_FULLSCREEN", //                = 30;
-        "DOM_FOCUS_CHANGED", //              = 31;
-        "IMMEDIATE_REPAINT_MSG_ID", //       = 32;
-        "SET_ROOT_LAYER_MSG_ID", //          = 33;
-        "RETURN_LABEL", //                   = 34;
-        "FIND_AGAIN" //                      = 35;
+        "PREVENT_DEFAULT_TIMEOUT" //         = 10;
+    };
+
+    static final String[] HandlerPackageDebugString = {
+        "SCROLL_TO_MSG_ID", //               = 101;
+        "SCROLL_BY_MSG_ID", //               = 102;
+        "SPAWN_SCROLL_TO_MSG_ID", //         = 103;
+        "SYNC_SCROLL_TO_MSG_ID", //          = 104;
+        "NEW_PICTURE_MSG_ID", //             = 105;
+        "UPDATE_TEXT_ENTRY_MSG_ID", //       = 106;
+        "WEBCORE_INITIALIZED_MSG_ID", //     = 107;
+        "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 108;
+        "UPDATE_ZOOM_RANGE", //              = 109;
+        "MOVE_OUT_OF_PLUGIN", //             = 110;
+        "CLEAR_TEXT_ENTRY", //               = 111;
+        "UPDATE_TEXT_SELECTION_MSG_ID", //   = 112;
+        "SHOW_RECT_MSG_ID", //               = 113;
+        "LONG_PRESS_CENTER", //              = 114;
+        "PREVENT_TOUCH_ID", //               = 115;
+        "WEBCORE_NEED_TOUCH_EVENTS", //      = 116;
+        "INVAL_RECT_MSG_ID", //              = 117;
+        "REQUEST_KEYBOARD", //               = 118;
+        "DO_MOTION_UP", //                   = 119;
+        "SHOW_FULLSCREEN", //                = 120;
+        "HIDE_FULLSCREEN", //                = 121;
+        "DOM_FOCUS_CHANGED", //              = 122;
+        "IMMEDIATE_REPAINT_MSG_ID", //       = 123;
+        "SET_ROOT_LAYER_MSG_ID", //          = 124;
+        "RETURN_LABEL", //                   = 125;
+        "FIND_AGAIN" //                      = 126;
     };
 
     // If the site doesn't use the viewport meta tag to specify the viewport,
@@ -2182,14 +2199,15 @@
     // Sets r to be our visible rectangle in content coordinates
     private void calcOurContentVisibleRect(Rect r) {
         calcOurVisibleRect(r);
-        r.left = viewToContentX(r.left);
+        // since we might overscroll, pin the rect to the bounds of the content
+        r.left = Math.max(viewToContentX(r.left), 0);
         // viewToContentY will remove the total height of the title bar.  Add
         // the visible height back in to account for the fact that if the title
         // bar is partially visible, the part of the visible rect which is
         // displaying our content is displaced by that amount.
-        r.top = viewToContentY(r.top + getVisibleTitleHeight());
-        r.right = viewToContentX(r.right);
-        r.bottom = viewToContentY(r.bottom);
+        r.top = Math.max(viewToContentY(r.top + getVisibleTitleHeight()), 0);
+        r.right = Math.min(viewToContentX(r.right), mContentWidth);
+        r.bottom = Math.min(viewToContentY(r.bottom), mContentHeight);
     }
 
     static class ViewSizeData {
@@ -2288,9 +2306,11 @@
             boolean clampedY) {
         mInOverScrollMode = false;
         int maxX = computeMaxScrollX();
-        if (Math.abs(mMinZoomScale - mMaxZoomScale) < 0.01f && maxX == 0) {
-            // do not over scroll x if the page can't be zoomed and it just fits
-            // the screen
+        if (maxX == 0 && (Math.abs(mMinZoomScale - mMaxZoomScale) < 0.01f)
+                || !getSettings().supportZoom()
+                || !getSettings().getUseWideViewPort()) {
+            // do not over scroll x if the page just fits the screen and it
+            // can't zoom or the view doesn't use wide viewport
             scrollX = pinLocX(scrollX);
         } else if (scrollX < 0 || scrollX > maxX) {
             mInOverScrollMode = true;
@@ -3095,7 +3115,8 @@
         }
 
         int saveCount = canvas.save();
-        if (mInOverScrollMode) {
+        if (mInOverScrollMode
+                && getSettings().getUseSystemOverscrollBackground()) {
             if (mOverScrollBackground == null) {
                 mOverScrollBackground = new Paint();
                 Bitmap bm = BitmapFactory.decodeResource(
@@ -3238,10 +3259,11 @@
         }
 
         boolean animateZoom = mZoomScale != 0;
-        boolean animateScroll = (!mScroller.isFinished()
+        boolean animateScroll = ((!mScroller.isFinished()
                 || mVelocityTracker != null)
                 && (mTouchMode != TOUCH_DRAG_MODE ||
-                mHeldMotionless != MOTIONLESS_TRUE);
+                mHeldMotionless != MOTIONLESS_TRUE))
+                || mDeferTouchMode == TOUCH_DRAG_MODE;
         if (mTouchMode == TOUCH_DRAG_MODE) {
             if (mHeldMotionless == MOTIONLESS_PENDING) {
                 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
@@ -3338,11 +3360,9 @@
             if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
                 mTouchMode = TOUCH_SHORTPRESS_MODE;
                 HitTestResult hitTest = getHitTestResult();
-                if (mPreventLongPress || (hitTest != null &&
-                        hitTest.mType != HitTestResult.UNKNOWN_TYPE)) {
-                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
-                            .obtainMessage(SWITCH_TO_LONGPRESS),
-                            LONG_PRESS_TIMEOUT);
+                if (hitTest == null
+                        || hitTest.mType == HitTestResult.UNKNOWN_TYPE) {
+                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
                 }
             }
         }
@@ -3675,11 +3695,13 @@
             return false;
         }
 
-        if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false
-                && !nativeFocusIsPlugin()
-                && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
-                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
-            setUpSelectXY();
+        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
+                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
+            if (nativeFocusIsPlugin()) {
+                mShiftIsPressed = true;
+            } else if (!nativeCursorWantsKeyEvents() && !mShiftIsPressed) {
+                setUpSelectXY();
+            }
         }
 
         if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
@@ -3818,7 +3840,10 @@
 
         if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
                 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
-            if (commitCopy()) {
+            if (nativeFocusIsPlugin()) {
+                mShiftIsPressed = false;
+                return true;
+            } else if (commitCopy()) {
                 return true;
             }
         }
@@ -4179,7 +4204,9 @@
     public boolean dispatchKeyEvent(KeyEvent event) {
         boolean dispatch = true;
 
-        if (!inEditingMode()) {
+        // Textfields and plugins need to receive the shift up key even if
+        // another key was released while the shift key was held down.
+        if (!inEditingMode() && !nativeFocusIsPlugin()) {
             if (event.getAction() == KeyEvent.ACTION_DOWN) {
                 mGotKeyDown = true;
             } else {
@@ -4458,6 +4485,7 @@
             // may trigger the unwanted click, can't use TOUCH_DRAG_MODE as it
             // may trigger the unwanted fling.
             mTouchMode = TOUCH_PINCH_DRAG;
+            mConfirmMove = true;
             startTouch(detector.getFocusX(), detector.getFocusY(),
                     mLastTouchTime);
         }
@@ -4483,6 +4511,22 @@
         }
     }
 
+    private boolean hitFocusedPlugin(int contentX, int contentY) {
+        return nativeFocusIsPlugin()
+                && nativePointInNavCache(contentX, contentY, mNavSlop)
+                && nativeCacheHitNodePointer() == nativeFocusNodePointer();
+    }
+
+    private boolean shouldForwardTouchEvent() {
+        return mFullScreenHolder != null || (mForwardTouchEvents
+                && mTouchMode != TOUCH_SELECT_MODE
+                && mPreventDefault != PREVENT_DEFAULT_IGNORE);
+    }
+
+    private boolean inFullScreenMode() {
+        return mFullScreenHolder != null;
+    }
+
     @Override
     public boolean onTouchEvent(MotionEvent ev) {
         if (mNativeClass == 0 || !isClickable() || !isLongClickable()) {
@@ -4544,46 +4588,33 @@
             y = getViewHeightWithTitle() - 1;
         }
 
-        // pass the touch events, except ACTION_MOVE which will be handled
-        // later, from UI thread to WebCore thread
-        if (mFullScreenHolder != null || (mForwardTouchEvents
-                && action != MotionEvent.ACTION_MOVE
-                && (action == MotionEvent.ACTION_DOWN || mPreventDrag
-                        != PREVENT_DRAG_CANCEL))) {
-            WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-            ted.mAction = action;
-            ted.mX = viewToContentX((int) x + mScrollX);
-            ted.mY = viewToContentY((int) y + mScrollY);
-            ted.mEventTime = eventTime;
-            ted.mMetaState = ev.getMetaState();
-            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-            mLastSentTouchTime = eventTime;
-        }
-
         float fDeltaX = mLastTouchX - x;
         float fDeltaY = mLastTouchY - y;
         int deltaX = (int) fDeltaX;
         int deltaY = (int) fDeltaY;
+        int contentX = viewToContentX((int) x + mScrollX);
+        int contentY = viewToContentY((int) y + mScrollY);
 
         switch (action) {
             case MotionEvent.ACTION_DOWN: {
-                mPreventDrag = PREVENT_DRAG_NO;
+                mPreventDefault = PREVENT_DEFAULT_NO;
+                mConfirmMove = false;
                 if (!mScroller.isFinished()) {
                     // stop the current scroll animation, but if this is
                     // the start of a fling, allow it to add to the current
                     // fling's velocity
                     mScroller.abortAnimation();
                     mTouchMode = TOUCH_DRAG_START_MODE;
+                    mConfirmMove = true;
                     mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
-                } else if (mShiftIsPressed) {
+                } else if (!inFullScreenMode() && mShiftIsPressed) {
                     mSelectX = mScrollX + (int) x;
                     mSelectY = mScrollY + (int) y;
                     mTouchMode = TOUCH_SELECT_MODE;
                     if (DebugFlags.WEB_VIEW) {
                         Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY);
                     }
-                    nativeMoveSelection(viewToContentX(mSelectX),
-                            viewToContentY(mSelectY), false);
+                    nativeMoveSelection(contentX, contentY, false);
                     mTouchSelection = mExtendSelection = true;
                     invalidate(); // draw the i-beam instead of the arrow
                 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
@@ -4593,15 +4624,17 @@
                     } else {
                         // commit the short press action for the previous tap
                         doShortPress();
-                        // continue, mTouchMode should be still TOUCH_INIT_MODE
+                        mTouchMode = TOUCH_INIT_MODE;
+                        mDeferTouchProcess = (!inFullScreenMode()
+                                && mForwardTouchEvents) ? hitFocusedPlugin(
+                                contentX, contentY) : false;
                     }
-                } else {
+                } else { // the normal case
                     mPreviewZoomOnly = false;
                     mTouchMode = TOUCH_INIT_MODE;
-                    mPreventDrag = mForwardTouchEvents ? PREVENT_DRAG_MAYBE_YES
-                            : PREVENT_DRAG_NO;
-                    mPreventLongPress = false;
-                    mPreventDoubleTap = false;
+                    mDeferTouchProcess = (!inFullScreenMode()
+                            && mForwardTouchEvents) ? hitFocusedPlugin(
+                            contentX, contentY) : false;
                     mWebViewCore.sendMessage(
                             EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
                     if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
@@ -4612,19 +4645,87 @@
                 // Trigger the link
                 if (mTouchMode == TOUCH_INIT_MODE
                         || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
-                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
-                            .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT);
+                    mPrivateHandler.sendEmptyMessageDelayed(
+                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
+                    mPrivateHandler.sendEmptyMessageDelayed(
+                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
+                    if (inFullScreenMode() || mDeferTouchProcess) {
+                        mPreventDefault = PREVENT_DEFAULT_YES;
+                    } else if (mForwardTouchEvents) {
+                        mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
+                    } else {
+                        mPreventDefault = PREVENT_DEFAULT_NO;
+                    }
+                    // pass the touch events from UI thread to WebCore thread
+                    if (shouldForwardTouchEvent()) {
+                        TouchEventData ted = new TouchEventData();
+                        ted.mAction = action;
+                        ted.mX = contentX;
+                        ted.mY = contentY;
+                        ted.mMetaState = ev.getMetaState();
+                        ted.mReprocess = mDeferTouchProcess;
+                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
+                        if (mDeferTouchProcess) {
+                            // still needs to set them for compute deltaX/Y
+                            mLastTouchX = x;
+                            mLastTouchY = y;
+                            break;
+                        }
+                        if (!inFullScreenMode()) {
+                            mPrivateHandler.sendMessageDelayed(mPrivateHandler
+                                    .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
+                                            action, 0), TAP_TIMEOUT);
+                        }
+                    }
                 }
                 startTouch(x, y, eventTime);
                 break;
             }
             case MotionEvent.ACTION_MOVE: {
-                if (mTouchMode == TOUCH_DONE_MODE) {
-                    // no dragging during scroll zoom animation
+                boolean firstMove = false;
+                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
+                        >= mTouchSlopSquare) {
+                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
+                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
+                    mConfirmMove = true;
+                    firstMove = true;
+                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
+                        mTouchMode = TOUCH_INIT_MODE;
+                    }
+                }
+                // pass the touch events from UI thread to WebCore thread
+                if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
+                        || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
+                    TouchEventData ted = new TouchEventData();
+                    ted.mAction = action;
+                    ted.mX = contentX;
+                    ted.mY = contentY;
+                    ted.mMetaState = ev.getMetaState();
+                    ted.mReprocess = mDeferTouchProcess;
+                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
+                    mLastSentTouchTime = eventTime;
+                    if (mDeferTouchProcess) {
+                        break;
+                    }
+                    if (firstMove && !inFullScreenMode()) {
+                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
+                                .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
+                                        action, 0), TAP_TIMEOUT);
+                    }
+                }
+                if (mTouchMode == TOUCH_DONE_MODE
+                        || mPreventDefault == PREVENT_DEFAULT_YES) {
+                    // no dragging during scroll zoom animation, or when prevent
+                    // default is yes
                     break;
                 }
+                if (mVelocityTracker == null) {
+                    Log.e(LOGTAG, "Got null mVelocityTracker when "
+                            + "mPreventDefault = " + mPreventDefault
+                            + " mDeferTouchProcess = " + mDeferTouchProcess
+                            + " mTouchMode = " + mTouchMode);
+                }
                 mVelocityTracker.addMovement(ev);
-
                 if (mTouchMode != TOUCH_DRAG_MODE) {
                     if (mTouchMode == TOUCH_SELECT_MODE) {
                         mSelectX = mScrollX + (int) x;
@@ -4632,48 +4733,20 @@
                         if (DebugFlags.WEB_VIEW) {
                             Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY);
                         }
-                        nativeMoveSelection(viewToContentX(mSelectX),
-                               viewToContentY(mSelectY), true);
+                        nativeMoveSelection(contentX, contentY, true);
                         invalidate();
                         break;
                     }
-                    if ((deltaX * deltaX + deltaY * deltaY) < mTouchSlopSquare) {
+                    if (!mConfirmMove) {
                         break;
                     }
-
-                    // pass the first ACTION_MOVE from UI thread to WebCore
-                    // thread after the distance is confirmed that it is a drag
-                    if (mFullScreenHolder == null && mForwardTouchEvents
-                            && mPreventDrag != PREVENT_DRAG_CANCEL) {
-                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-                        ted.mAction = action;
-                        ted.mX = viewToContentX((int) x + mScrollX);
-                        ted.mY = viewToContentY((int) y + mScrollY);
-                        ted.mEventTime = eventTime;
-                        ted.mMetaState = ev.getMetaState();
-                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-                        mLastSentTouchTime = eventTime;
-                    }
-
-                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
+                    if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
+                            || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
                         // track mLastTouchTime as we may need to do fling at
                         // ACTION_UP
                         mLastTouchTime = eventTime;
                         break;
                     }
-                    if (mTouchMode == TOUCH_SHORTPRESS_MODE
-                            || mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
-                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
-                    } else if (mTouchMode == TOUCH_INIT_MODE
-                            || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
-                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
-                    }
-                    if (mFullScreenHolder != null) {
-                        // in full screen mode, the WebView can't be panned.
-                        mTouchMode = TOUCH_DONE_MODE;
-                        break;
-                    }
-
                     // if it starts nearly horizontal or vertical, enforce it
                     int ax = Math.abs(deltaX);
                     int ay = Math.abs(deltaY);
@@ -4693,38 +4766,11 @@
                     deltaX = 0;
                     deltaY = 0;
 
-                    WebViewCore.reducePriority();
-                    if (!mDragFromTextInput) {
-                        nativeHideCursor();
-                    }
-                    WebSettings settings = getSettings();
-                    if (settings.supportZoom()
-                            && settings.getBuiltInZoomControls()
-                            && !mZoomButtonsController.isVisible()
-                            && mMinZoomScale < mMaxZoomScale) {
-                        mZoomButtonsController.setVisible(true);
-                        int count = settings.getDoubleTapToastCount();
-                        if (mInZoomOverview && count > 0) {
-                            settings.setDoubleTapToastCount(--count);
-                            Toast.makeText(mContext,
-                                    com.android.internal.R.string.double_tap_toast,
-                                    Toast.LENGTH_LONG).show();
-                        }
-                    }
-                } else {
-                    // pass the touch events from UI thread to WebCore thread
-                    if (mFullScreenHolder == null && mForwardTouchEvents
-                            && eventTime - mLastSentTouchTime > mCurrentTouchInterval
-                            && mPreventDrag != PREVENT_DRAG_CANCEL) {
-                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-                        ted.mAction = action;
-                        ted.mX = viewToContentX((int) x + mScrollX);
-                        ted.mY = viewToContentY((int) y + mScrollY);
-                        ted.mEventTime = eventTime;
-                        ted.mMetaState = ev.getMetaState();
-                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-                        mLastSentTouchTime = eventTime;
-                    }
+                    startDrag();
+                }
+
+                if (mDragTrackerHandler != null) {
+                    mDragTrackerHandler.dragTo(x, y);
                 }
 
                 // do pan
@@ -4772,9 +4818,6 @@
                         }
                     }
                     if ((deltaX | deltaY) != 0) {
-                        overscrollBy(deltaX, deltaY, mScrollX, mScrollY,
-                                computeMaxScrollX(), computeMaxScrollY(),
-                                getViewWidth() / 3, getViewHeight() / 3);
                         if (deltaX != 0) {
                             mLastTouchX = x;
                         }
@@ -4791,22 +4834,7 @@
                     mUserScroll = true;
                 }
 
-                if (!getSettings().getBuiltInZoomControls()) {
-                    boolean showPlusMinus = mMinZoomScale < mMaxZoomScale;
-                    if (mZoomControls != null && showPlusMinus) {
-                        if (mZoomControls.getVisibility() == View.VISIBLE) {
-                            mPrivateHandler.removeCallbacks(mZoomControlRunnable);
-                        } else {
-                            mZoomControls.show(showPlusMinus, false);
-                        }
-                        mPrivateHandler.postDelayed(mZoomControlRunnable,
-                                ZOOM_CONTROLS_TIMEOUT);
-                    }
-                }
-
-                if (mDragTrackerHandler != null) {
-                    mDragTrackerHandler.dragTo(x, y);
-                }
+                doDrag(deltaX, deltaY);
 
                 if (keepScrollBarsVisible) {
                     if (mHeldMotionless != MOTIONLESS_TRUE) {
@@ -4823,25 +4851,32 @@
                 break;
             }
             case MotionEvent.ACTION_UP: {
-                if (mDragTrackerHandler != null) {
-                    mDragTrackerHandler.stopDrag();
+                // pass the touch events from UI thread to WebCore thread
+                if (shouldForwardTouchEvent()) {
+                    TouchEventData ted = new TouchEventData();
+                    ted.mAction = action;
+                    ted.mX = contentX;
+                    ted.mY = contentY;
+                    ted.mMetaState = ev.getMetaState();
+                    ted.mReprocess = mDeferTouchProcess;
+                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
                 }
                 mLastTouchUpTime = eventTime;
                 switch (mTouchMode) {
                     case TOUCH_DOUBLE_TAP_MODE: // double tap
                         mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
-                        mTouchMode = TOUCH_DONE_MODE;
-                        if (mPreventDoubleTap) {
-                            WebViewCore.TouchEventData ted
-                                    = new WebViewCore.TouchEventData();
+                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
+                        if (inFullScreenMode() || mDeferTouchProcess) {
+                            TouchEventData ted = new TouchEventData();
                             ted.mAction = WebViewCore.ACTION_DOUBLETAP;
-                            ted.mX = viewToContentX((int) x + mScrollX);
-                            ted.mY = viewToContentY((int) y + mScrollY);
-                            ted.mEventTime = eventTime;
+                            ted.mX = contentX;
+                            ted.mY = contentY;
                             ted.mMetaState = ev.getMetaState();
+                            ted.mReprocess = mDeferTouchProcess;
                             mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-                        } else if (mFullScreenHolder == null) {
+                        } else if (mPreventDefault != PREVENT_DEFAULT_YES){
                             doDoubleTap();
+                            mTouchMode = TOUCH_DONE_MODE;
                         }
                         break;
                     case TOUCH_SELECT_MODE:
@@ -4853,20 +4888,15 @@
                     case TOUCH_SHORTPRESS_MODE:
                         mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
                         mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
-                        if ((deltaX * deltaX + deltaY * deltaY) > mTouchSlopSquare) {
+                        if (mConfirmMove) {
                             Log.w(LOGTAG, "Miss a drag as we are waiting for" +
                                     " WebCore's response for touch down.");
-                            if (mFullScreenHolder == null
+                            if (mPreventDefault != PREVENT_DEFAULT_YES
                                     && (computeMaxScrollX() > 0
                                             || computeMaxScrollY() > 0)) {
-                                // remove the pending TOUCH_EVENT and send a
-                                // cancel
-                                mWebViewCore
-                                        .removeMessages(EventHub.TOUCH_EVENT);
-                                WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-                                ted.mAction = MotionEvent.ACTION_CANCEL;
-                                mWebViewCore.sendMessage(EventHub.TOUCH_EVENT,
-                                        ted);
+                                // UI takes control back, cancel WebCore touch
+                                cancelWebCoreTouchEvent(contentX, contentY,
+                                        true);
                                 // we will not rewrite drag code here, but we
                                 // will try fling if it applies.
                                 WebViewCore.reducePriority();
@@ -4875,20 +4905,12 @@
                                 break;
                             }
                         } else {
-                            // mPreventDrag can be PREVENT_DRAG_MAYBE_YES in
-                            // TOUCH_INIT_MODE. To give WebCoreThread a little
-                            // more time to send PREVENT_TOUCH_ID, we check
-                            // again in responding RELEASE_SINGLE_TAP.
-                            if (mPreventDrag != PREVENT_DRAG_YES) {
-                                if (mTouchMode == TOUCH_INIT_MODE) {
-                                    mPrivateHandler.sendMessageDelayed(
-                                            mPrivateHandler.obtainMessage(
-                                            RELEASE_SINGLE_TAP),
-                                            ViewConfiguration.getDoubleTapTimeout());
-                                } else {
-                                    mTouchMode = TOUCH_DONE_MODE;
-                                    doShortPress();
-                                }
+                            if (mTouchMode == TOUCH_INIT_MODE) {
+                                mPrivateHandler.sendEmptyMessageDelayed(
+                                        RELEASE_SINGLE_TAP, ViewConfiguration
+                                                .getDoubleTapTimeout());
+                            } else {
+                                doShortPress();
                             }
                             break;
                         }
@@ -4901,6 +4923,13 @@
                         // if the user waits a while w/o moving before the
                         // up, we don't want to do a fling
                         if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
+                            if (mVelocityTracker == null) {
+                                Log.e(LOGTAG, "Got null mVelocityTracker when "
+                                        + "mPreventDefault = "
+                                        + mPreventDefault
+                                        + " mDeferTouchProcess = "
+                                        + mDeferTouchProcess);
+                            }
                             mVelocityTracker.addMovement(ev);
                             doFling();
                             break;
@@ -4914,34 +4943,38 @@
                         mLastVelocity = 0;
                         WebViewCore.resumePriority();
                         break;
-                    case TOUCH_DRAG_START_MODE:
-                    case TOUCH_DONE_MODE:
-                        // do nothing
-                        break;
                 }
-                // we also use mVelocityTracker == null to tell us that we are
-                // not "moving around", so we can take the slower/prettier
-                // mode in the drawing code
-                if (mVelocityTracker != null) {
-                    mVelocityTracker.recycle();
-                    mVelocityTracker = null;
-                }
+                stopTouch();
                 break;
             }
             case MotionEvent.ACTION_CANCEL: {
-                cancelTouch();
                 if (mTouchMode == TOUCH_DRAG_MODE) {
-                    if (mScroller.springback(mScrollX, mScrollY, 0,
-                            computeMaxScrollX(), 0, computeMaxScrollY())) {
-                        invalidate();
-                    }
+                    mScroller.springback(mScrollX, mScrollY, 0,
+                            computeMaxScrollX(), 0, computeMaxScrollY());
+                    invalidate();
                 }
+                cancelWebCoreTouchEvent(contentX, contentY, false);
+                cancelTouch();
                 break;
             }
         }
         return true;
     }
 
+    private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
+        if (shouldForwardTouchEvent()) {
+            if (removeEvents) {
+                mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
+            }
+            TouchEventData ted = new TouchEventData();
+            ted.mX = x;
+            ted.mY = y;
+            ted.mAction = MotionEvent.ACTION_CANCEL;
+            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
+            mPreventDefault = PREVENT_DEFAULT_IGNORE;
+        }
+    }
+
     private void startTouch(float x, float y, long eventTime) {
         // Remember where the motion event started
         mLastTouchX = x;
@@ -4954,6 +4987,60 @@
         }
     }
 
+    private void startDrag() {
+        WebViewCore.reducePriority();
+        if (!mDragFromTextInput) {
+            nativeHideCursor();
+        }
+        WebSettings settings = getSettings();
+        if (settings.supportZoom()
+                && settings.getBuiltInZoomControls()
+                && !mZoomButtonsController.isVisible()
+                && mMinZoomScale < mMaxZoomScale) {
+            mZoomButtonsController.setVisible(true);
+            int count = settings.getDoubleTapToastCount();
+            if (mInZoomOverview && count > 0) {
+                settings.setDoubleTapToastCount(--count);
+                Toast.makeText(mContext,
+                        com.android.internal.R.string.double_tap_toast,
+                        Toast.LENGTH_LONG).show();
+            }
+        }
+    }
+
+    private void doDrag(int deltaX, int deltaY) {
+        if ((deltaX | deltaY) != 0) {
+            overscrollBy(deltaX, deltaY, mScrollX, mScrollY,
+                    computeMaxScrollX(), computeMaxScrollY(),
+                    getViewWidth() / 3, getViewHeight() / 3);
+        }
+        if (!getSettings().getBuiltInZoomControls()) {
+            boolean showPlusMinus = mMinZoomScale < mMaxZoomScale;
+            if (mZoomControls != null && showPlusMinus) {
+                if (mZoomControls.getVisibility() == View.VISIBLE) {
+                    mPrivateHandler.removeCallbacks(mZoomControlRunnable);
+                } else {
+                    mZoomControls.show(showPlusMinus, false);
+                }
+                mPrivateHandler.postDelayed(mZoomControlRunnable,
+                        ZOOM_CONTROLS_TIMEOUT);
+            }
+        }
+    }
+
+    private void stopTouch() {
+        if (mDragTrackerHandler != null) {
+            mDragTrackerHandler.stopDrag();
+        }
+        // we also use mVelocityTracker == null to tell us that we are
+        // not "moving around", so we can take the slower/prettier
+        // mode in the drawing code
+        if (mVelocityTracker != null) {
+            mVelocityTracker.recycle();
+            mVelocityTracker = null;
+        }
+    }
+
     private void cancelTouch() {
         if (mDragTrackerHandler != null) {
             mDragTrackerHandler.stopDrag();
@@ -5573,6 +5660,10 @@
         if (mNativeClass == 0) {
             return;
         }
+        if (mPreventDefault == PREVENT_DEFAULT_YES) {
+            return;
+        }
+        mTouchMode = TOUCH_DONE_MODE;
         switchOutDrawHistory();
         // mLastTouchX and mLastTouchY are the point in the current viewport
         int contentX = viewToContentX((int) mLastTouchX + mScrollX);
@@ -5861,9 +5952,17 @@
         public void handleMessage(Message msg) {
             // exclude INVAL_RECT_MSG_ID since it is frequently output
             if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
-                Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what
-                        > FIND_AGAIN ? Integer.toString(msg.what)
-                        : HandlerDebugString[msg.what - REMEMBER_PASSWORD]);
+                if (msg.what >= FIRST_PRIVATE_MSG_ID
+                        && msg.what <= LAST_PRIVATE_MSG_ID) {
+                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
+                            - FIRST_PRIVATE_MSG_ID]);
+                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
+                        && msg.what <= LAST_PACKAGE_MSG_ID) {
+                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
+                            - FIRST_PACKAGE_MSG_ID]);
+                } else {
+                    Log.v(LOGTAG, Integer.toString(msg.what));
+                }
             }
             if (mWebViewCore == null) {
                 // after WebView's destroy() is called, skip handling messages.
@@ -5884,70 +5983,57 @@
                     ((Message) msg.obj).sendToTarget();
                     break;
                 }
-                case SWITCH_TO_SHORTPRESS: {
-                    // if mPreventDrag is not confirmed, cancel it so that it
-                    // won't block panning the page.
-                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
-                        mPreventDrag = PREVENT_DRAG_CANCEL;
-                        mPreventLongPress = false;
-                        mPreventDoubleTap = false;
-                        // remove the pending TOUCH_EVENT and send a cancel
-                        mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
-                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-                        ted.mAction = MotionEvent.ACTION_CANCEL;
-                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
+                case PREVENT_DEFAULT_TIMEOUT: {
+                    // if timeout happens, cancel it so that it won't block UI
+                    // to continue handling touch events
+                    if ((msg.arg1 == MotionEvent.ACTION_DOWN
+                            && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
+                            || (msg.arg1 == MotionEvent.ACTION_MOVE
+                            && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
+                        cancelWebCoreTouchEvent(
+                                viewToContentX((int) mLastTouchX + mScrollX),
+                                viewToContentY((int) mLastTouchY + mScrollY),
+                                true);
                     }
+                    break;
+                }
+                case SWITCH_TO_SHORTPRESS: {
                     if (mTouchMode == TOUCH_INIT_MODE) {
-                        mTouchMode = mFullScreenHolder == null
-                                ? TOUCH_SHORTPRESS_START_MODE
-                                        : TOUCH_SHORTPRESS_MODE;
-                        updateSelection();
+                        if (mPreventDefault != PREVENT_DEFAULT_YES) {
+                            mTouchMode = TOUCH_SHORTPRESS_START_MODE;
+                            updateSelection();
+                        } else {
+                            // set to TOUCH_SHORTPRESS_MODE so that it won't
+                            // trigger double tap any more
+                            mTouchMode = TOUCH_SHORTPRESS_MODE;
+                        }
                     } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
                         mTouchMode = TOUCH_DONE_MODE;
                     }
                     break;
                 }
                 case SWITCH_TO_LONGPRESS: {
-                    if (mPreventLongPress) {
-                        mTouchMode = TOUCH_DONE_MODE;
-                        WebViewCore.TouchEventData ted
-                                = new WebViewCore.TouchEventData();
+                    if (inFullScreenMode() || mDeferTouchProcess) {
+                        TouchEventData ted = new TouchEventData();
                         ted.mAction = WebViewCore.ACTION_LONGPRESS;
                         ted.mX = viewToContentX((int) mLastTouchX + mScrollX);
                         ted.mY = viewToContentY((int) mLastTouchY + mScrollY);
-                        ted.mEventTime = SystemClock.uptimeMillis();
-                        // metaState for long press is tricky. Should it be the state
-                        // when the press started or when the press was released? Or
-                        // some intermediary key state? For simplicity for now, we
-                        // don't set it.
+                        // metaState for long press is tricky. Should it be the
+                        // state when the press started or when the press was
+                        // released? Or some intermediary key state? For
+                        // simplicity for now, we don't set it.
                         ted.mMetaState = 0;
+                        ted.mReprocess = mDeferTouchProcess;
                         mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-                    } else if (mPreventDrag != PREVENT_DRAG_YES) {
+                    } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
                         mTouchMode = TOUCH_DONE_MODE;
-                        if (mFullScreenHolder == null) {
-                            performLongClick();
-                            rebuildWebTextView();
-                        }
+                        performLongClick();
+                        rebuildWebTextView();
                     }
                     break;
                 }
                 case RELEASE_SINGLE_TAP: {
-                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
-                        // if mPreventDrag is not confirmed, cancel it so that
-                        // it won't block panning the page.
-                        mPreventDrag = PREVENT_DRAG_CANCEL;
-                        mPreventLongPress = false;
-                        mPreventDoubleTap = false;
-                        // remove the pending TOUCH_EVENT and send a cancel
-                        mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
-                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
-                        ted.mAction = MotionEvent.ACTION_CANCEL;
-                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
-                    }
-                    if (mPreventDrag != PREVENT_DRAG_YES) {
-                        mTouchMode = TOUCH_DONE_MODE;
-                        doShortPress();
-                    }
+                    doShortPress();
                     break;
                 }
                 case SCROLL_BY_MSG_ID:
@@ -6193,23 +6279,81 @@
                     break;
 
                 case PREVENT_TOUCH_ID:
-                    if (msg.arg1 == MotionEvent.ACTION_DOWN) {
-                        // dont override if mPreventDrag has been set to no due
-                        // to time out
-                        if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
-                            mPreventDrag = (msg.arg2 & TOUCH_PREVENT_DRAG)
-                                    == TOUCH_PREVENT_DRAG ? PREVENT_DRAG_YES
-                                    : PREVENT_DRAG_NO;
-                            if (mPreventDrag == PREVENT_DRAG_YES) {
-                                mTouchMode = TOUCH_DONE_MODE;
-                            } else {
-                                mPreventLongPress =
-                                        (msg.arg2 & TOUCH_PREVENT_LONGPRESS)
-                                        == TOUCH_PREVENT_LONGPRESS;
-                                mPreventDoubleTap =
-                                        (msg.arg2 & TOUCH_PREVENT_DOUBLETAP)
-                                        == TOUCH_PREVENT_DOUBLETAP;
+                    if (inFullScreenMode()) {
+                        break;
+                    }
+                    if (msg.obj == null) {
+                        if (msg.arg1 == MotionEvent.ACTION_DOWN
+                                && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
+                            // if prevent default is called from WebCore, UI
+                            // will not handle the rest of the touch events any
+                            // more.
+                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
+                                    : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
+                        } else if (msg.arg1 == MotionEvent.ACTION_MOVE
+                                && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
+                            // the return for the first ACTION_MOVE will decide
+                            // whether UI will handle touch or not. Currently no
+                            // support for alternating prevent default
+                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
+                                    : PREVENT_DEFAULT_NO;
+                        }
+                    } else if (msg.arg2 == 0) {
+                        // prevent default is not called in WebCore, so the
+                        // message needs to be reprocessed in UI
+                        TouchEventData ted = (TouchEventData) msg.obj;
+                        switch (ted.mAction) {
+                            case MotionEvent.ACTION_DOWN:
+                                mLastDeferTouchX = contentToViewX(ted.mX)
+                                        - mScrollX;
+                                mLastDeferTouchY = contentToViewY(ted.mY)
+                                        - mScrollY;
+                                mDeferTouchMode = TOUCH_INIT_MODE;
+                                break;
+                            case MotionEvent.ACTION_MOVE: {
+                                // no snapping in defer process
+                                int x = contentToViewX(ted.mX) - mScrollX;
+                                int y = contentToViewY(ted.mY) - mScrollY;
+                                if (mDeferTouchMode != TOUCH_DRAG_MODE) {
+                                    mDeferTouchMode = TOUCH_DRAG_MODE;
+                                    mLastDeferTouchX = x;
+                                    mLastDeferTouchY = y;
+                                    startDrag();
+                                }
+                                doDrag((int) (mLastDeferTouchX - x),
+                                        (int) (mLastDeferTouchY - y));
+                                mLastDeferTouchX = x;
+                                mLastDeferTouchY = y;
+                                break;
                             }
+                            case MotionEvent.ACTION_UP:
+                            case MotionEvent.ACTION_CANCEL:
+                                if (mDeferTouchMode == TOUCH_DRAG_MODE) {
+                                    // no fling in defer process
+                                    mScroller.springback(mScrollX, mScrollY, 0,
+                                            computeMaxScrollX(), 0,
+                                            computeMaxScrollY());
+                                    invalidate();
+                                    WebViewCore.resumePriority();
+                                }
+                                mDeferTouchMode = TOUCH_DONE_MODE;
+                                break;
+                            case WebViewCore.ACTION_DOUBLETAP:
+                                // doDoubleTap() needs mLastTouchX/Y as anchor
+                                mLastTouchX = contentToViewX(ted.mX) - mScrollX;
+                                mLastTouchY = contentToViewY(ted.mY) - mScrollY;
+                                doDoubleTap();
+                                mDeferTouchMode = TOUCH_DONE_MODE;
+                                break;
+                            case WebViewCore.ACTION_LONGPRESS:
+                                HitTestResult hitTest = getHitTestResult();
+                                if (hitTest != null && hitTest.mType
+                                        != HitTestResult.UNKNOWN_TYPE) {
+                                    performLongClick();
+                                    rebuildWebTextView();
+                                }
+                                mDeferTouchMode = TOUCH_DONE_MODE;
+                                break;
                         }
                     }
                     break;
@@ -6253,7 +6397,7 @@
                     WebViewCore.PluginFullScreenData data
                             = (WebViewCore.PluginFullScreenData) msg.obj;
                     if (data.mNpp != 0 && data.mView != null) {
-                        if (mFullScreenHolder != null) {
+                        if (inFullScreenMode()) {
                             Log.w(LOGTAG,
                                     "Should not have another full screen.");
                             mFullScreenHolder.dismiss();
@@ -6264,14 +6408,14 @@
                         // embedded mode, we have to remove the
                         // AbsoluteLayout.LayoutParams set by embedded mode to
                         // ViewGroup.LayoutParams before adding it to the dialog
-                        data.mView.setLayoutParams(new ViewGroup.LayoutParams(
+                        data.mView.setLayoutParams(new FrameLayout.LayoutParams(
                                 ViewGroup.LayoutParams.FILL_PARENT,
                                 ViewGroup.LayoutParams.FILL_PARENT));
                         mFullScreenHolder.setContentView(data.mView);
                         mFullScreenHolder.setCancelable(false);
                         mFullScreenHolder.setCanceledOnTouchOutside(false);
                         mFullScreenHolder.show();
-                    } else if (mFullScreenHolder == null) {
+                    } else if (!inFullScreenMode()) {
                         // this may happen if user dismisses the fullscreen and
                         // then the WebCore re-position message finally reached
                         // the UI thread.
@@ -6325,7 +6469,7 @@
                     break;
 
                 case HIDE_FULLSCREEN:
-                    if (mFullScreenHolder != null) {
+                    if (inFullScreenMode()) {
                         mFullScreenHolder.dismiss();
                         mFullScreenHolder = null;
                     }
diff --git a/core/java/android/webkit/WebViewCore.java b/core/java/android/webkit/WebViewCore.java
index b339015..27c7208 100644
--- a/core/java/android/webkit/WebViewCore.java
+++ b/core/java/android/webkit/WebViewCore.java
@@ -515,7 +515,8 @@
     private native void nativeTouchUp(int touchGeneration,
             int framePtr, int nodePtr, int x, int y);
 
-    private native int nativeHandleTouchEvent(int action, int x, int y, long time, int metaState);
+    private native boolean nativeHandleTouchEvent(int action, int x, int y,
+            int metaState);
 
     private native void nativeUpdateFrameCache();
 
@@ -705,8 +706,8 @@
         int mAction;
         int mX;
         int mY;
-        long mEventTime;
         int mMetaState;
+        boolean mReprocess;
     }
 
     static class GeolocationPermissionsData {
@@ -1160,9 +1161,11 @@
                             TouchEventData ted = (TouchEventData) msg.obj;
                             Message.obtain(
                                     mWebView.mPrivateHandler,
-                                    WebView.PREVENT_TOUCH_ID, ted.mAction,
+                                    WebView.PREVENT_TOUCH_ID,
+                                    ted.mAction,
                                     nativeHandleTouchEvent(ted.mAction, ted.mX,
-                                    ted.mY, ted.mEventTime, ted.mMetaState)).sendToTarget();
+                                            ted.mY, ted.mMetaState) ? 1 : 0,
+                                    ted.mReprocess ? ted : null).sendToTarget();
                             break;
                         }
 
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index e87455c..a1c3fa2 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -1641,7 +1641,7 @@
                 mResurrectToPosition = mSelectedPosition;
             }
         } else {
-            if (mFiltered) {
+            if (mFiltered && !mPopupHidden) {
                 // Show the type filter only if a filter is in effect
                 showPopup();
             }
@@ -2773,7 +2773,7 @@
             final int lastPos = firstPos + getChildCount() - 1;
             
             int viewTravelCount = 0;
-            if (position < firstPos) {
+            if (position <= firstPos) {
                 final int boundPosFromLast = lastPos - boundPosition;
                 if (boundPosFromLast < 1) {
                     // Moving would shift our bound position off the screen. Abort.
@@ -2789,7 +2789,7 @@
                     viewTravelCount = posTravel;
                     mMode = MOVE_UP_POS;
                 }
-            } else if (position > lastPos) {
+            } else if (position >= lastPos) {
                 final int boundPosFromFirst = boundPosition - firstPos;
                 if (boundPosFromFirst < 1) {
                     // Moving would shift our bound position off the screen. Abort.
@@ -3510,7 +3510,6 @@
         if (mPopup != null) {
             mPopup.dismiss();
         }
-        mPopupHidden = false;
     }
 
     /**
diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java
index 1a9c0df5..0594844 100644
--- a/core/java/android/widget/ListView.java
+++ b/core/java/android/widget/ListView.java
@@ -117,6 +117,9 @@
 
     Drawable mDivider;
     int mDividerHeight;
+    
+    Drawable mOverscrollHeader;
+    Drawable mOverscrollFooter;
 
     private boolean mIsCacheColorOpaque;
     private boolean mDividerIsOpaque;
@@ -171,6 +174,16 @@
             // If a divider is specified use its intrinsic height for divider height
             setDivider(d);
         }
+        
+        final Drawable osHeader = a.getDrawable(com.android.internal.R.styleable.ListView_overscrollHeader);
+        if (osHeader != null) {
+            setOverscrollHeader(osHeader);
+        }
+        
+        final Drawable osFooter = a.getDrawable(com.android.internal.R.styleable.ListView_overscrollFooter);
+        if (osFooter != null) {
+            setOverscrollFooter(osFooter);
+        }
 
         // Use the height specified, zero being the default
         final int dividerHeight = a.getDimensionPixelSize(
@@ -2934,12 +2947,51 @@
         super.setCacheColorHint(color);
     }
 
+    void drawOverscrollHeader(Canvas canvas, Drawable drawable, Rect bounds) {
+        final int height = drawable.getMinimumHeight();
+
+        canvas.save();
+        canvas.clipRect(bounds);
+
+        final int span = bounds.bottom - bounds.top;
+        if (span < height) {
+            bounds.top = bounds.bottom - height; 
+        }
+
+        drawable.setBounds(bounds);
+        drawable.draw(canvas);
+
+        canvas.restore();
+    }
+
+    void drawOverscrollFooter(Canvas canvas, Drawable drawable, Rect bounds) {
+        final int height = drawable.getMinimumHeight();
+
+        canvas.save();
+        canvas.clipRect(bounds);
+
+        final int span = bounds.bottom - bounds.top;
+        if (span < height) {
+            bounds.bottom = bounds.top + height;
+        }
+
+        drawable.setBounds(bounds);
+        drawable.draw(canvas);
+
+        canvas.restore();
+    }
+
     @Override
     protected void dispatchDraw(Canvas canvas) {
         // Draw the dividers
         final int dividerHeight = mDividerHeight;
+        final Drawable overscrollHeader = mOverscrollHeader;
+        final Drawable overscrollFooter = mOverscrollFooter;
+        final boolean drawOverscrollHeader = overscrollHeader != null;
+        final boolean drawOverscrollFooter = overscrollFooter != null;
+        final boolean drawDividers = dividerHeight > 0 && mDivider != null;
 
-        if (dividerHeight > 0 && mDivider != null) {
+        if (drawDividers || drawOverscrollHeader || drawOverscrollFooter) {
             // Only modify the top and bottom in the loop, we set the left and right here
             final Rect bounds = mTempRect;
             bounds.left = mPaddingLeft;
@@ -2947,7 +2999,8 @@
 
             final int count = getChildCount();
             final int headerCount = mHeaderViewInfos.size();
-            final int footerLimit = mItemCount - mFooterViewInfos.size() - 1;
+            final int itemCount = mItemCount;
+            final int footerLimit = itemCount - mFooterViewInfos.size() - 1;
             final boolean headerDividers = mHeaderDividersEnabled;
             final boolean footerDividers = mFooterDividersEnabled;
             final int first = mFirstPosition;
@@ -2957,7 +3010,7 @@
             // fill a rect where the dividers would be for non-selectable items
             // If the list is opaque and the background is also opaque, we don't
             // need to draw anything since the background will do it for us
-            final boolean fillForMissingDividers = isOpaque() && !super.isOpaque();
+            final boolean fillForMissingDividers = drawDividers && isOpaque() && !super.isOpaque();
 
             if (fillForMissingDividers && mDividerPaint == null && mIsCacheColorOpaque) {
                 mDividerPaint = new Paint();
@@ -2965,15 +3018,22 @@
             }
             final Paint paint = mDividerPaint;
 
+            final int listBottom = mBottom - mTop - mListPadding.bottom + mScrollY;
             if (!mStackFromBottom) {
-                int bottom;
-                int listBottom = mBottom - mTop - mListPadding.bottom + mScrollY;
+                int bottom = 0;
                 
-                // Draw top divider for overscroll
-                if (count > 0 && mScrollY < 0) {
-                    bounds.bottom = 0;
-                    bounds.top = -dividerHeight;
-                    drawDivider(canvas, bounds, -1);
+                // Draw top divider or header for overscroll
+                final int scrollY = mScrollY;
+                if (count > 0 && scrollY < 0) {
+                    if (drawOverscrollHeader) {
+                        bounds.bottom = 0;
+                        bounds.top = scrollY;
+                        drawOverscrollHeader(canvas, overscrollHeader, bounds);
+                    } else if (drawDividers) {
+                        bounds.bottom = 0;
+                        bounds.top = -dividerHeight;
+                        drawDivider(canvas, bounds, -1);
+                    }
                 }
 
                 for (int i = 0; i < count; i++) {
@@ -2982,7 +3042,8 @@
                         View child = getChildAt(i);
                         bottom = child.getBottom();
                         // Don't draw dividers next to items that are not enabled
-                        if (bottom < listBottom) {
+                        if (drawDividers &&
+                                (bottom < listBottom && !(drawOverscrollFooter && i == count - 1))) {
                             if ((areAllItemsSelectable ||
                                     (adapter.isEnabled(first + i) && (i == count - 1 ||
                                             adapter.isEnabled(first + i + 1))))) {
@@ -2997,17 +3058,34 @@
                         }
                     }
                 }
+                
+                final int overFooterBottom = mBottom + mScrollY;
+                if (drawOverscrollFooter && first + count == itemCount &&
+                        overFooterBottom > bottom) {
+                    bounds.top = bottom;
+                    bounds.bottom = overFooterBottom;
+                    drawOverscrollFooter(canvas, overscrollFooter, bounds);
+                }
             } else {
                 int top;
                 int listTop = mListPadding.top;
 
-                for (int i = 0; i < count; i++) {
+                final int scrollY = mScrollY;
+                
+                if (count > 0 && drawOverscrollHeader) {
+                    bounds.top = scrollY;
+                    bounds.bottom = getChildAt(0).getTop();
+                    drawOverscrollHeader(canvas, overscrollHeader, bounds);
+                }
+
+                final int start = drawOverscrollHeader ? 1 : 0;
+                for (int i = start; i < count; i++) {
                     if ((headerDividers || first + i >= headerCount) &&
                             (footerDividers || first + i < footerLimit)) {
                         View child = getChildAt(i);
                         top = child.getTop();
                         // Don't draw dividers next to items that are not enabled
-                        if (top > listTop) {
+                        if (drawDividers && top > listTop) {
                             if ((areAllItemsSelectable ||
                                     (adapter.isEnabled(first + i) && (i == count - 1 ||
                                             adapter.isEnabled(first + i + 1))))) {
@@ -3026,6 +3104,19 @@
                         }
                     }
                 }
+                
+                if (count > 0 && scrollY > 0) {
+                    if (drawOverscrollFooter) {
+                        final int absListBottom = mBottom;
+                        bounds.top = absListBottom;
+                        bounds.bottom = absListBottom + scrollY;
+                        drawOverscrollFooter(canvas, overscrollFooter, bounds);
+                    } else if (drawDividers) {
+                        bounds.top = listBottom;
+                        bounds.bottom = listBottom + dividerHeight;
+                        drawDivider(canvas, bounds, -1);
+                    }
+                }
             }
         }
 
@@ -3132,6 +3223,45 @@
         mFooterDividersEnabled = footerDividersEnabled;
         invalidate();
     }
+    
+    /**
+     * Sets the drawable that will be drawn above all other list content.
+     * This area can become visible when the user overscrolls the list.
+     * 
+     * @param header The drawable to use
+     */
+    public void setOverscrollHeader(Drawable header) {
+        mOverscrollHeader = header;
+        if (mScrollY < 0) {
+            invalidate();
+        }
+    }
+    
+    /**
+     * @return The drawable that will be drawn above all other list content
+     */
+    public Drawable getOverscrollHeader() {
+        return mOverscrollHeader;
+    }
+    
+    /**
+     * Sets the drawable that will be drawn below all other list content.
+     * This area can become visible when the user overscrolls the list,
+     * or when the list's content does not fully fill the container area.
+     * 
+     * @param footer The drawable to use
+     */
+    public void setOverscrollFooter(Drawable footer) {
+        mOverscrollFooter = footer;
+        invalidate();
+    }
+    
+    /**
+     * @return The drawable that will be drawn below all other list content
+     */
+    public Drawable getOverscrollFooter() {
+        return mOverscrollFooter;
+    }
 
     @Override
     protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
@@ -3480,10 +3610,41 @@
      * @return A new array which contains the id of each checked item in the
      *         list.
      *         
-     * @deprecated Use {@link #getCheckedItemIds()} instead. 
+     * @deprecated Use {@link #getCheckedItemIds()} instead.
      */
     public long[] getCheckItemIds() {
-        return getCheckedItemIds();
+        // Use new behavior that correctly handles stable ID mapping.
+        if (mAdapter != null && mAdapter.hasStableIds()) {
+            return getCheckedItemIds();
+        }
+
+        // Old behavior was buggy, but would sort of work for adapters without stable IDs.
+        // Fall back to it to support legacy apps.
+        if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null && mAdapter != null) {
+            final SparseBooleanArray states = mCheckStates;
+            final int count = states.size();
+            final long[] ids = new long[count];
+            final ListAdapter adapter = mAdapter;
+
+            int checkedCount = 0;
+            for (int i = 0; i < count; i++) {
+                if (states.valueAt(i)) {
+                    ids[checkedCount++] = adapter.getItemId(states.keyAt(i));
+                }
+            }
+
+            // Trim array if needed. mCheckStates may contain false values
+            // resulting in checkedCount being smaller than count.
+            if (checkedCount == count) {
+                return ids;
+            } else {
+                final long[] result = new long[checkedCount];
+                System.arraycopy(ids, 0, result, 0, checkedCount);
+
+                return result;
+            }
+        }
+        return new long[0];
     }
     
     /**
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 7b21be5..64c9c99 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -6989,6 +6989,10 @@
 
     @Override
     public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
+        if (!isShown()) {
+            return false;
+        }
+
         final boolean isPassword = isPasswordInputType(mInputType);
 
         if (!isPassword) {
diff --git a/core/java/android/widget/VideoView.java b/core/java/android/widget/VideoView.java
index fb8b5aa..ded0559 100644
--- a/core/java/android/widget/VideoView.java
+++ b/core/java/android/widget/VideoView.java
@@ -291,7 +291,7 @@
                 mCanSeekForward = !data.has(Metadata.SEEK_FORWARD_AVAILABLE)
                         || data.getBoolean(Metadata.SEEK_FORWARD_AVAILABLE);
             } else {
-                mCanPause = mCanSeekForward = mCanSeekForward = true;
+                mCanPause = mCanSeekBack = mCanSeekForward = true;
             }
 
             if (mOnPreparedListener != null) {
diff --git a/core/java/com/android/internal/app/ShutdownThread.java b/core/java/com/android/internal/app/ShutdownThread.java
index 37898a1..51cd0f8 100644
--- a/core/java/com/android/internal/app/ShutdownThread.java
+++ b/core/java/com/android/internal/app/ShutdownThread.java
@@ -28,12 +28,13 @@
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.os.Handler;
+import android.os.Power;
 import android.os.PowerManager;
 import android.os.RemoteException;
-import android.os.Power;
 import android.os.ServiceManager;
 import android.os.SystemClock;
 import android.os.storage.IMountService;
+import android.os.storage.IMountShutdownObserver;
 
 import com.android.internal.telephony.ITelephony;
 import android.util.Log;
@@ -46,16 +47,20 @@
     private static final int PHONE_STATE_POLL_SLEEP_MSEC = 500;
     // maximum time we wait for the shutdown broadcast before going on.
     private static final int MAX_BROADCAST_TIME = 10*1000;
+    private static final int MAX_SHUTDOWN_WAIT_TIME = 20*1000;
     
     // state tracking
     private static Object sIsStartedGuard = new Object();
     private static boolean sIsStarted = false;
     
+    private static boolean mReboot;
+    private static String mRebootReason;
+
     // static instance of this thread
     private static final ShutdownThread sInstance = new ShutdownThread();
     
-    private final Object mBroadcastDoneSync = new Object();
-    private boolean mBroadcastDone;
+    private final Object mActionDoneSync = new Object();
+    private boolean mActionDone;
     private Context mContext;
     private PowerManager mPowerManager;
     private PowerManager.WakeLock mWakeLock;
@@ -64,12 +69,13 @@
     private ShutdownThread() {
     }
  
-    /** 
+    /**
      * Request a clean shutdown, waiting for subsystems to clean up their
      * state etc.  Must be called from a Looper thread in which its UI
      * is shown.
-     * 
+     *
      * @param context Context used to display the shutdown progress dialog.
+     * @param confirm true if user confirmation is needed before shutting down.
      */
     public static void shutdown(final Context context, boolean confirm) {
         // ensure that only one thread is trying to power down.
@@ -106,6 +112,21 @@
         }
     }
 
+    /**
+     * Request a clean shutdown, waiting for subsystems to clean up their
+     * state etc.  Must be called from a Looper thread in which its UI
+     * is shown.
+     *
+     * @param context Context used to display the shutdown progress dialog.
+     * @param reason code to pass to the kernel (e.g. "recovery"), or null.
+     * @param confirm true if user confirmation is needed before shutting down.
+     */
+    public static void reboot(final Context context, String reason, boolean confirm) {
+        mReboot = true;
+        mRebootReason = reason;
+        shutdown(context, confirm);
+    }
+
     private static void beginShutdownSequence(Context context) {
         synchronized (sIsStartedGuard) {
             sIsStarted = true;
@@ -145,13 +166,13 @@
         sInstance.start();
     }
 
-    void broadcastDone() {
-        synchronized (mBroadcastDoneSync) {
-            mBroadcastDone = true;
-            mBroadcastDoneSync.notifyAll();
+    void actionDone() {
+        synchronized (mActionDoneSync) {
+            mActionDone = true;
+            mActionDoneSync.notifyAll();
         }
     }
-    
+
     /**
      * Makes sure we handle the shutdown gracefully.
      * Shuts off power regardless of radio and bluetooth state if the alloted time has passed.
@@ -163,27 +184,27 @@
         BroadcastReceiver br = new BroadcastReceiver() {
             @Override public void onReceive(Context context, Intent intent) {
                 // We don't allow apps to cancel this, so ignore the result.
-                broadcastDone();
+                actionDone();
             }
         };
         
         Log.i(TAG, "Sending shutdown broadcast...");
         
         // First send the high-level shut down broadcast.
-        mBroadcastDone = false;
+        mActionDone = false;
         mContext.sendOrderedBroadcast(new Intent(Intent.ACTION_SHUTDOWN), null,
                 br, mHandler, 0, null, null);
         
         final long endTime = System.currentTimeMillis() + MAX_BROADCAST_TIME;
-        synchronized (mBroadcastDoneSync) {
-            while (!mBroadcastDone) {
+        synchronized (mActionDoneSync) {
+            while (!mActionDone) {
                 long delay = endTime - System.currentTimeMillis();
                 if (delay <= 0) {
                     Log.w(TAG, "Shutdown broadcast timed out");
                     break;
                 }
                 try {
-                    mBroadcastDoneSync.wait(delay);
+                    mActionDoneSync.wait(delay);
                 } catch (InterruptedException e) {
                 }
             }
@@ -262,17 +283,50 @@
         }
 
         // Shutdown MountService to ensure media is in a safe state
-        try {
-            if (mount != null) {
-                mount.shutdown();
-            } else {
-                Log.w(TAG, "MountService unavailable for shutdown");
+        IMountShutdownObserver observer = new IMountShutdownObserver.Stub() {
+            public void onShutDownComplete(int statusCode) throws RemoteException {
+                Log.w(TAG, "Result code " + statusCode + " from MountService.shutdown");
+                actionDone();
             }
-        } catch (Exception e) {
-            Log.e(TAG, "Exception during MountService shutdown", e);
+        };
+
+        Log.i(TAG, "Shutting down MountService");
+        // Set initial variables and time out time.
+        mActionDone = false;
+        final long endShutTime = System.currentTimeMillis() + MAX_SHUTDOWN_WAIT_TIME;
+        synchronized (mActionDoneSync) {
+            try {
+                if (mount != null) {
+                    mount.shutdown(observer);
+                } else {
+                    Log.w(TAG, "MountService unavailable for shutdown");
+                }
+            } catch (Exception e) {
+                Log.e(TAG, "Exception during MountService shutdown", e);
+            }
+            while (!mActionDone) {
+                long delay = endShutTime - System.currentTimeMillis();
+                if (delay <= 0) {
+                    Log.w(TAG, "Shutdown wait timed out");
+                    break;
+                }
+                try {
+                    mActionDoneSync.wait(delay);
+                } catch (InterruptedException e) {
+                }
+            }
         }
 
-        //shutdown power
+        if (mReboot) {
+            Log.i(TAG, "Rebooting, reason: " + mRebootReason);
+            try {
+                Power.reboot(mRebootReason);
+            } catch (Exception e) {
+                Log.e(TAG, "Reboot failed, will attempt shutdown instead", e);
+            }
+        }
+
+        // Shutdown power
         Log.i(TAG, "Performing low-level shutdown...");
         Power.shutdown();
     }
diff --git a/core/java/com/android/internal/content/PackageHelper.java b/core/java/com/android/internal/content/PackageHelper.java
index de6a175..80efca4 100644
--- a/core/java/com/android/internal/content/PackageHelper.java
+++ b/core/java/com/android/internal/content/PackageHelper.java
@@ -40,6 +40,10 @@
     public static final int RECOMMEND_FAILED_ALREADY_EXISTS = -4;
     private static final boolean localLOGV = true;
     private static final String TAG = "PackageHelper";
+    // App installation location settings values
+    public static final int APP_INSTALL_AUTO = 0;
+    public static final int APP_INSTALL_INTERNAL = 1;
+    public static final int APP_INSTALL_EXTERNAL = 2;
 
     public static IMountService getMountService() {
         IBinder service = ServiceManager.getService("mount");
diff --git a/core/java/com/android/internal/content/SelectionBuilder.java b/core/java/com/android/internal/content/SelectionBuilder.java
new file mode 100644
index 0000000..0e29411
--- /dev/null
+++ b/core/java/com/android/internal/content/SelectionBuilder.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.content;
+
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.text.TextUtils;
+
+import java.util.ArrayList;
+
+/**
+ * Helper for building selection clauses for {@link SQLiteDatabase}. Each
+ * appended clause is combined using {@code AND}. This class is <em>not</em>
+ * thread safe.
+ *
+ * @hide
+ */
+public class SelectionBuilder {
+    private StringBuilder mSelection = new StringBuilder();
+    private ArrayList<String> mSelectionArgs = new ArrayList<String>();
+
+    /**
+     * Reset any internal state, allowing this builder to be recycled.
+     */
+    public SelectionBuilder reset() {
+        mSelection.setLength(0);
+        mSelectionArgs.clear();
+        return this;
+    }
+
+    /**
+     * Append the given selection clause to the internal state. Each clause is
+     * surrounded with parenthesis and combined using {@code AND}.
+     */
+    public SelectionBuilder append(String selection, String... selectionArgs) {
+        if (TextUtils.isEmpty(selection)) {
+            if (selectionArgs != null && selectionArgs.length > 0) {
+                throw new IllegalArgumentException(
+                        "Valid selection required when including arguments");
+            }
+
+            // Shortcut when clause is empty
+            return this;
+        }
+
+        if (mSelection.length() > 0) {
+            mSelection.append(" AND ");
+        }
+
+        mSelection.append("(").append(selection).append(")");
+        for (String arg : selectionArgs) {
+            mSelectionArgs.add(arg);
+        }
+
+        return this;
+    }
+
+    /**
+     * Return selection string for current internal state.
+     *
+     * @see #getSelectionArgs()
+     */
+    public String getSelection() {
+        return mSelection.toString();
+    }
+
+    /**
+     * Return selection arguments for current internal state.
+     *
+     * @see #getSelection()
+     */
+    public String[] getSelectionArgs() {
+        return mSelectionArgs.toArray(new String[mSelectionArgs.size()]);
+    }
+
+    /**
+     * Execute query using the current internal state as {@code WHERE} clause.
+     * Missing arguments as treated as {@code null}.
+     */
+    public Cursor query(SQLiteDatabase db, String table, String[] columns, String orderBy) {
+        return query(db, table, columns, null, null, orderBy, null);
+    }
+
+    /**
+     * Execute query using the current internal state as {@code WHERE} clause.
+     */
+    public Cursor query(SQLiteDatabase db, String table, String[] columns, String groupBy,
+            String having, String orderBy, String limit) {
+        return db.query(table, columns, getSelection(), getSelectionArgs(), groupBy, having,
+                orderBy, limit);
+    }
+
+    /**
+     * Execute update using the current internal state as {@code WHERE} clause.
+     */
+    public int update(SQLiteDatabase db, String table, ContentValues values) {
+        return db.update(table, values, getSelection(), getSelectionArgs());
+    }
+
+    /**
+     * Execute delete using the current internal state as {@code WHERE} clause.
+     */
+    public int delete(SQLiteDatabase db, String table) {
+        return db.delete(table, getSelection(), getSelectionArgs());
+    }
+}
diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp
index 9965fe5..b6f3997 100644
--- a/core/jni/android/graphics/BitmapFactory.cpp
+++ b/core/jni/android/graphics/BitmapFactory.cpp
@@ -331,12 +331,14 @@
 // i.e. dynamically allocated, since its lifetime may exceed the current stack
 // frame.
 static jobject doDecode(JNIEnv* env, SkStream* stream, jobject padding,
-                        jobject options, bool allowPurgeable) {
+                        jobject options, bool allowPurgeable,
+                        bool forcePurgeable = false) {
     int sampleSize = 1;
     SkImageDecoder::Mode mode = SkImageDecoder::kDecodePixels_Mode;
     SkBitmap::Config prefConfig = SkBitmap::kNo_Config;
     bool doDither = true;
-    bool isPurgeable = allowPurgeable && optionsPurgeable(env, options);
+    bool isPurgeable = forcePurgeable ||
+                        (allowPurgeable && optionsPurgeable(env, options));
     bool reportSizeToVM = optionsReportSizeToVM(env, options);
     
     if (NULL != options) {
@@ -568,8 +570,10 @@
                                  jobject options) { // BitmapFactory$Options
     SkStream* stream;
     Asset* asset = reinterpret_cast<Asset*>(native_asset);
+    // assets can always be rebuilt, so force this
+    bool forcePurgeable = true;
 
-    if (optionsPurgeable(env, options)) {
+    if (forcePurgeable || optionsPurgeable(env, options)) {
         // if we could "ref/reopen" the asset, we may not need to copy it here
         // and we could assume optionsShareable, since assets are always RO
         stream = copyAssetToStream(asset);
@@ -582,7 +586,7 @@
         stream = new AssetStreamAdaptor(asset);
     }
     SkAutoUnref aur(stream);
-    return doDecode(env, stream, padding, options, true);
+    return doDecode(env, stream, padding, options, true, forcePurgeable);
 }
 
 static jobject nativeDecodeByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
diff --git a/core/jni/android/graphics/YuvToJpegEncoder.cpp b/core/jni/android/graphics/YuvToJpegEncoder.cpp
index 819cce8..0a0c5b3 100644
--- a/core/jni/android/graphics/YuvToJpegEncoder.cpp
+++ b/core/jni/android/graphics/YuvToJpegEncoder.cpp
@@ -49,19 +49,16 @@
 
 void YuvToJpegEncoder::setJpegCompressStruct(jpeg_compress_struct* cinfo,
         int width, int height, int quality) {
-    jpeg_set_quality(cinfo, quality, TRUE);
-
     cinfo->image_width = width;
     cinfo->image_height = height;
-
     cinfo->input_components = 3;
     cinfo->in_color_space = JCS_YCbCr;
     jpeg_set_defaults(cinfo);
+
+    jpeg_set_quality(cinfo, quality, TRUE);
     jpeg_set_colorspace(cinfo, JCS_YCbCr);
     cinfo->raw_data_in = TRUE;
-
     cinfo->dct_method = JDCT_IFAST;
-
     configSamplingFactors(cinfo);
 }
 
diff --git a/core/jni/android_server_BluetoothService.cpp b/core/jni/android_server_BluetoothService.cpp
index ea64305..4420aca 100644
--- a/core/jni/android_server_BluetoothService.cpp
+++ b/core/jni/android_server_BluetoothService.cpp
@@ -861,6 +861,26 @@
     return JNI_FALSE;
 }
 
+static jboolean setLinkTimeoutNative(JNIEnv *env, jobject object, jstring object_path,
+                                     jint num_slots) {
+    LOGV(__FUNCTION__);
+#ifdef HAVE_BLUETOOTH
+    native_data_t *nat = get_native_data(env, object);
+    if (nat) {
+        const char *c_object_path = env->GetStringUTFChars(object_path, NULL);
+        DBusMessage *reply = dbus_func_args(env, nat->conn,
+                           get_adapter_path(env, object),
+                           DBUS_ADAPTER_IFACE, "SetLinkTimeout",
+                           DBUS_TYPE_OBJECT_PATH, &c_object_path,
+                           DBUS_TYPE_UINT32, &num_slots,
+                           DBUS_TYPE_INVALID);
+        env->ReleaseStringUTFChars(object_path, c_object_path);
+        return reply ? JNI_TRUE : JNI_FALSE;
+    }
+#endif
+    return JNI_FALSE;
+}
+
 static JNINativeMethod sMethods[] = {
      /* name, signature, funcPtr */
     {"classInitNative", "()V", (void*)classInitNative},
@@ -905,6 +925,7 @@
     {"discoverServicesNative", "(Ljava/lang/String;Ljava/lang/String;)Z", (void *)discoverServicesNative},
     {"addRfcommServiceRecordNative", "(Ljava/lang/String;JJS)I", (void *)addRfcommServiceRecordNative},
     {"removeServiceRecordNative", "(I)Z", (void *)removeServiceRecordNative},
+    {"setLinkTimeoutNative", "(Ljava/lang/String;I)Z", (void *)setLinkTimeoutNative},
 };
 
 int register_android_server_BluetoothService(JNIEnv *env) {
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index f1e614b..4e2caa0 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -648,7 +648,7 @@
          for details. -->
     <permission android:name="android.permission.SET_PREFERRED_APPLICATIONS"
         android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
-        android:protectionLevel="dangerous"
+        android:protectionLevel="signature"
         android:label="@string/permlab_setPreferredApplications"
         android:description="@string/permdesc_setPreferredApplications" />
 
diff --git a/core/res/res/drawable-hdpi/stat_notify_car_mode.png b/core/res/res/drawable-hdpi/stat_notify_car_mode.png
index 6c51b32..03499a4 100644
--- a/core/res/res/drawable-hdpi/stat_notify_car_mode.png
+++ b/core/res/res/drawable-hdpi/stat_notify_car_mode.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_tether_bluetooth.png b/core/res/res/drawable-hdpi/stat_sys_tether_bluetooth.png
new file mode 100644
index 0000000..e43fbae
--- /dev/null
+++ b/core/res/res/drawable-hdpi/stat_sys_tether_bluetooth.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_tether_general.png b/core/res/res/drawable-hdpi/stat_sys_tether_general.png
new file mode 100644
index 0000000..e43fbae
--- /dev/null
+++ b/core/res/res/drawable-hdpi/stat_sys_tether_general.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_tether_usb.png b/core/res/res/drawable-hdpi/stat_sys_tether_usb.png
old mode 100755
new mode 100644
index 4c14c07..c6c533d
--- a/core/res/res/drawable-hdpi/stat_sys_tether_usb.png
+++ b/core/res/res/drawable-hdpi/stat_sys_tether_usb.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_tether_wifi.png b/core/res/res/drawable-hdpi/stat_sys_tether_wifi.png
new file mode 100644
index 0000000..9fcadef
--- /dev/null
+++ b/core/res/res/drawable-hdpi/stat_sys_tether_wifi.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_notify_car_mode.png b/core/res/res/drawable-mdpi/stat_notify_car_mode.png
index c664244..0272e6b 100644
--- a/core/res/res/drawable-mdpi/stat_notify_car_mode.png
+++ b/core/res/res/drawable-mdpi/stat_notify_car_mode.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_sys_tether_bluetooth.png b/core/res/res/drawable-mdpi/stat_sys_tether_bluetooth.png
new file mode 100644
index 0000000..efb64ad
--- /dev/null
+++ b/core/res/res/drawable-mdpi/stat_sys_tether_bluetooth.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_sys_tether_general.png b/core/res/res/drawable-mdpi/stat_sys_tether_general.png
new file mode 100644
index 0000000..efb64ad
--- /dev/null
+++ b/core/res/res/drawable-mdpi/stat_sys_tether_general.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_sys_tether_usb.png b/core/res/res/drawable-mdpi/stat_sys_tether_usb.png
index 2d0da4c..73f1a81 100644
--- a/core/res/res/drawable-mdpi/stat_sys_tether_usb.png
+++ b/core/res/res/drawable-mdpi/stat_sys_tether_usb.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_sys_tether_wifi.png b/core/res/res/drawable-mdpi/stat_sys_tether_wifi.png
new file mode 100644
index 0000000..d448491
--- /dev/null
+++ b/core/res/res/drawable-mdpi/stat_sys_tether_wifi.png
Binary files differ
diff --git a/core/res/res/layout/status_bar_expanded.xml b/core/res/res/layout/status_bar_expanded.xml
index 30138a7..d443247 100644
--- a/core/res/res/layout/status_bar_expanded.xml
+++ b/core/res/res/layout/status_bar_expanded.xml
@@ -86,6 +86,7 @@
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:fadingEdge="none"
+            android:overscrollMode="ifContentScrolls"
             >
             <com.android.server.status.NotificationLinearLayout
                 android:id="@+id/notificationLinearLayout"
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 1ced121..f5e2f1d 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -1747,6 +1747,10 @@
         <!-- When set to false, the ListView will not draw the divider before each footer view.
              The default value is true. -->
         <attr name="footerDividersEnabled" format="boolean" />
+        <!-- Drawable to draw above list content. -->
+        <attr name="overscrollHeader" format="reference" />
+        <!-- Drawable to draw below list content. -->
+        <attr name="overscrollFooter" format="reference" />
     </declare-styleable>
     <declare-styleable name="MenuView">
         <!-- Default appearance of menu item text. -->
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 36a8f5b..8c00884 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -1235,6 +1235,8 @@
   <public type="attr" name="stripLeft" id="0x010102bc" />
   <public type="attr" name="stripRight" id="0x010102bd" />
   <public type="attr" name="stripEnabled" id="0x010102be" />
+  <public type="attr" name="overscrollHeader" id="0x010102bf" />
+  <public type="attr" name="overscrollFooter" id="0x010102c0" />
 
   <public type="anim" name="cycle_interpolator" id="0x010a000c" />
     
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index e68f214..3fb9607 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -2251,4 +2251,8 @@
     <string name="car_mode_disable_notification_title">Car mode enabled</string>
     <string name="car_mode_disable_notification_message">Select to exit car mode.</string>
 
+    <!-- Strings for tethered notification -->
+    <!-- Shown when the device is tethered -->
+    <string name="tethered_notification_title">Tethering active</string>
+    <string name="tethered_notification_message">Touch to configure</string>
 </resources>
diff --git a/core/tests/coretests/AndroidManifest.xml b/core/tests/coretests/AndroidManifest.xml
index 6bc6f2e..6a7c6ec 100644
--- a/core/tests/coretests/AndroidManifest.xml
+++ b/core/tests/coretests/AndroidManifest.xml
@@ -70,9 +70,6 @@
     <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     <uses-permission android:name="android.permission.HARDWARE_TEST" />
-    <uses-permission android:name="android.permission.ACCESSIBILITY_EVENT_VIEW_TYPES" />
-    <uses-permission android:name="android.permission.ACCESSIBILITY_EVENT_TRANSITION_TYPES" />
-    <uses-permission android:name="android.permission.ACCESSIBILITY_EVENT_NOTIFICATION_TYPES" />
 
     <!-- package manager test permissions -->
     <uses-permission android:name="android.permission.INSTALL_PACKAGES" />
@@ -1002,7 +999,7 @@
             </intent-filter>
         </activity>
 
-        <service android:name="android.accessibility.AccessibilityTestService">
+        <service android:name="android.accessibilityservice.AccessibilityTestService">
             <intent-filter>
                 <action android:name="android.accessibilityservice.AccessibilityService" />
             </intent-filter>
diff --git a/graphics/java/android/renderscript/RSSurfaceView.java b/graphics/java/android/renderscript/RSSurfaceView.java
index 1d3f82d..f05e84c 100644
--- a/graphics/java/android/renderscript/RSSurfaceView.java
+++ b/graphics/java/android/renderscript/RSSurfaceView.java
@@ -161,5 +161,9 @@
         mRS.destroy();
         mRS = null;
     }
+    
+    public void createRenderScript(RenderScriptGL rs) {
+        mRS = rs;
+    }
 }
 
diff --git a/include/media/stagefright/HTTPDataSource.h b/include/media/stagefright/HTTPDataSource.h
index 98ebc48..23522bd 100644
--- a/include/media/stagefright/HTTPDataSource.h
+++ b/include/media/stagefright/HTTPDataSource.h
@@ -50,7 +50,7 @@
 
 private:
     enum {
-        kBufferSize = 64 * 1024
+        kBufferSize = 32 * 1024
     };
 
     String8 mHeaders;
diff --git a/include/media/stagefright/StagefrightMediaScanner.h b/include/media/stagefright/StagefrightMediaScanner.h
index af125dc..4437eee 100644
--- a/include/media/stagefright/StagefrightMediaScanner.h
+++ b/include/media/stagefright/StagefrightMediaScanner.h
@@ -22,7 +22,7 @@
 
 namespace android {
 
-struct StagefrightMetadataRetriever;
+struct MediaMetadataRetriever;
 
 struct StagefrightMediaScanner : public MediaScanner {
     StagefrightMediaScanner();
@@ -35,7 +35,7 @@
     virtual char *extractAlbumArt(int fd);
 
 private:
-    sp<StagefrightMetadataRetriever> mRetriever;
+    sp<MediaMetadataRetriever> mRetriever;
 
     StagefrightMediaScanner(const StagefrightMediaScanner &);
     StagefrightMediaScanner &operator=(const StagefrightMediaScanner &);
diff --git a/include/utils/ResourceTypes.h b/include/utils/ResourceTypes.h
index 0e796dc..b701ce7 100644
--- a/include/utils/ResourceTypes.h
+++ b/include/utils/ResourceTypes.h
@@ -631,6 +631,8 @@
 
     void restart();
 
+    const ResStringPool& getStrings() const;
+
     event_code_t getEventType() const;
     // Note, unlike XmlPullParser, the first call to next() will return
     // START_TAG of the first element.
@@ -716,8 +718,6 @@
 
     void uninit();
 
-    const ResStringPool& getStrings() const;
-
 private:
     friend class ResXMLParser;
 
diff --git a/keystore/java/android/security/KeyStore.java b/keystore/java/android/security/KeyStore.java
index 6041b83..4614b53 100644
--- a/keystore/java/android/security/KeyStore.java
+++ b/keystore/java/android/security/KeyStore.java
@@ -22,6 +22,7 @@
 import java.io.InputStream;
 import java.io.IOException;
 import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
 import java.util.ArrayList;
 
 /**
@@ -57,12 +58,12 @@
 
     public byte[] get(byte[] key) {
         ArrayList<byte[]> values = execute('g', key);
-        return (values == null || values.size() == 0) ? null : values.get(0);
+        return (values == null || values.isEmpty()) ? null : values.get(0);
     }
 
     public String get(String key) {
-        byte[] value = get(key.getBytes());
-        return (value == null) ? null : new String(value);
+        byte[] value = get(getBytes(key));
+        return (value == null) ? null : toString(value);
     }
 
     public boolean put(byte[] key, byte[] value) {
@@ -71,7 +72,7 @@
     }
 
     public boolean put(String key, String value) {
-        return put(key.getBytes(), value.getBytes());
+        return put(getBytes(key), getBytes(value));
     }
 
     public boolean delete(byte[] key) {
@@ -80,7 +81,7 @@
     }
 
     public boolean delete(String key) {
-        return delete(key.getBytes());
+        return delete(getBytes(key));
     }
 
     public boolean contains(byte[] key) {
@@ -89,7 +90,7 @@
     }
 
     public boolean contains(String key) {
-        return contains(key.getBytes());
+        return contains(getBytes(key));
     }
 
     public byte[][] saw(byte[] prefix) {
@@ -98,13 +99,13 @@
     }
 
     public String[] saw(String prefix) {
-        byte[][] values = saw(prefix.getBytes());
+        byte[][] values = saw(getBytes(prefix));
         if (values == null) {
             return null;
         }
         String[] strings = new String[values.length];
         for (int i = 0; i < values.length; ++i) {
-            strings[i] = new String(values[i]);
+            strings[i] = toString(values[i]);
         }
         return strings;
     }
@@ -120,7 +121,7 @@
     }
 
     public boolean password(String oldPassword, String newPassword) {
-        return password(oldPassword.getBytes(), newPassword.getBytes());
+        return password(getBytes(oldPassword), getBytes(newPassword));
     }
 
     public boolean password(byte[] password) {
@@ -128,7 +129,7 @@
     }
 
     public boolean password(String password) {
-        return password(password.getBytes());
+        return password(getBytes(password));
     }
 
     public boolean lock() {
@@ -142,7 +143,7 @@
     }
 
     public boolean unlock(String password) {
-        return unlock(password.getBytes());
+        return unlock(getBytes(password));
     }
 
     public int getLastError() {
@@ -208,4 +209,22 @@
         }
         return null;
     }
+
+    private static byte[] getBytes(String string) {
+        try {
+            return string.getBytes("UTF-8");
+        } catch (UnsupportedEncodingException e) {
+            // will never happen
+            throw new RuntimeException(e);
+        }
+    }
+
+    private static String toString(byte[] bytes) {
+        try {
+            return new String(bytes, "UTF-8");
+        } catch (UnsupportedEncodingException e) {
+            // will never happen
+            throw new RuntimeException(e);
+        }
+    }
 }
diff --git a/keystore/tests/src/android/security/KeyStoreTest.java b/keystore/tests/src/android/security/KeyStoreTest.java
index 569d8da..6630a4f 100755
--- a/keystore/tests/src/android/security/KeyStoreTest.java
+++ b/keystore/tests/src/android/security/KeyStoreTest.java
@@ -39,6 +39,9 @@
     private static final String TEST_KEYNAME2 = "testkey2";
     private static final String TEST_KEYVALUE = "test value";
 
+    // "Hello, World" in Chinese
+    private static final String TEST_I18N = "\u4F60\u597D, \u4E16\u754C";
+
     private KeyStore mKeyStore = null;
 
     public KeyStoreTest() {
@@ -83,6 +86,14 @@
         assertTrue(mKeyStore.put(TEST_KEYNAME, TEST_KEYVALUE));
     }
 
+    public void testI18n() throws Exception {
+        assertFalse(mKeyStore.put(TEST_I18N, TEST_I18N));
+        assertFalse(mKeyStore.contains(TEST_I18N));
+        mKeyStore.password(TEST_I18N);
+        assertTrue(mKeyStore.put(TEST_I18N, TEST_I18N));
+        assertTrue(mKeyStore.contains(TEST_I18N));
+    }
+
     public void testDelete() throws Exception {
         assertTrue(mKeyStore.delete(TEST_KEYNAME));
         mKeyStore.password(TEST_PASSWD);
diff --git a/libs/audioflinger/Android.mk b/libs/audioflinger/Android.mk
index b68bfc1..870c0b8 100644
--- a/libs/audioflinger/Android.mk
+++ b/libs/audioflinger/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
     libutils \
-	libbinder \
+    libbinder \
     libmedia \
     libhardware_legacy
 
@@ -85,7 +85,7 @@
 LOCAL_SHARED_LIBRARIES := \
     libcutils \
     libutils \
-	libbinder \
+    libbinder \
     libmedia \
     libhardware_legacy
 
@@ -114,9 +114,17 @@
 endif
 
 ifeq ($(TARGET_SIMULATOR),true)
-	ifeq ($(HOST_OS),linux)
-		LOCAL_LDLIBS += -lrt -lpthread
-	endif
+    ifeq ($(HOST_OS),linux)
+        LOCAL_LDLIBS += -lrt -lpthread
+    endif
+endif
+
+ifeq ($(BOARD_USE_LVMX),true)
+    LOCAL_CFLAGS += -DLVMX
+    LOCAL_C_INCLUDES += vendor/nxp
+    LOCAL_STATIC_LIBRARIES += liblifevibes
+    LOCAL_SHARED_LIBRARIES += liblvmxservice
+#    LOCAL_SHARED_LIBRARIES += liblvmxipc
 endif
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/libs/audioflinger/AudioFlinger.cpp b/libs/audioflinger/AudioFlinger.cpp
index 8089389..7902212 100644
--- a/libs/audioflinger/AudioFlinger.cpp
+++ b/libs/audioflinger/AudioFlinger.cpp
@@ -47,6 +47,10 @@
 #include "A2dpAudioInterface.h"
 #endif
 
+#ifdef LVMX
+#include "lifevibes.h"
+#endif
+
 // ----------------------------------------------------------------------------
 // the sim build doesn't have gettid
 
@@ -132,6 +136,9 @@
     } else {
         LOGE("Couldn't even initialize the stubbed audio hardware!");
     }
+#ifdef LVMX
+    LifeVibes::init();
+#endif
 }
 
 AudioFlinger::~AudioFlinger()
@@ -411,6 +418,11 @@
     AutoMutex lock(mHardwareLock);
     mHardwareStatus = AUDIO_HW_SET_MODE;
     status_t ret = mAudioHardware->setMode(mode);
+#ifdef LVMX
+    if (NO_ERROR == ret) {
+        LifeVibes::setMode(mode);
+    }
+#endif
     mHardwareStatus = AUDIO_HW_IDLE;
     return ret;
 }
@@ -566,11 +578,37 @@
         return PERMISSION_DENIED;
     }
 
+#ifdef LVMX
+    AudioParameter param = AudioParameter(keyValuePairs);
+    LifeVibes::setParameters(ioHandle,keyValuePairs);
+    String8 key = String8(AudioParameter::keyRouting);
+    int device;
+    if (NO_ERROR != param.getInt(key, device)) {
+        device = -1;
+    }
+
+    key = String8(LifevibesTag);
+    String8 value;
+    int musicEnabled = -1;
+    if (NO_ERROR == param.get(key, value)) {
+        if (value == LifevibesEnable) {
+            musicEnabled = 1;
+        } else if (value == LifevibesDisable) {
+            musicEnabled = 0;
+        }
+    }
+#endif
+
     // ioHandle == 0 means the parameters are global to the audio hardware interface
     if (ioHandle == 0) {
         AutoMutex lock(mHardwareLock);
         mHardwareStatus = AUDIO_SET_PARAMETER;
         result = mAudioHardware->setParameters(keyValuePairs);
+#ifdef LVMX
+        if ((NO_ERROR == result) && (musicEnabled != -1)) {
+            LifeVibes::enableMusic((bool) musicEnabled);
+        }
+#endif
         mHardwareStatus = AUDIO_HW_IDLE;
         return result;
     }
@@ -586,7 +624,13 @@
         }
     }
     if (thread != NULL) {
-        return thread->setParameters(keyValuePairs);
+        result = thread->setParameters(keyValuePairs);
+#ifdef LVMX
+        if ((NO_ERROR == result) && (device != -1)) {
+            LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread->id()), device);
+        }
+#endif
+        return result;
     }
     return BAD_VALUE;
 }
@@ -1058,12 +1102,24 @@
 
 status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
 {
+#ifdef LVMX
+    int audioOutputType = LifeVibes::getMixerType(mId, mType);
+    if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
+        LifeVibes::setMasterVolume(audioOutputType, value);
+    }
+#endif
     mMasterVolume = value;
     return NO_ERROR;
 }
 
 status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
 {
+#ifdef LVMX
+    int audioOutputType = LifeVibes::getMixerType(mId, mType);
+    if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
+        LifeVibes::setMasterMute(audioOutputType, muted);
+    }
+#endif
     mMasterMute = muted;
     return NO_ERROR;
 }
@@ -1080,12 +1136,24 @@
 
 status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
 {
+#ifdef LVMX
+    int audioOutputType = LifeVibes::getMixerType(mId, mType);
+    if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
+        LifeVibes::setStreamVolume(audioOutputType, stream, value);
+    }
+#endif
     mStreamTypes[stream].volume = value;
     return NO_ERROR;
 }
 
 status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
 {
+#ifdef LVMX
+    int audioOutputType = LifeVibes::getMixerType(mId, mType);
+    if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
+        LifeVibes::setStreamMute(audioOutputType, stream, muted);
+    }
+#endif
     mStreamTypes[stream].mute = muted;
     return NO_ERROR;
 }
@@ -1333,6 +1401,12 @@
             mLastWriteTime = systemTime();
             mInWrite = true;
             mBytesWritten += mixBufferSize;
+#ifdef LVMX
+            int audioOutputType = LifeVibes::getMixerType(mId, mType);
+            if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
+               LifeVibes::process(audioOutputType, curBuf, mixBufferSize);
+            }
+#endif
             int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
             if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
             mNumWrites++;
@@ -1376,6 +1450,29 @@
     uint32_t mixerStatus = MIXER_IDLE;
     // find out which tracks need to be processed
     size_t count = activeTracks.size();
+
+    float masterVolume = mMasterVolume;
+    bool  masterMute = mMasterMute;
+
+#ifdef LVMX
+    bool tracksConnectedChanged = false;
+    bool stateChanged = false;
+
+    int audioOutputType = LifeVibes::getMixerType(mId, mType);
+    if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
+    {
+        int activeTypes = 0;
+        for (size_t i=0 ; i<count ; i++) {
+            sp<Track> t = activeTracks[i].promote();
+            if (t == 0) continue;
+            Track* const track = t.get();
+            int iTracktype=track->type();
+            activeTypes |= 1<<track->type();
+        }
+        LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
+    }
+#endif
+
     for (size_t i=0 ; i<count ; i++) {
         sp<Track> t = activeTracks[i].promote();
         if (t == 0) continue;
@@ -1393,15 +1490,27 @@
 
             // compute volume for this track
             int16_t left, right;
-            if (track->isMuted() || mMasterMute || track->isPausing() ||
+            if (track->isMuted() || masterMute || track->isPausing() ||
                 mStreamTypes[track->type()].mute) {
                 left = right = 0;
                 if (track->isPausing()) {
                     track->setPaused();
                 }
             } else {
+                // read original volumes with volume control
                 float typeVolume = mStreamTypes[track->type()].volume;
-                float v = mMasterVolume * typeVolume;
+#ifdef LVMX
+                bool streamMute=false;
+                // read the volume from the LivesVibes audio engine.
+                if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
+                {
+                    LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
+                    if (streamMute) {
+                        typeVolume = 0;
+                    }
+                }
+#endif
+                float v = masterVolume * typeVolume;
                 float v_clamped = v * cblk->volume[0];
                 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
                 left = int16_t(v_clamped);
@@ -1427,7 +1536,13 @@
                 // do not apply ramp
                 param = AudioMixer::RAMP_VOLUME;
             }
-
+#ifdef LVMX
+            if ( tracksConnectedChanged || stateChanged )
+            {
+                 // only do the ramp when the volume is changed by the user / application
+                 param = AudioMixer::VOLUME;
+            }
+#endif
             mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
             mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
             mAudioMixer->setParameter(
@@ -3652,6 +3767,18 @@
         } else {
             thread = new MixerThread(this, output, ++mNextThreadId);
             LOGV("openOutput() created mixer output: ID %d thread %p", mNextThreadId, thread);
+
+#ifdef LVMX
+            unsigned bitsPerSample =
+                (format == AudioSystem::PCM_16_BIT) ? 16 :
+                    ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
+            unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
+            int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
+
+            LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
+            LifeVibes::setDevice(audioOutputType, *pDevices);
+#endif
+
         }
         mPlaybackThreads.add(mNextThreadId, thread);
 
diff --git a/libs/audioflinger/AudioHardwareStub.cpp b/libs/audioflinger/AudioHardwareStub.cpp
index ae215d1..d481150 100644
--- a/libs/audioflinger/AudioHardwareStub.cpp
+++ b/libs/audioflinger/AudioHardwareStub.cpp
@@ -166,7 +166,7 @@
 // ----------------------------------------------------------------------------
 
 status_t AudioStreamInStub::set(int *pFormat, uint32_t *pChannels, uint32_t *pRate,
-				AudioSystem::audio_in_acoustics acoustics)
+                AudioSystem::audio_in_acoustics acoustics)
 {
     return NO_ERROR;
 }
diff --git a/libs/audioflinger/AudioPolicyManagerBase.cpp b/libs/audioflinger/AudioPolicyManagerBase.cpp
index cfcc3ea..2b0a6c8 100644
--- a/libs/audioflinger/AudioPolicyManagerBase.cpp
+++ b/libs/audioflinger/AudioPolicyManagerBase.cpp
@@ -344,6 +344,7 @@
 {
     LOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
 
+    bool forceVolumeReeval = false;
     switch(usage) {
     case AudioSystem::FOR_COMMUNICATION:
         if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
@@ -374,6 +375,7 @@
             config != AudioSystem::FORCE_BT_DESK_DOCK && config != AudioSystem::FORCE_WIRED_ACCESSORY) {
             LOGW("setForceUse() invalid config %d for FOR_DOCK", config);
         }
+        forceVolumeReeval = true;
         mForceUse[usage] = config;
         break;
     default:
@@ -388,6 +390,9 @@
 #endif
     updateDeviceForStrategy();
     setOutputDevice(mHardwareOutput, newDevice);
+    if (forceVolumeReeval) {
+        applyStreamVolumes(mHardwareOutput, newDevice);
+    }
 }
 
 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
diff --git a/libs/audioflinger/AudioResampler.h b/libs/audioflinger/AudioResampler.h
index 39656c0..2dfac76 100644
--- a/libs/audioflinger/AudioResampler.h
+++ b/libs/audioflinger/AudioResampler.h
@@ -76,8 +76,8 @@
     int32_t mInSampleRate;
     AudioBufferProvider::Buffer mBuffer;
     union {
-    	int16_t mVolume[2];
-    	uint32_t mVolumeRL;
+        int16_t mVolume[2];
+        uint32_t mVolumeRL;
     };
     int16_t mTargetVolume[2];
     format mFormat;
diff --git a/libs/utils/ResourceTypes.cpp b/libs/utils/ResourceTypes.cpp
index 38d8412..7e0f881 100644
--- a/libs/utils/ResourceTypes.cpp
+++ b/libs/utils/ResourceTypes.cpp
@@ -625,6 +625,10 @@
     mCurNode = NULL;
     mEventCode = mTree.mError == NO_ERROR ? START_DOCUMENT : BAD_DOCUMENT;
 }
+const ResStringPool& ResXMLParser::getStrings() const
+{
+    return mTree.mStrings;
+}
 
 ResXMLParser::event_code_t ResXMLParser::getEventType() const
 {
@@ -1149,11 +1153,6 @@
     restart();
 }
 
-const ResStringPool& ResXMLTree::getStrings() const
-{
-    return mStrings;
-}
-
 status_t ResXMLTree::validateNode(const ResXMLTree_node* node) const
 {
     const uint16_t eventCode = dtohs(node->header.type);
diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java
index e586869..618f239 100644
--- a/media/java/android/media/AudioService.java
+++ b/media/java/android/media/AudioService.java
@@ -113,9 +113,6 @@
     private Object mSettingsLock = new Object();
     private boolean mMediaServerOk;
 
-    /** cached value of the BT dock address to recognize undocking events */
-    private static String sBtDockAddress = "";
-
     private SoundPool mSoundPool;
     private Object mSoundEffectsLock = new Object();
     private static final int NUM_SOUNDPOOL_CHANNELS = 4;
@@ -269,6 +266,7 @@
                 new IntentFilter(Intent.ACTION_HEADSET_PLUG);
         intentFilter.addAction(BluetoothA2dp.ACTION_SINK_STATE_CHANGED);
         intentFilter.addAction(BluetoothHeadset.ACTION_STATE_CHANGED);
+        intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
         context.registerReceiver(mReceiver, intentFilter);
 
     }
@@ -1498,7 +1496,23 @@
         public void onReceive(Context context, Intent intent) {
             String action = intent.getAction();
 
-            if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
+            if (action.equals(Intent.ACTION_DOCK_EVENT)) {
+                int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
+                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
+                int config;
+                switch (dockState) {
+                    case Intent.EXTRA_DOCK_STATE_DESK:
+                        config = AudioSystem.FORCE_BT_DESK_DOCK;
+                        break;
+                    case Intent.EXTRA_DOCK_STATE_CAR:
+                        config = AudioSystem.FORCE_BT_CAR_DOCK;
+                        break;
+                    case Intent.EXTRA_DOCK_STATE_UNDOCKED:
+                    default:
+                        config = AudioSystem.FORCE_NONE;
+                }
+                AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
+            } else if (action.equals(BluetoothA2dp.ACTION_SINK_STATE_CHANGED)) {
                 int state = intent.getIntExtra(BluetoothA2dp.EXTRA_SINK_STATE,
                                                BluetoothA2dp.STATE_DISCONNECTED);
                 BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
@@ -1508,10 +1522,6 @@
 
                 if (isConnected &&
                     state != BluetoothA2dp.STATE_CONNECTED && state != BluetoothA2dp.STATE_PLAYING) {
-                    if (address.equals(sBtDockAddress)) {
-                        Log.v(TAG, "Recognized undocking from BT dock");
-                        AudioSystem.setForceUse(AudioSystem.FOR_DOCK, AudioSystem.FORCE_NONE);
-                    }
                     AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
                             AudioSystem.DEVICE_STATE_UNAVAILABLE,
                             address);
@@ -1519,27 +1529,6 @@
                 } else if (!isConnected &&
                              (state == BluetoothA2dp.STATE_CONNECTED ||
                               state == BluetoothA2dp.STATE_PLAYING)) {
-                    if (btDevice.isBluetoothDock()) {
-                        Log.v(TAG, "Recognized connection to BT dock");
-                        sBtDockAddress = address;
-                        Intent i = context.registerReceiver(null, new IntentFilter(Intent.ACTION_DOCK_EVENT));
-                        if (i != null) {
-                            int dockState = i.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED);
-                            int config;
-                            switch (dockState) {
-                                case Intent.EXTRA_DOCK_STATE_DESK:
-                                    config = AudioSystem.FORCE_BT_DESK_DOCK;
-                                    break;
-                                case Intent.EXTRA_DOCK_STATE_CAR:
-                                    config = AudioSystem.FORCE_BT_CAR_DOCK;
-                                    break;
-                                case Intent.EXTRA_DOCK_STATE_UNDOCKED:
-                                default:
-                                    config = AudioSystem.FORCE_NONE;
-                            }
-                            AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config);
-                        }
-                    }
                     AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP,
                                                          AudioSystem.DEVICE_STATE_AVAILABLE,
                                                          address);
diff --git a/media/java/android/media/MediaScanner.java b/media/java/android/media/MediaScanner.java
index 1f02608..1047fa4 100644
--- a/media/java/android/media/MediaScanner.java
+++ b/media/java/android/media/MediaScanner.java
@@ -630,13 +630,9 @@
                 map.put(Video.Media.ARTIST, (mArtist != null && mArtist.length() > 0 ? mArtist : MediaStore.UNKNOWN_STRING));
                 map.put(Video.Media.ALBUM, (mAlbum != null && mAlbum.length() > 0 ? mAlbum : MediaStore.UNKNOWN_STRING));
                 map.put(Video.Media.DURATION, mDuration);
-                map.put(Video.Media.DATE_TAKEN, mLastModified * 1000);
                 // FIXME - add RESOLUTION
             } else if (MediaFile.isImageFileType(mFileType)) {
                 // FIXME - add DESCRIPTION
-                // DATE_TAKEN will be overridden later if this is a JPEG image whose EXIF data
-                // contains date time information.
-                map.put(Images.Media.DATE_TAKEN, mLastModified * 1000);
             } else if (MediaFile.isAudioFileType(mFileType)) {
                 map.put(Audio.Media.ARTIST, (mArtist != null && mArtist.length() > 0 ? mArtist : MediaStore.UNKNOWN_STRING));
                 map.put(Audio.Media.ALBUM, (mAlbum != null && mAlbum.length() > 0 ? mAlbum : MediaStore.UNKNOWN_STRING));
diff --git a/media/libmedia/mediaplayer.cpp b/media/libmedia/mediaplayer.cpp
index d2cec0c..f623295b 100644
--- a/media/libmedia/mediaplayer.cpp
+++ b/media/libmedia/mediaplayer.cpp
@@ -104,7 +104,8 @@
     { // scope for the lock
         Mutex::Autolock _l(mLock);
 
-        if ( !( mCurrentState & ( MEDIA_PLAYER_IDLE | MEDIA_PLAYER_STATE_ERROR ) ) ) {
+        if ( !( (mCurrentState & MEDIA_PLAYER_IDLE) ||
+                (mCurrentState == MEDIA_PLAYER_STATE_ERROR ) ) ) {
             LOGE("setDataSource called in state %d", mCurrentState);
             return INVALID_OPERATION;
         }
diff --git a/media/libstagefright/DataSource.cpp b/media/libstagefright/DataSource.cpp
index 1696eb96..8468a07 100644
--- a/media/libstagefright/DataSource.cpp
+++ b/media/libstagefright/DataSource.cpp
@@ -102,7 +102,7 @@
         source = new FileSource(uri + 7);
     } else if (!strncasecmp("http://", uri, 7)) {
         source = new HTTPDataSource(uri, headers);
-        source = new CachingDataSource(source, 64 * 1024, 10);
+        source = new CachingDataSource(source, 32 * 1024, 20);
     } else {
         // Assume it's a filename.
         source = new FileSource(uri);
diff --git a/media/libstagefright/StagefrightMediaScanner.cpp b/media/libstagefright/StagefrightMediaScanner.cpp
index b1eca2b..34fb2bc 100644
--- a/media/libstagefright/StagefrightMediaScanner.cpp
+++ b/media/libstagefright/StagefrightMediaScanner.cpp
@@ -20,7 +20,8 @@
 
 #include <media/stagefright/StagefrightMediaScanner.h>
 
-#include "include/StagefrightMetadataRetriever.h"
+#include <media/mediametadataretriever.h>
+#include <private/media/VideoFrame.h>
 
 // Sonivox includes
 #include <libsonivox/eas.h>
@@ -32,7 +33,7 @@
 namespace android {
 
 StagefrightMediaScanner::StagefrightMediaScanner()
-    : mRetriever(new StagefrightMetadataRetriever) {
+    : mRetriever(new MediaMetadataRetriever) {
 }
 
 StagefrightMediaScanner::~StagefrightMediaScanner() {}
@@ -146,6 +147,8 @@
 status_t StagefrightMediaScanner::processFile(
         const char *path, const char *mimeType,
         MediaScannerClient &client) {
+    LOGV("processFile '%s'.", path);
+
     client.setLocale(locale());
     client.beginFile();
 
@@ -218,6 +221,8 @@
 }
 
 char *StagefrightMediaScanner::extractAlbumArt(int fd) {
+    LOGV("extractAlbumArt %d", fd);
+
     off_t size = lseek(fd, 0, SEEK_END);
     if (size < 0) {
         return NULL;
@@ -227,15 +232,14 @@
     if (mRetriever->setDataSource(fd, 0, size) == OK
             && mRetriever->setMode(
                 METADATA_MODE_FRAME_CAPTURE_ONLY) == OK) {
-        MediaAlbumArt *art = mRetriever->extractAlbumArt();
+        sp<IMemory> mem = mRetriever->extractAlbumArt();
 
-        if (art != NULL) {
+        if (mem != NULL) {
+            MediaAlbumArt *art = static_cast<MediaAlbumArt *>(mem->pointer());
+
             char *data = (char *)malloc(art->mSize + 4);
             *(int32_t *)data = art->mSize;
-            memcpy(&data[4], art->mData, art->mSize);
-
-            delete art;
-            art = NULL;
+            memcpy(&data[4], &art[1], art->mSize);
 
             return data;
         }
diff --git a/media/libstagefright/StagefrightMetadataRetriever.cpp b/media/libstagefright/StagefrightMetadataRetriever.cpp
index df6235f..c0cf97c 100644
--- a/media/libstagefright/StagefrightMetadataRetriever.cpp
+++ b/media/libstagefright/StagefrightMetadataRetriever.cpp
@@ -20,7 +20,6 @@
 
 #include "include/StagefrightMetadataRetriever.h"
 
-#include <media/stagefright/CachingDataSource.h>
 #include <media/stagefright/ColorConverter.h>
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/FileSource.h>
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaNames.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaNames.java
index 0e883e6..9a48c92 100755
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaNames.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaNames.java
@@ -394,7 +394,7 @@
            "ID3V2.3 Artist", "ID3V2.3 Lyricist", "ID3V2.3 Composer", null,
            "Blues", "ID3V2.3 Title", "1234", "295", "1", null},
       {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V2_TRCK_2.mp3", "01", "ID3V2.3 Album", 
-           "ID3V2.3 Artist", null, null, null, "255", "ID3V2.3 Title", "1234", "295", "1", null},
+           "ID3V2.3 Artist", null, null, null, null, "ID3V2.3 Title", null, "295", "1", null},
       {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V2_TYER.mp3", "01", "ID3V2.3 Album",
            "ID3V2.3 Artist", null, null, null, null, "ID3V2.3 Title", "9999", "295", "1", null},
       {"/sdcard/media_api/metaDataTestMedias/MP3/Corrupted_ID3V2_TYER_2.mp3", "01", "ID3V2.3 Album",
@@ -416,7 +416,7 @@
           null, null, "231180", "1", null},
       {"/sdcard/media_api/metaDataTestMedias/M4A/Jaws Of Life_ver1.m4a", "1/8", "Suspended Animation",
           "John Petrucci", null, null, "20070510T125223.000Z", 
-          "13", "Jaws Of Life", "2005", "449329", "1", "m4a composer"},
+          "12", "Jaws Of Life", "2005", "449329", "1", "m4a composer"},
       {"/sdcard/media_api/metaDataTestMedias/M4V/sample_iPod.m4v", null, null, 
           null, null, null, "20051220T202015.000Z", 
           null, null, null, "85500", "2", null},
@@ -425,7 +425,7 @@
           null, null, "2005", "231180", "1", null},
       {"/sdcard/media_api/metaDataTestMedias/MP4/kung_fu_panda_h264.mp4", "2/0", "mp4 album Kung Fu Panda",
           "mp4 artist Kung Fu Panda", null, null, "20080517T091451.000Z", 
-          "41", "Kung Fu Panda", "2008", "128521", "2", "mp4 composer"},
+          "40", "Kung Fu Panda", "2008", "128521", "2", "mp4 composer"},
       {"/sdcard/media_api/metaDataTestMedias/OGG/Ring_Classic_02.ogg", null, "Suspended Animation", 
           "John Petrucci", null, null, "20070510T125223.000Z", 
           null, null, "2005", "231180", "1", null},
diff --git a/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java b/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java
index 4635f48..7714911 100644
--- a/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java
+++ b/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java
@@ -349,11 +349,11 @@
                 int installPreference = Settings.System.getInt(getApplicationContext()
                         .getContentResolver(),
                         Settings.System.DEFAULT_INSTALL_LOCATION,
-                        PackageInfo.INSTALL_LOCATION_AUTO);
-                if (installPreference == 1) {
+                        PackageHelper.APP_INSTALL_AUTO);
+                if (installPreference == PackageHelper.APP_INSTALL_INTERNAL) {
                     installOnlyInternal = true;
                     auto = false;
-                } else if (installPreference == 2) {
+                } else if (installPreference == PackageHelper.APP_INSTALL_EXTERNAL) {
                     installOnlyOnSd = true;
                     auto = false;
                 }
diff --git a/packages/SettingsProvider/etc/Android.mk b/packages/SettingsProvider/etc/Android.mk
deleted file mode 100644
index 81ca4b1..0000000
--- a/packages/SettingsProvider/etc/Android.mk
+++ /dev/null
@@ -1,33 +0,0 @@
-#
-# Copyright (C) 2008 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.
-#
-
-LOCAL_PATH := $(my-dir)
-
-########################
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := bookmarks.xml
-
-LOCAL_MODULE_TAGS := user
-
-# This will install the file in /system/etc
-#
-LOCAL_MODULE_CLASS := ETC
-
-LOCAL_SRC_FILES := $(LOCAL_MODULE)
-
-include $(BUILD_PREBUILT)
-
diff --git a/packages/SettingsProvider/res/values/defaults.xml b/packages/SettingsProvider/res/values/defaults.xml
index bd131e0..34302c4 100644
--- a/packages/SettingsProvider/res/values/defaults.xml
+++ b/packages/SettingsProvider/res/values/defaults.xml
@@ -56,7 +56,10 @@
     <bool name="def_mount_ums_autostart">false</bool>
     <bool name="def_mount_ums_prompt">true</bool>
     <bool name="def_mount_ums_notify_enabled">true</bool>
+    <!-- Enable User preference for setting install location -->
     <bool name="set_install_location">true</bool>
+    <!-- Default install location if user preference for setting install location is turned on. -->
+    <integer name="def_install_location">2</integer>
 
     <!-- user interface sound effects -->
     <integer name="def_power_sounds_enabled">1</integer>
@@ -70,4 +73,6 @@
     <string name="def_lock_sound" translatable="false">/system/media/audio/ui/Lock.ogg</string>
     <string name="def_unlock_sound" translatable="false">/system/media/audio/ui/Unlock.ogg</string>
 
+    <!-- Default for Settings.System.VIBRATE_IN_SILENT -->
+    <bool name="def_vibrate_in_silent">true</bool>
 </resources>
diff --git a/packages/SettingsProvider/etc/bookmarks.xml b/packages/SettingsProvider/res/xml/bookmarks.xml
similarity index 88%
rename from packages/SettingsProvider/etc/bookmarks.xml
rename to packages/SettingsProvider/res/xml/bookmarks.xml
index 734e0cd..dfaeeaf 100644
--- a/packages/SettingsProvider/etc/bookmarks.xml
+++ b/packages/SettingsProvider/res/xml/bookmarks.xml
@@ -32,8 +32,8 @@
         class="com.google.android.gm.ConversationListActivityGmail"
         shortcut="g" />
     <bookmark
-        package="com.android.providers.im"
-        class="com.android.providers.im.LandingPage"
+        package="com.android.im"
+        class="com.android.im.app.LandingPage"
         shortcut="i" />
     <bookmark
         package="com.android.calendar"
@@ -53,8 +53,4 @@
         package="com.android.mms"
         class="com.android.mms.ui.ConversationList"
         shortcut="s" />
-    <bookmark
-        package="com.google.android.youtube"
-        class="com.google.android.youtube.HomeActivity"
-        shortcut="y" />
 </bookmarks>
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
index bccf7d2..ba66dc5 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
@@ -23,40 +23,29 @@
 import android.content.pm.ActivityInfo;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.content.pm.ServiceInfo;
-import android.content.res.Resources;
+import android.content.res.XmlResourceParser;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteDoneException;
-import android.database.sqlite.SQLiteException;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.database.sqlite.SQLiteStatement;
 import android.media.AudioManager;
 import android.media.AudioService;
 import android.net.ConnectivityManager;
-import android.os.Environment;
 import android.os.SystemProperties;
 import android.provider.Settings;
 import android.provider.Settings.Secure;
-import android.speech.RecognitionService;
-import android.speech.RecognizerIntent;
 import android.text.TextUtils;
+import android.util.AttributeSet;
 import android.util.Config;
 import android.util.Log;
 import android.util.Xml;
 import com.android.internal.telephony.RILConstants;
 import com.android.internal.util.XmlUtils;
-
 import com.android.internal.widget.LockPatternUtils;
 import com.android.internal.widget.LockPatternView;
-
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
 import java.io.IOException;
 import java.util.List;
 
@@ -65,11 +54,6 @@
  * Mostly just has a bit {@link #onCreate} to initialize the database.
  */
 public class DatabaseHelper extends SQLiteOpenHelper {
-    /**
-     * Path to file containing default bookmarks, relative to ANDROID_ROOT.
-     */
-    private static final String DEFAULT_BOOKMARKS_PATH = "etc/bookmarks.xml";
-
     private static final String TAG = "SettingsProvider";
     private static final String DATABASE_NAME = "settings.db";
 
@@ -77,7 +61,7 @@
     // database gets upgraded properly. At a minimum, please confirm that 'upgradeVersion'
     // is properly propagated through your change.  Not doing so will result in a loss of user
     // settings.
-    private static final int DATABASE_VERSION = 52;
+    private static final int DATABASE_VERSION = 54;
 
     private Context mContext;
 
@@ -158,7 +142,6 @@
              * notification vibrate to on.
              */
             loadVibrateSetting(db, true);
-            if (Config.LOGD) Log.d(TAG, "Reset system vibrate setting");
 
             upgradeVersion = 21;
         }
@@ -651,7 +634,45 @@
            upgradeVersion = 52;
        }
 
-       if (upgradeVersion != currentVersion) {
+        if (upgradeVersion == 52) {
+            // new vibration/silent mode settings
+            db.beginTransaction();
+            try {
+                SQLiteStatement stmt = db.compileStatement("INSERT INTO system(name,value)"
+                        + " VALUES(?,?);");
+                loadBooleanSetting(stmt, Settings.System.VIBRATE_IN_SILENT,
+                        R.bool.def_vibrate_in_silent);
+                stmt.close();
+                db.setTransactionSuccessful();
+            } finally {
+                db.endTransaction();
+            }
+
+            upgradeVersion = 53;
+        }
+        
+        if (upgradeVersion == 53) {
+            /*
+             * New settings for set install location UI.
+             */
+            db.beginTransaction();
+            try {
+                 SQLiteStatement stmt = db.compileStatement("INSERT INTO system(name,value)"
+                         + " VALUES(?,?);");
+                 loadIntegerSetting(stmt, Settings.System.DEFAULT_INSTALL_LOCATION,
+                         R.integer.def_install_location);
+                 stmt.close();
+                 db.setTransactionSuccessful();
+             } finally {
+                 db.endTransaction();
+             }
+
+            upgradeVersion = 54;
+        }
+
+        // *** Remember to update DATABASE_VERSION above!
+
+        if (upgradeVersion != currentVersion) {
             Log.w(TAG, "Got stuck trying to upgrade from version " + upgradeVersion
                     + ", must wipe the settings provider");
             db.execSQL("DROP TABLE IF EXISTS system");
@@ -735,39 +756,28 @@
      *
      * @param db The database to write the values into
      * @param startingIndex The zero-based position at which bookmarks in this file should begin
-     * @param subPath The relative path from ANDROID_ROOT to the file to read
-     * @param quiet If true, do no complain if the file is missing
      */
-    private int loadBookmarks(SQLiteDatabase db, int startingIndex, String subPath,
-            boolean quiet) {
-        FileReader bookmarksReader;
-
-        // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
-        final File favFile = new File(Environment.getRootDirectory(), subPath);
-        try {
-            bookmarksReader = new FileReader(favFile);
-        } catch (FileNotFoundException e) {
-            if (!quiet) {
-                Log.e(TAG, "Couldn't find or open bookmarks file " + favFile);
-            }
-            return 0;
-        }
-
+    private int loadBookmarks(SQLiteDatabase db, int startingIndex) {
         Intent intent = new Intent(Intent.ACTION_MAIN, null);
         intent.addCategory(Intent.CATEGORY_LAUNCHER);
         ContentValues values = new ContentValues();
 
         PackageManager packageManager = mContext.getPackageManager();
-        ActivityInfo info;
         int i = startingIndex;
-        try {
-            XmlPullParser parser = Xml.newPullParser();
-            parser.setInput(bookmarksReader);
 
+        try {
+            XmlResourceParser parser = mContext.getResources().getXml(R.xml.bookmarks);
             XmlUtils.beginDocument(parser, "bookmarks");
 
-            while (true) {
-                XmlUtils.nextElement(parser);
+            final int depth = parser.getDepth();
+            int type;
+
+            while (((type = parser.next()) != XmlPullParser.END_TAG ||
+                    parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
+
+                if (type != XmlPullParser.START_TAG) {
+                    continue;
+                }
 
                 String name = parser.getName();
                 if (!"bookmark".equals(name)) {
@@ -777,23 +787,36 @@
                 String pkg = parser.getAttributeValue(null, "package");
                 String cls = parser.getAttributeValue(null, "class");
                 String shortcutStr = parser.getAttributeValue(null, "shortcut");
+
                 int shortcutValue = (int) shortcutStr.charAt(0);
                 if (TextUtils.isEmpty(shortcutStr)) {
                     Log.w(TAG, "Unable to get shortcut for: " + pkg + "/" + cls);
                 }
+
+                ActivityInfo info = null;                
+                ComponentName cn = new ComponentName(pkg, cls);
                 try {
-                    ComponentName cn = new ComponentName(pkg, cls);
                     info = packageManager.getActivityInfo(cn, 0);
+                } catch (PackageManager.NameNotFoundException e) {
+                    String[] packages = packageManager.canonicalToCurrentPackageNames(
+                            new String[] { pkg });
+                    cn = new ComponentName(packages[0], cls);
+                    try {
+                        info = packageManager.getActivityInfo(cn, 0);
+                    } catch (PackageManager.NameNotFoundException e1) {
+                        Log.w(TAG, "Unable to add bookmark: " + pkg + "/" + cls, e);
+                    }
+                }
+                
+                if (info != null) {
                     intent.setComponent(cn);
                     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-                    values.put(Settings.Bookmarks.INTENT, intent.toURI());
+                    values.put(Settings.Bookmarks.INTENT, intent.toUri(0));
                     values.put(Settings.Bookmarks.TITLE,
                             info.loadLabel(packageManager).toString());
                     values.put(Settings.Bookmarks.SHORTCUT, shortcutValue);
                     db.insert("bookmarks", null, values);
                     i++;
-                } catch (PackageManager.NameNotFoundException e) {
-                    Log.w(TAG, "Unable to add bookmark: " + pkg + "/" + cls, e);
                 }
             }
         } catch (XmlPullParserException e) {
@@ -811,7 +834,7 @@
      * @param db The database to write the values into
      */
     private void loadBookmarks(SQLiteDatabase db) {
-        loadBookmarks(db, 0, DEFAULT_BOOKMARKS_PATH, false);
+        loadBookmarks(db, 0);
     }
 
     /**
@@ -890,8 +913,6 @@
         SQLiteStatement stmt = db.compileStatement("INSERT OR IGNORE INTO system(name,value)"
                 + " VALUES(?,?);");
 
-        Resources r = mContext.getResources();
-
         loadBooleanSetting(stmt, Settings.System.DIM_SCREEN,
                 R.bool.def_dim_screen);
         loadSetting(stmt, Settings.System.STAY_ON_WHILE_PLUGGED_IN,
@@ -941,12 +962,16 @@
 
         loadBooleanSetting(stmt, Settings.System.NOTIFICATION_LIGHT_PULSE,
                 R.bool.def_notification_pulse);
-        loadBooleanSetting(stmt, Settings.System.SET_INSTALL_LOCATION, R.bool.set_install_location);
-        loadSetting(stmt, Settings.System.DEFAULT_INSTALL_LOCATION,
-                PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY);
+        loadBooleanSetting(stmt, Settings.System.SET_INSTALL_LOCATION,
+                R.bool.set_install_location);
+        loadIntegerSetting(stmt, Settings.System.DEFAULT_INSTALL_LOCATION,
+                R.integer.def_install_location);
 
         loadUISoundEffectsSettings(stmt);
 
+        loadBooleanSetting(stmt, Settings.System.VIBRATE_IN_SILENT,
+                R.bool.def_vibrate_in_silent);
+
         stmt.close();
     }
 
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 942d32d..1b4ba81 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -60,6 +60,11 @@
     private static final SettingsCache sSystemCache = new SettingsCache();
     private static final SettingsCache sSecureCache = new SettingsCache();
 
+    // Over this size we don't reject loading or saving settings but
+    // we do consider them broken/malicious and don't keep them in
+    // memory at least:
+    private static final int MAX_CACHE_ENTRY_SIZE = 500;
+
     private static final Bundle NULL_SETTING = Bundle.forPair("value", null);
 
     protected DatabaseHelper mOpenHelper;
@@ -264,10 +269,7 @@
                               null, null, null, null);
             if (cursor != null && cursor.getCount() == 1) {
                 cursor.moveToFirst();
-                String value = cursor.getString(0);
-                Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
-                cache.putIfAbsentLocked(key, bundle);
-                return bundle;
+                return cache.putIfAbsent(key, cursor.getString(0));
             }
         } catch (SQLiteException e) {
             Log.w(TAG, "settings lookup error", e);
@@ -275,7 +277,7 @@
         } finally {
             if (cursor != null) cursor.close();
         }
-        cache.putIfAbsentLocked(key, NULL_SETTING);
+        cache.putIfAbsent(key, null);
         return NULL_SETTING;
     }
 
@@ -434,11 +436,16 @@
             if (!parseProviderList(url, initialValues)) return null;
         }
 
+        SettingsCache cache = SettingsCache.forTable(args.table);
+        String value = initialValues.getAsString(Settings.NameValueTable.VALUE);
+        if (SettingsCache.isRedundantSetValue(cache, name, value)) {
+            return Uri.withAppendedPath(url, name);
+        }
+
         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
         final long rowId = db.insert(args.table, null, initialValues);
         if (rowId <= 0) return null;
 
-        SettingsCache cache = SettingsCache.forTable(args.table);
         SettingsCache.populate(cache, initialValues);  // before we notify
 
         if (LOCAL_LOGV) Log.v(TAG, args.table + " <- " + initialValues);
@@ -592,6 +599,7 @@
      * database.
      */
     private static final class SettingsCache extends LinkedHashMap<String, Bundle> {
+
         public SettingsCache() {
             super(MAX_CACHE_ENTRIES, 0.75f /* load factor */, true /* access ordered */);
         }
@@ -601,14 +609,23 @@
             return size() > MAX_CACHE_ENTRIES;
         }
 
-        public void putIfAbsentLocked(String key, Bundle value) {
-            synchronized (this) {
-                if (containsKey(key)) {
-                    // Lost a race.
-                    return;
+        /**
+         * Atomic cache population, conditional on size of value and if
+         * we lost a race.
+         *
+         * @returns a Bundle to send back to the client from call(), even
+         *     if we lost the race.
+         */
+        public Bundle putIfAbsent(String key, String value) {
+            Bundle bundle = (value == null) ? NULL_SETTING : Bundle.forPair("value", value);
+            if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
+                synchronized (this) {
+                    if (!containsKey(key)) {
+                        put(key, bundle);
+                    }
                 }
-                put(key, value);
             }
+            return bundle;
         }
 
         public static SettingsCache forTable(String tableName) {
@@ -635,7 +652,11 @@
             }
             String value = contentValues.getAsString(Settings.NameValueTable.VALUE);
             synchronized (cache) {
-                cache.put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
+                if (value == null || value.length() <= MAX_CACHE_ENTRY_SIZE) {
+                    cache.put(name, Bundle.forPair(Settings.NameValueTable.VALUE, value));
+                } else {
+                    cache.remove(name);
+                }
             }
         }
 
@@ -653,5 +674,21 @@
             }
         }
 
+        /**
+         * For suppressing duplicate/redundant settings inserts early,
+         * checking our cache first (but without faulting it in),
+         * before going to sqlite with the mutation.
+         */
+        public static boolean isRedundantSetValue(SettingsCache cache, String name, String value) {
+            if (cache == null) return false;
+            synchronized (cache) {
+                Bundle bundle = cache.get(name);
+                if (bundle == null) return false;
+                String oldValue = bundle.getPairValue();
+                if (oldValue == null && value == null) return true;
+                if ((oldValue == null) != (value == null)) return false;
+                return oldValue.equals(value);
+            }
+        }
     }
 }
diff --git a/services/java/com/android/server/AlarmManagerService.java b/services/java/com/android/server/AlarmManagerService.java
index 43fe6ab..1ffb427 100644
--- a/services/java/com/android/server/AlarmManagerService.java
+++ b/services/java/com/android/server/AlarmManagerService.java
@@ -821,6 +821,11 @@
                 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
                     pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
                 } else {
+                    if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
+                            && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
+                        // This package is being updated; don't kill its alarms.
+                        return;
+                    }
                     Uri data = intent.getData();
                     if (data != null) {
                         String pkg = data.getSchemeSpecificPart();
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index a1c45dc..fa06244 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -668,6 +668,7 @@
         synchronized(this) {
             // check if this process still has an outstanding start request
             if (!mFeatureUsers.contains(u)) {
+                if (DBG) Slog.d(TAG, "ignoring - this process has no outstanding requests");
                 return 1;
             }
             u.unlinkDeathRecipient();
@@ -706,6 +707,7 @@
             }
             tracker =  mNetTrackers[usedNetworkType];
             if (tracker == null) {
+                if (DBG) Slog.d(TAG, "ignoring - no known tracker for net type " + usedNetworkType);
                 return -1;
             }
             if (usedNetworkType != networkType) {
@@ -720,7 +722,7 @@
                 callTeardown = true;
             }
         }
-
+        if (DBG) Slog.d(TAG, "Doing network teardown");
         if (callTeardown) {
             tracker.teardown();
             return 1;
@@ -995,6 +997,8 @@
                     }
                 } else {
                     newNet.reconnect();
+                    newNet = null; // not officially avail..  try anyway, but
+                                   // report no failover
                 }
             }
         }
diff --git a/services/java/com/android/server/DropBoxManagerService.java b/services/java/com/android/server/DropBoxManagerService.java
index 667953c..b38f1d2 100644
--- a/services/java/com/android/server/DropBoxManagerService.java
+++ b/services/java/com/android/server/DropBoxManagerService.java
@@ -603,7 +603,9 @@
             for (EntryFile late : future) {
                 mAllFiles.blocks -= late.blocks;
                 FileList tagFiles = mFilesByTag.get(late.tag);
-                if (tagFiles.contents.remove(late)) tagFiles.blocks -= late.blocks;
+                if (tagFiles != null && tagFiles.contents.remove(late)) {
+                    tagFiles.blocks -= late.blocks;
+                }
                 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
                     enrollEntry(new EntryFile(
                             late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
diff --git a/services/java/com/android/server/MountService.java b/services/java/com/android/server/MountService.java
index 0974f7f..713358d 100644
--- a/services/java/com/android/server/MountService.java
+++ b/services/java/com/android/server/MountService.java
@@ -26,6 +26,7 @@
 import android.net.Uri;
 import android.os.storage.IMountService;
 import android.os.storage.IMountServiceListener;
+import android.os.storage.IMountShutdownObserver;
 import android.os.storage.StorageResultCode;
 import android.os.Handler;
 import android.os.Message;
@@ -172,69 +173,110 @@
         }
     }
 
+    class ShutdownCallBack extends UnmountCallBack {
+        IMountShutdownObserver observer;
+        ShutdownCallBack(String path, IMountShutdownObserver observer) {
+            super(path, true);
+            this.observer = observer;
+        }
+
+        @Override
+        void handleFinished() {
+            int ret = doUnmountVolume(path, true);
+            if (observer != null) {
+                try {
+                    observer.onShutDownComplete(ret);
+                } catch (RemoteException e) {
+                    Log.w(TAG, "RemoteException when shutting down");
+                }
+            }
+        }
+    }
+
     final private Handler mHandler = new Handler() {
         ArrayList<UnmountCallBack> mForceUnmounts = new ArrayList<UnmountCallBack>();
+        boolean mRegistered = false;
+
+        void registerReceiver() {
+            mRegistered = true;
+            mContext.registerReceiver(mPmReceiver, mPmFilter);
+        }
+
+        void unregisterReceiver() {
+            mRegistered = false;
+            mContext.unregisterReceiver(mPmReceiver);
+        }
 
         public void handleMessage(Message msg) {
             switch (msg.what) {
                 case H_UNMOUNT_PM_UPDATE: {
                     UnmountCallBack ucb = (UnmountCallBack) msg.obj;
                     mForceUnmounts.add(ucb);
-                    mContext.registerReceiver(mPmReceiver, mPmFilter);
-                    boolean hasExtPkgs = mPms.updateExternalMediaStatus(false);
-                    if (!hasExtPkgs) {
-                        // Unregister right away
-                        mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
+                    // Register only if needed.
+                    if (!mRegistered) {
+                        registerReceiver();
+                        boolean hasExtPkgs = mPms.updateExternalMediaStatus(false);
+                        if (!hasExtPkgs) {
+                            // Unregister right away
+                            mHandler.sendEmptyMessage(H_UNMOUNT_PM_DONE);
+                        }
                     }
                     break;
                 }
                 case H_UNMOUNT_PM_DONE: {
-                    // Unregister receiver
-                    mContext.unregisterReceiver(mPmReceiver);
-                    UnmountCallBack ucb = mForceUnmounts.get(0);
-                    if (ucb == null || ucb.path == null) {
-                        // Just ignore
-                        return;
+                    // Unregister now.
+                    if (mRegistered) {
+                        unregisterReceiver();
                     }
-                    String path = ucb.path;
-                    boolean done = false;
-                    if (!ucb.force) {
-                        done = true;
-                    } else {
-                        int pids[] = getStorageUsers(path);
-                        if (pids == null || pids.length == 0) {
+                    int size = mForceUnmounts.size();
+                    int sizeArr[] = new int[size];
+                    int sizeArrN = 0;
+                    for (int i = 0; i < size; i++) {
+                        UnmountCallBack ucb = mForceUnmounts.get(i);
+                        String path = ucb.path;
+                        boolean done = false;
+                        if (!ucb.force) {
                             done = true;
                         } else {
-                            // Kill processes holding references first
-                            ActivityManagerService ams = (ActivityManagerService)
-                            ServiceManager.getService("activity");
-                            // Eliminate system process here?
-                            boolean ret = ams.killPidsForMemory(pids);
-                            if (ret) {
-                                // Confirm if file references have been freed.
-                                pids = getStorageUsers(path);
-                                if (pids == null || pids.length == 0) {
-                                    done = true;
+                            int pids[] = getStorageUsers(path);
+                            if (pids == null || pids.length == 0) {
+                                done = true;
+                            } else {
+                                // Kill processes holding references first
+                                ActivityManagerService ams = (ActivityManagerService)
+                                ServiceManager.getService("activity");
+                                // Eliminate system process here?
+                                boolean ret = ams.killPidsForMemory(pids);
+                                if (ret) {
+                                    // Confirm if file references have been freed.
+                                    pids = getStorageUsers(path);
+                                    if (pids == null || pids.length == 0) {
+                                        done = true;
+                                    }
                                 }
                             }
                         }
-                    }
-                    if (done) {
-                        mForceUnmounts.remove(0);
-                        mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
-                                ucb));
-                    } else {
-                        if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
-                            Log.i(TAG, "Cannot unmount inspite of " +
-                                    MAX_UNMOUNT_RETRIES + " to unmount media");
-                            // Send final broadcast indicating failure to unmount.                      
+                        if (done) {
+                            sizeArr[sizeArrN++] = i;
+                            mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_MS,
+                                    ucb));
                         } else {
-                            mHandler.sendMessageDelayed(
-                                    mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
-                                            ucb.retries++),
-                                    RETRY_UNMOUNT_DELAY);
+                            if (ucb.retries >= MAX_UNMOUNT_RETRIES) {
+                                Log.i(TAG, "Cannot unmount inspite of " +
+                                        MAX_UNMOUNT_RETRIES + " to unmount media");
+                                // Send final broadcast indicating failure to unmount.                 
+                            } else {
+                                mHandler.sendMessageDelayed(
+                                        mHandler.obtainMessage(H_UNMOUNT_PM_DONE,
+                                                ucb.retries++),
+                                        RETRY_UNMOUNT_DELAY);
+                            }
                         }
                     }
+                    // Remove already processed elements from list.
+                    for (int i = (sizeArrN-1); i >= 0; i--) {
+                        mForceUnmounts.remove(sizeArr[i]);
+                    }
                     break;
                 }
                 case H_UNMOUNT_MS : {
@@ -826,7 +868,7 @@
         }
     }
 
-    public void shutdown() {
+    public void shutdown(final IMountShutdownObserver observer) {
         validatePermission(android.Manifest.permission.SHUTDOWN);
 
         Log.i(TAG, "Shutting down");
@@ -865,12 +907,9 @@
         }
 
         if (state.equals(Environment.MEDIA_MOUNTED)) {
-            /*
-             * If the media is mounted, then gracefully unmount it.
-             */
-            if (doUnmountVolume(path, true) != StorageResultCode.OperationSucceeded) {
-                Log.e(TAG, "Failed to unmount media for shutdown");
-            }
+            // Post a unmount message.
+            ShutdownCallBack ucb = new ShutdownCallBack(path, observer);
+            mHandler.sendMessage(mHandler.obtainMessage(H_UNMOUNT_PM_UPDATE, ucb));
         }
     }
 
diff --git a/services/java/com/android/server/PackageManagerService.java b/services/java/com/android/server/PackageManagerService.java
index 371fa37..63afabc 100644
--- a/services/java/com/android/server/PackageManagerService.java
+++ b/services/java/com/android/server/PackageManagerService.java
@@ -4589,7 +4589,7 @@
                         } else {
                             // When replacing apps make sure we honour
                             // the existing app location if not overwritten by other options
-                            boolean prevOnSd = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0;
+                            boolean prevOnSd = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
                             if (onSd) {
                                 // Install flag overrides everything.
                                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
@@ -5995,7 +5995,7 @@
         // Delete application code and resources
         if (deleteCodeAndResources) {
             // TODO can pick up from PackageSettings as well
-            int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
+            int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
                     PackageManager.INSTALL_EXTERNAL : 0;
             installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
                     PackageManager.INSTALL_FORWARD_LOCK : 0;
@@ -6321,10 +6321,14 @@
     }
 
     public void clearPackagePreferredActivities(String packageName) {
-        mContext.enforceCallingOrSelfPermission(
-                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
-
         synchronized (mPackages) {
+            int uid = Binder.getCallingUid();
+            PackageParser.Package pkg = mPackages.get(packageName);
+            if (pkg.applicationInfo.uid != uid) {
+                mContext.enforceCallingOrSelfPermission(
+                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
+            }
+
             if (clearPackagePreferredActivitiesLP(packageName)) {
                 mSettings.writeLP();
             }
@@ -7214,7 +7218,7 @@
         void setFlags(int pkgFlags) {
             this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
             (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
-            (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD) |
+            (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) |
             (pkgFlags & ApplicationInfo.FLAG_NEVER_ENCRYPT);
         }
     }
@@ -9058,7 +9062,7 @@
                return false;
            }
            mMediaMounted = mediaStatus;
-           Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
+           Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_EXTERNAL_STORAGE);
            ret = appList != null && appList.size() > 0;
        }
        // Queue up an async operation since the package installation may take a little while.
@@ -9107,7 +9111,7 @@
                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
                    PackageSetting ps = mSettings.mPackages.get(pkgName);
                    if (ps != null && ps.codePathString != null &&
-                           (ps.pkgFlags & ApplicationInfo.FLAG_ON_SDCARD) != 0) {
+                           (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
                                " corresponds to pkg : " + pkgName +
                                " at code path: " + ps.codePathString);
@@ -9333,7 +9337,7 @@
                } else {
                    newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
                            PackageManager.INSTALL_EXTERNAL : 0;
-                   currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0 ?
+                   currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
                            PackageManager.INSTALL_EXTERNAL : 0;
                    if (newFlags == currFlags) {
                        Log.w(TAG, "No move required. Trying to move to same location");
@@ -9400,9 +9404,9 @@
                                ps.resourcePathString = ps.resourcePath.getPath();
                                // Set the application info flag correctly.
                                if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
-                                   pkg.applicationInfo.flags |= ApplicationInfo.FLAG_ON_SDCARD;
+                                   pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
                                } else {
-                                   pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_ON_SDCARD;
+                                   pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
                                }
                                ps.setFlags(pkg.applicationInfo.flags);
                                mAppDirs.remove(oldCodePath);
diff --git a/services/java/com/android/server/PowerManagerService.java b/services/java/com/android/server/PowerManagerService.java
index 0189c60..fc6bfcd 100644
--- a/services/java/com/android/server/PowerManagerService.java
+++ b/services/java/com/android/server/PowerManagerService.java
@@ -17,6 +17,7 @@
 package com.android.server;
 
 import com.android.internal.app.IBatteryStats;
+import com.android.internal.app.ShutdownThread;
 import com.android.server.am.BatteryStatsService;
 
 import android.app.ActivityManagerNative;
@@ -41,7 +42,6 @@
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.IBinder;
-import android.os.storage.IMountService;
 import android.os.IPowerManager;
 import android.os.LocalPowerManager;
 import android.os.Power;
@@ -2202,28 +2202,35 @@
     {
         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
 
-        /*
-         * Manually shutdown the MountService to ensure media is
-         * put into a safe state.
-         */
-        IMountService mSvc = IMountService.Stub.asInterface(
-                ServiceManager.getService("mount"));
-
-        if (mSvc != null) {
-            try {
-                mSvc.shutdown();
-            } catch (Exception e) {
-                Slog.e(TAG, "MountService shutdown failed", e);
+        if (mHandler == null || !ActivityManagerNative.isSystemReady()) {
+            throw new IllegalStateException("Too early to call reboot()");
+        }
+        
+        final String finalReason = reason;
+        Runnable runnable = new Runnable() {
+            public void run() {
+                synchronized (this) {
+                    ShutdownThread.reboot(mContext, finalReason, false);
+                    // if we get here we failed
+                    notify();
+                }
+                
             }
-        } else {
-            Slog.w(TAG, "MountService unavailable for shutdown");
-        }
+        };
 
-        try {
-            Power.reboot(reason);
-        } catch (IOException e) {
-            Slog.e(TAG, "reboot failed", e);
+        mHandler.post(runnable);
+
+        // block until we reboot or fail.
+        // throw an exception if we failed to reboot
+        synchronized (runnable) {
+            try {
+                runnable.wait();
+            } catch (InterruptedException e) {
+            }
         }
+     
+        // if we get here we failed
+        throw new IllegalStateException("unable to reboot!");
     }
 
     /**
diff --git a/services/java/com/android/server/UiModeManagerService.java b/services/java/com/android/server/UiModeManagerService.java
index 5f23a90..8103d7c 100644
--- a/services/java/com/android/server/UiModeManagerService.java
+++ b/services/java/com/android/server/UiModeManagerService.java
@@ -88,7 +88,9 @@
 
     private boolean mComputedNightMode;
     private int mCurUiMode = 0;
+    private int mSetUiMode = 0;
     
+    private boolean mHoldingConfiguration = false;
     private Configuration mConfiguration = new Configuration();
     
     private boolean mSystemReady;
@@ -114,25 +116,32 @@
                 return;
             }
 
-            // Launch a dock activity
-            String category;
-            if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(intent.getAction())) {
-                // Only launch car home when car mode is enabled.
-                category = Intent.CATEGORY_CAR_DOCK;
-            } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(intent.getAction())) {
-                category = Intent.CATEGORY_DESK_DOCK;
-            } else {
-                category = null;
-            }
-            if (category != null) {
-                intent = new Intent(Intent.ACTION_MAIN);
-                intent.addCategory(category);
-                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
-                        | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
-                try {
-                    mContext.startActivity(intent);
-                } catch (ActivityNotFoundException e) {
-                    Slog.w(TAG, e.getCause());
+            synchronized (mLock) {
+                // Launch a dock activity
+                String category;
+                if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(intent.getAction())) {
+                    // Only launch car home when car mode is enabled.
+                    category = Intent.CATEGORY_CAR_DOCK;
+                } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(intent.getAction())) {
+                    category = Intent.CATEGORY_DESK_DOCK;
+                } else {
+                    category = null;
+                }
+                if (category != null) {
+                    intent = new Intent(Intent.ACTION_MAIN);
+                    intent.addCategory(category);
+                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
+                            | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
+                    try {
+                        mContext.startActivity(intent);
+                    } catch (ActivityNotFoundException e) {
+                        Slog.w(TAG, e.getCause());
+                    }
+                }
+                
+                if (mHoldingConfiguration) {
+                    mHoldingConfiguration = false;
+                    updateConfigurationLocked();
                 }
             }
         }
@@ -370,42 +379,46 @@
         }
     }
 
+    final void updateConfigurationLocked() {
+        int uiMode = 0;
+        if (mCarModeEnabled) {
+            uiMode = Configuration.UI_MODE_TYPE_CAR;
+        } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
+            uiMode = Configuration.UI_MODE_TYPE_DESK;
+        }
+        if (uiMode != 0) {
+            if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
+                updateTwilightLocked();
+                uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
+                        : Configuration.UI_MODE_NIGHT_NO;
+            } else {
+                uiMode |= mNightMode << 4;
+            }
+        } else {
+            // Disabling the car mode clears the night mode.
+            uiMode = Configuration.UI_MODE_TYPE_NORMAL |
+                    Configuration.UI_MODE_NIGHT_NO;
+        }
+        
+        mCurUiMode = uiMode;
+        
+        if (!mHoldingConfiguration && uiMode != mSetUiMode) {
+            mSetUiMode = uiMode;
+            
+            try {
+                final IActivityManager am = ActivityManagerNative.getDefault();
+                mConfiguration.uiMode = uiMode;
+                am.updateConfiguration(mConfiguration);
+            } catch (RemoteException e) {
+                Slog.w(TAG, "Failure communicating with activity manager", e);
+            }
+        }
+    }
+    
     final void updateLocked() {
         long ident = Binder.clearCallingIdentity();
         
         try {
-            int uiMode = 0;
-            if (mCarModeEnabled) {
-                uiMode = Configuration.UI_MODE_TYPE_CAR;
-            } else if (mDockState == Intent.EXTRA_DOCK_STATE_DESK) {
-                uiMode = Configuration.UI_MODE_TYPE_DESK;
-            }
-            if (uiMode != 0) {
-                if (mNightMode == UiModeManager.MODE_NIGHT_AUTO) {
-                    updateTwilightLocked();
-                    uiMode |= mComputedNightMode ? Configuration.UI_MODE_NIGHT_YES
-                            : Configuration.UI_MODE_NIGHT_NO;
-                } else {
-                    uiMode |= mNightMode << 4;
-                }
-            } else {
-                // Disabling the car mode clears the night mode.
-                uiMode = Configuration.UI_MODE_TYPE_NORMAL |
-                        Configuration.UI_MODE_NIGHT_NO;
-            }
-            
-            if (uiMode != mCurUiMode) {
-                mCurUiMode = uiMode;
-                
-                try {
-                    final IActivityManager am = ActivityManagerNative.getDefault();
-                    mConfiguration.uiMode = uiMode;
-                    am.updateConfiguration(mConfiguration);
-                } catch (RemoteException e) {
-                    Slog.w(TAG, "Failure communicating with activity manager", e);
-                }
-            }
-            
             String action = null;
             String oldAction = null;
             if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
@@ -450,7 +463,13 @@
                 // placed into a dock.
                 mContext.sendOrderedBroadcast(new Intent(action), null,
                         mResultReceiver, null, Activity.RESULT_OK, null, null);
+                // Attempting to make this transition a little more clean, we are going
+                // to hold off on doing a configuration change until we have finished
+                // the broacast and started the home activity.
+                mHoldingConfiguration = true;
             }
+            
+            updateConfigurationLocked();
 
             // keep screen on when charging and in car mode
             boolean keepScreenOn = mCharging &&
@@ -685,6 +704,8 @@
                     pw.print(" mCarModeEnabled="); pw.print(mCarModeEnabled);
                     pw.print(" mComputedNightMode="); pw.println(mComputedNightMode);
             pw.print("  mCurUiMode=0x"); pw.print(Integer.toHexString(mCurUiMode));
+                    pw.print(" mSetUiMode=0x"); pw.println(Integer.toHexString(mSetUiMode));
+            pw.print("  mHoldingConfiguration="); pw.print(mHoldingConfiguration);
                     pw.print(" mSystemReady="); pw.println(mSystemReady);
             if (mLocation != null) {
                 pw.print("  mLocation="); pw.println(mLocation);
diff --git a/services/java/com/android/server/Watchdog.java b/services/java/com/android/server/Watchdog.java
index f97f50a..3f64b25 100644
--- a/services/java/com/android/server/Watchdog.java
+++ b/services/java/com/android/server/Watchdog.java
@@ -29,6 +29,7 @@
 import android.os.Handler;
 import android.os.Message;
 import android.os.Process;
+import android.os.ServiceManager;
 import android.os.SystemClock;
 import android.os.SystemProperties;
 import android.provider.Settings;
@@ -676,11 +677,8 @@
      */
     void rebootSystem(String reason) {
         Slog.i(TAG, "Rebooting system because: " + reason);
-        try {
-            android.os.Power.reboot(reason);
-        } catch (IOException e) {
-            Slog.e(TAG, "Reboot failed!", e);
-        }
+        PowerManagerService pms = (PowerManagerService) ServiceManager.getService("power");
+        pms.reboot(reason);
     }
 
     /**
diff --git a/services/java/com/android/server/WifiService.java b/services/java/com/android/server/WifiService.java
index 8fa862d..248f579 100644
--- a/services/java/com/android/server/WifiService.java
+++ b/services/java/com/android/server/WifiService.java
@@ -96,7 +96,6 @@
     private final WifiStateTracker mWifiStateTracker;
 
     private Context mContext;
-    private int mWifiState;
     private int mWifiApState;
 
     private AlarmManager mAlarmManager;
@@ -216,7 +215,7 @@
         wifiThread.start();
         mWifiHandler = new WifiHandler(wifiThread.getLooper());
 
-        mWifiState = WIFI_STATE_DISABLED;
+        mWifiStateTracker.setWifiState(WIFI_STATE_DISABLED);
         mWifiApState = WIFI_AP_STATE_DISABLED;
         boolean wifiEnabled = getPersistedWifiEnabled();
         boolean wifiAPEnabled = wifiEnabled ? false : getPersistedWifiApEnabled();
@@ -346,9 +345,8 @@
      */
     public boolean pingSupplicant() {
         enforceChangePermission();
-        synchronized (mWifiStateTracker) {
-            return WifiNative.pingCommand();
-        }
+
+        return mWifiStateTracker.ping();
     }
 
     /**
@@ -357,20 +355,19 @@
      */
     public boolean startScan(boolean forceActive) {
         enforceChangePermission();
-        synchronized (mWifiStateTracker) {
-            switch (mWifiStateTracker.getSupplicantState()) {
-                case DISCONNECTED:
-                case INACTIVE:
-                case SCANNING:
-                case DORMANT:
-                    break;
-                default:
-                    WifiNative.setScanResultHandlingCommand(
-                            WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
-                    break;
-            }
-            return WifiNative.scanCommand(forceActive);
+
+        switch (mWifiStateTracker.getSupplicantState()) {
+            case DISCONNECTED:
+            case INACTIVE:
+            case SCANNING:
+            case DORMANT:
+                break;
+            default:
+                mWifiStateTracker.setScanResultHandling(
+                        WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
+                break;
         }
+        return mWifiStateTracker.scan(forceActive);
     }
 
     /**
@@ -408,8 +405,9 @@
      */
     private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
         final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
+        final int wifiState = mWifiStateTracker.getWifiState();
 
-        if (mWifiState == eventualWifiState) {
+        if (wifiState == eventualWifiState) {
             return true;
         }
         if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
@@ -423,7 +421,7 @@
          * Avoid doing a disable when the current Wifi state is UNKNOWN
          * TODO: Handle driver load fail and supplicant lost as seperate states
          */
-        if ((mWifiState == WIFI_STATE_UNKNOWN) && !enable) {
+        if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
             return false;
         }
 
@@ -434,19 +432,18 @@
         }
 
         if (enable) {
-            synchronized (mWifiStateTracker) {
-                if (!WifiNative.loadDriver()) {
-                    Slog.e(TAG, "Failed to load Wi-Fi driver.");
-                    setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
-                    return false;
-                }
-                if (!WifiNative.startSupplicant()) {
-                    WifiNative.unloadDriver();
-                    Slog.e(TAG, "Failed to start supplicant daemon.");
-                    setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
-                    return false;
-                }
+            if (!mWifiStateTracker.loadDriver()) {
+                Slog.e(TAG, "Failed to load Wi-Fi driver.");
+                setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
+                return false;
             }
+            if (!mWifiStateTracker.startSupplicant()) {
+                mWifiStateTracker.unloadDriver();
+                Slog.e(TAG, "Failed to start supplicant daemon.");
+                setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
+                return false;
+            }
+
             registerForBroadcasts();
             mWifiStateTracker.startEventLoop();
         } else {
@@ -456,27 +453,27 @@
             mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
 
             boolean failedToStopSupplicantOrUnloadDriver = false;
-            synchronized (mWifiStateTracker) {
-                if (!WifiNative.stopSupplicant()) {
-                    Slog.e(TAG, "Failed to stop supplicant daemon.");
+
+            if (!mWifiStateTracker.stopSupplicant()) {
+                Slog.e(TAG, "Failed to stop supplicant daemon.");
+                setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
+                failedToStopSupplicantOrUnloadDriver = true;
+            }
+
+            /**
+             * Reset connections and disable interface
+             * before we unload the driver
+             */
+            mWifiStateTracker.resetConnections(true);
+
+            if (!mWifiStateTracker.unloadDriver()) {
+                Slog.e(TAG, "Failed to unload Wi-Fi driver.");
+                if (!failedToStopSupplicantOrUnloadDriver) {
                     setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
                     failedToStopSupplicantOrUnloadDriver = true;
                 }
-
-                /**
-                 * Reset connections and disable interface
-                 * before we unload the driver
-                 */
-                mWifiStateTracker.resetConnections(true);
-
-                if (!WifiNative.unloadDriver()) {
-                    Slog.e(TAG, "Failed to unload Wi-Fi driver.");
-                    if (!failedToStopSupplicantOrUnloadDriver) {
-                        setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
-                        failedToStopSupplicantOrUnloadDriver = true;
-                    }
-                }
             }
+
             if (failedToStopSupplicantOrUnloadDriver) {
                 return false;
             }
@@ -492,7 +489,7 @@
     }
 
     private void setWifiEnabledState(int wifiState, int uid) {
-        final int previousWifiState = mWifiState;
+        final int previousWifiState = mWifiStateTracker.getWifiState();
 
         long ident = Binder.clearCallingIdentity();
         try {
@@ -507,7 +504,7 @@
         }
 
         // Update state
-        mWifiState = wifiState;
+        mWifiStateTracker.setWifiState(wifiState);
 
         // Broadcast
         final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
@@ -544,7 +541,7 @@
      */
     public int getWifiEnabledState() {
         enforceAccessPermission();
-        return mWifiState;
+        return mWifiStateTracker.getWifiState();
     }
 
     /**
@@ -553,9 +550,8 @@
      */
     public boolean disconnect() {
         enforceChangePermission();
-        synchronized (mWifiStateTracker) {
-            return WifiNative.disconnectCommand();
-        }
+
+        return mWifiStateTracker.disconnect();
     }
 
     /**
@@ -564,9 +560,8 @@
      */
     public boolean reconnect() {
         enforceChangePermission();
-        synchronized (mWifiStateTracker) {
-            return WifiNative.reconnectCommand();
-        }
+
+        return mWifiStateTracker.reconnectCommand();
     }
 
     /**
@@ -575,9 +570,8 @@
      */
     public boolean reassociate() {
         enforceChangePermission();
-        synchronized (mWifiStateTracker) {
-            return WifiNative.reassociateCommand();
-        }
+
+        return mWifiStateTracker.reassociate();
     }
 
     private boolean getPersistedWifiApEnabled() {
@@ -645,17 +639,15 @@
 
         setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING : WIFI_AP_STATE_DISABLING, uid);
 
-        if (enable && (mWifiState == WIFI_STATE_ENABLED)) {
+        if (enable && (mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED)) {
             setWifiEnabledBlocking(false, true, Process.myUid());
         }
 
         if (enable) {
-            synchronized (mWifiStateTracker) {
-                if (!WifiNative.loadDriver()) {
-                    Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
-                    setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
-                    return false;
-                }
+            if (!mWifiStateTracker.loadDriver()) {
+                Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
+                setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
+                return false;
             }
 
             try {
@@ -672,12 +664,10 @@
                 Slog.e(TAG, "Exception in stopAccessPoint()");
             }
 
-            synchronized (mWifiStateTracker) {
-                if (!WifiNative.unloadDriver()) {
-                    Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
-                    setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
-                    return false;
-                }
+            if (!mWifiStateTracker.unloadDriver()) {
+                Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
+                setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid);
+                return false;
             }
         }
 
@@ -735,15 +725,15 @@
     public List<WifiConfiguration> getConfiguredNetworks() {
         enforceAccessPermission();
         String listStr;
+
         /*
          * We don't cache the list, because we want to allow
          * for the possibility that the configuration file
          * has been modified through some external means,
          * such as the wpa_cli command line program.
          */
-        synchronized (mWifiStateTracker) {
-            listStr = WifiNative.listNetworksCommand();
-        }
+        listStr = mWifiStateTracker.listNetworks();
+
         List<WifiConfiguration> networks =
             new ArrayList<WifiConfiguration>();
         if (listStr == null)
@@ -767,11 +757,10 @@
                    config.status = WifiConfiguration.Status.DISABLED;
                else
                    config.status = WifiConfiguration.Status.ENABLED;
-           } else
+           } else {
                config.status = WifiConfiguration.Status.ENABLED;
-           synchronized (mWifiStateTracker) {
-               readNetworkVariables(config);
            }
+           readNetworkVariables(config);
            networks.add(config);
        }
 
@@ -785,7 +774,7 @@
      * The caller must hold the synchronization monitor.
      * @param config the {@link WifiConfiguration} object to be filled in.
      */
-    private static void readNetworkVariables(WifiConfiguration config) {
+    private void readNetworkVariables(WifiConfiguration config) {
 
         int netId = config.networkId;
         if (netId < 0)
@@ -798,21 +787,21 @@
          */
         String value;
 
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
         if (!TextUtils.isEmpty(value)) {
             config.SSID = removeDoubleQuotes(value);
         } else {
             config.SSID = null;
         }
 
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
         if (!TextUtils.isEmpty(value)) {
             config.BSSID = value;
         } else {
             config.BSSID = null;
         }
 
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
         config.priority = -1;
         if (!TextUtils.isEmpty(value)) {
             try {
@@ -821,7 +810,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
         config.hiddenSSID = false;
         if (!TextUtils.isEmpty(value)) {
             try {
@@ -830,7 +819,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
         config.wepTxKeyIndex = -1;
         if (!TextUtils.isEmpty(value)) {
             try {
@@ -844,7 +833,7 @@
          * just a "*" if the key is set, or the null string otherwise.
          */
         for (int i = 0; i < 4; i++) {
-            value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepKeyVarNames[i]);
+            value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
             if (!TextUtils.isEmpty(value)) {
                 config.wepKeys[i] = value;
             } else {
@@ -856,14 +845,14 @@
          * Get the private shared key. Note that the actual keys are not passed back,
          * just a "*" if the key is set, or the null string otherwise.
          */
-        value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
+        value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
         if (!TextUtils.isEmpty(value)) {
             config.preSharedKey = value;
         } else {
             config.preSharedKey = null;
         }
 
-        value = WifiNative.getNetworkVariableCommand(config.networkId,
+        value = mWifiStateTracker.getNetworkVariable(config.networkId,
                 WifiConfiguration.Protocol.varName);
         if (!TextUtils.isEmpty(value)) {
             String vals[] = value.split(" ");
@@ -876,7 +865,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(config.networkId,
+        value = mWifiStateTracker.getNetworkVariable(config.networkId,
                 WifiConfiguration.KeyMgmt.varName);
         if (!TextUtils.isEmpty(value)) {
             String vals[] = value.split(" ");
@@ -889,7 +878,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(config.networkId,
+        value = mWifiStateTracker.getNetworkVariable(config.networkId,
                 WifiConfiguration.AuthAlgorithm.varName);
         if (!TextUtils.isEmpty(value)) {
             String vals[] = value.split(" ");
@@ -902,7 +891,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(config.networkId,
+        value = mWifiStateTracker.getNetworkVariable(config.networkId,
                 WifiConfiguration.PairwiseCipher.varName);
         if (!TextUtils.isEmpty(value)) {
             String vals[] = value.split(" ");
@@ -915,7 +904,7 @@
             }
         }
 
-        value = WifiNative.getNetworkVariableCommand(config.networkId,
+        value = mWifiStateTracker.getNetworkVariable(config.networkId,
                 WifiConfiguration.GroupCipher.varName);
         if (!TextUtils.isEmpty(value)) {
             String vals[] = value.split(" ");
@@ -930,7 +919,7 @@
 
         for (WifiConfiguration.EnterpriseField field :
                 config.enterpriseFields) {
-            value = WifiNative.getNetworkVariableCommand(netId,
+            value = mWifiStateTracker.getNetworkVariable(netId,
                     field.varName());
             if (!TextUtils.isEmpty(value)) {
                 if (field != config.eap) value = removeDoubleQuotes(value);
@@ -955,6 +944,7 @@
      */
     public int addOrUpdateNetwork(WifiConfiguration config) {
         enforceChangePermission();
+
         /*
          * If the supplied networkId is -1, we create a new empty
          * network configuration. Otherwise, the networkId should
@@ -967,7 +957,7 @@
         // networkId of -1 means we want to create a new network
         synchronized (mWifiStateTracker) {
             if (newNetwork) {
-                netId = WifiNative.addNetworkCommand();
+                netId = mWifiStateTracker.addNetwork();
                 if (netId < 0) {
                     if (DBG) {
                         Slog.d(TAG, "Failed to add a network!");
@@ -976,7 +966,8 @@
                 }
                 doReconfig = true;
             } else {
-                String priorityVal = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
+                String priorityVal = mWifiStateTracker.getNetworkVariable(
+                                            netId, WifiConfiguration.priorityVarName);
                 currentPriority = -1;
                 if (!TextUtils.isEmpty(priorityVal)) {
                     try {
@@ -987,16 +978,17 @@
                 doReconfig = currentPriority != config.priority;
             }
             mNeedReconfig = mNeedReconfig || doReconfig;
+        }
 
-            setVariables: {
+        setVariables: {
             /*
              * Note that if a networkId for a non-existent network
-             * was supplied, then the first setNetworkVariableCommand()
+             * was supplied, then the first setNetworkVariable()
              * will fail, so we don't bother to make a separate check
              * for the validity of the ID up front.
              */
             if (config.SSID != null &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.ssidVarName,
                         convertToQuotedString(config.SSID))) {
@@ -1007,7 +999,7 @@
             }
 
             if (config.BSSID != null &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.bssidVarName,
                         config.BSSID)) {
@@ -1020,7 +1012,7 @@
             String allowedKeyManagementString =
                 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
             if (config.allowedKeyManagement.cardinality() != 0 &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.KeyMgmt.varName,
                         allowedKeyManagementString)) {
@@ -1034,7 +1026,7 @@
             String allowedProtocolsString =
                 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
             if (config.allowedProtocols.cardinality() != 0 &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.Protocol.varName,
                         allowedProtocolsString)) {
@@ -1048,7 +1040,7 @@
             String allowedAuthAlgorithmsString =
                 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
             if (config.allowedAuthAlgorithms.cardinality() != 0 &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.AuthAlgorithm.varName,
                         allowedAuthAlgorithmsString)) {
@@ -1062,7 +1054,7 @@
             String allowedPairwiseCiphersString =
                 makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
             if (config.allowedPairwiseCiphers.cardinality() != 0 &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.PairwiseCipher.varName,
                         allowedPairwiseCiphersString)) {
@@ -1076,7 +1068,7 @@
             String allowedGroupCiphersString =
                 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
             if (config.allowedGroupCiphers.cardinality() != 0 &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.GroupCipher.varName,
                         allowedGroupCiphersString)) {
@@ -1090,7 +1082,7 @@
             // Prevent client screw-up by passing in a WifiConfiguration we gave it
             // by preventing "*" as a key.
             if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
-                    !WifiNative.setNetworkVariableCommand(
+                    !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.pskVarName,
                         config.preSharedKey)) {
@@ -1106,7 +1098,7 @@
                     // Prevent client screw-up by passing in a WifiConfiguration we gave it
                     // by preventing "*" as a key.
                     if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
-                        if (!WifiNative.setNetworkVariableCommand(
+                        if (!mWifiStateTracker.setNetworkVariable(
                                     netId,
                                     WifiConfiguration.wepKeyVarNames[i],
                                     config.wepKeys[i])) {
@@ -1123,7 +1115,7 @@
             }
 
             if (hasSetKey) {
-                if (!WifiNative.setNetworkVariableCommand(
+                if (!mWifiStateTracker.setNetworkVariable(
                             netId,
                             WifiConfiguration.wepTxKeyIdxVarName,
                             Integer.toString(config.wepTxKeyIndex))) {
@@ -1136,7 +1128,7 @@
                 }
             }
 
-            if (!WifiNative.setNetworkVariableCommand(
+            if (!mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.priorityVarName,
                         Integer.toString(config.priority))) {
@@ -1147,7 +1139,7 @@
                 break setVariables;
             }
 
-            if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
+            if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
                         netId,
                         WifiConfiguration.hiddenSSIDVarName,
                         Integer.toString(config.hiddenSSID ? 1 : 0))) {
@@ -1166,7 +1158,7 @@
                     if (field != config.eap) {
                         value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
                     }
-                    if (!WifiNative.setNetworkVariableCommand(
+                    if (!mWifiStateTracker.setNetworkVariable(
                                 netId,
                                 varName,
                                 value)) {
@@ -1179,21 +1171,20 @@
                 }
             }
             return netId;
-            }
+        }
 
-            /*
-             * For an update, if one of the setNetworkVariable operations fails,
-             * we might want to roll back all the changes already made. But the
-             * chances are that if anything is going to go wrong, it'll happen
-             * the first time we try to set one of the variables.
-             */
-            if (newNetwork) {
-                removeNetwork(netId);
-                if (DBG) {
-                    Slog.d(TAG,
-                            "Failed to set a network variable, removed network: "
-                            + netId);
-                }
+        /*
+         * For an update, if one of the setNetworkVariable operations fails,
+         * we might want to roll back all the changes already made. But the
+         * chances are that if anything is going to go wrong, it'll happen
+         * the first time we try to set one of the variables.
+         */
+        if (newNetwork) {
+            removeNetwork(netId);
+            if (DBG) {
+                Slog.d(TAG,
+                        "Failed to set a network variable, removed network: "
+                        + netId);
             }
         }
         return -1;
@@ -1260,15 +1251,13 @@
     public boolean enableNetwork(int netId, boolean disableOthers) {
         enforceChangePermission();
 
-        synchronized (mWifiStateTracker) {
-            String ifname = mWifiStateTracker.getInterfaceName();
-            NetworkUtils.enableInterface(ifname);
-            boolean result = WifiNative.enableNetworkCommand(netId, disableOthers);
-            if (!result) {
-                NetworkUtils.disableInterface(ifname);
-            }
-            return result;
+        String ifname = mWifiStateTracker.getInterfaceName();
+        NetworkUtils.enableInterface(ifname);
+        boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
+        if (!result) {
+            NetworkUtils.disableInterface(ifname);
         }
+        return result;
     }
 
     /**
@@ -1280,9 +1269,7 @@
     public boolean disableNetwork(int netId) {
         enforceChangePermission();
 
-        synchronized (mWifiStateTracker) {
-            return WifiNative.disableNetworkCommand(netId);
-        }
+        return mWifiStateTracker.disableNetwork(netId);
     }
 
     /**
@@ -1306,9 +1293,8 @@
     public List<ScanResult> getScanResults() {
         enforceAccessPermission();
         String reply;
-        synchronized (mWifiStateTracker) {
-            reply = WifiNative.scanResultsCommand();
-        }
+
+        reply = mWifiStateTracker.scanResults();
         if (reply == null) {
             return null;
         }
@@ -1456,11 +1442,12 @@
     public boolean saveConfiguration() {
         boolean result;
         enforceChangePermission();
+
         synchronized (mWifiStateTracker) {
-            result = WifiNative.saveConfigCommand();
+            result = mWifiStateTracker.saveConfig();
             if (result && mNeedReconfig) {
                 mNeedReconfig = false;
-                result = WifiNative.reloadConfigCommand();
+                result = mWifiStateTracker.reloadConfig();
 
                 if (result) {
                     Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
@@ -1532,18 +1519,17 @@
         int numChannels;
 
         enforceAccessPermission();
-        synchronized (mWifiStateTracker) {
-            /*
-             * If we can't get the value from the driver (e.g., because
-             * Wi-Fi is not currently enabled), get the value from
-             * Settings.
-             */
-            numChannels = WifiNative.getNumAllowedChannelsCommand();
-            if (numChannels < 0) {
-                numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
-                                                     Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
-                                                     -1);
-            }
+
+        /*
+         * If we can't get the value from the driver (e.g., because
+         * Wi-Fi is not currently enabled), get the value from
+         * Settings.
+         */
+        numChannels = mWifiStateTracker.getNumAllowedChannels();
+        if (numChannels < 0) {
+            numChannels = Settings.Secure.getInt(mContext.getContentResolver(),
+                    Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
+                    -1);
         }
         return numChannels;
     }
@@ -1735,7 +1721,7 @@
         }
 
         synchronized (mWifiHandler) {
-            if (mWifiState == WIFI_STATE_ENABLING && !airplaneMode) {
+            if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
                 return;
             }
             if (wifiShouldBeEnabled) {
@@ -1878,7 +1864,7 @@
                     + ", uid=" + Binder.getCallingUid());
             return;
         }
-        pw.println("Wi-Fi is " + stateName(mWifiState));
+        pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
         pw.println("Stay-awake conditions: " +
                 Settings.System.getInt(mContext.getContentResolver(),
                                        Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
@@ -2126,14 +2112,13 @@
 
     public void initializeMulticastFiltering() {
         enforceMulticastChangePermission();
+
         synchronized (mMulticasters) {
             // if anybody had requested filters be off, leave off
             if (mMulticasters.size() != 0) {
                 return;
             } else {
-                synchronized (mWifiStateTracker) {
-                    WifiNative.startPacketFiltering();
-                }
+                mWifiStateTracker.startPacketFiltering();
             }
         }
     }
@@ -2148,9 +2133,7 @@
             // our new size == 1 (first call), but this function won't
             // be called often and by making the stopPacket call each
             // time we're less fragile and self-healing.
-            synchronized (mWifiStateTracker) {
-                WifiNative.stopPacketFiltering();
-            }
+            mWifiStateTracker.stopPacketFiltering();
         }
 
         int uid = Binder.getCallingUid();
@@ -2182,13 +2165,12 @@
     private void removeMulticasterLocked(int i, int uid)
     {
         Multicaster removed = mMulticasters.remove(i);
+
         if (removed != null) {
             removed.unlinkDeathRecipient();
         }
         if (mMulticasters.size() == 0) {
-            synchronized (mWifiStateTracker) {
-                WifiNative.startPacketFiltering();
-            }
+            mWifiStateTracker.startPacketFiltering();
         }
 
         Long ident = Binder.clearCallingIdentity();
diff --git a/services/java/com/android/server/WindowManagerService.java b/services/java/com/android/server/WindowManagerService.java
index f5d3e8e..989fe2a 100644
--- a/services/java/com/android/server/WindowManagerService.java
+++ b/services/java/com/android/server/WindowManagerService.java
@@ -43,6 +43,7 @@
 
 import com.android.internal.app.IBatteryStats;
 import com.android.internal.policy.PolicyManager;
+import com.android.internal.policy.impl.PhoneWindowManager;
 import com.android.internal.view.IInputContext;
 import com.android.internal.view.IInputMethodClient;
 import com.android.internal.view.IInputMethodManager;
@@ -984,10 +985,15 @@
         //Slog.i(TAG, "Placing input method @" + (i+1));
         if (w != null) {
             if (willMove) {
-                RuntimeException e = new RuntimeException();
-                if (!HIDE_STACK_CRAWLS) e.fillInStackTrace();
-                if (DEBUG_INPUT_METHOD) Slog.w(TAG, "Moving IM target from "
-                        + mInputMethodTarget + " to " + w, e);
+                if (DEBUG_INPUT_METHOD) {
+                    RuntimeException e = null;
+                    if (!HIDE_STACK_CRAWLS) {
+                        e = new RuntimeException();
+                        e.fillInStackTrace();
+                    }
+                    Slog.w(TAG, "Moving IM target from "
+                            + mInputMethodTarget + " to " + w, e);
+                }
                 mInputMethodTarget = w;
                 if (w.mAppToken != null) {
                     setInputMethodAnimLayerAdjustment(w.mAppToken.animLayerAdjustment);
@@ -998,10 +1004,15 @@
             return i+1;
         }
         if (willMove) {
-            RuntimeException e = new RuntimeException();
-            if (!HIDE_STACK_CRAWLS) e.fillInStackTrace();
-            if (DEBUG_INPUT_METHOD) Slog.w(TAG, "Moving IM target from "
-                    + mInputMethodTarget + " to null", e);
+            if (DEBUG_INPUT_METHOD) {
+                RuntimeException e = null;
+                if (!HIDE_STACK_CRAWLS) {
+                    e = new RuntimeException();
+                    e.fillInStackTrace();
+                }
+                Slog.w(TAG, "Moving IM target from "
+                        + mInputMethodTarget + " to null", e);
+            }
             mInputMethodTarget = null;
             setInputMethodAnimLayerAdjustment(0);
         }
@@ -2178,6 +2189,16 @@
         }
     }
 
+    private static void logSurface(WindowState w, String msg, RuntimeException where) {
+        String str = "  SURFACE " + Integer.toHexString(w.hashCode())
+                + ": " + msg + " / " + w.mAttrs.getTitle();
+        if (where != null) {
+            Slog.i(TAG, str, where);
+        } else {
+            Slog.i(TAG, str);
+        }
+    }
+    
     private void setTransparentRegionWindow(Session session, IWindow client, Region region) {
         long origId = Binder.clearCallingIdentity();
         try {
@@ -2187,9 +2208,8 @@
                     if (SHOW_TRANSACTIONS) Slog.i(TAG, ">>> OPEN TRANSACTION");
                     Surface.openTransaction();
                     try {
-                        if (SHOW_TRANSACTIONS) Slog.i(
-                                TAG, "  SURFACE " + w.mSurface
-                                + ": transparentRegionHint=" + region);
+                        if (SHOW_TRANSACTIONS) logSurface(w,
+                                "transparentRegionHint=" + region, null);
                         w.mSurface.setTransparentRegionHint(region);
                     } finally {
                         if (SHOW_TRANSACTIONS) Slog.i(TAG, "<<< CLOSE TRANSACTION");
@@ -2654,8 +2674,11 @@
                     + " isEntrance=" + isEntrance);
             if (a != null) {
                 if (DEBUG_ANIM) {
-                    RuntimeException e = new RuntimeException();
-                    if (!HIDE_STACK_CRAWLS) e.fillInStackTrace();
+                    RuntimeException e = null;
+                    if (!HIDE_STACK_CRAWLS) {
+                        e = new RuntimeException();
+                        e.fillInStackTrace();
+                    }
                     Slog.v(TAG, "Loaded animation " + a + " for " + win, e);
                 }
                 win.setAnimation(a);
@@ -2777,8 +2800,11 @@
             }
             if (a != null) {
                 if (DEBUG_ANIM) {
-                    RuntimeException e = new RuntimeException();
-                    if (!HIDE_STACK_CRAWLS) e.fillInStackTrace();
+                    RuntimeException e = null;
+                    if (!HIDE_STACK_CRAWLS) {
+                        e = new RuntimeException();
+                        e.fillInStackTrace();
+                    }
                     Slog.v(TAG, "Loaded animation " + a + " for " + wtoken, e);
                 }
                 wtoken.setAnimation(a);
@@ -3569,8 +3595,11 @@
             }
 
             if (DEBUG_APP_TRANSITIONS || DEBUG_ORIENTATION) {
-                RuntimeException e = new RuntimeException();
-                if (!HIDE_STACK_CRAWLS) e.fillInStackTrace();
+                RuntimeException e = null;
+                if (!HIDE_STACK_CRAWLS) {
+                    e = new RuntimeException();
+                    e.fillInStackTrace();
+                }
                 Slog.v(TAG, "setAppVisibility(" + token + ", " + visible
                         + "): mNextAppTransition=" + mNextAppTransition
                         + " hidden=" + wtoken.hidden
@@ -3671,8 +3700,11 @@
     public void startAppFreezingScreenLocked(AppWindowToken wtoken,
             int configChanges) {
         if (DEBUG_ORIENTATION) {
-            RuntimeException e = new RuntimeException();
-            if (!HIDE_STACK_CRAWLS) e.fillInStackTrace();
+            RuntimeException e = null;
+            if (!HIDE_STACK_CRAWLS) {
+                e = new RuntimeException();
+                e.fillInStackTrace();
+            }
             Slog.i(TAG, "Set freezing of " + wtoken.appToken
                     + ": hidden=" + wtoken.hidden + " freezing="
                     + wtoken.freezingScreen, e);
@@ -7305,7 +7337,8 @@
                             + mSession.mSurfaceSession
                             + ": pid=" + mSession.mPid + " format="
                             + mAttrs.format + " flags=0x"
-                            + Integer.toHexString(flags));
+                            + Integer.toHexString(flags)
+                            + " / " + this);
                 } catch (Surface.OutOfResourcesException e) {
                     Slog.w(TAG, "OutOfResourcesException creating surface");
                     reclaimSomeSurfaceMemoryLocked(this, "create");
@@ -7321,11 +7354,10 @@
                     + ", animLayer=" + mAnimLayer);
                 if (SHOW_TRANSACTIONS) {
                     Slog.i(TAG, ">>> OPEN TRANSACTION");
-                    Slog.i(TAG, "  SURFACE " + mSurface + ": CREATE ("
-                            + mAttrs.getTitle() + ") pos=(" +
-                          mFrame.left + "," + mFrame.top + ") (" +
-                          mFrame.width() + "x" + mFrame.height() + "), layer=" +
-                          mAnimLayer + " HIDE");
+                    if (SHOW_TRANSACTIONS) logSurface(this,
+                            "CREATE pos=(" + mFrame.left + "," + mFrame.top + ") (" +
+                            mFrame.width() + "x" + mFrame.height() + "), layer=" +
+                            mAnimLayer + " HIDE", null);
                 }
                 Surface.openTransaction();
                 try {
@@ -7335,8 +7367,7 @@
                         mSurface.setLayer(mAnimLayer);
                         mSurface.hide();
                         if ((mAttrs.flags&WindowManager.LayoutParams.FLAG_DITHER) != 0) {
-                            if (SHOW_TRANSACTIONS) Slog.i(TAG, "  SURFACE "
-                                    + mSurface + ": DITHER");
+                            if (SHOW_TRANSACTIONS) logSurface(this, "DITHER", null);
                             mSurface.setFlags(Surface.SURFACE_DITHER,
                                     Surface.SURFACE_DITHER);
                         }
@@ -7393,16 +7424,21 @@
 
                 try {
                     if (DEBUG_VISIBILITY) {
-                        RuntimeException e = new RuntimeException();
-                        if (!HIDE_STACK_CRAWLS) e.fillInStackTrace();
+                        RuntimeException e = null;
+                        if (!HIDE_STACK_CRAWLS) {
+                            e = new RuntimeException();
+                            e.fillInStackTrace();
+                        }
                         Slog.w(TAG, "Window " + this + " destroying surface "
                                 + mSurface + ", session " + mSession, e);
                     }
                     if (SHOW_TRANSACTIONS) {
-                        RuntimeException ex = new RuntimeException();
-                        if (!HIDE_STACK_CRAWLS) ex.fillInStackTrace();
-                        Slog.i(TAG, "  SURFACE " + mSurface + ": DESTROY ("
-                                + mAttrs.getTitle() + ")", ex);
+                        RuntimeException e = null;
+                        if (!HIDE_STACK_CRAWLS) {
+                            e = new RuntimeException();
+                            e.fillInStackTrace();
+                        }
+                        if (SHOW_TRANSACTIONS) logSurface(this, "DESTROY", e);
                     }
                     mSurface.destroy();
                 } catch (RuntimeException e) {
@@ -7445,15 +7481,18 @@
         // This must be called while inside a transaction.
         boolean performShowLocked() {
             if (DEBUG_VISIBILITY) {
-                RuntimeException e = new RuntimeException();
-                if (!HIDE_STACK_CRAWLS) e.fillInStackTrace();
+                RuntimeException e = null;
+                if (!HIDE_STACK_CRAWLS) {
+                    e = new RuntimeException();
+                    e.fillInStackTrace();
+                }
                 Slog.v(TAG, "performShow on " + this
                         + ": readyToShow=" + mReadyToShow + " readyForDisplay=" + isReadyForDisplay()
                         + " starting=" + (mAttrs.type == TYPE_APPLICATION_STARTING), e);
             }
             if (mReadyToShow && isReadyForDisplay()) {
-                if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION) Slog.i(
-                        TAG, "  SURFACE " + mSurface + ": SHOW (performShowLocked)");
+                if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION) logSurface(this,
+                        "SHOW (performShowLocked)", null);
                 if (DEBUG_VISIBILITY) Slog.v(TAG, "Showing " + this
                         + " during animation: policyVis=" + mPolicyVisibility
                         + " attHidden=" + mAttachedHidden
@@ -7666,8 +7705,7 @@
             if (mSurface != null) {
                 mDestroySurface.add(this);
                 mDestroying = true;
-                if (SHOW_TRANSACTIONS) Slog.i(
-                        TAG, "  SURFACE " + mSurface + ": HIDE (finishExit)");
+                if (SHOW_TRANSACTIONS) logSurface(this, "HIDE (finishExit)", null);
                 try {
                     mSurface.hide();
                 } catch (RuntimeException e) {
@@ -7826,6 +7864,7 @@
             final AppWindowToken atoken = mAppToken;
             return mSurface != null && !mAttachedHidden
                     && (atoken == null ? mPolicyVisibility : !atoken.hiddenRequested)
+                    && !mDrawPending && !mCommitDrawPending
                     && !mExiting && !mDestroying;
         }
 
@@ -8045,6 +8084,18 @@
                 return false;
             }
             if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility true: " + this);
+            if (doAnimation) {
+                if (DEBUG_VISIBILITY) Slog.v(TAG, "doAnimation: mPolicyVisibility="
+                        + mPolicyVisibility + " mAnimation=" + mAnimation);
+                if (mDisplayFrozen || !mPolicy.isScreenOn()) {
+                    doAnimation = false;
+                } else if (mPolicyVisibility && mAnimation == null) {
+                    // Check for the case where we are currently visible and
+                    // not animating; we do not want to do animation at such a
+                    // point to become visible when we already are.
+                    doAnimation = false;
+                }
+            }
             mPolicyVisibility = true;
             mPolicyVisibilityAfterAnim = true;
             if (doAnimation) {
@@ -8061,6 +8112,11 @@
         }
 
         boolean hideLw(boolean doAnimation, boolean requestAnim) {
+            if (doAnimation) {
+                if (mDisplayFrozen || !mPolicy.isScreenOn()) {
+                    doAnimation = false;
+                }
+            }
             boolean current = doAnimation ? mPolicyVisibilityAfterAnim
                     : mPolicyVisibility;
             if (!current) {
@@ -8082,6 +8138,9 @@
                 // for it to be displayed before enabling the display, that
                 // we allow the display to be enabled now.
                 enableScreenIfNeededLocked();
+                if (mCurrentFocus == this) {
+                    mFocusMayChange = true;
+                }
             }
             if (requestAnim) {
                 requestAnimationLocked(0);
@@ -9283,131 +9342,106 @@
         }
     }
 
-    private final void performLayoutLockedInner() {
+    private final int performLayoutLockedInner() {
+        if (!mLayoutNeeded) {
+            return 0;
+        }
+        
+        mLayoutNeeded = false;
+        
         final int dw = mDisplay.getWidth();
         final int dh = mDisplay.getHeight();
 
         final int N = mWindows.size();
-        int repeats = 0;
         int i;
 
         if (DEBUG_LAYOUT) Slog.v(TAG, "performLayout: needed="
                 + mLayoutNeeded + " dw=" + dw + " dh=" + dh);
         
-        // FIRST LOOP: Perform a layout, if needed.
+        mPolicy.beginLayoutLw(dw, dh);
 
-        while (mLayoutNeeded) {
-            mPolicy.beginLayoutLw(dw, dh);
+        int seq = mLayoutSeq+1;
+        if (seq < 0) seq = 0;
+        mLayoutSeq = seq;
+        
+        // First perform layout of any root windows (not attached
+        // to another window).
+        int topAttached = -1;
+        for (i = N-1; i >= 0; i--) {
+            WindowState win = (WindowState) mWindows.get(i);
 
-            int seq = mLayoutSeq+1;
-            if (seq < 0) seq = 0;
-            mLayoutSeq = seq;
+            // Don't do layout of a window if it is not visible, or
+            // soon won't be visible, to avoid wasting time and funky
+            // changes while a window is animating away.
+            final AppWindowToken atoken = win.mAppToken;
+            final boolean gone = win.mViewVisibility == View.GONE
+                    || !win.mRelayoutCalled
+                    || win.mRootToken.hidden
+                    || (atoken != null && atoken.hiddenRequested)
+                    || win.mAttachedHidden
+                    || win.mExiting || win.mDestroying;
+
+            if (!win.mLayoutAttached) {
+                if (DEBUG_LAYOUT) Slog.v(TAG, "First pass " + win
+                        + ": gone=" + gone + " mHaveFrame=" + win.mHaveFrame
+                        + " mLayoutAttached=" + win.mLayoutAttached);
+                if (DEBUG_LAYOUT && gone) Slog.v(TAG, "  (mViewVisibility="
+                        + win.mViewVisibility + " mRelayoutCalled="
+                        + win.mRelayoutCalled + " hidden="
+                        + win.mRootToken.hidden + " hiddenRequested="
+                        + (atoken != null && atoken.hiddenRequested)
+                        + " mAttachedHidden=" + win.mAttachedHidden);
+            }
             
-            // First perform layout of any root windows (not attached
-            // to another window).
-            int topAttached = -1;
-            for (i = N-1; i >= 0; i--) {
-                WindowState win = (WindowState) mWindows.get(i);
-
-                // Don't do layout of a window if it is not visible, or
-                // soon won't be visible, to avoid wasting time and funky
-                // changes while a window is animating away.
-                final AppWindowToken atoken = win.mAppToken;
-                final boolean gone = win.mViewVisibility == View.GONE
-                        || !win.mRelayoutCalled
-                        || win.mRootToken.hidden
-                        || (atoken != null && atoken.hiddenRequested)
-                        || win.mAttachedHidden
-                        || win.mExiting || win.mDestroying;
-
+            // If this view is GONE, then skip it -- keep the current
+            // frame, and let the caller know so they can ignore it
+            // if they want.  (We do the normal layout for INVISIBLE
+            // windows, since that means "perform layout as normal,
+            // just don't display").
+            if (!gone || !win.mHaveFrame) {
                 if (!win.mLayoutAttached) {
-                    if (DEBUG_LAYOUT) Slog.v(TAG, "First pass " + win
-                            + ": gone=" + gone + " mHaveFrame=" + win.mHaveFrame
-                            + " mLayoutAttached=" + win.mLayoutAttached);
-                    if (DEBUG_LAYOUT && gone) Slog.v(TAG, "  (mViewVisibility="
-                            + win.mViewVisibility + " mRelayoutCalled="
-                            + win.mRelayoutCalled + " hidden="
-                            + win.mRootToken.hidden + " hiddenRequested="
-                            + (atoken != null && atoken.hiddenRequested)
-                            + " mAttachedHidden=" + win.mAttachedHidden);
-                }
-                
-                // If this view is GONE, then skip it -- keep the current
-                // frame, and let the caller know so they can ignore it
-                // if they want.  (We do the normal layout for INVISIBLE
-                // windows, since that means "perform layout as normal,
-                // just don't display").
-                if (!gone || !win.mHaveFrame) {
-                    if (!win.mLayoutAttached) {
-                        mPolicy.layoutWindowLw(win, win.mAttrs, null);
-                        win.mLayoutSeq = seq;
-                        if (DEBUG_LAYOUT) Slog.v(TAG, "-> mFrame="
-                                + win.mFrame + " mContainingFrame="
-                                + win.mContainingFrame + " mDisplayFrame="
-                                + win.mDisplayFrame);
-                    } else {
-                        if (topAttached < 0) topAttached = i;
-                    }
-                }
-            }
-
-            // Now perform layout of attached windows, which usually
-            // depend on the position of the window they are attached to.
-            // XXX does not deal with windows that are attached to windows
-            // that are themselves attached.
-            for (i = topAttached; i >= 0; i--) {
-                WindowState win = (WindowState) mWindows.get(i);
-
-                // If this view is GONE, then skip it -- keep the current
-                // frame, and let the caller know so they can ignore it
-                // if they want.  (We do the normal layout for INVISIBLE
-                // windows, since that means "perform layout as normal,
-                // just don't display").
-                if (win.mLayoutAttached) {
-                    if (DEBUG_LAYOUT) Slog.v(TAG, "Second pass " + win
-                            + " mHaveFrame=" + win.mHaveFrame
-                            + " mViewVisibility=" + win.mViewVisibility
-                            + " mRelayoutCalled=" + win.mRelayoutCalled);
-                    if ((win.mViewVisibility != View.GONE && win.mRelayoutCalled)
-                            || !win.mHaveFrame) {
-                        mPolicy.layoutWindowLw(win, win.mAttrs, win.mAttachedWindow);
-                        win.mLayoutSeq = seq;
-                        if (DEBUG_LAYOUT) Slog.v(TAG, "-> mFrame="
-                                + win.mFrame + " mContainingFrame="
-                                + win.mContainingFrame + " mDisplayFrame="
-                                + win.mDisplayFrame);
-                    }
-                }
-            }
-
-            int changes = mPolicy.finishLayoutLw();
-            if ((changes&WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER) != 0) {
-                if ((adjustWallpaperWindowsLocked()&ADJUST_WALLPAPER_LAYERS_CHANGED) != 0) {
-                    assignLayersLocked();
-                }
-            }
-            if (changes == 0) {
-                mLayoutNeeded = false;
-            } else if (repeats > 2) {
-                Slog.w(TAG, "Layout repeat aborted after too many iterations");
-                mLayoutNeeded = false;
-                if ((changes&WindowManagerPolicy.FINISH_LAYOUT_REDO_CONFIG) != 0) {
-                    if (updateOrientationFromAppTokensLocked()) {
-                        mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
-                    }
-                }
-            } else {
-                if (DEBUG_LAYOUT) Slog.v(TAG, "Repeating layout because changes=0x"
-                        + Integer.toHexString(changes));
-                repeats++;
-                if ((changes&WindowManagerPolicy.FINISH_LAYOUT_REDO_CONFIG) != 0) {
-                    if (DEBUG_LAYOUT) Slog.v(TAG, "Computing new config from layout");
-                    if (updateOrientationFromAppTokensLocked()) {
-                        mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
-                    }
+                    mPolicy.layoutWindowLw(win, win.mAttrs, null);
+                    win.mLayoutSeq = seq;
+                    if (DEBUG_LAYOUT) Slog.v(TAG, "-> mFrame="
+                            + win.mFrame + " mContainingFrame="
+                            + win.mContainingFrame + " mDisplayFrame="
+                            + win.mDisplayFrame);
+                } else {
+                    if (topAttached < 0) topAttached = i;
                 }
             }
         }
+
+        // Now perform layout of attached windows, which usually
+        // depend on the position of the window they are attached to.
+        // XXX does not deal with windows that are attached to windows
+        // that are themselves attached.
+        for (i = topAttached; i >= 0; i--) {
+            WindowState win = (WindowState) mWindows.get(i);
+
+            // If this view is GONE, then skip it -- keep the current
+            // frame, and let the caller know so they can ignore it
+            // if they want.  (We do the normal layout for INVISIBLE
+            // windows, since that means "perform layout as normal,
+            // just don't display").
+            if (win.mLayoutAttached) {
+                if (DEBUG_LAYOUT) Slog.v(TAG, "Second pass " + win
+                        + " mHaveFrame=" + win.mHaveFrame
+                        + " mViewVisibility=" + win.mViewVisibility
+                        + " mRelayoutCalled=" + win.mRelayoutCalled);
+                if ((win.mViewVisibility != View.GONE && win.mRelayoutCalled)
+                        || !win.mHaveFrame) {
+                    mPolicy.layoutWindowLw(win, win.mAttrs, win.mAttachedWindow);
+                    win.mLayoutSeq = seq;
+                    if (DEBUG_LAYOUT) Slog.v(TAG, "-> mFrame="
+                            + win.mFrame + " mContainingFrame="
+                            + win.mContainingFrame + " mDisplayFrame="
+                            + win.mDisplayFrame);
+                }
+            }
+        }
+
+        return mPolicy.finishLayoutLw();
     }
 
     private final void performLayoutAndPlaceSurfacesLockedInner(
@@ -9423,9 +9457,6 @@
             updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES);
         }
         
-        // FIRST LOOP: Perform a layout, if needed.
-        performLayoutLockedInner();
-
         if (mFxSession == null) {
             mFxSession = new SurfaceSession();
         }
@@ -9442,7 +9473,6 @@
             mExitingAppTokens.get(i).hasVisible = false;
         }
 
-        // SECOND LOOP: Execute animations and update visibility of windows.
         boolean orientationChangeComplete = true;
         Session holdScreen = null;
         float screenBrightness = -1;
@@ -9452,11 +9482,50 @@
 
         Surface.openTransaction();
         try {
-            boolean restart;
-            boolean forceHiding = false;
             boolean wallpaperForceHidingChanged = false;
-
+            int repeats = 0;
+            int changes = 0;
+            
             do {
+                repeats++;
+                if (repeats > 6) {
+                    Slog.w(TAG, "Animation repeat aborted after too many iterations");
+                    mLayoutNeeded = false;
+                    break;
+                }
+                
+                if ((changes&(WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER
+                        | WindowManagerPolicy.FINISH_LAYOUT_REDO_CONFIG
+                        | WindowManagerPolicy.FINISH_LAYOUT_REDO_LAYOUT)) != 0) {
+                    if ((changes&WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER) != 0) {
+                        if ((adjustWallpaperWindowsLocked()&ADJUST_WALLPAPER_LAYERS_CHANGED) != 0) {
+                            assignLayersLocked();
+                            mLayoutNeeded = true;
+                        }
+                    }
+                    if ((changes&WindowManagerPolicy.FINISH_LAYOUT_REDO_CONFIG) != 0) {
+                        if (DEBUG_LAYOUT) Slog.v(TAG, "Computing new config from layout");
+                        if (updateOrientationFromAppTokensLocked()) {
+                            mLayoutNeeded = true;
+                            mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
+                        }
+                    }
+                    if ((changes&WindowManagerPolicy.FINISH_LAYOUT_REDO_LAYOUT) != 0) {
+                        mLayoutNeeded = true;
+                    }
+                }
+                
+                // FIRST LOOP: Perform a layout, if needed.
+                if (repeats < 4) {
+                    changes = performLayoutLockedInner();
+                    if (changes != 0) {
+                        continue;
+                    }
+                } else {
+                    Slog.w(TAG, "Layout repeat skipped after too many iterations");
+                    changes = 0;
+                }
+                
                 final int transactionSequence = ++mTransactionSequence;
 
                 // Update animations of all applications, including those
@@ -9475,15 +9544,17 @@
                     }
                 }
 
+                // SECOND LOOP: Execute animations and update visibility of windows.
+                
                 if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "*** ANIM STEP: seq="
                         + transactionSequence + " tokensAnimating="
                         + tokensAnimating);
                         
                 animating = tokensAnimating;
-                restart = false;
 
                 boolean tokenMayBeDrawn = false;
                 boolean wallpaperMayChange = false;
+                boolean forceHiding = false;
 
                 mPolicy.beginAnimationLw(dw, dh);
 
@@ -9536,7 +9607,7 @@
                                         "Now policy shown: " + w);
                                 if (changed) {
                                     if (wallpaperForceHidingChanged
-                                            && w.isReadyForDisplay()) {
+                                            && w.isVisibleNow() /*w.isReadyForDisplay()*/) {
                                         // Assume we will need to animate.  If
                                         // we don't (because the wallpaper will
                                         // stay with the lock screen), then we will
@@ -9609,9 +9680,7 @@
                     }
                 }
 
-                if (mPolicy.finishAnimationLw()) {
-                    restart = true;
-                }
+                changes |= mPolicy.finishAnimationLw();
 
                 if (tokenMayBeDrawn) {
                     // See if any windows have been drawn, so they (and others
@@ -9641,7 +9710,7 @@
                                         + " interesting=" + numInteresting
                                         + " drawn=" + wtoken.numDrawnWindows);
                                 wtoken.allDrawn = true;
-                                restart = true;
+                                changes |= PhoneWindowManager.FINISH_LAYOUT_REDO_ANIM;
 
                                 // We can now show all of the drawn windows!
                                 if (!mOpeningApps.contains(wtoken)) {
@@ -9856,15 +9925,13 @@
 
                         // This has changed the visibility of windows, so perform
                         // a new layout to get them all up-to-date.
+                        changes |= PhoneWindowManager.FINISH_LAYOUT_REDO_LAYOUT;
                         mLayoutNeeded = true;
                         if (!moveInputMethodWindowsIfNeededLocked(true)) {
                             assignLayersLocked();
                         }
-                        performLayoutLockedInner();
                         updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES);
                         mFocusMayChange = false;
-
-                        restart = true;
                     }
                 }
 
@@ -9880,10 +9947,9 @@
                     mToBottomApps.clear();
 
                     rebuildAppWindowListLocked();
-                    restart = true;
+                    changes |= PhoneWindowManager.FINISH_LAYOUT_REDO_LAYOUT;
                     moveInputMethodWindowsIfNeededLocked(false);
                     wallpaperMayChange = true;
-                    mLayoutNeeded = true;
                     // Since the window list has been rebuilt, focus might
                     // have to be recomputed since the actual order of windows
                     // might have changed again.
@@ -9892,7 +9958,7 @@
 
                 int adjResult = 0;
 
-                if (wallpaperForceHidingChanged && !restart && !mAppTransitionReady) {
+                if (wallpaperForceHidingChanged && changes == 0 && !mAppTransitionReady) {
                     // At this point, there was a window with a wallpaper that
                     // was force hiding other windows behind it, but now it
                     // is going away.  This may be simple -- just animate
@@ -9913,7 +9979,7 @@
                             // actually started the animation...  let's completely
                             // re-evaluate everything.
                             mLowerWallpaperTarget = mUpperWallpaperTarget = null;
-                            restart = true;
+                            changes |= PhoneWindowManager.FINISH_LAYOUT_REDO_ANIM;
                         }
                     }
                     adjResult = adjustWallpaperWindowsLocked();
@@ -9954,33 +10020,30 @@
                 if ((adjResult&ADJUST_WALLPAPER_LAYERS_CHANGED) != 0) {
                     if (DEBUG_WALLPAPER) Slog.v(TAG,
                             "Wallpaper layer changed: assigning layers + relayout");
-                    restart = true;
-                    mLayoutNeeded = true;
+                    changes |= PhoneWindowManager.FINISH_LAYOUT_REDO_LAYOUT;
                     assignLayersLocked();
                 } else if ((adjResult&ADJUST_WALLPAPER_VISIBILITY_CHANGED) != 0) {
                     if (DEBUG_WALLPAPER) Slog.v(TAG,
                             "Wallpaper visibility changed: relayout");
-                    restart = true;
-                    mLayoutNeeded = true;
+                    changes |= PhoneWindowManager.FINISH_LAYOUT_REDO_LAYOUT;
                 }
 
                 if (mFocusMayChange) {
                     mFocusMayChange = false;
                     if (updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES)) {
-                        restart = true;
+                        changes |= PhoneWindowManager.FINISH_LAYOUT_REDO_ANIM;
                         adjResult = 0;
                     }
                 }
 
                 if (mLayoutNeeded) {
-                    restart = true;
-                    performLayoutLockedInner();
+                    changes |= PhoneWindowManager.FINISH_LAYOUT_REDO_LAYOUT;
                 }
 
-                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "*** ANIM STEP: restart="
-                        + restart);
+                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "*** ANIM STEP: changes=0x"
+                        + Integer.toHexString(changes));
                 
-            } while (restart);
+            } while (changes != 0);
 
             // THIRD LOOP: Update the surfaces of all windows.
 
@@ -10022,10 +10085,9 @@
                         w.mLastRequestedHeight = height;
                         w.mLastShownFrame.set(w.mShownFrame);
                         try {
-                            if (SHOW_TRANSACTIONS) Slog.i(
-                                    TAG, "  SURFACE " + w.mSurface
-                                    + ": POS " + w.mShownFrame.left
-                                    + ", " + w.mShownFrame.top);
+                            if (SHOW_TRANSACTIONS) logSurface(w,
+                                    "POS " + w.mShownFrame.left
+                                    + ", " + w.mShownFrame.top, null);
                             w.mSurface.setPosition(w.mShownFrame.left, w.mShownFrame.top);
                         } catch (RuntimeException e) {
                             Slog.w(TAG, "Error positioning surface in " + w, e);
@@ -10045,12 +10107,11 @@
                         if (height < 1) height = 1;
                         if (w.mSurface != null) {
                             try {
-                                if (SHOW_TRANSACTIONS) Slog.i(
-                                        TAG, "  SURFACE " + w.mSurface + ": POS "
-                                        + w.mShownFrame.left + ","
+                                if (SHOW_TRANSACTIONS) logSurface(w,
+                                        "POS " + w.mShownFrame.left + ","
                                         + w.mShownFrame.top + " SIZE "
                                         + w.mShownFrame.width() + "x"
-                                        + w.mShownFrame.height());
+                                        + w.mShownFrame.height(), null);
                                 w.mSurface.setSize(width, height);
                                 w.mSurface.setPosition(w.mShownFrame.left,
                                         w.mShownFrame.top);
@@ -10136,8 +10197,8 @@
                         if (!w.mLastHidden) {
                             //dump();
                             w.mLastHidden = true;
-                            if (SHOW_TRANSACTIONS) Slog.i(
-                                    TAG, "  SURFACE " + w.mSurface + ": HIDE (performLayout)");
+                            if (SHOW_TRANSACTIONS) logSurface(w,
+                                    "HIDE (performLayout)", null);
                             if (w.mSurface != null) {
                                 try {
                                     w.mSurface.hide();
@@ -10176,13 +10237,12 @@
                         w.mLastDtDy = w.mDtDy;
                         w.mLastHScale = w.mHScale;
                         w.mLastVScale = w.mVScale;
-                        if (SHOW_TRANSACTIONS) Slog.i(
-                                TAG, "  SURFACE " + w.mSurface + ": alpha="
-                                + w.mShownAlpha + " layer=" + w.mAnimLayer
+                        if (SHOW_TRANSACTIONS) logSurface(w,
+                                "alpha=" + w.mShownAlpha + " layer=" + w.mAnimLayer
                                 + " matrix=[" + (w.mDsDx*w.mHScale)
                                 + "," + (w.mDtDx*w.mVScale)
                                 + "][" + (w.mDsDy*w.mHScale)
-                                + "," + (w.mDtDy*w.mVScale) + "]");
+                                + "," + (w.mDtDy*w.mVScale) + "]", null);
                         if (w.mSurface != null) {
                             try {
                                 w.mSurface.setAlpha(w.mShownAlpha);
@@ -10201,8 +10261,8 @@
                         if (w.mLastHidden && !w.mDrawPending
                                 && !w.mCommitDrawPending
                                 && !w.mReadyToShow) {
-                            if (SHOW_TRANSACTIONS) Slog.i(
-                                    TAG, "  SURFACE " + w.mSurface + ": SHOW (performLayout)");
+                            if (SHOW_TRANSACTIONS) logSurface(w,
+                                    "SHOW (performLayout)", null);
                             if (DEBUG_VISIBILITY) Slog.v(TAG, "Showing " + w
                                     + " during relayout");
                             if (showSurfaceRobustlyLocked(w)) {
@@ -10267,9 +10327,10 @@
                                 && buttonBrightness < 0) {
                             buttonBrightness = w.mAttrs.buttonBrightness;
                         }
-                        if (attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG
-                                || attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD
-                                || attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_ERROR) {
+                        if (canBeSeen
+                                && (attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG
+                                 || attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD
+                                 || attrs.type == WindowManager.LayoutParams.TYPE_SYSTEM_ERROR)) {
                             syswin = true;
                         }
                     }
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index b53100f..f6289ae 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -13226,9 +13226,11 @@
                     ac.updateConfiguration(mConfiguration);
                 }
 
-                Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
-                msg.obj = new Configuration(mConfiguration);
-                mHandler.sendMessage(msg);
+                if (Settings.System.hasInterestingConfigurationChanges(changes)) {
+                    Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
+                    msg.obj = new Configuration(mConfiguration);
+                    mHandler.sendMessage(msg);
+                }
         
                 for (int i=mLruProcesses.size()-1; i>=0; i--) {
                     ProcessRecord app = mLruProcesses.get(i);
diff --git a/services/java/com/android/server/connectivity/Tethering.java b/services/java/com/android/server/connectivity/Tethering.java
index 78329db..ebd3314 100644
--- a/services/java/com/android/server/connectivity/Tethering.java
+++ b/services/java/com/android/server/connectivity/Tethering.java
@@ -33,6 +33,7 @@
 import android.net.NetworkInfo;
 import android.os.BatteryManager;
 import android.os.Binder;
+import android.os.Environment;
 import android.os.IBinder;
 import android.os.INetworkManagementService;
 import android.os.Message;
@@ -54,14 +55,12 @@
  * @hide
  *
  * Timeout
- * TODO - review error states - they currently are dead-ends with no recovery possible
  *
  * TODO - look for parent classes and code sharing
  */
 
 public class Tethering extends INetworkManagementEventObserver.Stub {
 
-    private Notification mTetheringNotification;
     private Context mContext;
     private final String TAG = "Tethering";
 
@@ -74,7 +73,7 @@
     private String[] mTetherableWifiRegexs;
     private String[] mUpstreamIfaceRegexs;
 
-    private HashMap<String, TetherInterfaceSM> mIfaces;
+    private HashMap<String, TetherInterfaceSM> mIfaces; // all tethered/tetherable ifaces
 
     private BroadcastReceiver mStateReceiver;
 
@@ -88,11 +87,19 @@
     private static final String DNS_DEFAULT_SERVER1 = "8.8.8.8";
     private static final String DNS_DEFAULT_SERVER2 = "4.2.2.2";
 
-    private boolean mDunRequired;
+    private boolean mDunRequired;  // configuration info - must use DUN apn on 3g
     private boolean mUseHiPri;
+
     private String mUpstreamIfaceName;
 
-    HierarchicalStateMachine mTetherMasterSM;
+    private HierarchicalStateMachine mTetherMasterSM;
+
+    private Notification mTetheredNotification;
+
+    // whether we can tether is the && of these two - they come in as separate
+    // broadcasts so track them so we can decide what to do when either changes
+    private boolean mUsbMassStorageOff;  // track the status of USB Mass Storage
+    private boolean mUsbConnected;       // track the status of USB connection
 
     public Tethering(Context context) {
         Log.d(TAG, "Tethering starting");
@@ -117,6 +124,10 @@
         filter.addAction(Intent.ACTION_BATTERY_CHANGED);
         filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
+        filter.addAction(Intent.ACTION_MEDIA_SHARED);
+        filter.addAction(Intent.ACTION_MEDIA_UNSHARED);
+        mUsbMassStorageOff = !Environment.MEDIA_SHARED.equals(
+                Environment.getExternalStorageState());
         mStateReceiver = new StateReceiver();
         mContext.registerReceiver(mStateReceiver, filter);
 
@@ -152,18 +163,11 @@
         Log.d(TAG, "interfaceLinkStatusChanged " + iface + ", " + link);
         boolean found = false;
         boolean usb = false;
-        for (String regex : mTetherableWifiRegexs) {
-            if (iface.matches(regex)) {
-                found = true;
-                break;
-            }
-        }
-        for (String regex: mTetherableUsbRegexs) {
-            if (iface.matches(regex)) {
-                found = true;
-                usb = true;
-                break;
-            }
+        if (isWifi(iface)) {
+            found = true;
+        } else if (isUsb(iface)) {
+            found = true;
+            usb = true;
         }
         if (found == false) return;
 
@@ -184,23 +188,31 @@
         }
     }
 
+    private boolean isUsb(String iface) {
+        for (String regex : mTetherableUsbRegexs) {
+            if (iface.matches(regex)) return true;
+        }
+        return false;
+    }
+
+    public boolean isWifi(String iface) {
+        for (String regex : mTetherableWifiRegexs) {
+            if (iface.matches(regex)) return true;
+        }
+        return false;
+    }
+
     public void interfaceAdded(String iface) {
         IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
         INetworkManagementService service = INetworkManagementService.Stub.asInterface(b);
         boolean found = false;
         boolean usb = false;
-        for (String regex : mTetherableWifiRegexs) {
-            if (iface.matches(regex)) {
-                found = true;
-                break;
-            }
+        if (isWifi(iface)) {
+            found = true;
         }
-        for (String regex : mTetherableUsbRegexs) {
-            if (iface.matches(regex)) {
-                found = true;
-                usb = true;
-                break;
-            }
+        if (isUsb(iface)) {
+            found = true;
+            usb = true;
         }
         if (found == false) {
             Log.d(TAG, iface + " is not a tetherable iface, ignoring");
@@ -293,6 +305,9 @@
         ArrayList<String> activeList = new ArrayList<String>();
         ArrayList<String> erroredList = new ArrayList<String>();
 
+        boolean wifiTethered = false;
+        boolean usbTethered = false;
+
         synchronized (mIfaces) {
             Set ifaces = mIfaces.keySet();
             for (Object iface : ifaces) {
@@ -303,6 +318,11 @@
                     } else if (sm.isAvailable()) {
                         availableList.add((String)iface);
                     } else if (sm.isTethered()) {
+                        if (isUsb((String)iface)) {
+                            usbTethered = true;
+                        } else if (isWifi((String)iface)) {
+                            wifiTethered = true;
+                        }
                         activeList.add((String)iface);
                     }
                 }
@@ -318,19 +338,82 @@
         mContext.sendStickyBroadcast(broadcast);
         Log.d(TAG, "sendTetherStateChangedBroadcast " + availableList.size() + ", " +
                 activeList.size() + ", " + erroredList.size());
+
+        if (usbTethered) {
+            if (wifiTethered) {
+                showTetheredNotification(com.android.internal.R.drawable.stat_sys_tether_general);
+            } else {
+                showTetheredNotification(com.android.internal.R.drawable.stat_sys_tether_usb);
+            }
+        } else if (wifiTethered) {
+            showTetheredNotification(com.android.internal.R.drawable.stat_sys_tether_wifi);
+        } else {
+            clearTetheredNotification();
+        }
+    }
+
+    private void showTetheredNotification(int icon) {
+        NotificationManager notificationManager =
+                (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
+        if (notificationManager == null) {
+            return;
+        }
+
+        Intent intent = new Intent();
+        intent.setClassName("com.android.settings", "com.android.settings.TetherSettings");
+        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
+
+        PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
+
+        Resources r = Resources.getSystem();
+        CharSequence title = r.getText(com.android.internal.R.string.tethered_notification_title);
+        CharSequence message = r.getText(com.android.internal.R.string.
+                tethered_notification_message);
+
+        if(mTetheredNotification == null) {
+            mTetheredNotification = new Notification();
+            mTetheredNotification.when = 0;
+        }
+        mTetheredNotification.icon = icon;
+        mTetheredNotification.defaults &= ~Notification.DEFAULT_SOUND;
+        mTetheredNotification.flags = Notification.FLAG_ONGOING_EVENT;
+        mTetheredNotification.tickerText = title;
+        mTetheredNotification.setLatestEventInfo(mContext, title, message, pi);
+
+        notificationManager.notify(mTetheredNotification.icon, mTetheredNotification);
+    }
+
+    private void clearTetheredNotification() {
+        NotificationManager notificationManager =
+            (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
+        if (notificationManager != null && mTetheredNotification != null) {
+            notificationManager.cancel(mTetheredNotification.icon);
+            mTetheredNotification = null;
+        }
+    }
+
+    private void updateUsbStatus() {
+        boolean enable = mUsbConnected && mUsbMassStorageOff;
+
+        if (mBooted) {
+            enableUsbIfaces(enable);
+        }
     }
 
     private class StateReceiver extends BroadcastReceiver {
         public void onReceive(Context content, Intent intent) {
             String action = intent.getAction();
             if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
-                boolean usbConnected = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
+                mUsbConnected = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                         == BatteryManager.BATTERY_PLUGGED_USB);
-                if (mBooted) {
-                    Tethering.this.enableUsbIfaces(usbConnected); // add or remove them
-                } else {
-                    mDeferedUsbConnection = usbConnected;
-                }
+                Tethering.this.updateUsbStatus();
+            } else if (action.equals(Intent.ACTION_MEDIA_SHARED)) {
+                mUsbMassStorageOff = false;
+                updateUsbStatus();
+            }
+            else if (action.equals(Intent.ACTION_MEDIA_UNSHARED)) {
+                mUsbMassStorageOff = true;
+                updateUsbStatus();
             } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                 IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
                 IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
@@ -348,9 +431,7 @@
                 } catch (RemoteException e) {}
             } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
                 mBooted = true;
-                if (mDeferedUsbConnection) {
-                    Tethering.this.enableUsbIfaces(true);
-                }
+                updateUsbStatus();
             }
         }
     }
@@ -367,13 +448,11 @@
             return;
         }
         for (String iface : ifaces) {
-            for (String regex : mTetherableUsbRegexs) {
-                if (iface.matches(regex)) {
-                    if (enable) {
-                        interfaceAdded(iface);
-                    } else {
-                        interfaceRemoved(iface);
-                    }
+            if (isUsb(iface)) {
+                if (enable) {
+                    interfaceAdded(iface);
+                } else {
+                    interfaceRemoved(iface);
                 }
             }
         }
@@ -420,27 +499,25 @@
             return false;
         }
         for (String iface : ifaces) {
-            for (String regex : mTetherableUsbRegexs) {
-                if (iface.matches(regex)) {
-                    InterfaceConfiguration ifcg = null;
-                    try {
-                        ifcg = service.getInterfaceConfig(iface);
-                        if (ifcg != null) {
-                            ifcg.ipAddr = (169 << 24) + (254 << 16) + (2 << 8) + 1;
-                            ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
-                            if (enabled) {
-                                ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
-                            } else {
-                                ifcg.interfaceFlags = ifcg.interfaceFlags.replace("up", "down");
-                            }
-                            ifcg.interfaceFlags = ifcg.interfaceFlags.replace("running", "");
-                            ifcg.interfaceFlags = ifcg.interfaceFlags.replace("  "," ");
-                            service.setInterfaceConfig(iface, ifcg);
+            if (isUsb(iface)) {
+                InterfaceConfiguration ifcg = null;
+                try {
+                    ifcg = service.getInterfaceConfig(iface);
+                    if (ifcg != null) {
+                        ifcg.ipAddr = (169 << 24) + (254 << 16) + (2 << 8) + 1;
+                        ifcg.netmask = (255 << 24) + (255 << 16) + (255 << 8) + 0;
+                        if (enabled) {
+                            ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
+                        } else {
+                            ifcg.interfaceFlags = ifcg.interfaceFlags.replace("up", "down");
                         }
-                    } catch (Exception e) {
-                        Log.e(TAG, "Error configuring interface " + iface + ", :" + e);
-                        return false;
+                        ifcg.interfaceFlags = ifcg.interfaceFlags.replace("running", "");
+                        ifcg.interfaceFlags = ifcg.interfaceFlags.replace("  "," ");
+                        service.setInterfaceConfig(iface, ifcg);
                     }
+                } catch (Exception e) {
+                    Log.e(TAG, "Error configuring interface " + iface + ", :" + e);
+                    return false;
                 }
             }
         }
diff --git a/tests/AndroidTests/AndroidManifest.xml b/tests/AndroidTests/AndroidManifest.xml
index e06c3a8..1f0bf4d 100644
--- a/tests/AndroidTests/AndroidManifest.xml
+++ b/tests/AndroidTests/AndroidManifest.xml
@@ -35,6 +35,7 @@
     <uses-permission android:name="android.permission.ASEC_DESTROY" />
     <uses-permission android:name="android.permission.ASEC_MOUNT_UNMOUNT" />
     <uses-permission android:name="android.permission.ASEC_RENAME" />
+    <uses-permission android:name="android.permission.SHUTDOWN" />
     <uses-permission android:name="com.android.unit_tests.permission.TEST_GRANTED" />
     <uses-permission android:name="com.google.android.googleapps.permission.ACCESS_GOOGLE_PASSWORD" />
     <uses-permission android:name="com.google.android.googleapps.permission.GOOGLE_AUTH" />
diff --git a/tests/AndroidTests/src/com/android/unit_tests/AsecTests.java b/tests/AndroidTests/src/com/android/unit_tests/AsecTests.java
index c7bacd4..9aed363 100755
--- a/tests/AndroidTests/src/com/android/unit_tests/AsecTests.java
+++ b/tests/AndroidTests/src/com/android/unit_tests/AsecTests.java
@@ -16,6 +16,8 @@
 
 package com.android.unit_tests;
 
+import com.android.unit_tests.PackageManagerTests.StorageListener;
+
 import android.os.storage.IMountService.Stub;
 
 import android.net.Uri;
@@ -41,6 +43,9 @@
 import android.os.Handler;
 import android.os.IBinder;
 import android.os.storage.IMountService;
+import android.os.storage.IMountShutdownObserver;
+import android.os.storage.StorageEventListener;
+import android.os.storage.StorageManager;
 import android.os.storage.StorageResultCode;
 import android.os.RemoteException;
 import android.os.ServiceManager;
@@ -365,4 +370,256 @@
         }
     }
 
+    /*------------ Tests for unmounting volume ---*/
+    public final long MAX_WAIT_TIME=120*1000;
+    public final long WAIT_TIME_INCR=20*1000;
+    boolean getMediaState() {
+        try {
+        String mPath = Environment.getExternalStorageDirectory().toString();
+        String state = getMs().getVolumeState(mPath);
+        return Environment.MEDIA_MOUNTED.equals(state);
+        } catch (RemoteException e) {
+            return false;
+        }
+    }
+
+    boolean mountMedia() {
+        if (getMediaState()) {
+            return true;
+        }
+        try {
+        String mPath = Environment.getExternalStorageDirectory().toString();
+        int ret = getMs().mountVolume(mPath);
+        return ret == StorageResultCode.OperationSucceeded;
+        } catch (RemoteException e) {
+            return false;
+        }
+    }
+
+    class StorageListener extends StorageEventListener {
+        String oldState;
+        String newState;
+        String path;
+        private boolean doneFlag = false;
+
+        public void action() {
+            synchronized (this) {
+                doneFlag = true;
+                notifyAll();
+            }
+        }
+
+        public boolean isDone() {
+            return doneFlag;
+        }
+
+        @Override
+        public void onStorageStateChanged(String path, String oldState, String newState) {
+            if (localLOGV) Log.i(TAG, "Storage state changed from " + oldState + " to " + newState);
+            this.oldState = oldState;
+            this.newState = newState;
+            this.path = path;
+            action();
+        }
+    }
+
+    private boolean unmountMedia() {
+        if (!getMediaState()) {
+            return true;
+        }
+        String path = Environment.getExternalStorageDirectory().toString();
+        StorageListener observer = new StorageListener();
+        StorageManager sm = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
+        sm.registerListener(observer);
+        try {
+            // Wait on observer
+            synchronized(observer) {
+                getMs().unmountVolume(path, false);
+                long waitTime = 0;
+                while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
+                    observer.wait(WAIT_TIME_INCR);
+                    waitTime += WAIT_TIME_INCR;
+                }
+                if(!observer.isDone()) {
+                    throw new Exception("Timed out waiting for packageInstalled callback");
+                }
+                return true;
+            }
+        } catch (Exception e) {
+            return false;
+        } finally {
+            sm.unregisterListener(observer);
+        }
+    }
+    public void testUnmount() {
+        boolean oldStatus = getMediaState();
+        Log.i(TAG, "oldStatus="+oldStatus);
+        try {
+            // Mount media firsts
+            if (!getMediaState()) {
+                mountMedia();
+            }
+            assertTrue(unmountMedia());
+        } finally {
+            // Restore old status
+            boolean currStatus = getMediaState();
+            if (oldStatus != currStatus) {
+                if (oldStatus) {
+                    // Mount media
+                    mountMedia();
+                } else {
+                    unmountMedia();
+                }
+            }
+        }
+    }
+
+    class MultipleStorageLis extends StorageListener {
+        int count = 0;
+        public void onStorageStateChanged(String path, String oldState, String newState) {
+            count++;
+            super.action();
+        }
+    }
+    /*
+     * This test invokes unmount multiple time and expects the call back
+     * to be invoked just once.
+     */
+    public void testUnmountMultiple() {
+        boolean oldStatus = getMediaState();
+        StorageManager sm = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
+        MultipleStorageLis observer = new MultipleStorageLis();
+        try {
+            // Mount media firsts
+            if (!getMediaState()) {
+                mountMedia();
+            }
+            String path = Environment.getExternalStorageDirectory().toString();
+            sm.registerListener(observer);
+            // Wait on observer
+            synchronized(observer) {
+                for (int i = 0; i < 5; i++) {
+                    getMs().unmountVolume(path, false);
+                }
+                long waitTime = 0;
+                while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
+                    observer.wait(WAIT_TIME_INCR);
+                    waitTime += WAIT_TIME_INCR;
+                }
+                if(!observer.isDone()) {
+                    failStr("Timed out waiting for packageInstalled callback");
+                }
+            }
+            assertEquals(observer.count, 1);
+        } catch (Exception e) {
+            failStr(e);
+        } finally {
+            sm.unregisterListener(observer);
+            // Restore old status
+            boolean currStatus = getMediaState();
+            if (oldStatus != currStatus) {
+                if (oldStatus) {
+                    // Mount media
+                    mountMedia();
+                } else {
+                    unmountMedia();
+                }
+            }
+        }
+    }
+    
+    class ShutdownObserver extends  IMountShutdownObserver.Stub{
+        private boolean doneFlag = false;
+        int statusCode;
+
+        public void action() {
+            synchronized (this) {
+                doneFlag = true;
+                notifyAll();
+            }
+        }
+
+        public boolean isDone() {
+            return doneFlag;
+        }
+        public void onShutDownComplete(int statusCode) throws RemoteException {
+            this.statusCode = statusCode;
+            action();
+        }
+        
+    }
+
+    boolean invokeShutdown() {
+        IMountService ms = getMs();
+        ShutdownObserver observer = new ShutdownObserver();
+        synchronized (observer) {
+            try {
+                ms.shutdown(observer);
+                return true;
+            } catch (RemoteException e) {
+                failStr(e);
+            }
+        }
+        return false;
+    }
+
+    public void testShutdown() {
+        boolean oldStatus = getMediaState();
+        try {
+            // Mount media firsts
+            if (!getMediaState()) {
+                mountMedia();
+            }
+            assertTrue(invokeShutdown());
+        } finally {
+            // Restore old status
+            boolean currStatus = getMediaState();
+            if (oldStatus != currStatus) {
+                if (oldStatus) {
+                    // Mount media
+                    mountMedia();
+                } else {
+                    unmountMedia();
+                }
+            }
+        }
+    }
+
+    /*
+     * This test invokes unmount multiple time and expects the call back
+     * to be invoked just once.
+     */
+    public void testShutdownMultiple() {
+        boolean oldStatus = getMediaState();
+        try {
+            // Mount media firsts
+            if (!getMediaState()) {
+                mountMedia();
+            }
+            IMountService ms = getMs();
+            ShutdownObserver observer = new ShutdownObserver();
+            synchronized (observer) {
+                try {
+                    ms.shutdown(observer);
+                    for (int i = 0; i < 4; i++) {
+                        ms.shutdown(null);
+                    }
+                } catch (RemoteException e) {
+                    failStr(e);
+                }
+            }
+        } finally {
+            // Restore old status
+            boolean currStatus = getMediaState();
+            if (oldStatus != currStatus) {
+                if (oldStatus) {
+                    // Mount media
+                    mountMedia();
+                } else {
+                    unmountMedia();
+                }
+            }
+        }
+    }
+
 }
diff --git a/tests/AndroidTests/src/com/android/unit_tests/PackageManagerTests.java b/tests/AndroidTests/src/com/android/unit_tests/PackageManagerTests.java
index 0b69020..8c8b00c 100755
--- a/tests/AndroidTests/src/com/android/unit_tests/PackageManagerTests.java
+++ b/tests/AndroidTests/src/com/android/unit_tests/PackageManagerTests.java
@@ -16,6 +16,8 @@
 
 package com.android.unit_tests;
 
+import com.android.internal.content.PackageHelper;
+
 import android.os.storage.IMountService.Stub;
 
 import android.net.Uri;
@@ -73,9 +75,9 @@
     public final long MAX_WAIT_TIME=120*1000;
     public final long WAIT_TIME_INCR=20*1000;
     private static final String SECURE_CONTAINERS_PREFIX = "/mnt/asec";
-    private static final int APP_INSTALL_AUTO = 0;
-    private static final int APP_INSTALL_DEVICE = 1;
-    private static final int APP_INSTALL_SDCARD = 2;
+    private static final int APP_INSTALL_AUTO = PackageHelper.APP_INSTALL_AUTO;
+    private static final int APP_INSTALL_DEVICE = PackageHelper.APP_INSTALL_INTERNAL;
+    private static final int APP_INSTALL_SDCARD = PackageHelper.APP_INSTALL_EXTERNAL;
 
     void failStr(String errMsg) {
         Log.w(TAG, "errMsg="+errMsg);
@@ -315,9 +317,9 @@
             if (!getInstallLoc(flags, expInstallLocation)) {
                 assertEquals(srcPath, appInstallPath);
                 assertEquals(publicSrcPath, appInstallPath);
-                assertFalse((info.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0);
+                assertFalse((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
             } else {
-                assertTrue((info.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0);
+                assertTrue((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
                 assertTrue(srcPath.startsWith(SECURE_CONTAINERS_PREFIX));
                 assertTrue(publicSrcPath.startsWith(SECURE_CONTAINERS_PREFIX));
             }
@@ -1172,9 +1174,9 @@
                 ApplicationInfo info = getPm().getApplicationInfo(ip.pkg.packageName, 0);
                 assertNotNull(info);
                 if ((moveFlags & PackageManager.MOVE_INTERNAL) != 0) {
-                    assertTrue((info.flags & ApplicationInfo.FLAG_ON_SDCARD) == 0);
+                    assertTrue((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == 0);
                 } else if ((moveFlags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0){
-                    assertTrue((info.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0);
+                    assertTrue((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
                 }
             } else {
                 assertFalse(retCode);
diff --git a/tests/DumpRenderTree/assets/run_layout_tests.py b/tests/DumpRenderTree/assets/run_layout_tests.py
index 7f3ef2d..b6e7bf3 100755
--- a/tests/DumpRenderTree/assets/run_layout_tests.py
+++ b/tests/DumpRenderTree/assets/run_layout_tests.py
@@ -192,7 +192,7 @@
   # JS_ENGINE environment  variable, which is used by the build system in
   # external/webkit/Android.mk.
   js_engine = options.js_engine
-  if not js_engine:
+  if not js_engine and os.environ.has_key('JS_ENGINE'):
     js_engine = os.environ['JS_ENGINE']
   if js_engine:
     run_layout_test_cmd_postfix += " -e jsengine " + js_engine
@@ -246,6 +246,7 @@
 
   result_files = ["/sdcard/layout_tests_passed.txt",
                   "/sdcard/layout_tests_failed.txt",
+                  "/sdcard/layout_tests_ignored.txt",
                   "/sdcard/layout_tests_nontext.txt"]
   for file in result_files:
     shell_cmd_str = adb_cmd + " pull " + file + " " + results_dir
@@ -263,10 +264,13 @@
   logging.info(str(passed_tests) + " passed")
   failed_tests = CountLineNumber(results_dir + "/layout_tests_failed.txt")
   logging.info(str(failed_tests) + " failed")
+  ignored_tests = CountLineNumber(results_dir + "/layout_tests_ignored.txt")
+  logging.info(str(ignored_tests) + " ignored results")
   crashed_tests = CountLineNumber(results_dir + "/layout_tests_crashed.txt")
   logging.info(str(crashed_tests) + " crashed")
   nontext_tests = CountLineNumber(results_dir + "/layout_tests_nontext.txt")
   logging.info(str(nontext_tests) + " no dumpAsText")
+  logging.info(str(passed_tests + failed_tests + ignored_tests + crashed_tests + nontext_tests) + " TOTAL")
 
   logging.info("Results are stored under: " + results_dir + "\n")
 
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java b/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
index 4250043..eecd00a 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
@@ -23,27 +23,33 @@
 
     private static final String LOGTAG = "FileFilter";
 
+    // Returns whether we should ignore this test and skip running it.
+    // Currently we use this only for tests that crash the browser.
+    // TODO: Once these crashes are fixed, we should probably eliminate this
+    // method, as no test should crash.
     public static boolean ignoreTest(String file) {
-        // treat files like directories for the time being.
-        for (int i = 0; i < ignoreTestList.length; i ++) {
+        for (int i = 0; i < ignoreTestList.length; i++) {
             if (file.endsWith(ignoreTestList[i])) {
                 Log.v(LOGTAG, "File path in list of ignored tests: " + file);
                 return true;
             }
         }
-        for (int i = 0; i < ignoreTestDirs.length; i++) {
-            if (file.endsWith(ignoreTestDirs[i])) {
-                Log.v(LOGTAG, "File path in list of ignored directories: " + file);
+        return false;
+    }
+
+    // Returns whether a directory does not contain layout tests and so can be
+    // ignored.
+    public static boolean isNonTestDir(String file) {
+        for (int i = 0; i < nonTestDirs.length; i++) {
+            if (file.endsWith(nonTestDirs[i])) {
                 return true;
             }
         }
-        // We should run tests for which the expected result is wrong, as there is
-        // value in checking that they don't cause crashes.
-        // TODO: Run these tests but ignore the result.
-        return ignoreResults(file);
+        return false;
     }
 
-    public static boolean ignoreResults(String file) {
+    // Returns whether we should ignore the result of this test.
+    public static boolean ignoreResult(String file) {
         for (int i = 0; i < ignoreResultList.size(); i++) {
             if (file.endsWith(ignoreResultList.get(i))) {
                 Log.v(LOGTAG, "File path in list of ignored results: " + file);
@@ -51,7 +57,7 @@
             }
         }
         return false;
-      }
+    }
 
     final static Vector<String> ignoreResultList = new Vector<String>();
 
@@ -59,22 +65,16 @@
         fillIgnoreResultList();
     }
 
-    static final String[] ignoreTestDirs = {
+    static final String[] nonTestDirs = {
         ".", // ignore hidden directories and files
         "resources", // ignore resource directories
         ".svn", // don't run anything under .svn folder
-        "profiler",  // profiler is not supported
-        "svg",  // svg is not supported
-        "platform",  // platform specific
-        "http/wml",
+        "platform"  // No-Android specific tests
     };
 
-    static final String [] ignoreTestList = {
-        "editing/selection/move-left-right.html",
+    static final String[] ignoreTestList = {
         "fast/js/regexp-charclass-crash.html", // RegExp is too large, causing OOM
-        "storage/domstorage/localstorage/private-browsing-affects-storage.html", // No notion of private browsing.
-        "storage/domstorage/sessionstorage/private-browsing-affects-storage.html", // No notion of private browsing.
-        "storage/private-browsing-readonly.html", // No notion of private browsing.
+        "editing/selection/move-left-right.html" // Causes DumpRenderTree to hang
     };
 
     static void fillIgnoreResultList() {
@@ -114,6 +114,7 @@
         ignoreResultList.add("fast/workers/shared-worker-shared.html"); // shared workers not supported
         ignoreResultList.add("fast/workers/shared-worker-simple.html"); // shared workers not supported
 
+        // TODO: These need to be triaged
         ignoreResultList.add("fast/css/case-transform.html"); // will not fix #619707
         ignoreResultList.add("fast/dom/Element/offsetLeft-offsetTop-body-quirk.html"); // different screen size result in extra spaces in Apple compared to us
         ignoreResultList.add("fast/dom/Window/Plug-ins.html"); // need test plugin
@@ -184,6 +185,12 @@
         ignoreResultList.add("fast/parser/script-tag-with-trailing-slash.html"); // not capturing the console messages
         ignoreResultList.add("fast/replaced/image-map.html"); // requires eventSender.mouseDown(),mouseUp()
         ignoreResultList.add("fast/text/plain-text-line-breaks.html"); // extra spacing because iFrames rendered next to each other on Apple
+        ignoreResultList.add("profiler"); // profiler is not supported
+        ignoreResultList.add("storage/domstorage/localstorage/private-browsing-affects-storage.html"); // No notion of private browsing.
+        ignoreResultList.add("storage/domstorage/sessionstorage/private-browsing-affects-storage.html"); // No notion of private browsing.
+        ignoreResultList.add("storage/private-browsing-readonly.html"); // No notion of private browsing.
+        ignoreResultList.add("svg"); // svg is not supported
+
     }
 
 }
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/FsUtils.java b/tests/DumpRenderTree/src/com/android/dumprendertree/FsUtils.java
index ef0c6c6..322b0d2 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/FsUtils.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/FsUtils.java
@@ -43,38 +43,45 @@
     }
 
     public static void findLayoutTestsRecursively(BufferedOutputStream bos,
-            String dir) throws IOException {
+            String dir, boolean ignoreResultsInDir) throws IOException {
         Log.v(LOGTAG, "Searching tests under " + dir);
 
         File d = new File(dir);
         if (!d.isDirectory()) {
             throw new AssertionError("A directory expected, but got " + dir);
         }
+        ignoreResultsInDir |= FileFilter.ignoreResult(dir);
 
         String[] files = d.list();
         for (int i = 0; i < files.length; i++) {
             String s = dir + "/" + files[i];
-            if (s.endsWith("TEMPLATE.html")) {
-                continue;
-            }
-            if (FileFilter.ignoreTest(s)) {
-                Log.v(LOGTAG, "  Ignoring: " + s);
-                continue;
-            }
-            if (s.toLowerCase().endsWith(".html")
-                    || s.toLowerCase().endsWith(".xml")) {
-                bos.write(s.getBytes());
-                bos.write('\n');
-                continue;
-            }
 
             File f = new File(s);
             if (f.isDirectory()) {
-                findLayoutTestsRecursively(bos, s);
+                // If this is not a test directory, we don't recurse into it.
+                if (!FileFilter.isNonTestDir(s)) {
+                    Log.v(LOGTAG, "Recursing on " + s);
+                    findLayoutTestsRecursively(bos, s, ignoreResultsInDir);
+                }
                 continue;
             }
 
-            Log.v(LOGTAG, "Skipping " + s);
+            // If this test should be ignored, we skip it completely.
+            if (FileFilter.ignoreTest(s)) {
+                Log.v(LOGTAG, "Ignoring: " + s);
+                continue;
+            }
+
+            if ((s.toLowerCase().endsWith(".html") || s.toLowerCase().endsWith(".xml"))
+                    && !s.endsWith("TEMPLATE.html")) {
+                Log.v(LOGTAG, "Recording " + s);
+                bos.write(s.getBytes());
+                // If the result of this test should be ignored, we still run the test.
+                if (ignoreResultsInDir || FileFilter.ignoreResult(s)) {
+                    bos.write((" IGNORE_RESULT").getBytes());
+                }
+                bos.write('\n');
+            }
         }
     }
 
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java
index ac6933fc..042158a 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestsAutoTest.java
@@ -38,14 +38,16 @@
 import java.io.OutputStream;
 import java.util.Vector;
 
-// TestRecorder creates three files ...
+// TestRecorder creates four files ...
 // - passing tests
 // - failing tests
+// - tests for which results are ignored
 // - tests with no text results available
 // TestRecorder does not have the ability to clear the results.
 class MyTestRecorder {
     private BufferedOutputStream mBufferedOutputPassedStream;
     private BufferedOutputStream mBufferedOutputFailedStream;
+    private BufferedOutputStream mBufferedOutputIgnoreResultStream;
     private BufferedOutputStream mBufferedOutputNoResultStream;
 
     public void passed(String layout_file) {
@@ -68,6 +70,16 @@
         }
     }
 
+    public void ignoreResult(String layout_file) {
+        try {
+            mBufferedOutputIgnoreResultStream.write(layout_file.getBytes());
+            mBufferedOutputIgnoreResultStream.write('\n');
+            mBufferedOutputIgnoreResultStream.flush();
+        } catch(Exception e) {
+            e.printStackTrace();
+        }
+    }
+
     public void noResult(String layout_file) {
         try {
             mBufferedOutputNoResultStream.write(layout_file.getBytes());
@@ -82,12 +94,15 @@
         try {
             File resultsPassedFile = new File("/sdcard/layout_tests_passed.txt");
             File resultsFailedFile = new File("/sdcard/layout_tests_failed.txt");
+            File resultsIgnoreResultFile = new File("/sdcard/layout_tests_ignored.txt");
             File noExpectedResultFile = new File("/sdcard/layout_tests_nontext.txt");
 
             mBufferedOutputPassedStream =
                 new BufferedOutputStream(new FileOutputStream(resultsPassedFile, resume));
             mBufferedOutputFailedStream =
                 new BufferedOutputStream(new FileOutputStream(resultsFailedFile, resume));
+            mBufferedOutputIgnoreResultStream =
+                new BufferedOutputStream(new FileOutputStream(resultsIgnoreResultFile, resume));
             mBufferedOutputNoResultStream =
                 new BufferedOutputStream(new FileOutputStream(noExpectedResultFile, resume));
         } catch (Exception e) {
@@ -99,6 +114,7 @@
         try {
             mBufferedOutputPassedStream.close();
             mBufferedOutputFailedStream.close();
+            mBufferedOutputIgnoreResultStream.close();
             mBufferedOutputNoResultStream.close();
         } catch (Exception e) {
             e.printStackTrace();
@@ -132,6 +148,8 @@
 
     private MyTestRecorder mResultRecorder;
     private Vector<String> mTestList;
+    // Whether we should ignore the result for the corresponding test. Ordered same as mTestList.
+    private Vector<Boolean> mTestListIgnoreResult;
     private boolean mRebaselineResults;
     // The JavaScript engine currently in use. This determines which set of Android-specific
     // expected test results we use.
@@ -158,8 +176,11 @@
             BufferedReader inReader = new BufferedReader(new FileReader(LAYOUT_TESTS_LIST_FILE));
             String line = inReader.readLine();
             while (line != null) {
-                if (line.startsWith(mTestPathPrefix))
-                    mTestList.add(line);
+                if (line.startsWith(mTestPathPrefix)) {
+                    String[] components = line.split(" ");
+                    mTestList.add(components[0]);
+                    mTestListIgnoreResult.add(components.length > 1 && components[1].equals("IGNORE_RESULT"));
+                }
                 line = inReader.readLine();
             }
             inReader.close();
@@ -176,6 +197,7 @@
             for (int i = 0; i < mTestList.size(); i++) {
                 if (mTestList.elementAt(i).equals(line)) {
                     mTestList = new Vector<String>(mTestList.subList(i+1, mTestList.size()));
+                    mTestListIgnoreResult = new Vector<Boolean>(mTestListIgnoreResult.subList(i+1, mTestListIgnoreResult.size()));
                     break;
                 }
             }
@@ -236,14 +258,24 @@
         mResultRecorder.passed(file);
     }
 
+    private void ignoreResultCase(String file) {
+        Log.v("Layout test:", file + " ignore result");
+        mResultRecorder.ignoreResult(file);
+    }
+
     private void noResultCase(String file) {
         Log.v("Layout test:", file + " no expected result");
         mResultRecorder.noResult(file);
     }
 
-    private void processResult(String testFile, String actualResultFile, String expectedResultFile) {
+    private void processResult(String testFile, String actualResultFile, String expectedResultFile, boolean ignoreResult) {
         Log.v(LOGTAG, "  Processing result: " + testFile);
 
+        if (ignoreResult) {
+            ignoreResultCase(testFile);
+            return;
+        }
+
         File actual = new File(actualResultFile);
         File expected = new File(expectedResultFile);
         if (actual.exists() && expected.exists()) {
@@ -266,7 +298,7 @@
         }
     }
 
-    private void runTestAndWaitUntilDone(TestShellActivity activity, String test, int timeout) {
+    private void runTestAndWaitUntilDone(TestShellActivity activity, String test, int timeout, boolean ignoreResult) {
         activity.setCallback(new TestShellCallback() {
             public void finished() {
                 synchronized (LayoutTestsAutoTest.this) {
@@ -320,7 +352,7 @@
                 expectedResultFile = getAndroidExpectedResultFile(expectedResultFile);
             }
 
-            processResult(test, resultFile, expectedResultFile);
+            processResult(test, resultFile, expectedResultFile, ignoreResult);
         }
     }
 
@@ -336,6 +368,7 @@
         }
 
         this.mTestList = new Vector<String>();
+        this.mTestListIgnoreResult = new Vector<Boolean>();
 
         // Read settings
         mTestPathPrefix = (new File(LAYOUT_TESTS_ROOT + runner.mTestPath)).getAbsolutePath();
@@ -372,9 +405,10 @@
         }
         for (int i = 0; i < mTestList.size(); i++) {
             String s = mTestList.elementAt(i);
+            boolean ignoreResult = mTestListIgnoreResult.elementAt(i);
             FsUtils.updateTestStatus(TEST_STATUS_FILE, s);
             // Run tests
-            runTestAndWaitUntilDone(activity, s, runner.mTimeoutInMillis);
+            runTestAndWaitUntilDone(activity, s, runner.mTimeoutInMillis, ignoreResult);
         }
 
         FsUtils.updateTestStatus(TEST_STATUS_FILE, "#DONE");
@@ -399,7 +433,7 @@
         try {
             File tests_list = new File(LAYOUT_TESTS_LIST_FILE);
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tests_list, false));
-            FsUtils.findLayoutTestsRecursively(bos, getTestPath());
+            FsUtils.findLayoutTestsRecursively(bos, getTestPath(), false); // Don't ignore results
             bos.flush();
             bos.close();
        } catch (Exception e) {
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/Menu.java b/tests/DumpRenderTree/src/com/android/dumprendertree/Menu.java
index e15ab65..82671eb 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/Menu.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/Menu.java
@@ -68,7 +68,7 @@
         try {
             File tests_list = new File(LAYOUT_TESTS_LIST_FILE);
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tests_list, false));
-            FsUtils.findLayoutTestsRecursively(bos, path);
+            FsUtils.findLayoutTestsRecursively(bos, path, false); // Don't ignore results
             bos.flush();
             bos.close();
        } catch (Exception e) {
@@ -77,4 +77,3 @@
     }
 
 }
-
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index 537ae5e..735a80d 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -603,7 +603,7 @@
                     } else {
                         printf("versionCode='' ");
                     }
-                    String8 versionName = getAttribute(tree, VERSION_NAME_ATTR, &error);
+                    String8 versionName = getResolvedAttribute(&res, tree, VERSION_NAME_ATTR, &error);
                     if (error != "") {
                         fprintf(stderr, "ERROR getting 'android:versionName' attribute: %s\n", error.string());
                         goto bail;
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index b7580b3..c0ebb59 100644
--- a/tools/aapt/Resource.cpp
+++ b/tools/aapt/Resource.cpp
@@ -379,14 +379,64 @@
     ATTR_LEADING_SPACES = -3,
     ATTR_TRAILING_SPACES = -4
 };
-static int validateAttr(const String8& path, const ResXMLParser& parser,
+static int validateAttr(const String8& path, const ResTable& table,
+        const ResXMLParser& parser,
         const char* ns, const char* attr, const char* validChars, bool required)
 {
     size_t len;
 
     ssize_t index = parser.indexOfAttribute(ns, attr);
     const uint16_t* str;
-    if (index >= 0 && (str=parser.getAttributeStringValue(index, &len)) != NULL) {
+    Res_value value;
+    if (index >= 0 && parser.getAttributeValue(index, &value) >= 0) {
+        const ResStringPool* pool = &parser.getStrings();
+        if (value.dataType == Res_value::TYPE_REFERENCE) {
+            uint32_t specFlags = 0;
+            int strIdx;
+            if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) {
+                fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n",
+                        path.string(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).string(), attr,
+                        value.data);
+                return ATTR_NOT_FOUND;
+            }
+            
+            pool = table.getTableStringBlock(strIdx);
+            #if 0
+            if (pool != NULL) {
+                str = pool->stringAt(value.data, &len);
+            }
+            printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr,
+                    specFlags, strIdx, str != NULL ? String8(str).string() : "???");
+            #endif
+            if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) {
+                fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n",
+                        path.string(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).string(), attr,
+                        specFlags);
+                return ATTR_NOT_FOUND;
+            }
+        }
+        if (value.dataType == Res_value::TYPE_STRING) {
+            if (pool == NULL) {
+                fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n",
+                        path.string(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).string(), attr);
+                return ATTR_NOT_FOUND;
+            }
+            if ((str=pool->stringAt(value.data, &len)) == NULL) {
+                fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
+                        path.string(), parser.getLineNumber(),
+                        String8(parser.getElementName(&len)).string(), attr);
+                return ATTR_NOT_FOUND;
+            }
+        } else {
+            fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
+                    path.string(), parser.getLineNumber(),
+                    String8(parser.getElementName(&len)).string(), attr,
+                    value.dataType);
+            return ATTR_NOT_FOUND;
+        }
         if (validChars) {
             for (size_t i=0; i<len; i++) {
                 uint16_t c = str[i];
@@ -959,21 +1009,102 @@
         err = NO_ERROR;
     }
 
+    if (table.validateLocalizations()) {
+        hasErrors = true;
+    }
+    
+    if (hasErrors) {
+        return UNKNOWN_ERROR;
+    }
+
     const sp<AaptFile> manifestFile(androidManifestFile->getFiles().valueAt(0));
     String8 manifestPath(manifestFile->getPrintableSource());
 
+    // Generate final compiled manifest file.
+    manifestFile->clearData();
+    sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
+    if (manifestTree == NULL) {
+        return UNKNOWN_ERROR;
+    }
+    err = massageManifest(bundle, manifestTree);
+    if (err < NO_ERROR) {
+        return err;
+    }
+    err = compileXmlFile(assets, manifestTree, manifestFile, &table);
+    if (err < NO_ERROR) {
+        return err;
+    }
+
+    //block.restart();
+    //printXMLBlock(&block);
+
+    // --------------------------------------------------------------
+    // Generate the final resource table.
+    // Re-flatten because we may have added new resource IDs
+    // --------------------------------------------------------------
+
+    ResTable finalResTable;
+    sp<AaptFile> resFile;
+    
+    if (table.hasResources()) {
+        sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
+        err = table.addSymbols(symbols);
+        if (err < NO_ERROR) {
+            return err;
+        }
+
+        resFile = getResourceFile(assets);
+        if (resFile == NULL) {
+            fprintf(stderr, "Error: unable to generate entry for resource data\n");
+            return UNKNOWN_ERROR;
+        }
+
+        err = table.flatten(bundle, resFile);
+        if (err < NO_ERROR) {
+            return err;
+        }
+
+        if (bundle->getPublicOutputFile()) {
+            FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
+            if (fp == NULL) {
+                fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
+                        (const char*)bundle->getPublicOutputFile(), strerror(errno));
+                return UNKNOWN_ERROR;
+            }
+            if (bundle->getVerbose()) {
+                printf("  Writing public definitions to %s.\n", bundle->getPublicOutputFile());
+            }
+            table.writePublicDefinitions(String16(assets->getPackage()), fp);
+            fclose(fp);
+        }
+        
+        // Read resources back in,
+        finalResTable.add(resFile->getData(), resFile->getSize(), NULL);
+        
+#if 0
+        NOISY(
+              printf("Generated resources:\n");
+              finalResTable.print();
+        )
+#endif
+    }
+    
     // Perform a basic validation of the manifest file.  This time we
     // parse it with the comments intact, so that we can use them to
     // generate java docs...  so we are not going to write this one
     // back out to the final manifest data.
-    err = compileXmlFile(assets, manifestFile, &table,
+    sp<AaptFile> outManifestFile = new AaptFile(manifestFile->getSourceFile(),
+            manifestFile->getGroupEntry(),
+            manifestFile->getResourceType());
+    err = compileXmlFile(assets, manifestFile,
+            outManifestFile, &table,
             XML_COMPILE_ASSIGN_ATTRIBUTE_IDS
             | XML_COMPILE_STRIP_WHITESPACE | XML_COMPILE_STRIP_RAW_VALUES);
     if (err < NO_ERROR) {
         return err;
     }
     ResXMLTree block;
-    block.setTo(manifestFile->getData(), manifestFile->getSize(), true);
+    block.setTo(outManifestFile->getData(), outManifestFile->getSize(), true);
     String16 manifest16("manifest");
     String16 permission16("permission");
     String16 permission_group16("permission-group");
@@ -1012,16 +1143,20 @@
                 continue;
             }
             if (strcmp16(block.getElementName(&len), manifest16.string()) == 0) {
-                if (validateAttr(manifestPath, block, NULL, "package",
+                if (validateAttr(manifestPath, finalResTable, block, NULL, "package",
                                  packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
+                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
+                                 "sharedUserId", packageIdentChars, false) != ATTR_OKAY) {
+                    hasErrors = true;
+                }
             } else if (strcmp16(block.getElementName(&len), permission16.string()) == 0
                     || strcmp16(block.getElementName(&len), permission_group16.string()) == 0) {
                 const bool isGroup = strcmp16(block.getElementName(&len),
                         permission_group16.string()) == 0;
-                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
-                                 isGroup ? packageIdentCharsWithTheStupid
+                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
+                                 "name", isGroup ? packageIdentCharsWithTheStupid
                                  : packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
@@ -1099,56 +1234,56 @@
                 }
                 syms->makeSymbolPublic(String8(e), srcPos);
             } else if (strcmp16(block.getElementName(&len), uses_permission16.string()) == 0) {
-                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
-                                 packageIdentChars, true) != ATTR_OKAY) {
+                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
+                                 "name", packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
             } else if (strcmp16(block.getElementName(&len), instrumentation16.string()) == 0) {
-                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
-                                 classIdentChars, true) != ATTR_OKAY) {
+                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
+                                 "name", classIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "targetPackage",
                                  packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
             } else if (strcmp16(block.getElementName(&len), application16.string()) == 0) {
-                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
-                                 classIdentChars, false) != ATTR_OKAY) {
+                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
+                                 "name", classIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "permission",
                                  packageIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "process",
                                  processIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
                                  processIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
             } else if (strcmp16(block.getElementName(&len), provider16.string()) == 0) {
-                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
-                                 classIdentChars, true) != ATTR_OKAY) {
+                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
+                                 "name", classIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "authorities",
                                  authoritiesIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "permission",
                                  packageIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "process",
                                  processIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
@@ -1156,39 +1291,39 @@
             } else if (strcmp16(block.getElementName(&len), service16.string()) == 0
                        || strcmp16(block.getElementName(&len), receiver16.string()) == 0
                        || strcmp16(block.getElementName(&len), activity16.string()) == 0) {
-                if (validateAttr(manifestPath, block, RESOURCES_ANDROID_NAMESPACE, "name",
-                                 classIdentChars, true) != ATTR_OKAY) {
+                if (validateAttr(manifestPath, finalResTable, block, RESOURCES_ANDROID_NAMESPACE,
+                                 "name", classIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "permission",
                                  packageIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "process",
                                  processIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "taskAffinity",
                                  processIdentChars, false) != ATTR_OKAY) {
                     hasErrors = true;
                 }
             } else if (strcmp16(block.getElementName(&len), action16.string()) == 0
                        || strcmp16(block.getElementName(&len), category16.string()) == 0) {
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "name",
                                  packageIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
             } else if (strcmp16(block.getElementName(&len), data16.string()) == 0) {
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "mimeType",
                                  typeIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
                 }
-                if (validateAttr(manifestPath, block,
+                if (validateAttr(manifestPath, finalResTable, block,
                                  RESOURCES_ANDROID_NAMESPACE, "scheme",
                                  schemeIdentChars, true) != ATTR_OKAY) {
                     hasErrors = true;
@@ -1197,76 +1332,7 @@
         }
     }
 
-    if (table.validateLocalizations()) {
-        hasErrors = true;
-    }
-    
-    if (hasErrors) {
-        return UNKNOWN_ERROR;
-    }
-
-    // Generate final compiled manifest file.
-    manifestFile->clearData();
-    sp<XMLNode> manifestTree = XMLNode::parse(manifestFile);
-    if (manifestTree == NULL) {
-        return UNKNOWN_ERROR;
-    }
-    err = massageManifest(bundle, manifestTree);
-    if (err < NO_ERROR) {
-        return err;
-    }
-    err = compileXmlFile(assets, manifestTree, manifestFile, &table);
-    if (err < NO_ERROR) {
-        return err;
-    }
-
-    //block.restart();
-    //printXMLBlock(&block);
-
-    // --------------------------------------------------------------
-    // Generate the final resource table.
-    // Re-flatten because we may have added new resource IDs
-    // --------------------------------------------------------------
-
-    if (table.hasResources()) {
-        sp<AaptSymbols> symbols = assets->getSymbolsFor(String8("R"));
-        err = table.addSymbols(symbols);
-        if (err < NO_ERROR) {
-            return err;
-        }
-
-        sp<AaptFile> resFile(getResourceFile(assets));
-        if (resFile == NULL) {
-            fprintf(stderr, "Error: unable to generate entry for resource data\n");
-            return UNKNOWN_ERROR;
-        }
-
-        err = table.flatten(bundle, resFile);
-        if (err < NO_ERROR) {
-            return err;
-        }
-
-        if (bundle->getPublicOutputFile()) {
-            FILE* fp = fopen(bundle->getPublicOutputFile(), "w+");
-            if (fp == NULL) {
-                fprintf(stderr, "ERROR: Unable to open public definitions output file %s: %s\n",
-                        (const char*)bundle->getPublicOutputFile(), strerror(errno));
-                return UNKNOWN_ERROR;
-            }
-            if (bundle->getVerbose()) {
-                printf("  Writing public definitions to %s.\n", bundle->getPublicOutputFile());
-            }
-            table.writePublicDefinitions(String16(assets->getPackage()), fp);
-            fclose(fp);
-        }
-#if 0
-        NOISY(
-              ResTable rt;
-              rt.add(resFile->getData(), resFile->getSize(), NULL);
-              printf("Generated resources:\n");
-              rt.print();
-        )
-#endif
+    if (resFile != NULL) {
         // These resources are now considered to be a part of the included
         // resources, for others to reference.
         err = assets->addIncludedResources(resFile);
@@ -1275,6 +1341,7 @@
             return err;
         }
     }
+    
     return err;
 }
 
diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp
index 1f9d152..ab5e937 100644
--- a/tools/aapt/ResourceTable.cpp
+++ b/tools/aapt/ResourceTable.cpp
@@ -28,6 +28,20 @@
 }
 
 status_t compileXmlFile(const sp<AaptAssets>& assets,
+                        const sp<AaptFile>& target,
+                        const sp<AaptFile>& outTarget,
+                        ResourceTable* table,
+                        int options)
+{
+    sp<XMLNode> root = XMLNode::parse(target);
+    if (root == NULL) {
+        return UNKNOWN_ERROR;
+    }
+    
+    return compileXmlFile(assets, root, outTarget, table, options);
+}
+
+status_t compileXmlFile(const sp<AaptAssets>& assets,
                         const sp<XMLNode>& root,
                         const sp<AaptFile>& target,
                         ResourceTable* table,
diff --git a/tools/aapt/ResourceTable.h b/tools/aapt/ResourceTable.h
index 60d0901..186c7ca 100644
--- a/tools/aapt/ResourceTable.h
+++ b/tools/aapt/ResourceTable.h
@@ -37,6 +37,12 @@
                         int options = XML_COMPILE_STANDARD_RESOURCE);
 
 status_t compileXmlFile(const sp<AaptAssets>& assets,
+                        const sp<AaptFile>& target,
+                        const sp<AaptFile>& outTarget,
+                        ResourceTable* table,
+                        int options = XML_COMPILE_STANDARD_RESOURCE);
+
+status_t compileXmlFile(const sp<AaptAssets>& assets,
                         const sp<XMLNode>& xmlTree,
                         const sp<AaptFile>& target,
                         ResourceTable* table,
diff --git a/wifi/java/android/net/wifi/WifiMonitor.java b/wifi/java/android/net/wifi/WifiMonitor.java
index 0928d2b..266d801 100644
--- a/wifi/java/android/net/wifi/WifiMonitor.java
+++ b/wifi/java/android/net/wifi/WifiMonitor.java
@@ -272,10 +272,8 @@
             int connectTries = 0;
 
             while (true) {
-                synchronized (mWifiStateTracker) {
-                    if (WifiNative.connectToSupplicant()) {
-                        return true;
-                    }
+                if (mWifiStateTracker.connectToSupplicant()) {
+                    return true;
                 }
                 if (connectTries++ < 3) {
                     nap(5);
diff --git a/wifi/java/android/net/wifi/WifiNative.java b/wifi/java/android/net/wifi/WifiNative.java
index c3c519f..f98cd287 100644
--- a/wifi/java/android/net/wifi/WifiNative.java
+++ b/wifi/java/android/net/wifi/WifiNative.java
@@ -26,6 +26,9 @@
  * <p/>
  * Note that methods whose names are not of the form "xxxCommand()" do
  * not talk to the supplicant daemon.
+ * Also, note that all WifiNative calls should happen in the
+ * WifiStateTracker class except for waitForEvent() call which is
+ * on a separate monitor channel for WifiMonitor
  *
  * {@hide}
  */
diff --git a/wifi/java/android/net/wifi/WifiStateTracker.java b/wifi/java/android/net/wifi/WifiStateTracker.java
index 810e4d2..9339428 100644
--- a/wifi/java/android/net/wifi/WifiStateTracker.java
+++ b/wifi/java/android/net/wifi/WifiStateTracker.java
@@ -16,6 +16,12 @@
 
 package android.net.wifi;
 
+import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
+import static android.net.wifi.WifiManager.WIFI_STATE_DISABLING;
+import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
+import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING;
+import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
+
 import android.app.ActivityManagerNative;
 import android.net.NetworkInfo;
 import android.net.NetworkStateTracker;
@@ -270,6 +276,14 @@
     private boolean mIsScanModeActive;
     private boolean mEnableRssiPolling;
 
+    /**
+     * One of  {@link WifiManager#WIFI_STATE_DISABLED},
+     *         {@link WifiManager#WIFI_STATE_DISABLING},
+     *         {@link WifiManager#WIFI_STATE_ENABLED},
+     *         {@link WifiManager#WIFI_STATE_ENABLING},
+     *         {@link WifiManager#WIFI_STATE_UNKNOWN}
+     */
+    private int mWifiState;
     // Wi-Fi run states:
     private static final int RUN_STATE_STARTING = 1;
     private static final int RUN_STATE_RUNNING  = 2;
@@ -544,9 +558,7 @@
      */
     void notifyScanResultsAvailable() {
         // reset the supplicant's handling of scan results to "normal" mode
-        synchronized (this) {
-            WifiNative.setScanResultHandlingCommand(SUPPL_SCAN_HANDLING_NORMAL);
-        }
+        setScanResultHandling(SUPPL_SCAN_HANDLING_NORMAL);
         sendEmptyMessage(EVENT_SCAN_RESULTS_AVAILABLE);
     }
 
@@ -613,39 +625,6 @@
     }
 
     /**
-     * Set the number of allowed radio frequency channels from the system
-     * setting value, if any.
-     * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
-     * the number of channels is invalid.
-     */
-    public synchronized boolean setNumAllowedChannels() {
-        try {
-            return setNumAllowedChannels(
-                    Settings.Secure.getInt(mContext.getContentResolver(),
-                    Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS));
-        } catch (Settings.SettingNotFoundException e) {
-            if (mNumAllowedChannels != 0) {
-                WifiNative.setNumAllowedChannelsCommand(mNumAllowedChannels);
-            }
-            // otherwise, use the driver default
-        }
-        return true;
-    }
-
-    /**
-     * Set the number of radio frequency channels that are allowed to be used
-     * in the current regulatory domain.
-     * @param numChannels the number of allowed channels. Must be greater than 0
-     * and less than or equal to 16.
-     * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
-     * {@code numChannels} is outside the valid range.
-     */
-    public synchronized boolean setNumAllowedChannels(int numChannels) {
-        mNumAllowedChannels = numChannels;
-        return WifiNative.setNumAllowedChannelsCommand(numChannels);
-    }
-
-    /**
      * Set the run state to either "normal" or "scan-only".
      * @param scanOnlyMode true if the new mode should be scan-only.
      */
@@ -655,29 +634,19 @@
             int scanType = (scanOnlyMode ?
                     SUPPL_SCAN_HANDLING_LIST_ONLY : SUPPL_SCAN_HANDLING_NORMAL);
             if (LOCAL_LOGD) Log.v(TAG, "Scan-only mode changing to " + scanOnlyMode + " scanType=" + scanType);
-            if (WifiNative.setScanResultHandlingCommand(scanType)) {
+            if (setScanResultHandling(scanType)) {
                 mIsScanOnly = scanOnlyMode;
                 if (!isDriverStopped()) {
                     if (scanOnlyMode) {
-                        WifiNative.disconnectCommand();
+                        disconnect();
                     } else {
-                        WifiNative.reconnectCommand();
+                        reconnectCommand();
                     }
                 }
             }
         }
     }
 
-    /**
-     * Enable or disable Bluetooth coexistence scan mode. When this mode is on,
-     * some of the low-level scan parameters used by the driver are changed to
-     * reduce interference with A2DP streaming.
-     *
-     * @param isBluetoothPlaying whether to enable or disable this mode
-     */
-    public synchronized void setBluetoothScanMode(boolean isBluetoothPlaying) {
-        WifiNative.setBluetoothCoexistenceScanModeCommand(isBluetoothPlaying);
-    }
 
     private void checkIsBluetoothPlaying() {
         boolean isBluetoothPlaying = false;
@@ -765,10 +734,8 @@
                  * The MAC address isn't going to change, so just request it
                  * once here.
                  */
-                String macaddr;
-                synchronized (this) {
-                    macaddr = WifiNative.getMacAddressCommand();
-                }
+                String macaddr = getMacAddress();
+
                 if (macaddr != null) {
                     mWifiInfo.setMacAddress(macaddr);
                 }
@@ -818,9 +785,8 @@
             case EVENT_SUPPLICANT_DISCONNECT:
                 mRunState = RUN_STATE_STOPPED;
                 noteRunState();
-                int wifiState = mWM.getWifiState();
-                boolean died = wifiState != WifiManager.WIFI_STATE_DISABLED &&
-                        wifiState != WifiManager.WIFI_STATE_DISABLING;
+                boolean died = mWifiState != WIFI_STATE_DISABLED &&
+                               mWifiState != WIFI_STATE_DISABLING;
                 if (died) {
                     if (LOCAL_LOGD) Log.v(TAG, "Supplicant died unexpectedly");
                 } else {
@@ -831,9 +797,8 @@
                 // [ 1- 0] Connected to supplicant (1), disconnected from supplicant (0) ,
                 //         or supplicant died (2)
                 EventLog.writeEvent(EVENTLOG_SUPPLICANT_CONNECTION_STATE_CHANGED, died ? 2 : 0);
-                synchronized (this) {
-                    WifiNative.closeSupplicantConnection();
-                }
+                closeSupplicantConnection();
+
                 if (died) {
                     resetConnections(true);
                 }
@@ -861,9 +826,7 @@
                 // Only do this if we haven't gotten a new supplicant status since the timer
                 // started
                 if (mNumSupplicantStateChanges == msg.arg1) {
-                    synchronized (this) {
-                        WifiNative.scanCommand(false); // do a passive scan
-                    }
+                    scan(false); // do a passive scan
                 }
                 break;
 
@@ -954,13 +917,9 @@
                         if (mRunState == RUN_STATE_RUNNING && !mIsScanOnly && networkId != -1) {
                             sendMessageDelayed(reconnectMsg, RECONNECT_DELAY_MSECS);
                         } else if (mRunState == RUN_STATE_STOPPING) {
-                            synchronized (this) {
-                                WifiNative.stopDriverCommand();
-                            }
+                            stopDriver();
                         } else if (mRunState == RUN_STATE_STARTING && !mIsScanOnly) {
-                            synchronized (this) {
-                                WifiNative.reconnectCommand();
-                            }
+                            reconnectCommand();
                         }
                     } else if (newState == SupplicantState.DISCONNECTED) {
                         mHaveIpAddress = false;
@@ -1129,9 +1088,7 @@
                         }
                         addToBlacklist(BSSID);
                     }
-                    synchronized(this) {
-                        WifiNative.reconnectCommand();
-                    }
+                    reconnectCommand();
                 }
                 break;
 
@@ -1174,9 +1131,7 @@
                     mHaveIpAddress = false;
                     mWifiInfo.setIpAddress(0);
                     mObtainingIpAddress = false;
-                    synchronized(this) {
-                        WifiNative.disconnectCommand();
-                    }
+                    disconnect();
                 }
                 break;
 
@@ -1199,11 +1154,11 @@
                         if (mRunState == RUN_STATE_STARTING) {
                             mRunState = RUN_STATE_RUNNING;
                             if (!mIsScanOnly) {
-                                WifiNative.reconnectCommand();
+                                reconnectCommand();
                             } else {
                                 // In some situations, supplicant needs to be kickstarted to
                                 // start the background scanning
-                                WifiNative.scanCommand(true);
+                                scan(true);
                             }
                         }
                     }
@@ -1245,12 +1200,6 @@
         return disabledNetwork;
     }
 
-    public synchronized void setScanMode(boolean isScanModeActive) {
-        if (mIsScanModeActive != isScanModeActive) {
-            WifiNative.setScanModeCommand(mIsScanModeActive = isScanModeActive);
-        }
-    }
-
     private void configureInterface() {
         checkPollTimer();
         mLastSignalLevel = -1;
@@ -1371,10 +1320,7 @@
     }
 
     private void requestConnectionStatus(WifiInfo info) {
-        String reply;
-        synchronized (this) {
-            reply = WifiNative.statusCommand();
-        }
+        String reply = status();
         if (reply == null) {
             return;
         }
@@ -1423,7 +1369,7 @@
      */
     private synchronized void requestPolledInfo(WifiInfo info, boolean polling)
     {
-        int newRssi = (polling ? WifiNative.getRssiApproxCommand() : WifiNative.getRssiCommand());
+        int newRssi = (polling ? getRssiApprox() : getRssi());
         if (newRssi != -1 && -200 < newRssi && newRssi < 256) { // screen out invalid values
             /* some implementations avoid negative values by adding 256
              * so we need to adjust for that here.
@@ -1451,7 +1397,7 @@
         } else {
             info.setRssi(-200);
         }
-        int newLinkSpeed = WifiNative.getLinkSpeedCommand();
+        int newLinkSpeed = getLinkSpeed();
         if (newLinkSpeed != -1) {
             info.setLinkSpeed(newLinkSpeed);
         }
@@ -1521,9 +1467,9 @@
 
             mRunState = RUN_STATE_STOPPING;
             if (mWifiInfo.getSupplicantState() == SupplicantState.DORMANT) {
-                return WifiNative.stopDriverCommand();
+                return stopDriver();
             } else {
-                return WifiNative.disconnectCommand();
+                return disconnect();
             }
         } else {
             /*
@@ -1547,17 +1493,551 @@
         if (mRunState == RUN_STATE_STOPPED) {
             mRunState = RUN_STATE_STARTING;
             resetConnections(true);
-            return WifiNative.startDriverCommand();
+            return startDriver();
         } else if (mRunState == RUN_STATE_STOPPING) {
             mRunState = RUN_STATE_STARTING;
         }
         return true;
     }
 
+    public synchronized int getWifiState() {
+        return mWifiState;
+    }
+
+    public synchronized void setWifiState(int wifiState) {
+        mWifiState = wifiState;
+    }
+
+   /**
+     * The WifiNative interface functions are listed below.
+     * The only native call that is not synchronized on
+     * WifiStateTracker is waitForEvent() which waits on a
+     * seperate monitor channel.
+     *
+     * All supplicant commands need the wifi to be in an
+     * enabled state. This can be done by checking the
+     * mWifiState to be WIFI_STATE_ENABLED.
+     *
+     * All commands that can cause commands to driver
+     * initiated need the driver state to be started.
+     * This is done by checking isDriverStopped() to
+     * be false.
+     */
+
+    /**
+     * Load the driver and firmware
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean loadDriver() {
+        return WifiNative.loadDriver();
+    }
+
+    /**
+     * Unload the driver and firmware
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean unloadDriver() {
+        return WifiNative.unloadDriver();
+    }
+
+    /**
+     * Check the supplicant config and
+     * start the supplicant daemon
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean startSupplicant() {
+        return WifiNative.startSupplicant();
+    }
+
+    /**
+     * Stop the supplicant daemon
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean stopSupplicant() {
+        return WifiNative.stopSupplicant();
+    }
+
+    /**
+     * Establishes two channels - control channel for commands
+     * and monitor channel for notifying WifiMonitor
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean connectToSupplicant() {
+        return WifiNative.connectToSupplicant();
+    }
+
+    /**
+     * Close the control/monitor channels to supplicant
+     */
+    public synchronized void closeSupplicantConnection() {
+        WifiNative.closeSupplicantConnection();
+    }
+
+    /**
+     * Check if the supplicant is alive
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean ping() {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return false;
+        }
+        return WifiNative.pingCommand();
+    }
+
+    /**
+     * initiate an active or passive scan
+     *
+     * @param forceActive true if it is a active scan
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean scan(boolean forceActive) {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        return WifiNative.scanCommand(forceActive);
+    }
+
+    /**
+     * Specifies whether the supplicant or driver
+     * take care of initiating scan and doing AP selection
+     *
+     * @param mode
+     *    SUPPL_SCAN_HANDLING_NORMAL
+     *    SUPPL_SCAN_HANDLING_LIST_ONLY
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean setScanResultHandling(int mode) {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        return WifiNative.setScanResultHandlingCommand(mode);
+    }
+
+    /**
+     * Fetch the scan results from the supplicant
+     *
+     * @return example result string
+     * 00:bb:cc:dd:cc:ee       2427    166     [WPA-EAP-TKIP][WPA2-EAP-CCMP]   Net1
+     * 00:bb:cc:dd:cc:ff       2412    165     [WPA-EAP-TKIP][WPA2-EAP-CCMP]   Net2
+     */
+    public synchronized String scanResults() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return null;
+        }
+        return WifiNative.scanResultsCommand();
+    }
+
+    /**
+     * Set the scan mode - active or passive
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean setScanMode(boolean isScanModeActive) {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        if (mIsScanModeActive != isScanModeActive) {
+            return WifiNative.setScanModeCommand(mIsScanModeActive = isScanModeActive);
+        }
+        return true;
+    }
+
+    /**
+     * Disconnect from Access Point
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean disconnect() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        return WifiNative.disconnectCommand();
+    }
+
+    /**
+     * Initiate a reconnection to AP
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean reconnectCommand() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        return WifiNative.reconnectCommand();
+    }
+
+    /**
+     * Add a network
+     *
+     * @return network id of the new network
+     */
+    public synchronized int addNetwork() {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return -1;
+        }
+        return WifiNative.addNetworkCommand();
+    }
+
+    /**
+     * Delete a network
+     *
+     * @param networkId id of the network to be removed
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
     public synchronized boolean removeNetwork(int networkId) {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return false;
+        }
         return mDisconnectExpected = WifiNative.removeNetworkCommand(networkId);
     }
 
+    /**
+     * Enable a network
+     *
+     * @param netId network id of the network
+     * @param disableOthers true, if all other networks have to be disabled
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean enableNetwork(int netId, boolean disableOthers) {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return false;
+        }
+        return WifiNative.enableNetworkCommand(netId, disableOthers);
+    }
+
+    /**
+     * Disable a network
+     *
+     * @param netId network id of the network
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean disableNetwork(int netId) {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return false;
+        }
+        return WifiNative.disableNetworkCommand(netId);
+    }
+
+    /**
+     * Initiate a re-association in supplicant
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean reassociate() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        return WifiNative.reassociateCommand();
+    }
+
+    /**
+     * Blacklist a BSSID. This will avoid the AP if there are
+     * alternate APs to connect
+     *
+     * @param bssid BSSID of the network
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean addToBlacklist(String bssid) {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return false;
+        }
+        return WifiNative.addToBlacklistCommand(bssid);
+    }
+
+    /**
+     * Clear the blacklist list
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean clearBlacklist() {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return false;
+        }
+        return WifiNative.clearBlacklistCommand();
+    }
+
+    /**
+     * List all configured networks
+     *
+     * @return list of networks or null on failure
+     */
+    public synchronized String listNetworks() {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return null;
+        }
+        return WifiNative.listNetworksCommand();
+    }
+
+    /**
+     * Get network setting by name
+     *
+     * @param netId network id of the network
+     * @param name network variable key
+     * @return value corresponding to key
+     */
+    public synchronized String getNetworkVariable(int netId, String name) {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return null;
+        }
+        return WifiNative.getNetworkVariableCommand(netId, name);
+    }
+
+    /**
+     * Set network setting by name
+     *
+     * @param netId network id of the network
+     * @param name network variable key
+     * @param value network variable value
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean setNetworkVariable(int netId, String name, String value) {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return false;
+        }
+        return WifiNative.setNetworkVariableCommand(netId, name, value);
+    }
+
+    /**
+     * Get detailed status of the connection
+     *
+     * @return Example status result
+     *  bssid=aa:bb:cc:dd:ee:ff
+     *  ssid=TestNet
+     *  id=3
+     *  pairwise_cipher=NONE
+     *  group_cipher=NONE
+     *  key_mgmt=NONE
+     *  wpa_state=COMPLETED
+     *  ip_address=X.X.X.X
+     */
+    public synchronized String status() {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return null;
+        }
+        return WifiNative.statusCommand();
+    }
+
+    /**
+     * Get RSSI to currently connected network
+     *
+     * @return RSSI value, -1 on failure
+     */
+    public synchronized int getRssi() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return -1;
+        }
+        return WifiNative.getRssiApproxCommand();
+    }
+
+    /**
+     * Get approx RSSI to currently connected network
+     *
+     * @return RSSI value, -1 on failure
+     */
+    public synchronized int getRssiApprox() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return -1;
+        }
+        return WifiNative.getRssiApproxCommand();
+    }
+
+    /**
+     * Get link speed to currently connected network
+     *
+     * @return link speed, -1 on failure
+     */
+    public synchronized int getLinkSpeed() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return -1;
+        }
+        return WifiNative.getLinkSpeedCommand();
+    }
+
+    /**
+     * Get MAC address of radio
+     *
+     * @return MAC address, null on failure
+     */
+    public synchronized String getMacAddress() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return null;
+        }
+        return WifiNative.getMacAddressCommand();
+    }
+
+    /**
+     * Start driver
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean startDriver() {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return false;
+        }
+        return WifiNative.startDriverCommand();
+    }
+
+    /**
+     * Stop driver
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean stopDriver() {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return false;
+        }
+        return WifiNative.stopDriverCommand();
+    }
+
+    /**
+     * Start packet filtering
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean startPacketFiltering() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        return WifiNative.startPacketFiltering();
+    }
+
+    /**
+     * Stop packet filtering
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean stopPacketFiltering() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        return WifiNative.stopPacketFiltering();
+    }
+
+    /**
+     * Set power mode
+     * @param mode
+     *     DRIVER_POWER_MODE_AUTO
+     *     DRIVER_POWER_MODE_ACTIVE
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean setPowerMode(int mode) {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        return WifiNative.setPowerModeCommand(mode);
+    }
+
+    /**
+     * Set the number of allowed radio frequency channels from the system
+     * setting value, if any.
+     * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
+     * the number of channels is invalid.
+     */
+    public synchronized boolean setNumAllowedChannels() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        try {
+            return setNumAllowedChannels(
+                    Settings.Secure.getInt(mContext.getContentResolver(),
+                    Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS));
+        } catch (Settings.SettingNotFoundException e) {
+            if (mNumAllowedChannels != 0) {
+                WifiNative.setNumAllowedChannelsCommand(mNumAllowedChannels);
+            }
+            // otherwise, use the driver default
+        }
+        return true;
+    }
+
+    /**
+     * Set the number of radio frequency channels that are allowed to be used
+     * in the current regulatory domain.
+     * @param numChannels the number of allowed channels. Must be greater than 0
+     * and less than or equal to 16.
+     * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
+     * {@code numChannels} is outside the valid range.
+     */
+    public synchronized boolean setNumAllowedChannels(int numChannels) {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        mNumAllowedChannels = numChannels;
+        return WifiNative.setNumAllowedChannelsCommand(numChannels);
+    }
+
+    /**
+     * Get number of allowed channels
+     *
+     * @return channel count, -1 on failure
+     */
+    public synchronized int getNumAllowedChannels() {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return -1;
+        }
+        return WifiNative.getNumAllowedChannelsCommand();
+    }
+
+    /**
+     * Set bluetooth coex mode:
+     *
+     * @param mode
+     *  BLUETOOTH_COEXISTENCE_MODE_ENABLED
+     *  BLUETOOTH_COEXISTENCE_MODE_DISABLED
+     *  BLUETOOTH_COEXISTENCE_MODE_SENSE
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean setBluetoothCoexistenceMode(int mode) {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return false;
+        }
+        return WifiNative.setBluetoothCoexistenceModeCommand(mode);
+    }
+
+    /**
+     * Enable or disable Bluetooth coexistence scan mode. When this mode is on,
+     * some of the low-level scan parameters used by the driver are changed to
+     * reduce interference with A2DP streaming.
+     *
+     * @param isBluetoothPlaying whether to enable or disable this mode
+     */
+    public synchronized void setBluetoothScanMode(boolean isBluetoothPlaying) {
+        if (mWifiState != WIFI_STATE_ENABLED && !isDriverStopped()) {
+            return;
+        }
+        WifiNative.setBluetoothCoexistenceScanModeCommand(isBluetoothPlaying);
+    }
+
+    /**
+     * Save configuration on supplicant
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean saveConfig() {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return false;
+        }
+        return WifiNative.saveConfigCommand();
+    }
+
+    /**
+     * Reload the configuration from file
+     *
+     * @return {@code true} if the operation succeeds, {@code false} otherwise
+     */
+    public synchronized boolean reloadConfig() {
+        if (mWifiState != WIFI_STATE_ENABLED) {
+            return false;
+        }
+        return WifiNative.reloadConfigCommand();
+    }
+
     public boolean setRadio(boolean turnOn) {
         return mWM.setWifiEnabled(turnOn);
     }
@@ -1571,7 +2051,7 @@
     public int startUsingNetworkFeature(String feature, int callingPid, int callingUid) {
         return -1;
     }
-    
+
     /**
      * {@inheritDoc}
      * There are currently no Wi-Fi-specific features supported.
@@ -1584,11 +2064,11 @@
 
     @Override
     public void interpretScanResultsAvailable() {
-        
+
         // If we shouldn't place a notification on available networks, then
         // don't bother doing any of the following
         if (!mNotificationEnabled) return;
-        
+
         NetworkInfo networkInfo = getNetworkInfo();
 
         State state = networkInfo.getState();
@@ -1706,18 +2186,6 @@
         mNumScansSinceNetworkStateChange = 0;
     }
     
-    public synchronized boolean reassociate() {
-        return WifiNative.reassociateCommand();
-    }
-
-    public synchronized boolean addToBlacklist(String bssid) {
-        return WifiNative.addToBlacklistCommand(bssid);
-    }
-    
-    public synchronized boolean clearBlacklist() {
-        return WifiNative.clearBlacklistCommand();
-    }
-    
     @Override
     public String toString() {
         StringBuffer sb = new StringBuffer();
@@ -1796,15 +2264,12 @@
                         modifiedBluetoothCoexistenceMode = true;
 
                         // Disable the coexistence mode
-                        synchronized (WifiStateTracker.this) {
-                            WifiNative.setBluetoothCoexistenceModeCommand(
-                                    WifiNative.BLUETOOTH_COEXISTENCE_MODE_DISABLED);
-                        }
+                        setBluetoothCoexistenceMode(
+                                WifiNative.BLUETOOTH_COEXISTENCE_MODE_DISABLED);
                     }
-                    
-                    synchronized (WifiStateTracker.this) {
-                        WifiNative.setPowerModeCommand(DRIVER_POWER_MODE_ACTIVE);
-                    }
+
+                    setPowerMode(DRIVER_POWER_MODE_ACTIVE);
+
                     synchronized (this) {
                         // A new request is being made, so assume we will callback
                         mCancelCallback = false;
@@ -1818,18 +2283,15 @@
                         Log.i(TAG, "DhcpHandler: DHCP request failed: " +
                             NetworkUtils.getDhcpError());
                     }
-                    synchronized (WifiStateTracker.this) {
-                        WifiNative.setPowerModeCommand(DRIVER_POWER_MODE_AUTO);
-                    }
-                    
+
+                    setPowerMode(DRIVER_POWER_MODE_AUTO);
+
                     if (modifiedBluetoothCoexistenceMode) {
                         // Set the coexistence mode back to its default value
-                        synchronized (WifiStateTracker.this) {
-                            WifiNative.setBluetoothCoexistenceModeCommand(
-                                    WifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE);
-                        }
+                        setBluetoothCoexistenceMode(
+                                WifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE);
                     }
-                    
+
                     synchronized (this) {
                         if (!mCancelCallback) {
                             mTarget.sendEmptyMessage(event);
@@ -1838,7 +2300,7 @@
                     break;
             }
         }
-        
+
         public synchronized void setCancelCallback(boolean cancelCallback) {
             mCancelCallback = cancelCallback;
         }