merge mozilla-inbound to mozilla-central. r=merge a=merge
authorSebastian Hengst <archaeopteryx@coole-files.de>
Fri, 16 Jun 2017 09:50:00 +0200
changeset 413028 fe809f57bf2287bb937c3422ed03a63740b3448b
parent 412989 64a2ba65f0d6f77d1f9d5e3957478ef5d1cafed5 (current diff)
parent 413027 cd069d0b934eb5f6da003bf5015ff8a9e520dc7b (diff)
child 413029 b266774b8d40b08a931cdc72309176ab90ccede4
child 413055 4e22e16db2fa4ee7fe50a11acc418c83ae3d5a7c
child 413111 16da5a629b13229cd7fe8acec214082f79c7ceb9
push id7566
push usermtabara@mozilla.com
push dateWed, 02 Aug 2017 08:25:16 +0000
treeherdermozilla-beta@86913f512c3c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge, merge
milestone56.0a1
first release with
nightly linux32
fe809f57bf22 / 56.0a1 / 20170616100254 / files
nightly linux64
fe809f57bf22 / 56.0a1 / 20170616100254 / files
nightly mac
fe809f57bf22 / 56.0a1 / 20170616030207 / files
nightly win32
fe809f57bf22 / 56.0a1 / 20170616030207 / files
nightly win64
fe809f57bf22 / 56.0a1 / 20170616030207 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
merge mozilla-inbound to mozilla-central. r=merge a=merge MozReview-Commit-ID: 5wTyHWufcCh
dom/base/nsDocument.cpp
toolkit/components/telemetry/Histograms.json
toolkit/mozapps/update/tests/unit_aus_update/downloadAndHashCheckMar.js
widget/gonk/GeckoTouchDispatcher.cpp
widget/gonk/GeckoTouchDispatcher.h
widget/gonk/GfxInfo.cpp
widget/gonk/GfxInfo.h
widget/gonk/GonkClipboardData.cpp
widget/gonk/GonkClipboardData.h
widget/gonk/GonkKeyMapping.h
widget/gonk/GonkMemoryPressureMonitoring.cpp
widget/gonk/GonkMemoryPressureMonitoring.h
widget/gonk/GonkPermission.cpp
widget/gonk/GonkPermission.h
widget/gonk/HwcComposer2D.cpp
widget/gonk/HwcComposer2D.h
widget/gonk/HwcUtils.cpp
widget/gonk/HwcUtils.h
widget/gonk/ProcessOrientation.cpp
widget/gonk/ProcessOrientation.h
widget/gonk/WidgetTraceEvent.cpp
widget/gonk/hwchal/HwcHAL.cpp
widget/gonk/hwchal/HwcHAL.h
widget/gonk/hwchal/HwcHALBase.h
widget/gonk/libdisplay/BootAnimation.cpp
widget/gonk/libdisplay/BootAnimation.h
widget/gonk/libdisplay/DisplaySurface.h
widget/gonk/libdisplay/FramebufferSurface.cpp
widget/gonk/libdisplay/FramebufferSurface.h
widget/gonk/libdisplay/GonkDisplay.h
widget/gonk/libdisplay/GonkDisplayJB.cpp
widget/gonk/libdisplay/GonkDisplayJB.h
widget/gonk/libdisplay/GraphicBufferAlloc.cpp
widget/gonk/libdisplay/GraphicBufferAlloc.h
widget/gonk/libdisplay/VirtualDisplaySurface.cpp
widget/gonk/libdisplay/VirtualDisplaySurface.h
widget/gonk/libdisplay/moz.build
widget/gonk/libui/EventHub.cpp
widget/gonk/libui/EventHub.h
widget/gonk/libui/Input.cpp
widget/gonk/libui/Input.h
widget/gonk/libui/InputApplication.cpp
widget/gonk/libui/InputApplication.h
widget/gonk/libui/InputDevice.cpp
widget/gonk/libui/InputDevice.h
widget/gonk/libui/InputDispatcher.cpp
widget/gonk/libui/InputDispatcher.h
widget/gonk/libui/InputListener.cpp
widget/gonk/libui/InputListener.h
widget/gonk/libui/InputManager.cpp
widget/gonk/libui/InputManager.h
widget/gonk/libui/InputReader.cpp
widget/gonk/libui/InputReader.h
widget/gonk/libui/InputTransport.cpp
widget/gonk/libui/InputTransport.h
widget/gonk/libui/InputWindow.cpp
widget/gonk/libui/InputWindow.h
widget/gonk/libui/KeyCharacterMap.cpp
widget/gonk/libui/KeyCharacterMap.h
widget/gonk/libui/KeyLayoutMap.cpp
widget/gonk/libui/KeyLayoutMap.h
widget/gonk/libui/Keyboard.cpp
widget/gonk/libui/Keyboard.h
widget/gonk/libui/KeycodeLabels.h
widget/gonk/libui/PointerController.cpp
widget/gonk/libui/PointerController.h
widget/gonk/libui/PowerManager.h
widget/gonk/libui/SpriteController.cpp
widget/gonk/libui/SpriteController.h
widget/gonk/libui/Tokenizer.cpp
widget/gonk/libui/Tokenizer.h
widget/gonk/libui/Trace.h
widget/gonk/libui/VelocityControl.cpp
widget/gonk/libui/VelocityControl.h
widget/gonk/libui/VelocityTracker.cpp
widget/gonk/libui/VelocityTracker.h
widget/gonk/libui/VirtualKeyMap.cpp
widget/gonk/libui/VirtualKeyMap.h
widget/gonk/libui/android_input.h
widget/gonk/libui/android_keycodes.h
widget/gonk/libui/cutils_log.h
widget/gonk/libui/cutils_trace.h
widget/gonk/libui/linux_input.h
widget/gonk/libui/sha1.c
widget/gonk/libui/sha1.h
widget/gonk/nativewindow/FakeSurfaceComposer.cpp
widget/gonk/nativewindow/FakeSurfaceComposer.h
widget/gonk/nativewindow/GonkBufferQueue.h
widget/gonk/nativewindow/GonkBufferQueueJB.cpp
widget/gonk/nativewindow/GonkBufferQueueJB.h
widget/gonk/nativewindow/GonkBufferQueueKK.cpp
widget/gonk/nativewindow/GonkBufferQueueKK.h
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferItem.cpp
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferItem.h
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.cpp
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.h
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.cpp
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.h
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueDefs.h
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueLL.cpp
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueLL.h
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.cpp
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.h
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferSlot.cpp
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferSlot.h
widget/gonk/nativewindow/GonkConsumerBaseJB.cpp
widget/gonk/nativewindow/GonkConsumerBaseJB.h
widget/gonk/nativewindow/GonkConsumerBaseKK.cpp
widget/gonk/nativewindow/GonkConsumerBaseKK.h
widget/gonk/nativewindow/GonkConsumerBaseLL.cpp
widget/gonk/nativewindow/GonkConsumerBaseLL.h
widget/gonk/nativewindow/GonkNativeWindow.h
widget/gonk/nativewindow/GonkNativeWindowJB.cpp
widget/gonk/nativewindow/GonkNativeWindowJB.h
widget/gonk/nativewindow/GonkNativeWindowKK.cpp
widget/gonk/nativewindow/GonkNativeWindowKK.h
widget/gonk/nativewindow/GonkNativeWindowLL.cpp
widget/gonk/nativewindow/GonkNativeWindowLL.h
widget/gonk/nativewindow/IGonkGraphicBufferConsumer.h
widget/gonk/nativewindow/IGonkGraphicBufferConsumerKK.cpp
widget/gonk/nativewindow/IGonkGraphicBufferConsumerKK.h
widget/gonk/nativewindow/IGonkGraphicBufferConsumerLL.cpp
widget/gonk/nativewindow/IGonkGraphicBufferConsumerLL.h
widget/gonk/nativewindow/moz.build
widget/gonk/nsAppShell.cpp
widget/gonk/nsAppShell.h
widget/gonk/nsClipboard.cpp
widget/gonk/nsClipboard.h
widget/gonk/nsIdleServiceGonk.cpp
widget/gonk/nsIdleServiceGonk.h
widget/gonk/nsLookAndFeel.cpp
widget/gonk/nsLookAndFeel.h
widget/gonk/nsScreenManagerGonk.cpp
widget/gonk/nsScreenManagerGonk.h
widget/gonk/nsWidgetFactory.cpp
widget/gonk/nsWindow.cpp
widget/gonk/nsWindow.h
--- a/accessible/base/Platform.h
+++ b/accessible/base/Platform.h
@@ -39,16 +39,20 @@ void PreInit();
 #if defined(MOZ_ACCESSIBILITY_ATK) || defined(XP_MACOSX)
 /**
  * Is platform accessibility enabled.
  * Only used on linux with atk and MacOS for now.
  */
 bool ShouldA11yBeEnabled();
 #endif
 
+#if defined(XP_WIN)
+bool IsHandlerRegistered();
+#endif
+
 /**
  * Called to initialize platform specific accessibility support.
  * Note this is called after internal accessibility support is initialized.
  */
 void PlatformInit();
 
 /**
  * Shutdown platform accessibility.
--- a/accessible/ipc/win/COMPtrTypes.cpp
+++ b/accessible/ipc/win/COMPtrTypes.cpp
@@ -4,16 +4,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/a11y/COMPtrTypes.h"
 
 #include "Accessible2_3.h"
 #include "MainThreadUtils.h"
 #include "mozilla/a11y/Accessible.h"
+#include "mozilla/a11y/Platform.h"
 #include "mozilla/a11y/HandlerProvider.h"
 #include "mozilla/Move.h"
 #include "mozilla/mscom/MainThreadHandoff.h"
 #include "mozilla/mscom/Utils.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/RefPtr.h"
 #include "nsXULAppAPI.h"
 
@@ -35,17 +36,18 @@ CreateHolderFromAccessible(Accessible* a
   STAUniquePtr<IAccessible> iaToProxy;
   aAccToWrap->GetNativeInterface(mscom::getter_AddRefs(iaToProxy));
   MOZ_ASSERT(iaToProxy);
   if (!iaToProxy) {
     return nullptr;
   }
 
   static const bool useHandler =
-    Preferences::GetBool("accessibility.handler.enabled", false);
+    Preferences::GetBool("accessibility.handler.enabled", false) &&
+    IsHandlerRegistered();
 
   RefPtr<HandlerProvider> payload;
   if (useHandler) {
     payload = new HandlerProvider(IID_IAccessible,
                                   mscom::ToInterceptorTargetPtr(iaToProxy));
   }
 
   ProxyUniquePtr<IAccessible> intercepted;
--- a/accessible/windows/msaa/Platform.cpp
+++ b/accessible/windows/msaa/Platform.cpp
@@ -5,21 +5,23 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "Platform.h"
 
 #include "AccEvent.h"
 #include "Compatibility.h"
 #include "HyperTextAccessibleWrap.h"
 #include "ia2AccessibleText.h"
+#include "nsIWindowsRegKey.h"
 #include "nsIXULRuntime.h"
 #include "nsWinUtils.h"
 #include "mozilla/a11y/ProxyAccessible.h"
 #include "mozilla/mscom/InterceptorLog.h"
 #include "mozilla/mscom/Registration.h"
+#include "mozilla/mscom/Utils.h"
 #include "mozilla/StaticPtr.h"
 #include "ProxyWrappers.h"
 
 using namespace mozilla;
 using namespace mozilla::a11y;
 using namespace mozilla::mscom;
 
 static StaticAutoPtr<RegisteredProxy> gRegCustomProxy;
@@ -139,17 +141,18 @@ a11y::ProxyTextChangeEvent(ProxyAccessib
 {
   AccessibleWrap* wrapper = WrapperFor(aText);
   MOZ_ASSERT(wrapper);
   if (!wrapper) {
     return;
   }
 
   static const bool useHandler =
-    Preferences::GetBool("accessibility.handler.enabled", false);
+    Preferences::GetBool("accessibility.handler.enabled", false) &&
+    IsHandlerRegistered();
 
   if (useHandler) {
     wrapper->DispatchTextChangeToHandler(aInsert, aStr, aStart, aLen);
     return;
   }
 
   auto text = static_cast<HyperTextAccessibleWrap*>(wrapper->AsHyperText());
   if (text) {
@@ -171,8 +174,34 @@ a11y::ProxyShowHideEvent(ProxyAccessible
 }
 
 void
 a11y::ProxySelectionEvent(ProxyAccessible* aTarget, ProxyAccessible*, uint32_t aType)
 {
   AccessibleWrap* wrapper = WrapperFor(aTarget);
   AccessibleWrap::FireWinEvent(wrapper, aType);
 }
+
+bool
+a11y::IsHandlerRegistered()
+{
+  nsresult rv;
+  nsCOMPtr<nsIWindowsRegKey> regKey =
+    do_CreateInstance("@mozilla.org/windows-registry-key;1", &rv);
+  if (NS_FAILED(rv)) {
+    return false;
+  }
+
+  nsAutoString subKey;
+  subKey.AppendLiteral("CLSID\\");
+  nsAutoString iid;
+  GUIDToString(CLSID_AccessibleHandler, iid);
+  subKey.Append(iid);
+  subKey.AppendLiteral("\\InprocHandler32");
+
+  rv = regKey->Open(nsIWindowsRegKey::ROOT_KEY_CLASSES_ROOT, subKey,
+                    nsIWindowsRegKey::ACCESS_READ);
+  if (NS_FAILED(rv)) {
+    return false;
+  }
+
+  return true;
+}
--- a/browser/components/tests/browser/browser_bug538331.js
+++ b/browser/components/tests/browser/browser_bug538331.js
@@ -20,19 +20,18 @@ const XML_PREFIX =  "<updates xmlns=\"ht
                     "installDate=\"1238441400314\" isCompleteUpdate=\"true\" " +
                     "name=\"Update Test 1.0\" type=\"minor\" detailsURL=" +
                     "\"http://example.com/\" previousAppVersion=\"1.0\" " +
                     "serviceURL=\"https://example.com/\" " +
                     "statusText=\"The Update was successfully installed\" " +
                     "foregroundDownload=\"true\"";
 
 const XML_SUFFIX = "><patch type=\"complete\" URL=\"http://example.com/\" " +
-                   "hashFunction=\"MD5\" hashValue=" +
-                   "\"6232cd43a1c77e30191c53a329a3f99d\" size=\"775\" " +
-                   "selected=\"true\" state=\"succeeded\"/></update></updates>";
+                   "size=\"775\" selected=\"true\" state=\"succeeded\"/>" +
+                   "</update></updates>";
 
 // nsBrowserContentHandler.js defaultArgs tests
 const BCH_TESTS = [
   {
     description: "no mstone change and no update",
     noPostUpdatePref: true,
     noMstoneChange: true
   }, {
--- a/browser/extensions/pdfjs/README.mozilla
+++ b/browser/extensions/pdfjs/README.mozilla
@@ -1,5 +1,5 @@
 This is the PDF.js project output, https://github.com/mozilla/pdf.js
 
-Current extension version is: 1.8.439
+Current extension version is: 1.8.450
 
-Taken from upstream commit: 08c64371
+Taken from upstream commit: 20975134
--- a/browser/extensions/pdfjs/content/build/pdf.js
+++ b/browser/extensions/pdfjs/content/build/pdf.js
@@ -102,17 +102,17 @@ Object.defineProperty(exports, "__esModu
   value: true
 });
 exports.warn = exports.utf8StringToString = exports.stringToUTF8String = exports.stringToPDFString = exports.stringToBytes = exports.string32 = exports.shadow = exports.setVerbosityLevel = exports.ReadableStream = exports.removeNullCharacters = exports.readUint32 = exports.readUint16 = exports.readInt8 = exports.log2 = exports.loadJpegStream = exports.isEvalSupported = exports.isLittleEndian = exports.createValidAbsoluteUrl = exports.isSameOrigin = exports.isNodeJS = exports.isSpace = exports.isString = exports.isNum = exports.isInt = exports.isEmptyObj = exports.isBool = exports.isArrayBuffer = exports.isArray = exports.info = exports.globalScope = exports.getVerbosityLevel = exports.getLookupTableFactory = exports.error = exports.deprecated = exports.createObjectURL = exports.createPromiseCapability = exports.createBlob = exports.bytesToString = exports.assert = exports.arraysToBytes = exports.arrayByteLength = exports.XRefParseException = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.StatTimer = exports.PasswordResponses = exports.PasswordException = exports.PageViewport = exports.NotImplementedException = exports.NativeImageDecoding = exports.MissingPDFException = exports.MissingDataException = exports.MessageHandler = exports.InvalidPDFException = exports.CMapCompressionType = exports.ImageKind = exports.FontType = exports.AnnotationType = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.UNSUPPORTED_FEATURES = exports.VERBOSITY_LEVELS = exports.OPS = exports.IDENTITY_MATRIX = exports.FONT_IDENTITY_MATRIX = undefined;
 
 __w_pdfjs_require__(15);
 
 var _streamsLib = __w_pdfjs_require__(9);
 
-var globalScope = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : undefined;
+var globalScope = typeof window !== 'undefined' && window.Math === Math ? window : typeof global !== 'undefined' && global.Math === Math ? global : typeof self !== 'undefined' && self.Math === Math ? self : undefined;
 var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
 const NativeImageDecoding = {
   NONE: 'none',
   DECODE: 'decode',
   DISPLAY: 'display'
 };
 var TextRenderingMode = {
   FILL: 0,
@@ -2700,17 +2700,17 @@ var PDFPageProxy = function PDFPageProxy
       intentState.displayReadyCapability.promise.then(transparency => {
         if (this.pendingCleanup) {
           complete();
           return;
         }
         stats.time('Rendering');
         internalRenderTask.initializeGraphics(transparency);
         internalRenderTask.operatorListChanged();
-      }, complete);
+      }).catch(complete);
       return renderTask;
     },
     getOperatorList: function PDFPageProxy_getOperatorList() {
       function operatorListChanged() {
         if (intentState.operatorList.lastChunk) {
           intentState.opListReadCapability.resolve(intentState.operatorList);
           var i = intentState.renderTasks.indexOf(opListTask);
           if (i >= 0) {
@@ -2913,17 +2913,17 @@ var PDFWorker = function PDFWorkerClosur
     return fakeWorkerFilesLoadedCapability.promise;
   }
   function createCDNWrapper(url) {
     var wrapper = 'importScripts(\'' + url + '\');';
     return URL.createObjectURL(new Blob([wrapper]));
   }
   let pdfWorkerPorts = new WeakMap();
   function PDFWorker(name, port) {
-    if (pdfWorkerPorts.has(port)) {
+    if (port && pdfWorkerPorts.has(port)) {
       throw new Error('Cannot use more than one PDFWorker per port');
     }
     this.name = name;
     this.destroyed = false;
     this._readyCapability = (0, _util.createPromiseCapability)();
     this._port = null;
     this._webWorker = null;
     this._messageHandler = null;
@@ -3523,16 +3523,17 @@ var RenderTask = function RenderTaskClos
     },
     then: function RenderTask_then(onFulfilled, onRejected) {
       return this.promise.then.apply(this.promise, arguments);
     }
   };
   return RenderTask;
 }();
 var InternalRenderTask = function InternalRenderTaskClosure() {
+  let canvasInRendering = new WeakMap();
   function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber, canvasFactory) {
     this.callback = callback;
     this.params = params;
     this.objs = objs;
     this.commonObjs = commonObjs;
     this.operatorListIdx = null;
     this.operatorList = operatorList;
     this.pageNumber = pageNumber;
@@ -3542,19 +3543,26 @@ var InternalRenderTask = function Intern
     this.graphicsReady = false;
     this.useRequestAnimationFrame = false;
     this.cancelled = false;
     this.capability = (0, _util.createPromiseCapability)();
     this.task = new RenderTask(this);
     this._continueBound = this._continue.bind(this);
     this._scheduleNextBound = this._scheduleNext.bind(this);
     this._nextBound = this._next.bind(this);
+    this._canvas = params.canvasContext.canvas;
   }
   InternalRenderTask.prototype = {
     initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) {
+      if (this._canvas) {
+        if (canvasInRendering.has(this._canvas)) {
+          throw new Error('Cannot use the same canvas during multiple render() operations. ' + 'Use different canvas or ensure previous operations were ' + 'cancelled or completed.');
+        }
+        canvasInRendering.set(this._canvas, this);
+      }
       if (this.cancelled) {
         return;
       }
       if ((0, _dom_utils.getDefaultSetting)('pdfBug') && _util.globalScope.StepperManager && _util.globalScope.StepperManager.enabled) {
         this.stepper = _util.globalScope.StepperManager.create(this.pageNumber - 1);
         this.stepper.init(this.operatorList);
         this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
       }
@@ -3570,16 +3578,19 @@ var InternalRenderTask = function Intern
       this.graphicsReady = true;
       if (this.graphicsReadyCallback) {
         this.graphicsReadyCallback();
       }
     },
     cancel: function InternalRenderTask_cancel() {
       this.running = false;
       this.cancelled = true;
+      if (this._canvas) {
+        canvasInRendering.delete(this._canvas);
+      }
       this.callback(new _dom_utils.RenderingCancelledException('Rendering cancelled, page ' + this.pageNumber, 'canvas'));
     },
     operatorListChanged: function InternalRenderTask_operatorListChanged() {
       if (!this.graphicsReady) {
         if (!this.graphicsReadyCallback) {
           this.graphicsReadyCallback = this._continueBound;
         }
         return;
@@ -3614,16 +3625,19 @@ var InternalRenderTask = function Intern
       if (this.cancelled) {
         return;
       }
       this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
       if (this.operatorListIdx === this.operatorList.argsArray.length) {
         this.running = false;
         if (this.operatorList.lastChunk) {
           this.gfx.endDrawing();
+          if (this._canvas) {
+            canvasInRendering.delete(this._canvas);
+          }
           this.callback();
         }
       }
     }
   };
   return InternalRenderTask;
 }();
 var _UnsupportedManager = function UnsupportedManagerClosure() {
@@ -3637,18 +3651,18 @@ var _UnsupportedManager = function Unsup
       for (var i = 0, ii = listeners.length; i < ii; i++) {
         listeners[i](featureId);
       }
     }
   };
 }();
 var version, build;
 {
-  exports.version = version = '1.8.439';
-  exports.build = build = '08c64371';
+  exports.version = version = '1.8.450';
+  exports.build = build = '20975134';
 }
 exports.getDocument = getDocument;
 exports.LoopbackPort = LoopbackPort;
 exports.PDFDataRangeTransport = PDFDataRangeTransport;
 exports.PDFWorker = PDFWorker;
 exports.PDFDocumentProxy = PDFDocumentProxy;
 exports.PDFPageProxy = PDFPageProxy;
 exports._UnsupportedManager = _UnsupportedManager;
@@ -4640,18 +4654,18 @@ var _text_layer = __w_pdfjs_require__(5)
 var _svg = __w_pdfjs_require__(4);
 
 var isWorker = typeof window === 'undefined';
 if (!_util.globalScope.PDFJS) {
   _util.globalScope.PDFJS = {};
 }
 var PDFJS = _util.globalScope.PDFJS;
 {
-  PDFJS.version = '1.8.439';
-  PDFJS.build = '08c64371';
+  PDFJS.version = '1.8.450';
+  PDFJS.build = '20975134';
 }
 PDFJS.pdfBug = false;
 if (PDFJS.verbosity !== undefined) {
   (0, _util.setVerbosityLevel)(PDFJS.verbosity);
 }
 delete PDFJS.verbosity;
 Object.defineProperty(PDFJS, 'verbosity', {
   get() {
@@ -9988,18 +10002,18 @@ exports.TilingPattern = TilingPattern;
 
 /***/ }),
 /* 14 */
 /***/ (function(module, exports, __w_pdfjs_require__) {
 
 "use strict";
 
 
-var pdfjsVersion = '1.8.439';
-var pdfjsBuild = '08c64371';
+var pdfjsVersion = '1.8.450';
+var pdfjsBuild = '20975134';
 var pdfjsSharedUtil = __w_pdfjs_require__(0);
 var pdfjsDisplayGlobal = __w_pdfjs_require__(8);
 var pdfjsDisplayAPI = __w_pdfjs_require__(3);
 var pdfjsDisplayTextLayer = __w_pdfjs_require__(5);
 var pdfjsDisplayAnnotationLayer = __w_pdfjs_require__(2);
 var pdfjsDisplayDOMUtils = __w_pdfjs_require__(1);
 var pdfjsDisplaySVG = __w_pdfjs_require__(4);
 exports.PDFJS = pdfjsDisplayGlobal.PDFJS;
--- a/browser/extensions/pdfjs/content/build/pdf.worker.js
+++ b/browser/extensions/pdfjs/content/build/pdf.worker.js
@@ -102,17 +102,17 @@ Object.defineProperty(exports, "__esModu
   value: true
 });
 exports.warn = exports.utf8StringToString = exports.stringToUTF8String = exports.stringToPDFString = exports.stringToBytes = exports.string32 = exports.shadow = exports.setVerbosityLevel = exports.ReadableStream = exports.removeNullCharacters = exports.readUint32 = exports.readUint16 = exports.readInt8 = exports.log2 = exports.loadJpegStream = exports.isEvalSupported = exports.isLittleEndian = exports.createValidAbsoluteUrl = exports.isSameOrigin = exports.isNodeJS = exports.isSpace = exports.isString = exports.isNum = exports.isInt = exports.isEmptyObj = exports.isBool = exports.isArrayBuffer = exports.isArray = exports.info = exports.globalScope = exports.getVerbosityLevel = exports.getLookupTableFactory = exports.error = exports.deprecated = exports.createObjectURL = exports.createPromiseCapability = exports.createBlob = exports.bytesToString = exports.assert = exports.arraysToBytes = exports.arrayByteLength = exports.XRefParseException = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.StatTimer = exports.PasswordResponses = exports.PasswordException = exports.PageViewport = exports.NotImplementedException = exports.NativeImageDecoding = exports.MissingPDFException = exports.MissingDataException = exports.MessageHandler = exports.InvalidPDFException = exports.CMapCompressionType = exports.ImageKind = exports.FontType = exports.AnnotationType = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.UNSUPPORTED_FEATURES = exports.VERBOSITY_LEVELS = exports.OPS = exports.IDENTITY_MATRIX = exports.FONT_IDENTITY_MATRIX = undefined;
 
 __w_pdfjs_require__(37);
 
 var _streamsLib = __w_pdfjs_require__(18);
 
-var globalScope = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : undefined;
+var globalScope = typeof window !== 'undefined' && window.Math === Math ? window : typeof global !== 'undefined' && global.Math === Math ? global : typeof self !== 'undefined' && self.Math === Math ? self : undefined;
 var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
 const NativeImageDecoding = {
   NONE: 'none',
   DECODE: 'decode',
   DISPLAY: 'display'
 };
 var TextRenderingMode = {
   FILL: 0,
@@ -39775,18 +39775,18 @@ exports.Type1Parser = Type1Parser;
 
 /***/ }),
 /* 36 */
 /***/ (function(module, exports, __w_pdfjs_require__) {
 
 "use strict";
 
 
-var pdfjsVersion = '1.8.439';
-var pdfjsBuild = '08c64371';
+var pdfjsVersion = '1.8.450';
+var pdfjsBuild = '20975134';
 var pdfjsCoreWorker = __w_pdfjs_require__(17);
 ;
 exports.WorkerMessageHandler = pdfjsCoreWorker.WorkerMessageHandler;
 
 /***/ }),
 /* 37 */
 /***/ (function(module, exports, __w_pdfjs_require__) {
 
--- a/browser/extensions/pdfjs/content/web/viewer.js
+++ b/browser/extensions/pdfjs/content/web/viewer.js
@@ -4983,21 +4983,16 @@ class PDFPageView {
     }
     this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL;
     this.resume = null;
     if (this.textLayer) {
       this.textLayer.cancel();
       this.textLayer = null;
     }
   }
-  updatePosition() {
-    if (this.textLayer) {
-      this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
-    }
-  }
   cssTransform(target, redrawAnnotations = false) {
     let width = this.viewport.width;
     let height = this.viewport.height;
     let div = this.div;
     target.style.width = target.parentNode.style.width = div.style.width = Math.floor(width) + 'px';
     target.style.height = target.parentNode.style.height = div.style.height = Math.floor(height) + 'px';
     let relativeRotation = this.viewport.rotation - this.paintedViewportMap.get(target).rotation;
     let absRotation = Math.abs(relativeRotation);
@@ -6640,24 +6635,21 @@ var PDFViewer = function pdfViewer() {
       this._pageLabels = null;
       this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
       this._location = null;
       this._pagesRotation = 0;
       this._pagesRequests = [];
       this._pageViewsReady = false;
       this.viewer.textContent = '';
     },
-    _scrollUpdate: function PDFViewer_scrollUpdate() {
+    _scrollUpdate() {
       if (this.pagesCount === 0) {
         return;
       }
       this.update();
-      for (var i = 0, ii = this._pages.length; i < ii; i++) {
-        this._pages[i].updatePosition();
-      }
     },
     _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(newScale, newValue, preset) {
       var arg = {
         source: this,
         scale: newScale,
         presetValue: preset ? newValue : undefined
       };
       this.eventBus.dispatch('scalechanging', arg);
--- a/dom/base/DispatcherTrait.cpp
+++ b/dom/base/DispatcherTrait.cpp
@@ -16,20 +16,20 @@ using namespace mozilla::dom;
 nsresult
 DispatcherTrait::Dispatch(const char* aName,
                           TaskCategory aCategory,
                           already_AddRefed<nsIRunnable>&& aRunnable)
 {
   return SchedulerGroup::UnlabeledDispatch(aName, aCategory, Move(aRunnable));
 }
 
-nsIEventTarget*
+nsISerialEventTarget*
 DispatcherTrait::EventTargetFor(TaskCategory aCategory) const
 {
-  return GetMainThreadEventTarget();
+  return GetMainThreadSerialEventTarget();
 }
 
 AbstractThread*
 DispatcherTrait::AbstractMainThreadFor(TaskCategory aCategory)
 {
   // Return non DocGroup version by default.
   return AbstractThread::MainThread();
 }
--- a/dom/base/DispatcherTrait.h
+++ b/dom/base/DispatcherTrait.h
@@ -5,18 +5,18 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_DispatcherTrait_h
 #define mozilla_dom_DispatcherTrait_h
 
 #include "mozilla/AlreadyAddRefed.h"
 #include "mozilla/TaskCategory.h"
 
-class nsIEventTarget;
 class nsIRunnable;
+class nsISerialEventTarget;
 
 namespace mozilla {
 class AbstractThread;
 namespace dom {
 class TabGroup;
 
 // This trait should be attached to classes like nsIGlobalObject and nsIDocument
 // that have a DocGroup or TabGroup attached to them. The methods here should
@@ -26,19 +26,19 @@ class DispatcherTrait {
 public:
   // This method may or may not be safe off of the main thread. For nsIDocument
   // it is safe. For nsIGlobalWindow it is not safe.
   virtual nsresult Dispatch(const char* aName,
                             TaskCategory aCategory,
                             already_AddRefed<nsIRunnable>&& aRunnable);
 
   // This method may or may not be safe off of the main thread. For nsIDocument
-  // it is safe. For nsIGlobalWindow it is not safe. The nsIEventTarget can
+  // it is safe. For nsIGlobalWindow it is not safe. The nsISerialEventTarget can
   // always be used off the main thread.
-  virtual nsIEventTarget* EventTargetFor(TaskCategory aCategory) const;
+  virtual nsISerialEventTarget* EventTargetFor(TaskCategory aCategory) const;
 
   // Must be called on the main thread. The AbstractThread can always be used
   // off the main thread.
   virtual AbstractThread* AbstractMainThreadFor(TaskCategory aCategory);
 };
 
 } // namespace dom
 } // namespace mozilla
--- a/dom/base/DocGroup.cpp
+++ b/dom/base/DocGroup.cpp
@@ -58,17 +58,17 @@ DocGroup::~DocGroup()
 nsresult
 DocGroup::Dispatch(const char* aName,
                    TaskCategory aCategory,
                    already_AddRefed<nsIRunnable>&& aRunnable)
 {
   return mTabGroup->Dispatch(aName, aCategory, Move(aRunnable));
 }
 
-nsIEventTarget*
+nsISerialEventTarget*
 DocGroup::EventTargetFor(TaskCategory aCategory) const
 {
   return mTabGroup->EventTargetFor(aCategory);
 }
 
 AbstractThread*
 DocGroup::AbstractMainThreadFor(TaskCategory aCategory)
 {
--- a/dom/base/DocGroup.h
+++ b/dom/base/DocGroup.h
@@ -79,17 +79,17 @@ public:
     MOZ_ASSERT(NS_IsMainThread());
     return mDocuments.end();
   }
 
   nsresult Dispatch(const char* aName,
                     TaskCategory aCategory,
                     already_AddRefed<nsIRunnable>&& aRunnable);
 
-  nsIEventTarget* EventTargetFor(TaskCategory aCategory) const;
+  nsISerialEventTarget* EventTargetFor(TaskCategory aCategory) const;
 
   AbstractThread*
   AbstractMainThreadFor(TaskCategory aCategory);
 
   // Ensure that it's valid to access the DocGroup at this time.
   void ValidateAccess() const
   {
     mTabGroup->ValidateAccess();
--- a/dom/base/TabGroup.cpp
+++ b/dom/base/TabGroup.cpp
@@ -61,17 +61,17 @@ TabGroup::EnsureThrottledEventQueues()
     return;
   }
 
   mThrottledQueuesInitialized = true;
 
   for (size_t i = 0; i < size_t(TaskCategory::Count); i++) {
     TaskCategory category = static_cast<TaskCategory>(i);
     if (category == TaskCategory::Worker || category == TaskCategory::Timer) {
-      nsCOMPtr<nsIEventTarget> target = ThrottledEventQueue::Create(mEventTargets[i]);
+      nsCOMPtr<nsISerialEventTarget> target = ThrottledEventQueue::Create(mEventTargets[i]);
       if (target) {
         // This may return nullptr during xpcom shutdown.  This is ok as we
         // do not guarantee a ThrottledEventQueue will be present.
         mEventTargets[i] = target;
       }
     }
   }
 }
@@ -245,17 +245,17 @@ TabGroup::GetTopLevelWindows() const
 
   return array;
 }
 
 TabGroup::HashEntry::HashEntry(const nsACString* aKey)
   : nsCStringHashKey(aKey), mDocGroup(nullptr)
 {}
 
-nsIEventTarget*
+nsISerialEventTarget*
 TabGroup::EventTargetFor(TaskCategory aCategory) const
 {
   if (aCategory == TaskCategory::Worker || aCategory == TaskCategory::Timer) {
     MOZ_RELEASE_ASSERT(mThrottledQueuesInitialized || mIsChrome);
   }
   return SchedulerGroup::EventTargetFor(aCategory);
 }
 
--- a/dom/base/TabGroup.h
+++ b/dom/base/TabGroup.h
@@ -114,17 +114,17 @@ public:
                    nsIDocShellTreeItem* aOriginalRequestor,
                    nsIDocShellTreeItem** aFoundItem);
 
   nsTArray<nsPIDOMWindowOuter*> GetTopLevelWindows() const;
   const nsTArray<nsPIDOMWindowOuter*>& GetWindows() { return mWindows; }
 
   // This method is always safe to call off the main thread. The nsIEventTarget
   // can always be used off the main thread.
-  nsIEventTarget* EventTargetFor(TaskCategory aCategory) const override;
+  nsISerialEventTarget* EventTargetFor(TaskCategory aCategory) const override;
 
   void WindowChangedBackgroundStatus(bool aIsNowBackground);
 
   // Returns true if all of the TabGroup's top-level windows are in
   // the background.
   bool IsBackground() const override;
 
 private:
--- a/dom/base/Timeout.h
+++ b/dom/base/Timeout.h
@@ -67,18 +67,18 @@ public:
 
   // Used to allow several reasons for setting a timeout, where each
   // 'Reason' value is using a possibly overlapping set of id:s.
   Reason mReason;
 
   // Returned as value of setTimeout()
   uint32_t mTimeoutId;
 
-  // Interval in milliseconds
-  uint32_t mInterval;
+  // Interval
+  TimeDuration mInterval;
 
   // Identifies which firing level this Timeout is being processed in
   // when sync loops trigger nested firing.
   uint32_t mFiringId;
 
   uint32_t mNestingLevel;
 
   // The popup state at timeout creation time if not created from
--- a/dom/base/TimeoutManager.cpp
+++ b/dom/base/TimeoutManager.cpp
@@ -124,21 +124,21 @@ TimeoutTelemetry::MaybeCollectTelemetry(
 
   mTelemetryData = TelemetryData();
   mLastCollection = aNow;
 }
 
 static int32_t              gRunningTimeoutDepth       = 0;
 
 // The default shortest interval/timeout we permit
-#define DEFAULT_MIN_TIMEOUT_VALUE 4 // 4ms
+#define DEFAULT_MIN_CLAMP_TIMEOUT_VALUE 4 // 4ms
 #define DEFAULT_MIN_BACKGROUND_TIMEOUT_VALUE 1000 // 1000ms
 #define DEFAULT_MIN_TRACKING_TIMEOUT_VALUE 4 // 4ms
 #define DEFAULT_MIN_TRACKING_BACKGROUND_TIMEOUT_VALUE 1000 // 1000ms
-static int32_t gMinTimeoutValue = 0;
+static int32_t gMinClampTimeoutValue = 0;
 static int32_t gMinBackgroundTimeoutValue = 0;
 static int32_t gMinTrackingTimeoutValue = 0;
 static int32_t gMinTrackingBackgroundTimeoutValue = 0;
 static int32_t gTrackingTimeoutThrottlingDelay = 0;
 static bool    gAnnotateTrackingChannels = false;
 
 // static
 const uint32_t TimeoutManager::InvalidFiringId = 0;
@@ -223,38 +223,49 @@ TimeoutManager::IsInvalidFiringId(uint32
   // Finally, fall back to verifying the firing id is not anywhere
   // in the stack.  This could be slow for a large stack, but that
   // should be rare.  It can only happen with deeply nested event
   // loop spinning.  For example, a page that does a lot of timers
   // and a lot of sync XHRs within those timers could be slow here.
   return !mFiringIdStack.Contains(aFiringId);
 }
 
-int32_t
-TimeoutManager::DOMMinTimeoutValue(bool aIsTracking) const {
-  bool throttleTracking = aIsTracking && mThrottleTrackingTimeouts;
-  auto minValue = throttleTracking ? gMinTrackingTimeoutValue
-                                   : gMinTimeoutValue;
-  return minValue;
+// The number of nested timeouts before we start clamping. HTML5 says 1, WebKit
+// uses 5.
+#define DOM_CLAMP_TIMEOUT_NESTING_LEVEL 5
+
+TimeDuration
+TimeoutManager::CalculateDelay(Timeout* aTimeout) const {
+  MOZ_DIAGNOSTIC_ASSERT(aTimeout);
+  TimeDuration result = aTimeout->mInterval;
+
+  if (aTimeout->mIsInterval ||
+      aTimeout->mNestingLevel >= DOM_CLAMP_TIMEOUT_NESTING_LEVEL) {
+    result = TimeDuration::Max(
+      result, TimeDuration::FromMilliseconds(gMinClampTimeoutValue));
+  }
+
+  if (aTimeout->mIsTracking && mThrottleTrackingTimeouts) {
+    result = TimeDuration::Max(
+      result, TimeDuration::FromMilliseconds(gMinTrackingTimeoutValue));
+  }
+
+  return result;
 }
 
 #define TRACKING_SEPARATE_TIMEOUT_BUCKETING_STRATEGY 0 // Consider all timeouts coming from tracking scripts as tracking
 // These strategies are useful for testing.
 #define ALL_NORMAL_TIMEOUT_BUCKETING_STRATEGY        1 // Consider all timeouts as normal
 #define ALTERNATE_TIMEOUT_BUCKETING_STRATEGY         2 // Put every other timeout in the list of tracking timeouts
 #define RANDOM_TIMEOUT_BUCKETING_STRATEGY            3 // Put timeouts into either the normal or tracking timeouts list randomly
 static int32_t gTimeoutBucketingStrategy = 0;
 
 #define DEFAULT_TRACKING_TIMEOUT_THROTTLING_DELAY  -1  // Only positive integers cause us to introduce a delay for tracking
                                                        // timeout throttling.
 
-// The number of nested timeouts before we start clamping. HTML5 says 1, WebKit
-// uses 5.
-#define DOM_CLAMP_TIMEOUT_NESTING_LEVEL 5
-
 // The longest interval (as PRIntervalTime) we permit, or that our
 // timer code can handle, really. See DELAY_INTERVAL_LIMIT in
 // nsTimerImpl.h for details.
 #define DOM_MAX_TIMEOUT_VALUE    DELAY_INTERVAL_LIMIT
 
 uint32_t TimeoutManager::sNestingLevel = 0;
 
 namespace {
@@ -294,19 +305,19 @@ TimeoutManager::~TimeoutManager()
   MOZ_LOG(gLog, LogLevel::Debug,
           ("TimeoutManager %p destroyed\n", this));
 }
 
 /* static */
 void
 TimeoutManager::Initialize()
 {
-  Preferences::AddIntVarCache(&gMinTimeoutValue,
+  Preferences::AddIntVarCache(&gMinClampTimeoutValue,
                               "dom.min_timeout_value",
-                              DEFAULT_MIN_TIMEOUT_VALUE);
+                              DEFAULT_MIN_CLAMP_TIMEOUT_VALUE);
   Preferences::AddIntVarCache(&gMinBackgroundTimeoutValue,
                               "dom.min_background_timeout_value",
                               DEFAULT_MIN_BACKGROUND_TIMEOUT_VALUE);
   Preferences::AddIntVarCache(&gMinTrackingTimeoutValue,
                               "dom.min_tracking_timeout_value",
                               DEFAULT_MIN_TRACKING_TIMEOUT_VALUE);
   Preferences::AddIntVarCache(&gMinTrackingBackgroundTimeoutValue,
                               "dom.min_tracking_background_timeout_value",
@@ -364,21 +375,25 @@ TimeoutManager::SetTimeout(nsITimeoutHan
   // code can handle. (Note: we already forced |interval| to be non-negative,
   // so the uint32_t cast (to avoid compiler warnings) is ok.)
   uint32_t maxTimeoutMs = PR_IntervalToMilliseconds(DOM_MAX_TIMEOUT_VALUE);
   if (static_cast<uint32_t>(interval) > maxTimeoutMs) {
     interval = maxTimeoutMs;
   }
 
   RefPtr<Timeout> timeout = new Timeout();
+  timeout->mWindow = &mWindow;
   timeout->mIsInterval = aIsInterval;
-  timeout->mInterval = interval;
+  timeout->mInterval = TimeDuration::FromMilliseconds(interval);
   timeout->mScriptHandler = aHandler;
   timeout->mReason = aReason;
 
+  // No popups from timeouts by default
+  timeout->mPopupState = openAbused;
+
   switch (gTimeoutBucketingStrategy) {
   default:
   case TRACKING_SEPARATE_TIMEOUT_BUCKETING_STRATEGY: {
     const char* filename = nullptr;
     uint32_t dummyLine = 0, dummyColumn = 0;
     aHandler->GetLocation(&filename, &dummyLine, &dummyColumn);
     timeout->mIsTracking = doc->IsScriptTracking(nsDependentCString(filename));
 
@@ -406,48 +421,34 @@ TimeoutManager::SetTimeout(nsITimeoutHan
     timeout->mIsTracking = (rand() % 2) == 0;
 
     MOZ_LOG(gLog, LogLevel::Debug,
             ("Classified timeout %p as %stracking (random mode)\n",
              timeout.get(), timeout->mIsTracking ? "" : "non-"));
     break;
   }
 
-  // Now clamp the actual interval we will use for the timer based on
   uint32_t nestingLevel = sNestingLevel + 1;
-  uint32_t realInterval = interval;
-  if (aIsInterval || nestingLevel >= DOM_CLAMP_TIMEOUT_NESTING_LEVEL ||
-      timeout->mIsTracking) {
-    // Don't allow timeouts less than DOMMinTimeoutValue() from
-    // now...
-    realInterval = std::max(realInterval,
-                            uint32_t(DOMMinTimeoutValue(timeout->mIsTracking)));
+  if (!aIsInterval) {
+    timeout->mNestingLevel = nestingLevel;
   }
 
-  timeout->mWindow = &mWindow;
-
-  TimeDuration delta = TimeDuration::FromMilliseconds(realInterval);
-  timeout->SetWhenOrTimeRemaining(TimeStamp::Now(), delta);
+  // Now clamp the actual interval we will use for the timer based on
+  TimeDuration realInterval = CalculateDelay(timeout);
+  timeout->SetWhenOrTimeRemaining(TimeStamp::Now(), realInterval);
 
   // If we're not suspended, then set the timer.
   if (!mWindow.IsSuspended()) {
     nsresult rv = mExecutor->MaybeSchedule(timeout->When(),
                                            MinSchedulingDelay());
     if (NS_FAILED(rv)) {
       return rv;
     }
   }
 
-  if (!aIsInterval) {
-    timeout->mNestingLevel = nestingLevel;
-  }
-
-  // No popups from timeouts by default
-  timeout->mPopupState = openAbused;
-
   if (gRunningTimeoutDepth == 0 &&
       mWindow.GetPopupControlState() < openAbused) {
     // This timeout is *not* set from another timeout and it's set
     // while popups are enabled. Propagate the state to the timeout if
     // its delay (interval) is equal to or less than what
     // "dom.disable_open_click_delay" is set to (in ms).
 
     int32_t delay =
@@ -469,25 +470,25 @@ TimeoutManager::SetTimeout(nsITimeoutHan
     mNormalTimeouts.Insert(timeout, sort);
   }
 
   timeout->mTimeoutId = GetTimeoutId(aReason);
   *aReturn = timeout->mTimeoutId;
 
   MOZ_LOG(gLog, LogLevel::Debug,
           ("Set%s(TimeoutManager=%p, timeout=%p, delay=%i, "
-           "minimum=%i, throttling=%s, background=%d, realInterval=%i) "
+           "minimum=%f, throttling=%s, background=%d, realInterval=%f) "
            "returned %stracking timeout ID %u\n",
            aIsInterval ? "Interval" : "Timeout",
            this, timeout.get(), interval,
-           DOMMinTimeoutValue(timeout->mIsTracking),
+           (CalculateDelay(timeout) - timeout->mInterval).ToMilliseconds(),
            mThrottleTrackingTimeouts ? "yes"
                                      : (mThrottleTrackingTimeoutsTimer ?
                                           "pending" : "no"),
-           int(IsBackground()), realInterval,
+           int(IsBackground()), realInterval.ToMilliseconds(),
            timeout->mIsTracking ? "" : "non-",
            timeout->mTimeoutId));
 
   return NS_OK;
 }
 
 void
 TimeoutManager::ClearTimeout(int32_t aTimerId, Timeout::Reason aReason)
@@ -798,21 +799,18 @@ TimeoutManager::RunTimeout(const TimeSta
 bool
 TimeoutManager::RescheduleTimeout(Timeout* aTimeout, const TimeStamp& now)
 {
   if (!aTimeout->mIsInterval) {
     return false;
   }
 
   // Compute time to next timeout for interval timer.
-  // Make sure nextInterval is at least DOMMinTimeoutValue().
-  TimeDuration nextInterval =
-    TimeDuration::FromMilliseconds(
-        std::max(aTimeout->mInterval,
-                 uint32_t(DOMMinTimeoutValue(aTimeout->mIsTracking))));
+  // Make sure nextInterval is at least CalculateDelay().
+  TimeDuration nextInterval = CalculateDelay(aTimeout);
 
   TimeStamp firingTime = now + nextInterval;
 
   TimeStamp currentNow = TimeStamp::Now();
   TimeDuration delay = firingTime - currentNow;
 
   // And make sure delay is nonnegative; that might happen if the timer
   // thread is firing our timers somewhat early or if they're taking a long
@@ -976,38 +974,20 @@ TimeoutManager::Resume()
 
   // When Suspend() has been called after IsDocumentLoaded(), but the
   // throttle tracking timer never managed to fire, start the timer
   // again.
   if (mWindow.AsInner()->IsDocumentLoaded() && !mThrottleTrackingTimeouts) {
     MaybeStartThrottleTrackingTimout();
   }
 
-  TimeStamp now = TimeStamp::Now();
-  TimeStamp nextWakeUp;
-
-  ForEachUnorderedTimeout([&](Timeout* aTimeout) {
-    // The timeout When() is set to the absolute time when the timer should
-    // fire.  Recalculate the delay from now until that deadline.  If the
-    // the deadline has already passed or falls within our minimum delay
-    // deadline, then clamp the resulting value to the minimum delay.
-    int32_t remaining = 0;
-    if (aTimeout->When() > now) {
-      remaining = static_cast<int32_t>((aTimeout->When() - now).ToMilliseconds());
-    }
-    uint32_t delay = std::max(remaining, DOMMinTimeoutValue(aTimeout->mIsTracking));
-    aTimeout->SetWhenOrTimeRemaining(now, TimeDuration::FromMilliseconds(delay));
-
-    if (nextWakeUp.IsNull() || aTimeout->When() < nextWakeUp) {
-      nextWakeUp = aTimeout->When();
-    }
-  });
-
-  if (!nextWakeUp.IsNull()) {
-    MOZ_ALWAYS_SUCCEEDS(mExecutor->MaybeSchedule(nextWakeUp,
+  OrderedTimeoutIterator iter(mNormalTimeouts, mTrackingTimeouts);
+  Timeout* nextTimeout = iter.Next();
+  if (nextTimeout) {
+    MOZ_ALWAYS_SUCCEEDS(mExecutor->MaybeSchedule(nextTimeout->When(),
                                                  MinSchedulingDelay()));
   }
 }
 
 void
 TimeoutManager::Freeze()
 {
   MOZ_LOG(gLog, LogLevel::Debug,
--- a/dom/base/TimeoutManager.h
+++ b/dom/base/TimeoutManager.h
@@ -50,17 +50,17 @@ public:
   // The timeout implementation functions.
   void RunTimeout(const TimeStamp& aNow, const TimeStamp& aTargetDeadline);
   // Return true if |aTimeout| needs to be reinserted into the timeout list.
   bool RescheduleTimeout(mozilla::dom::Timeout* aTimeout, const TimeStamp& now);
 
   void ClearAllTimeouts();
   uint32_t GetTimeoutId(mozilla::dom::Timeout::Reason aReason);
 
-  int32_t DOMMinTimeoutValue(bool aIsTracking) const;
+  TimeDuration CalculateDelay(Timeout* aTimeout) const;
 
   // aTimeout is the timeout that we're about to start running.  This function
   // returns the current timeout.
   mozilla::dom::Timeout* BeginRunningTimeout(mozilla::dom::Timeout* aTimeout);
   // aTimeout is the last running timeout.
   void EndRunningTimeout(mozilla::dom::Timeout* aTimeout);
 
   void UnmarkGrayTimers();
--- a/dom/base/nsContentPolicy.cpp
+++ b/dom/base/nsContentPolicy.cpp
@@ -16,16 +16,17 @@
 #include "mozilla/dom/nsCSPService.h"
 #include "nsContentPolicy.h"
 #include "nsIURI.h"
 #include "nsIDocShell.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMNode.h"
 #include "nsIDOMWindow.h"
 #include "nsIContent.h"
+#include "nsIImageLoadingContent.h"
 #include "nsILoadContext.h"
 #include "nsCOMArray.h"
 #include "nsContentUtils.h"
 #include "mozilla/dom/nsMixedContentBlocker.h"
 #include "nsIContentSecurityPolicy.h"
 #include "mozilla/dom/TabGroup.h"
 
 using mozilla::LogLevel;
@@ -151,16 +152,26 @@ nsContentPolicy::CheckPolicy(CPMethod   
           type = contentType;
         }
         rv = (entries[i]->*policyMethod)(type, contentLocation,
                                          requestingLocation, requestingContext,
                                          mimeType, extra, requestPrincipal,
                                          decision);
 
         if (NS_SUCCEEDED(rv) && NS_CP_REJECTED(*decision)) {
+            // If we are blocking an image, we have to let the
+            // ImageLoadingContent know that we blocked the load.
+            if (externalType == nsIContentPolicy::TYPE_IMAGE ||
+                externalType == nsIContentPolicy::TYPE_IMAGESET) {
+              nsCOMPtr<nsIImageLoadingContent> img =
+                do_QueryInterface(requestingContext);
+              if (img) {
+                img->SetBlockedRequest(*decision);
+              }
+            }
             /* policy says no, no point continuing to check */
             return NS_OK;
         }
     }
 
     nsCOMPtr<nsIDOMElement> topFrameElement;
     bool isTopLevel = true;
 
@@ -193,16 +204,26 @@ nsContentPolicy::CheckPolicy(CPMethod   
         /* check the appropriate policy */
         rv = (simpleEntries[i]->*simplePolicyMethod)(externalType, contentLocation,
                                                      requestingLocation,
                                                      topFrameElement, isTopLevel,
                                                      mimeType, extra, requestPrincipal,
                                                      decision);
 
         if (NS_SUCCEEDED(rv) && NS_CP_REJECTED(*decision)) {
+            // If we are blocking an image, we have to let the
+            // ImageLoadingContent know that we blocked the load.
+            if (externalType == nsIContentPolicy::TYPE_IMAGE ||
+                externalType == nsIContentPolicy::TYPE_IMAGESET) {
+              nsCOMPtr<nsIImageLoadingContent> img =
+                do_QueryInterface(requestingContext);
+              if (img) {
+                img->SetBlockedRequest(*decision);
+              }
+            }
             /* policy says no, no point continuing to check */
             return NS_OK;
         }
     }
 
     // everyone returned failure, or no policies: sanitize result
     *decision = nsIContentPolicy::ACCEPT;
     return NS_OK;
--- a/dom/base/nsDOMWindowUtils.cpp
+++ b/dom/base/nsDOMWindowUtils.cpp
@@ -79,16 +79,17 @@
 #include "mozilla/dom/TabChild.h"
 #include "mozilla/dom/IDBFactoryBinding.h"
 #include "mozilla/dom/IDBMutableFileBinding.h"
 #include "mozilla/dom/IDBMutableFile.h"
 #include "mozilla/dom/IndexedDatabaseManager.h"
 #include "mozilla/dom/PermissionMessageUtils.h"
 #include "mozilla/dom/quota/PersistenceType.h"
 #include "mozilla/dom/quota/QuotaManager.h"
+#include "mozilla/dom/ContentChild.h"
 #include "mozilla/layers/FrameUniformityData.h"
 #include "mozilla/layers/ShadowLayers.h"
 #include "nsPrintfCString.h"
 #include "nsViewportInfo.h"
 #include "nsIFormControl.h"
 #include "nsIScriptError.h"
 //#include "nsWidgetsCID.h"
 #include "FrameLayerBuilder.h"
@@ -4126,16 +4127,32 @@ nsDOMWindowUtils::EnterChaosMode()
 NS_IMETHODIMP
 nsDOMWindowUtils::LeaveChaosMode()
 {
   ChaosMode::leaveChaosMode();
   return NS_OK;
 }
 
 NS_IMETHODIMP
+nsDOMWindowUtils::TriggerDeviceReset()
+{
+  ContentChild* cc = ContentChild::GetSingleton();
+  if (cc) {
+    cc->SendDeviceReset();
+    return NS_OK;
+  }
+
+  GPUProcessManager* pm = GPUProcessManager::Get();
+  if (pm) {
+    pm->TriggerDeviceResetForTesting();
+  }
+  return NS_OK;
+}
+
+NS_IMETHODIMP
 nsDOMWindowUtils::ForceUseCounterFlush(nsIDOMNode *aNode)
 {
   NS_ENSURE_ARG_POINTER(aNode);
 
   if (nsCOMPtr<nsIDocument> doc = do_QueryInterface(aNode)) {
     mozilla::css::ImageLoader* loader = doc->StyleImageLoader();
     loader->FlushUseCounters();
 
--- a/dom/base/nsDocument.cpp
+++ b/dom/base/nsDocument.cpp
@@ -3040,17 +3040,17 @@ nsIDocument::Dispatch(const char* aName,
 {
   // Note that this method may be called off the main thread.
   if (mDocGroup) {
     return mDocGroup->Dispatch(aName, aCategory, Move(aRunnable));
   }
   return DispatcherTrait::Dispatch(aName, aCategory, Move(aRunnable));
 }
 
-nsIEventTarget*
+nsISerialEventTarget*
 nsIDocument::EventTargetFor(TaskCategory aCategory) const
 {
   if (mDocGroup) {
     return mDocGroup->EventTargetFor(aCategory);
   }
   return DispatcherTrait::EventTargetFor(aCategory);
 }
 
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -99,17 +99,16 @@
 #include "nsIWidget.h"
 #include "nsIWidgetListener.h"
 #include "nsIBaseWindow.h"
 #include "nsIDeviceSensors.h"
 #include "nsIContent.h"
 #include "nsIDocShell.h"
 #include "nsIDocCharset.h"
 #include "nsIDocument.h"
-#include "nsIDocumentInlines.h"
 #include "Crypto.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMOfflineResourceList.h"
 #include "nsDOMString.h"
 #include "nsIEmbeddingSiteWindow.h"
 #include "nsThreadUtils.h"
@@ -995,17 +994,16 @@ NextWindowID();
 
 template<class T>
 nsPIDOMWindow<T>::nsPIDOMWindow(nsPIDOMWindowOuter *aOuterWindow)
 : mFrameElement(nullptr), mDocShell(nullptr), mModalStateDepth(0),
   mMutationBits(0), mIsDocumentLoaded(false),
   mIsHandlingResizeEvent(false), mIsInnerWindow(aOuterWindow != nullptr),
   mMayHavePaintEventListener(false), mMayHaveTouchEventListener(false),
   mMayHaveMouseEnterLeaveEventListener(false),
-  mMayHaveMouseMoveEventListener(false),
   mMayHavePointerEnterLeaveEventListener(false),
   mInnerObjectsFreed(false),
   mIsModalContentWindow(false),
   mIsActive(false), mIsBackground(false),
   mMediaSuspend(Preferences::GetBool("media.block-autoplay-until-in-foreground", true) ?
     nsISuspendedTypes::SUSPENDED_BLOCK : nsISuspendedTypes::NONE_SUSPENDED),
   mAudioMuted(false), mAudioVolume(1.0), mAudioCaptured(false),
   mDesktopModeViewport(false), mIsRootOuterWindow(false), mInnerWindow(nullptr),
@@ -2077,33 +2075,16 @@ nsGlobalWindow::ClearControllers()
   }
 }
 
 void
 nsGlobalWindow::FreeInnerObjects()
 {
   NS_ASSERTION(IsInnerWindow(), "Don't free inner objects on an outer window");
 
-  if (mDoc && !nsContentUtils::IsSystemPrincipal(mDoc->NodePrincipal())) {
-    EventTarget* win = this;
-    EventTarget* html = mDoc->GetHtmlElement();
-    EventTarget* body = mDoc->GetBodyElement();
-
-    bool mouseAware = AsInner()->HasMouseMoveEventListeners();
-    bool keyboardAware = win->MayHaveAPZAwareKeyEventListener() ||
-                         mDoc->MayHaveAPZAwareKeyEventListener() ||
-                         (html && html->MayHaveAPZAwareKeyEventListener()) ||
-                         (body && body->MayHaveAPZAwareKeyEventListener());
-
-    Telemetry::Accumulate(Telemetry::APZ_AWARE_MOUSEMOVE_LISTENERS,
-                          mouseAware ? 1 : 0);
-    Telemetry::Accumulate(Telemetry::APZ_AWARE_KEY_LISTENERS,
-                          keyboardAware ? 1 : 0);
-  }
-
   // Make sure that this is called before we null out the document and
   // other members that the window destroyed observers could
   // re-create.
   NotifyDOMWindowDestroyed(this);
   if (auto* reporter = nsWindowMemoryReporter::Get()) {
     reporter->ObserveDOMWindowDetached(this);
   }
 
@@ -15331,17 +15312,17 @@ nsGlobalWindow::Dispatch(const char* aNa
 {
   MOZ_RELEASE_ASSERT(NS_IsMainThread());
   if (GetDocGroup()) {
     return GetDocGroup()->Dispatch(aName, aCategory, Move(aRunnable));
   }
   return DispatcherTrait::Dispatch(aName, aCategory, Move(aRunnable));
 }
 
-nsIEventTarget*
+nsISerialEventTarget*
 nsGlobalWindow::EventTargetFor(TaskCategory aCategory) const
 {
   MOZ_RELEASE_ASSERT(NS_IsMainThread());
   if (GetDocGroup()) {
     return GetDocGroup()->EventTargetFor(aCategory);
   }
   return DispatcherTrait::EventTargetFor(aCategory);
 }
--- a/dom/base/nsGlobalWindow.h
+++ b/dom/base/nsGlobalWindow.h
@@ -1823,17 +1823,17 @@ private:
   void SetIsBackgroundInternal(bool aIsBackground);
 
 public:
   // Dispatch a runnable related to the global.
   virtual nsresult Dispatch(const char* aName,
                             mozilla::TaskCategory aCategory,
                             already_AddRefed<nsIRunnable>&& aRunnable) override;
 
-  virtual nsIEventTarget*
+  virtual nsISerialEventTarget*
   EventTargetFor(mozilla::TaskCategory aCategory) const override;
 
   virtual mozilla::AbstractThread*
   AbstractMainThreadFor(mozilla::TaskCategory aCategory) override;
 
   void DisableIdleCallbackRequests();
   uint32_t LastIdleRequestHandle() const { return mIdleRequestCallbackCounter - 1; }
   nsresult RunIdleRequest(mozilla::dom::IdleRequest* aRequest,
--- a/dom/base/nsIDocument.h
+++ b/dom/base/nsIDocument.h
@@ -2919,17 +2919,17 @@ public:
   virtual void ScheduleIntersectionObserverNotification() = 0;
   virtual void NotifyIntersectionObservers() = 0;
 
   // Dispatch a runnable related to the document.
   virtual nsresult Dispatch(const char* aName,
                             mozilla::TaskCategory aCategory,
                             already_AddRefed<nsIRunnable>&& aRunnable) override;
 
-  virtual nsIEventTarget*
+  virtual nsISerialEventTarget*
   EventTargetFor(mozilla::TaskCategory aCategory) const override;
 
   virtual mozilla::AbstractThread*
   AbstractMainThreadFor(mozilla::TaskCategory aCategory) override;
 
   // The URLs passed to these functions should match what
   // JS::DescribeScriptedCaller() returns, since these APIs are used to
   // determine whether some code is being called from a tracking script.
--- a/dom/base/nsIImageLoadingContent.idl
+++ b/dom/base/nsIImageLoadingContent.idl
@@ -99,16 +99,25 @@ interface nsIImageLoadingContent : imgIN
    * is thrown)
    *
    * @throws NS_ERROR_UNEXPECTED if the request type requested is not
    * known
    */
   imgIRequest getRequest(in long aRequestType);
 
   /**
+   * Call this function when the request was blocked by any of the
+   * security policies enforced.
+   *
+   * @param aContentDecision the decision returned from nsIContentPolicy
+   *                         (any of the types REJECT_*)
+   */
+  void setBlockedRequest(in int16_t aContentDecision);
+
+  /**
    * @return true if the current request's size is available.
    */
   [noscript, notxpcom] boolean currentRequestHasSize();
 
   /**
    * Used to notify the image loading content node that a frame has been
    * created.
    */
--- a/dom/base/nsImageLoadingContent.cpp
+++ b/dom/base/nsImageLoadingContent.cpp
@@ -40,16 +40,17 @@
 #include "nsLayoutUtils.h"
 #include "nsIContentPolicy.h"
 #include "nsSVGEffects.h"
 
 #include "gfxPrefs.h"
 
 #include "mozAutoDocUpdate.h"
 #include "mozilla/AsyncEventDispatcher.h"
+#include "mozilla/AutoRestore.h"
 #include "mozilla/EventStateManager.h"
 #include "mozilla/EventStates.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/ImageTracker.h"
 #include "mozilla/dom/ScriptSettings.h"
 #include "mozilla/Preferences.h"
 
 #ifdef LoadImage
@@ -92,17 +93,18 @@ nsImageLoadingContent::nsImageLoadingCon
     // mBroken starts out true, since an image without a URI is broken....
     mBroken(true),
     mUserDisabled(false),
     mSuppressed(false),
     mNewRequestsWillNeedAnimationReset(false),
     mUseUrgentStartForChannel(false),
     mStateChangerDepth(0),
     mCurrentRequestRegistered(false),
-    mPendingRequestRegistered(false)
+    mPendingRequestRegistered(false),
+    mIsStartingImageLoad(false)
 {
   if (!nsContentUtils::GetImgLoaderForChannel(nullptr, nullptr)) {
     mLoadingEnabled = false;
   }
 
   mMostRecentRequestChange = TimeStamp::ProcessCreation();
 }
 
@@ -775,16 +777,21 @@ nsresult
 nsImageLoadingContent::LoadImage(nsIURI* aNewURI,
                                  bool aForce,
                                  bool aNotify,
                                  ImageLoadType aImageLoadType,
                                  bool aLoadStart,
                                  nsIDocument* aDocument,
                                  nsLoadFlags aLoadFlags)
 {
+  MOZ_ASSERT(!mIsStartingImageLoad, "some evil code is reentering LoadImage.");
+  if (mIsStartingImageLoad) {
+    return NS_OK;
+  }
+
   // Pending load/error events need to be canceled in some situations. This
   // is not documented in the spec, but can cause site compat problems if not
   // done. See bug 1309461 and https://github.com/whatwg/html/issues/1872.
   CancelPendingEvent();
 
   // Fire loadstart event if required
   if (aLoadStart) {
     FireEvent(NS_LITERAL_STRING("loadstart"));
@@ -804,16 +811,28 @@ nsImageLoadingContent::LoadImage(nsIURI*
   if (!aDocument) {
     aDocument = GetOurOwnerDoc();
     if (!aDocument) {
       // No reason to bother, I think...
       return NS_OK;
     }
   }
 
+  AutoRestore<bool> guard(mIsStartingImageLoad);
+  mIsStartingImageLoad = true;
+
+  // Data documents, or documents from DOMParser shouldn't perform image loading.
+  if (aDocument->IsLoadedAsData()) {
+    SetBlockedRequest(nsIContentPolicy::REJECT_REQUEST);
+
+    FireEvent(NS_LITERAL_STRING("error"));
+    FireEvent(NS_LITERAL_STRING("loadend"));
+    return NS_OK;
+  }
+
   // URI equality check.
   //
   // We skip the equality check if our current image was blocked, since in that
   // case we really do want to try loading again.
   if (!aForce && NS_CP_ACCEPTED(mImageBlockingStatus)) {
     nsCOMPtr<nsIURI> currentURI;
     GetCurrentURI(getter_AddRefs(currentURI));
     bool equal;
@@ -833,33 +852,18 @@ nsImageLoadingContent::LoadImage(nsIURI*
   // We use the principal of aDocument to avoid having to QI |this| an extra
   // time. It should always be the same as the principal of this node.
 #ifdef DEBUG
   nsIContent* thisContent = AsContent();
   MOZ_ASSERT(thisContent->NodePrincipal() == aDocument->NodePrincipal(),
              "Principal mismatch?");
 #endif
 
-  // Are we blocked?
-  int16_t cpDecision = nsIContentPolicy::REJECT_REQUEST;
   nsContentPolicyType policyType = PolicyTypeForLoad(aImageLoadType);
 
-  nsContentUtils::CanLoadImage(aNewURI,
-                               static_cast<nsIImageLoadingContent*>(this),
-                               aDocument,
-                               aDocument->NodePrincipal(),
-                               &cpDecision,
-                               policyType);
-  if (!NS_CP_ACCEPTED(cpDecision)) {
-    FireEvent(NS_LITERAL_STRING("error"));
-    FireEvent(NS_LITERAL_STRING("loadend"));
-    SetBlockedRequest(aNewURI, cpDecision);
-    return NS_OK;
-  }
-
   nsLoadFlags loadFlags = aLoadFlags;
   int32_t corsmode = GetCORSMode();
   if (corsmode == CORS_ANONYMOUS) {
     loadFlags |= imgILoader::LOAD_CORS_ANONYMOUS;
   } else if (corsmode == CORS_USE_CREDENTIALS) {
     loadFlags |= imgILoader::LOAD_CORS_USE_CREDENTIALS;
   }
 
@@ -867,17 +871,16 @@ nsImageLoadingContent::LoadImage(nsIURI*
   // if referrer attributes are enabled in preferences, load img referrer attribute
   // if the image does not provide a referrer attribute, ignore this
   net::ReferrerPolicy referrerPolicy = aDocument->GetReferrerPolicy();
   net::ReferrerPolicy imgReferrerPolicy = GetImageReferrerPolicy();
   if (imgReferrerPolicy != net::RP_Unset) {
     referrerPolicy = imgReferrerPolicy;
   }
 
-  // Not blocked. Do the load.
   RefPtr<imgRequestProxy>& req = PrepareNextRequest(aImageLoadType);
   nsCOMPtr<nsIContent> content =
       do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
   nsCOMPtr<nsINode> thisNode =
     do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
   nsresult rv = nsContentUtils::LoadImage(aNewURI,
                                           thisNode,
                                           aDocument,
@@ -926,17 +929,16 @@ nsImageLoadingContent::LoadImage(nsIURI*
     MOZ_ASSERT(!req, "Shouldn't have non-null request here");
     // If we don't have a current URI, we might as well store this URI so people
     // know what we tried (and failed) to load.
     if (!mCurrentRequest)
       mCurrentURI = aNewURI;
 
     FireEvent(NS_LITERAL_STRING("error"));
     FireEvent(NS_LITERAL_STRING("loadend"));
-    return NS_OK;
   }
 
   return NS_OK;
 }
 
 nsresult
 nsImageLoadingContent::ForceImageState(bool aForce,
                                        EventStates::InternalType aState)
@@ -1198,67 +1200,62 @@ nsImageLoadingContent::PrepareNextReques
       imageFrame->SetForceSyncDecoding(forceSync);
     } else {
       svgImageFrame->SetForceSyncDecoding(forceSync);
     }
 
     mMostRecentRequestChange = now;
   }
 
-  // If we don't have a usable current request, get rid of any half-baked
-  // request that might be sitting there and make this one current.
-  if (!HaveSize(mCurrentRequest))
-    return PrepareCurrentRequest(aImageLoadType);
-
-  // Otherwise, make it pending.
-  return PreparePendingRequest(aImageLoadType);
+  // We only want to cancel the existing current request if size is not
+  // available. bz says the web depends on this behavior.
+  // Otherwise, we get rid of any half-baked request that might be sitting there
+  // and make this one current.
+  // TODO: Bug 583491
+  // Investigate/Cleanup NS_ERROR_IMAGE_SRC_CHANGED use in nsImageFrame.cpp
+  return HaveSize(mCurrentRequest) ?
+           PreparePendingRequest(aImageLoadType) :
+           PrepareCurrentRequest(aImageLoadType);
 }
 
-void
-nsImageLoadingContent::SetBlockedRequest(nsIURI* aURI, int16_t aContentDecision)
+nsresult
+nsImageLoadingContent::SetBlockedRequest(int16_t aContentDecision)
 {
+  // If this is not calling from LoadImage, for example, from ServiceWorker,
+  // bail out.
+  if (!mIsStartingImageLoad) {
+    return NS_OK;
+  }
+
   // Sanity
   MOZ_ASSERT(!NS_CP_ACCEPTED(aContentDecision), "Blocked but not?");
 
-  // We do some slightly illogical stuff here to maintain consistency with
-  // old behavior that people probably depend on. Even in the case where the
-  // new image is blocked, the old one should really be canceled with the
-  // reason "image source changed". However, apparently there's some abuse
-  // over in nsImageFrame where the displaying of the "broken" icon for the
-  // next image depends on the cancel reason of the previous image. ugh.
-  // XXX(seth): So shouldn't we fix nsImageFrame?!
-  ClearPendingRequest(NS_ERROR_IMAGE_BLOCKED,
-                      Some(OnNonvisible::DISCARD_IMAGES));
+  // We should never have a pending request after we got blocked.
+  MOZ_ASSERT(!mPendingRequest, "mPendingRequest should be null.");
 
-  // For the blocked case, we only want to cancel the existing current request
-  // if size is not available. bz says the web depends on this behavior.
-  if (!HaveSize(mCurrentRequest)) {
-
+  if (HaveSize(mCurrentRequest)) {
+    // PreparePendingRequest set mPendingRequestFlags, now since we've decided
+    // to block it, we reset it back to 0.
+    mPendingRequestFlags = 0;
+  } else {
     mImageBlockingStatus = aContentDecision;
-    uint32_t keepFlags = mCurrentRequestFlags & REQUEST_IS_IMAGESET;
-    ClearCurrentRequest(NS_ERROR_IMAGE_BLOCKED,
-                        Some(OnNonvisible::DISCARD_IMAGES));
+  }
 
-    // We still want to remember what URI we were and if it was an imageset,
-    // despite not having an actual request. These are both cleared as part of
-    // ClearCurrentRequest() before a new request is started.
-    mCurrentURI = aURI;
-    mCurrentRequestFlags = keepFlags;
-  }
+  return NS_OK;
 }
 
 RefPtr<imgRequestProxy>&
 nsImageLoadingContent::PrepareCurrentRequest(ImageLoadType aImageLoadType)
 {
   // Blocked images go through SetBlockedRequest, which is a separate path. For
   // everything else, we're unblocked.
   mImageBlockingStatus = nsIContentPolicy::ACCEPT;
 
   // Get rid of anything that was there previously.
-  ClearCurrentRequest(NS_ERROR_IMAGE_SRC_CHANGED,
+  ClearCurrentRequest(NS_BINDING_ABORTED,
                       Some(OnNonvisible::DISCARD_IMAGES));
 
   if (mNewRequestsWillNeedAnimationReset) {
     mCurrentRequestFlags |= REQUEST_NEEDS_ANIMATION_RESET;
   }
 
   if (aImageLoadType == eImageLoadType_Imageset) {
     mCurrentRequestFlags |= REQUEST_IS_IMAGESET;
@@ -1267,17 +1264,17 @@ nsImageLoadingContent::PrepareCurrentReq
   // Return a reference.
   return mCurrentRequest;
 }
 
 RefPtr<imgRequestProxy>&
 nsImageLoadingContent::PreparePendingRequest(ImageLoadType aImageLoadType)
 {
   // Get rid of anything that was there previously.
-  ClearPendingRequest(NS_ERROR_IMAGE_SRC_CHANGED,
+  ClearPendingRequest(NS_BINDING_ABORTED,
                       Some(OnNonvisible::DISCARD_IMAGES));
 
   if (mNewRequestsWillNeedAnimationReset) {
     mPendingRequestFlags |= REQUEST_NEEDS_ANIMATION_RESET;
   }
 
   if (aImageLoadType == eImageLoadType_Imageset) {
     mPendingRequestFlags |= REQUEST_IS_IMAGESET;
--- a/dom/base/nsImageLoadingContent.h
+++ b/dom/base/nsImageLoadingContent.h
@@ -302,27 +302,20 @@ protected:
    * "pending" until it becomes usable. Otherwise, this becomes the current
    * request.
    *
    * @param aImageLoadType The ImageLoadType for this request
    */
    RefPtr<imgRequestProxy>& PrepareNextRequest(ImageLoadType aImageLoadType);
 
   /**
-   * Called when we would normally call PrepareNextRequest(), but the request was
-   * blocked.
-   */
-  void SetBlockedRequest(nsIURI* aURI, int16_t aContentDecision);
-
-  /**
    * Returns a COMPtr reference to the current/pending image requests, cleaning
    * up and canceling anything that was there before. Note that if you just want
    * to get rid of one of the requests, you should call
-   * Clear*Request(NS_BINDING_ABORTED) instead, since it passes a more appropriate
-   * aReason than Prepare*Request() does (NS_ERROR_IMAGE_SRC_CHANGED).
+   * Clear*Request(NS_BINDING_ABORTED) instead.
    *
    * @param aImageLoadType The ImageLoadType for this request
    */
   RefPtr<imgRequestProxy>& PrepareCurrentRequest(ImageLoadType aImageLoadType);
   RefPtr<imgRequestProxy>& PreparePendingRequest(ImageLoadType aImageLoadType);
 
   /**
    * Switch our pending request to be our current request.
@@ -465,11 +458,22 @@ protected:
 private:
   /* The number of nested AutoStateChangers currently tracking our state. */
   uint8_t mStateChangerDepth;
 
   // Flags to indicate whether each of the current and pending requests are
   // registered with the refresh driver.
   bool mCurrentRequestRegistered;
   bool mPendingRequestRegistered;
+
+  // TODO:
+  // Bug 1353685: Should ServiceWorker call SetBlockedRequest?
+  //
+  // This member is used in SetBlockedRequest, if it's true, then this call is
+  // triggered from LoadImage.
+  // If this is false, it means this call is from other places like
+  // ServiceWorker, then we will ignore call to SetBlockedRequest for now.
+  //
+  // Also we use this variable to check if some evil code is reentering LoadImage.
+  bool mIsStartingImageLoad;
 };
 
 #endif // nsImageLoadingContent_h__
--- a/dom/base/nsNodeUtils.cpp
+++ b/dom/base/nsNodeUtils.cpp
@@ -534,19 +534,16 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
         if (elm) {
           window->SetMutationListeners(elm->MutationListenerBits());
           if (elm->MayHavePaintEventListener()) {
             window->SetHasPaintEventListeners();
           }
           if (elm->MayHaveTouchEventListener()) {
             window->SetHasTouchEventListeners();
           }
-          if (elm->MayHaveMouseMoveEventListener()) {
-            window->SetHasMouseMoveEventListeners();
-          }
           if (elm->MayHaveMouseEnterLeaveEventListener()) {
             window->SetHasMouseEnterLeaveEventListeners();
           }
           if (elm->MayHavePointerEnterLeaveEventListener()) {
             window->SetHasPointerEnterLeaveEventListeners();
           }
         }
       }
--- a/dom/base/nsPIDOMWindow.h
+++ b/dom/base/nsPIDOMWindow.h
@@ -24,20 +24,20 @@
 
 class nsGlobalWindow;
 class nsIArray;
 class nsIContent;
 class nsICSSDeclaration;
 class nsIDocShell;
 class nsIDocShellLoadInfo;
 class nsIDocument;
-class nsIEventTarget;
 class nsIIdleObserver;
 class nsIPrincipal;
 class nsIScriptTimeoutHandler;
+class nsISerialEventTarget;
 class nsIURI;
 class nsPIDOMWindowInner;
 class nsPIDOMWindowOuter;
 class nsPIWindowRoot;
 class nsXBLPrototypeHandler;
 
 typedef uint32_t SuspendTypes;
 
@@ -604,17 +604,17 @@ public:
 
   virtual nsresult MoveBy(int32_t aXDif, int32_t aYDif) = 0;
   virtual nsresult UpdateCommands(const nsAString& anAction, nsISelection* aSel, int16_t aReason) = 0;
 
   mozilla::dom::TabGroup* TabGroup();
 
   mozilla::dom::DocGroup* GetDocGroup() const;
 
-  virtual nsIEventTarget*
+  virtual nsISerialEventTarget*
   EventTargetFor(mozilla::TaskCategory aCategory) const = 0;
 
 protected:
   // The nsPIDOMWindow constructor. The aOuterWindow argument should
   // be null if and only if the created window itself is an outer
   // window. In all other cases aOuterWindow should be the outer
   // window for the inner window that is being created.
   explicit nsPIDOMWindow<T>(nsPIDOMWindowOuter *aOuterWindow);
@@ -663,17 +663,16 @@ protected:
   uint32_t               mMutationBits;
 
   bool                   mIsDocumentLoaded;
   bool                   mIsHandlingResizeEvent;
   bool                   mIsInnerWindow;
   bool                   mMayHavePaintEventListener;
   bool                   mMayHaveTouchEventListener;
   bool                   mMayHaveMouseEnterLeaveEventListener;
-  bool                   mMayHaveMouseMoveEventListener;
   bool                   mMayHavePointerEnterLeaveEventListener;
 
   // Used to detect whether we have called FreeInnerObjects() (e.g. to ensure
   // that a call to ResumeTimeouts() after FreeInnerObjects() does nothing).
   // This member is only used by inner windows.
   bool                   mInnerObjectsFreed;
 
 
@@ -811,34 +810,16 @@ public:
       return;
     }
 
     mMutationBits |= aType;
   }
 
   /**
    * Call this to check whether some node (this window, its document,
-   * or content in that document) has or had a mousemove event listener.
-   */
-  bool HasMouseMoveEventListeners()
-  {
-    return mMayHaveMouseMoveEventListener;
-  }
-
-  /**
-   * Call this to indicate that some node (this window, its document,
-   * or content in that document) has or had a mousemove event listener.
-   */
-  void SetHasMouseMoveEventListeners()
-  {
-    mMayHaveMouseMoveEventListener = true;
-  }
-
-  /**
-   * Call this to check whether some node (this window, its document,
    * or content in that document) has a mouseenter/leave event listener.
    */
   bool HasMouseEnterLeaveEventListeners()
   {
     return mMayHaveMouseEnterLeaveEventListener;
   }
 
   /**
--- a/dom/base/test/browser.ini
+++ b/dom/base/test/browser.ini
@@ -1,14 +1,15 @@
 [DEFAULT]
 support-files =
   audio.ogg
   empty.html
   file_audioLoop.html
   file_audioLoopInIframe.html
+  file_blocking_image.html
   file_bug902350.html
   file_bug902350_frame.html
   file_bug1011748_redirect.sjs
   file_bug1011748_OK.sjs
   file_bug1303838.html
   file_bug1303838_target.html
   file_bug1303838_with_iframe.html
   file_messagemanager_unload.html
@@ -17,17 +18,19 @@ support-files =
   file_use_counter_svg_getElementById.svg
   file_use_counter_svg_currentScale.svg
   file_use_counter_svg_fill_pattern_definition.svg
   file_use_counter_svg_fill_pattern.svg
   file_use_counter_svg_fill_pattern_internal.svg
   file_use_counter_svg_fill_pattern_data.svg
   file_webaudioLoop.html
   plugin.js
+  !/image/test/mochitest/shaver.png
 
+[browser_blocking_image.js]
 [browser_bug593387.js]
 [browser_bug902350.js]
 tags = mcb
 [browser_bug1011748.js]
 [browser_bug1058164.js]
 [browser_force_process_selector.js]
 skip-if = !e10s # this only makes sense with e10s-multi
 [browser_messagemanager_loadprocessscript.js]
new file mode 100644
--- /dev/null
+++ b/dom/base/test/browser_blocking_image.js
@@ -0,0 +1,185 @@
+const TEST_URI = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "https://example.com") + "file_blocking_image.html";
+
+/**
+ * Loading an image from https:// should work.
+ */
+add_task(async function load_image_from_https_test() {
+  let tab = gBrowser.addTab(TEST_URI);
+  await BrowserTestUtils.browserLoaded(tab.linkedBrowser);
+
+  gBrowser.selectedTab = tab;
+
+  await ContentTask.spawn(tab.linkedBrowser, { }, async function() {
+    function imgListener(img) {
+      return new Promise((resolve, reject) => {
+        img.addEventListener("load", () => resolve());
+        img.addEventListener("error", () => reject());
+      });
+    }
+
+    let img = content.document.createElement("img");
+    img.src = "https://example.com/tests/image/test/mochitest/shaver.png";
+    content.document.body.appendChild(img);
+
+    try {
+      await imgListener(img);
+      Assert.ok(true);
+    } catch (e) {
+      Assert.ok(false);
+    }
+
+    Assert.equal(img.imageBlockingStatus, Ci.nsIContentPolicy.ACCEPT);
+  });
+
+  gBrowser.removeTab(tab);
+});
+
+/**
+ * Loading an image from http:// should be rejected.
+ */
+add_task(async function load_image_from_http_test() {
+  let tab = gBrowser.addTab(TEST_URI);
+  await BrowserTestUtils.browserLoaded(tab.linkedBrowser);
+
+  gBrowser.selectedTab = tab;
+
+  await ContentTask.spawn(tab.linkedBrowser, { }, async function () {
+    function imgListener(img) {
+      return new Promise((resolve, reject) => {
+        img.addEventListener("load", () => reject());
+        img.addEventListener("error", () => resolve());
+      });
+    }
+
+    let img = content.document.createElement('img');
+    img.src = "http://example.com/tests/image/test/mochitest/shaver.png";
+    content.document.body.appendChild(img);
+
+    try {
+      await imgListener(img);
+      Assert.ok(true);
+    } catch (e) {
+      Assert.ok(false);
+    }
+
+    Assert.equal(img.imageBlockingStatus, Ci.nsIContentPolicy.REJECT_SERVER,
+                 "images from http should be blocked");
+  });
+
+  gBrowser.removeTab(tab);
+});
+
+/**
+ * Loading an image from http:// immediately after loading from https://
+ * The load from https:// should be replaced.
+ */
+add_task(async function load_https_and_http_test() {
+  let tab = gBrowser.addTab(TEST_URI);
+  await BrowserTestUtils.browserLoaded(tab.linkedBrowser);
+
+  // Clear image cache, otherwise in non-e10s mode the image might be cached by
+  // previous test, and make the image from https is loaded immediately.
+  let imgTools = Cc["@mozilla.org/image/tools;1"].getService(Ci.imgITools);
+  let imageCache = imgTools.getImgCacheForDocument(window.document);
+  imageCache.clearCache(false); // false=content
+
+  gBrowser.selectedTab = tab;
+
+  await ContentTask.spawn(tab.linkedBrowser, { }, async function () {
+    function imgListener(img) {
+      return new Promise((resolve, reject) => {
+        img.addEventListener("load", () => reject());
+        img.addEventListener("error", () => resolve());
+      });
+    }
+
+    let img = content.document.createElement("img");
+    img.src = "https://example.com/tests/image/test/mochitest/shaver.png";
+    img.src = "http://example.com/tests/image/test/mochitest/shaver.png";
+
+    content.document.body.appendChild(img);
+
+    try {
+      await imgListener(img);
+      Assert.ok(true);
+    } catch (e) {
+      Assert.ok(false);
+    }
+
+    Assert.equal(img.imageBlockingStatus, Ci.nsIContentPolicy.REJECT_SERVER,
+                 "image.src changed to http should be blocked");
+  });
+
+  gBrowser.removeTab(tab);
+});
+
+/**
+ * Loading an image from https.
+ * Then after we have size information of the image, we immediately change the
+ * location to a http:// site (hence should be blocked by CSP). This will make
+ * the 2nd request as a PENDING_REQUEST, also blocking 2nd load shouldn't change
+ * the imageBlockingStatus value.
+ */
+add_task(async function block_pending_request_test() {
+  let tab = gBrowser.addTab(TEST_URI);
+  await BrowserTestUtils.browserLoaded(tab.linkedBrowser);
+
+  gBrowser.selectedTab = tab;
+
+  await ContentTask.spawn(tab.linkedBrowser, { }, async function () {
+    let wrapper = {
+      _resolve: null,
+      _sizeAvail: false,
+
+      sizeAvailable(request) {
+        // In non-e10s mode the image may have already been cached, so sometimes
+        // sizeAvailable() is called earlier then waitUntilSizeAvailable().
+        if (this._resolve) {
+          this._resolve();
+        } else {
+          this._sizeAvail = true;
+        }
+      },
+
+      waitUntilSizeAvailable() {
+        return new Promise(resolve => {
+          this._resolve = resolve;
+          if (this._sizeAvail) {
+            resolve();
+          }
+        });
+      },
+
+      QueryInterface(aIID) {
+        if (aIID.equals(Ci.imgIScriptedNotificationObserver))
+          return this;
+        throw Cr.NS_ERROR_NO_INTERFACE;
+      }
+    };
+
+    let observer = Cc["@mozilla.org/image/tools;1"].getService(Ci.imgITools)
+                     .createScriptedObserver(wrapper);
+
+    let img = content.document.createElement("img");
+    img.src = "https://example.com/tests/image/test/mochitest/shaver.png";
+
+    let req = img.getRequest(Ci.nsIImageLoadingContent.CURRENT_REQUEST);
+    img.addObserver(observer);
+
+    content.document.body.appendChild(img);
+
+    info("Wait until Size Available");
+    await wrapper.waitUntilSizeAvailable();
+    info("Size Available now!");
+    img.removeObserver(observer);
+
+    // Now we change to load from http:// site, which will be blocked.
+    img.src = "http://example.com/tests/image/test/mochitest/shaver.png";
+
+    Assert.equal(img.getRequest(Ci.nsIImageLoadingContent.CURRENT_REQUEST), req,
+                 "CURRENT_REQUEST shouldn't be replaced.");
+    Assert.equal(img.imageBlockingStatus, Ci.nsIContentPolicy.ACCEPT);
+  });
+
+  gBrowser.removeTab(tab);
+});
--- a/dom/base/test/chrome.ini
+++ b/dom/base/test/chrome.ini
@@ -1,24 +1,27 @@
 [DEFAULT]
 skip-if = os == 'android'
 support-files =
   file_empty.html
+  file_blocking_image.html
   file_bug945152.jar
   file_bug945152_worker.js
   file_bug1008126_worker.js
   file_inline_script.html
   file_inline_script.xhtml
   file_external_script.html
   file_external_script.xhtml
   file_script.js
   mozbrowser_api_utils.js
+  !/image/test/mochitest/shaver.png
 
 [test_anonymousContent_xul_window.xul]
 [test_blockParsing.html]
+[test_blocking_image.html]
 [test_bug715041.xul]
 [test_bug715041_removal.xul]
 [test_bug945152.html]
 [test_bug1008126.html]
 [test_bug1016960.html]
 [test_copypaste.xul]
 subsuite = clipboard
 [test_domrequesthelper.xul]
new file mode 100644
--- /dev/null
+++ b/dom/base/test/file_blocking_image.html
@@ -0,0 +1,10 @@
+<!DOCTYPE HTML>
+<html  xml:lang="en-US" lang="en-US">
+  <head>
+    <meta charset="utf8" http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">
+    <title>Image Blocking test </title>
+  </head>
+  <body>
+  </body>
+</html>
+
new file mode 100644
--- /dev/null
+++ b/dom/base/test/file_viewport_scroll_quirks.html
@@ -0,0 +1,1 @@
+<html><body style='height:2000px; width:2000px;'>
new file mode 100644
--- /dev/null
+++ b/dom/base/test/file_viewport_scroll_xml.xml
@@ -0,0 +1,1 @@
+<?xml-stylesheet href='data:text/css,html { display:block; height:2000px; width:2000px; }'?><foo><html></html></foo>
--- a/dom/base/test/file_x-frame-options_page.sjs
+++ b/dom/base/test/file_x-frame-options_page.sjs
@@ -49,12 +49,16 @@ function handleRequest(request, response
   if (testHeaders.hasOwnProperty(query['xfo'])) {
     response.setHeader("X-Frame-Options", testHeaders[query['xfo']], false);
   }
 
   // from the test harness we'll be checking for the presence of this element
   // to test if the page loaded
   response.write("<h1 id=\"test\">" + query["testid"] + "</h1>");
 
+  if (query['testid'] == "postmessage") {
+    response.write("<script>parent.opener.postMessage('ok', '*');</script>");
+  }
+
   if (query['multipart'] == "1") {
     response.write("\r\n--" + BOUNDARY + "\r\n");
   }
 }
--- a/dom/base/test/mochitest.ini
+++ b/dom/base/test/mochitest.ini
@@ -151,16 +151,18 @@ support-files =
   file_htmlserializer_ipv6_out.html
   file_lock_orientation.html
   file_mozfiledataurl_img.jpg
   file_record_orientation.html
   file_restrictedEventSource.sjs
   file_settimeout_inner.html
   file_simplecontentpolicy.js
   file_timer_flood.html
+  file_viewport_scroll_quirks.html
+  file_viewport_scroll_xml.xml
   file_websocket_basic_wsh.py
   file_websocket_hello_wsh.py
   file_websocket_http_resource.txt
   file_websocket_permessage_deflate_wsh.py
   file_websocket_permessage_deflate_disabled_wsh.py
   file_websocket_permessage_deflate_rejected_wsh.py
   file_websocket_permessage_deflate_params_wsh.py
   file_websocket_wsh.py
new file mode 100644
--- /dev/null
+++ b/dom/base/test/test_blocking_image.html
@@ -0,0 +1,110 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1267075
+-->
+  <title>Test for Bug 1267075</title>
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"></script>
+  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
+</head>
+<body onload="onLoad()">
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1267075">Mozilla Bug 1267075</a>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+const { classes: Cc, interfaces: Ci } = Components;
+SimpleTest.waitForExplicitFinish();
+
+function onLoad() {
+  var iframe = document.createElement("iframe");
+  iframe.onload = function () {
+    info("iframe loaded");
+    var winUtils = iframe.contentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
+                                       .getInterface(Ci.nsIDOMWindowUtils);
+    // load some styles at the agent level
+    var css = `
+      img:-moz-suppressed {
+        color: green
+      }
+      img:-moz-broken {
+       color: red
+      }
+      img:-moz-user-disabled {
+       color: blue
+      }`;
+    var sheetURL = "data:text/css," + encodeURIComponent(css);
+    winUtils.loadSheetUsingURIString(sheetURL, winUtils.AGENT_SHEET);
+
+    function imgListener(img) {
+      return new Promise((resolve, reject) => {
+        img.addEventListener("load", () => reject());
+        img.addEventListener("error", () => resolve());
+      });
+    }
+
+    var doc = iframe.contentDocument;
+    var img = doc.createElement("img");
+    var img2 = doc.createElement("img");
+    var img3 = doc.createElement("img");
+
+    // image from HTTP should be blocked.
+    img.src = "http://example.com/tests/image/test/mochitest/shaver.png";
+    doc.body.appendChild(img);
+
+    imgListener(img).then(() => {
+      ok(true, "img shouldn't be loaded");
+
+      // We can't use matches(":-moz-suppressed") here, as -moz-suppressed is
+      // chrome-only, however now we are in a content iframe.
+      is(iframe.contentWindow.getComputedStyle(img).color, "rgb(0, 128, 0)",
+         "color of img should be green");
+      is(img.imageBlockingStatus, Ci.nsIContentPolicy.REJECT_SERVER,
+         "imageBlockingStatues should be REJECT_SERVER.");
+
+      img2.src = "https://test.invalid";
+      doc.body.appendChild(img2);
+      return imgListener(img2);
+    }).then(() => {
+      ok(true, "img2 shouldn't be loaded");
+      is(iframe.contentWindow.getComputedStyle(img2).color, "rgb(255, 0, 0)",
+         "color of img2 should be red");
+      ok(img2.matches(":-moz-broken"), "should match ':-moz-broken' selector");
+
+      // Now prepare for the next test, deny image.
+      return new Promise(resolve => {
+          SpecialPowers.pushPrefEnv({"set": [["permissions.default.image", 2]]}, resolve)
+      });
+    }).then(() => {
+      // Now image is denied, loading image will be rejected with REJECT_TYPE,
+      // which will be mapped to :-moz-user-disabled
+      img3.src = "https://example.com/tests/image/test/mochitest/shaver.png";
+      doc.body.appendChild(img3);
+      return imgListener(img3);
+    }).then(() => {
+      ok(true, "img3 shouldn't be loaded");
+
+      // -moz-user-disabled is also chrome only, so we didn't use matches() to verify.
+      is(iframe.contentWindow.getComputedStyle(img3).color, "rgb(0, 0, 255)",
+         "color of img3 should be blue");
+      is(img3.imageBlockingStatus, Ci.nsIContentPolicy.REJECT_TYPE,
+         "imageBlockingStatues should be REJECT_TYPE.");
+
+      SimpleTest.finish();
+    }).catch((e) => {
+      ok(false, "throwing " + e);
+    });
+  };
+
+  // file_blocking_image.html contains meta tag for CSP, which will block images from
+  // http.
+  iframe.src = "http://mochi.test:8888/chrome/dom/base/test/file_blocking_image.html";
+  document.getElementById("content").appendChild(iframe);
+}
+</script>
+</pre>
+<p id="display"></p>
+<div id="content">
+</div>
+
+</body> </html>
--- a/dom/base/test/test_viewport_scroll.html
+++ b/dom/base/test/test_viewport_scroll.html
@@ -15,19 +15,19 @@
 <pre id="test">
 <script type="application/javascript">
 SimpleTest.waitForExplicitFinish();
 
 var quirks = document.getElementById("quirks");
 var standards = document.getElementById("standards");
 var xml = document.getElementById("xml");
 
-quirks.src = "data:text/html,<html><body style='height:2000px; width:2000px;'>";
-standards.src = "data:text/html,<!DOCTYPE HTML><html><body style='height:2000px; width:2000px;'>";
-xml.src = "data:text/xml,<?xml-stylesheet href='data:text/css,html { display:block; height:2000px; width:2000px; }'?><foo><html></html></foo>";
+quirks.src = "file_viewport_scroll_quirks.html";
+standards.srcdoc = "<!DOCTYPE HTML><html><body style='height:2000px; width:2000px;'>";
+xml.src = "file_viewport_scroll_xml.xml";
 
 function subtest(winProp, elemProp, win, correctElement, elemToSet, otherElem1, otherElem2) {
   win.scrollTo(50, 50);
   elemToSet[elemProp] = 100;
   if (elemToSet == correctElement) {
     is(Math.round(win[winProp]), 100, "Setting " + elemToSet.name + "." + elemProp + " should scroll");
     is(elemToSet[elemProp], 100, "Reading back " + elemToSet.name + "." + elemProp + " after scrolling");
   } else {
--- a/dom/base/test/test_x-frame-options.html
+++ b/dom/base/test/test_x-frame-options.html
@@ -10,16 +10,17 @@
 <div id="content" style="display: none">
 
 </div>
 
 <iframe style="width:100%;height:300px;" id="harness"></iframe>
 <script class="testbody" type="text/javascript">
 
 var path = "/tests/dom/base/test/";
+var isUnique = SpecialPowers.getBoolPref("security.data_uri.unique_opaque_origin");
 
 var testFramesLoaded = function() {
   var harness = SpecialPowers.wrap(document).getElementById("harness");
 
   // iframe from same origin, no X-F-O header - should load
   var frame = harness.contentDocument.getElementById("control1");
   var test1 = frame.contentDocument.getElementById("test").textContent;
   is(test1, "control1", "test control1");
@@ -104,50 +105,77 @@ var testFramesLoaded = function() {
     var theTestResult = frame.contentDocument.getElementById("test");
     is(theTestResult, null, "test allow-from-deny-" + i);
   }
 
   // call tests to check principal comparison, e.g. a document can open a window
   // to a data: or javascript: document which frames an
   // X-Frame-Options: SAMEORIGIN document and the frame should load
   testFrameInJSURI();
-}
+};
 
 // test that a document can be framed under a javascript: URL opened by the
 // same site as the frame
 var testFrameInJSURI = function() {
   var html = '<iframe id="sameorigin3" src="http://mochi.test:8888/tests/dom/base/test/file_x-frame-options_page.sjs?testid=sameorigin3&xfo=sameorigin"></iframe>';
   var win = window.open();
   win.onload = function() {
     var test = win.document.getElementById("sameorigin3")
               .contentDocument.getElementById("test");
     ok(test != null, "frame under javascript: URL should have loaded.");
     win.close();
 
     // run last test
-    testFrameInDataURI();
-   }
+    if (!isUnique) {
+      testFrameInDataURI();
+    } else {
+      testFrameNotLoadedInDataURI();
+    }
+  };
   win.location.href = "javascript:document.write('"+html+"');document.close();";
-}
+};
 
 // test that a document can be framed under a data: URL opened by the
 // same site as the frame
 var testFrameInDataURI = function() {
   var html = '<iframe id="sameorigin4" src="http://mochi.test:8888/tests/dom/base/test/file_x-frame-options_page.sjs?testid=sameorigin4&xfo=sameorigin"></iframe>';
   var win = window.open();
   win.onload = function() {
+    ok(!isUnique, "This test should be run only when security.data_uri.unique_opaque_origin is off");
     var test = win.document.getElementById("sameorigin4")
               .contentDocument.getElementById("test");
     ok(test != null, "frame under data: URL should have loaded.");
     win.close();
 
     SimpleTest.finish();
-   }
+  };
   win.location.href = "data:text/html,"+html;
-}
+};
+
+// test an iframe with X-FRAME-OPTIONS shouldn't be loaded in a cross-origin window,
+var testFrameNotLoadedInDataURI = function() {
+  // In this case we load two iframes, one is sameorigin4, which will have X-FRAME-OPTIONS,
+  // the other is postmessage, which won't get the XFO header.
+  // And because now window is navigated to a data: URI, which is considered as cross origin,
+  // So win.onload won't be fired, so we use the iframe 'postmessage' to know the iframes
+  // have been loaded.
+  var html = `<iframe id="sameorigin4" src="http://mochi.test:8888/tests/dom/base/test/file_x-frame-options_page.sjs?testid=sameorigin4&xfo=sameorigin"></iframe>
+              <iframe id="postmessage" src="http://mochi.test:8888/tests/dom/base/test/file_x-frame-options_page.sjs?testid=postmessage"></iframe>`;
+  var win = window.open();
+  window.onmessage = function(evt) {
+    ok(isUnique, "This test should be run only when security.data_uri.unique_opaque_origin is on");
+    var iframe = SpecialPowers.wrap(win).document.getElementById("sameorigin4");
+    var test = iframe.contentDocument.getElementById("test");
+    ok(test == null, "frame under data: URL should have blocked.");
+    win.close();
+
+    SimpleTest.finish();
+  };
+  win.location.href = "data:text/html,"+html;
+};
 
 SimpleTest.waitForExplicitFinish();
 
 // load the test harness
 document.getElementById("harness").src = "file_x-frame-options_main.html";
 
 </script>
 </pre>
--- a/dom/events/EventListenerManager.cpp
+++ b/dom/events/EventListenerManager.cpp
@@ -121,20 +121,18 @@ IsWebkitPrefixSupportEnabled()
 
 EventListenerManagerBase::EventListenerManagerBase()
   : mNoListenerForEvent(eVoidEvent)
   , mMayHavePaintEventListener(false)
   , mMayHaveMutationListeners(false)
   , mMayHaveCapturingListeners(false)
   , mMayHaveSystemGroupListeners(false)
   , mMayHaveTouchEventListener(false)
-  , mMayHaveMouseMoveEventListener(false)
   , mMayHaveMouseEnterLeaveEventListener(false)
   , mMayHavePointerEnterLeaveEventListener(false)
-  , mMayHaveAPZAwareKeyEventListener(false)
   , mMayHaveKeyEventListener(false)
   , mMayHaveInputOrCompositionEventListener(false)
   , mClearingListeners(false)
   , mIsMainThreadELM(NS_IsMainThread())
 {
   static_assert(sizeof(EventListenerManagerBase) == sizeof(uint32_t),
                 "Keep the size of EventListenerManagerBase size compact!");
 }
@@ -407,31 +405,23 @@ EventListenerManager::AddEventListenerIn
       window->SetHasGamepadEventListener();
     }
   } else if (aTypeAtom == nsGkAtoms::onkeydown ||
              aTypeAtom == nsGkAtoms::onkeypress ||
              aTypeAtom == nsGkAtoms::onkeyup) {
     if (!aFlags.mInSystemGroup) {
       mMayHaveKeyEventListener = true;
     }
-    if (!aFlags.mPassive && aTypeAtom != nsGkAtoms::onkeyup) {
-      mMayHaveAPZAwareKeyEventListener = true;
-    }
   } else if (aTypeAtom == nsGkAtoms::oncompositionend ||
              aTypeAtom == nsGkAtoms::oncompositionstart ||
              aTypeAtom == nsGkAtoms::oncompositionupdate ||
              aTypeAtom == nsGkAtoms::oninput) {
     if (!aFlags.mInSystemGroup) {
       mMayHaveInputOrCompositionEventListener = true;
     }
-  } else if (aTypeAtom == nsGkAtoms::onmousemove) {
-    mMayHaveMouseMoveEventListener = true;
-    if (nsPIDOMWindowInner* window = GetInnerWindowForTarget()) {
-      window->SetHasMouseMoveEventListeners();
-    }
   }
 
   if (IsApzAwareListener(listener)) {
     ProcessApzAwareEventListenerAdd();
   }
 
   if (mTarget) {
     if (aTypeAtom) {
--- a/dom/events/EventListenerManager.h
+++ b/dom/events/EventListenerManager.h
@@ -156,25 +156,23 @@ protected:
   EventListenerManagerBase();
 
   EventMessage mNoListenerForEvent;
   uint16_t mMayHavePaintEventListener : 1;
   uint16_t mMayHaveMutationListeners : 1;
   uint16_t mMayHaveCapturingListeners : 1;
   uint16_t mMayHaveSystemGroupListeners : 1;
   uint16_t mMayHaveTouchEventListener : 1;
-  uint16_t mMayHaveMouseMoveEventListener : 1;
   uint16_t mMayHaveMouseEnterLeaveEventListener : 1;
   uint16_t mMayHavePointerEnterLeaveEventListener : 1;
-  uint16_t mMayHaveAPZAwareKeyEventListener : 1;
   uint16_t mMayHaveKeyEventListener : 1;
   uint16_t mMayHaveInputOrCompositionEventListener : 1;
   uint16_t mClearingListeners : 1;
   uint16_t mIsMainThreadELM : 1;
-  // uint16_t mUnused : 3;
+  // uint16_t mUnused : 5;
 };
 
 /*
  * Event listener manager
  */
 
 class EventListenerManager final : public EventListenerManagerBase
 {
@@ -436,23 +434,19 @@ public:
   bool MayHavePaintEventListener() { return mMayHavePaintEventListener; }
 
   /**
    * Returns true if there may be a touch event listener registered,
    * false if there definitely isn't.
    */
   bool MayHaveTouchEventListener() { return mMayHaveTouchEventListener; }
 
-  bool MayHaveMouseMoveEventListener() { return mMayHaveMouseMoveEventListener; }
-
   bool MayHaveMouseEnterLeaveEventListener() { return mMayHaveMouseEnterLeaveEventListener; }
   bool MayHavePointerEnterLeaveEventListener() { return mMayHavePointerEnterLeaveEventListener; }
 
-  bool MayHaveAPZAwareKeyEventListener() const { return mMayHaveAPZAwareKeyEventListener; }
-
   /**
    * Returns true if there may be a key event listener (keydown, keypress,
    * or keyup) registered, or false if there definitely isn't.
    */
   bool MayHaveKeyEventListener() { return mMayHaveKeyEventListener; }
 
   /**
    * Returns true if there may be an advanced input event listener (input,
--- a/dom/events/EventTarget.cpp
+++ b/dom/events/EventTarget.cpp
@@ -60,23 +60,16 @@ EventTarget::SetEventHandler(nsIAtom* aT
 bool
 EventTarget::IsApzAware() const
 {
   EventListenerManager* elm = GetExistingListenerManager();
   return elm && elm->HasApzAwareListeners();
 }
 
 bool
-EventTarget::MayHaveAPZAwareKeyEventListener() const
-{
-  EventListenerManager* elm = GetExistingListenerManager();
-  return elm && elm->MayHaveAPZAwareKeyEventListener();
-}
-
-bool
 EventTarget::DispatchEvent(Event& aEvent,
                            CallerType aCallerType,
                            ErrorResult& aRv)
 {
   bool result = false;
   aRv = DispatchEvent(&aEvent, &result);
   return !aEvent.DefaultPrevented(aCallerType);
 }
--- a/dom/events/EventTarget.h
+++ b/dom/events/EventTarget.h
@@ -95,17 +95,16 @@ public:
    * exist.
    */
   virtual EventListenerManager* GetExistingListenerManager() const = 0;
 
   // Called from AsyncEventDispatcher to notify it is running.
   virtual void AsyncEventRunning(AsyncEventDispatcher* aEvent) {}
 
   virtual bool IsApzAware() const;
-  bool MayHaveAPZAwareKeyEventListener() const;
 
 protected:
   EventHandlerNonNull* GetEventHandler(nsIAtom* aType,
                                        const nsAString& aTypeString);
   void SetEventHandler(nsIAtom* aType, const nsAString& aTypeString,
                        EventHandlerNonNull* aHandler);
 };
 
--- a/dom/flyweb/FlyWebPublishedServer.cpp
+++ b/dom/flyweb/FlyWebPublishedServer.cpp
@@ -11,17 +11,16 @@
 #include "mozilla/dom/Request.h"
 #include "mozilla/dom/FlyWebServerEvents.h"
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/InternalResponse.h"
 #include "mozilla/ipc/IPCStreamUtils.h"
 #include "mozilla/net/NeckoParent.h"
 #include "mozilla/net/IPCTransportProvider.h"
-#include "mozilla/AbstractThread.h"
 #include "mozilla/ErrorResult.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Unused.h"
 #include "nsCharSeparatedTokenizer.h"
 #include "nsGlobalWindow.h"
 #include "WebSocketChannel.h"
 
 namespace mozilla {
@@ -167,18 +166,18 @@ FlyWebPublishedServer::OnWebSocketAccept
 NS_IMPL_ISUPPORTS_INHERITED0(FlyWebPublishedServerImpl, mozilla::DOMEventTargetHelper)
 
 FlyWebPublishedServerImpl::FlyWebPublishedServerImpl(nsPIDOMWindowInner* aOwner,
                                                      const nsAString& aName,
                                                      const FlyWebPublishOptions& aOptions)
   : FlyWebPublishedServer(aOwner, aName, aOptions)
   , mHttpServer(
       new HttpServer(aOwner ?
-        aOwner->GetDocGroup()->AbstractMainThreadFor(TaskCategory::Other) :
-        AbstractThread::MainThread()))
+        aOwner->GetDocGroup()->EventTargetFor(TaskCategory::Other) :
+        GetMainThreadSerialEventTarget()))
 {
   LOG_I("FlyWebPublishedServerImpl::FlyWebPublishedServerImpl(%p)", this);
 }
 
 void
 FlyWebPublishedServerImpl::PermissionGranted(bool aGranted)
 {
   LOG_I("FlyWebPublishedServerImpl::PermissionGranted(%d)", aGranted);
@@ -486,18 +485,18 @@ FlyWebPublishedServerParent::FlyWebPubli
   if (!mozPromise) {
     Unused << SendServerReady(NS_ERROR_FAILURE);
     return;
   }
 
   RefPtr<FlyWebPublishedServerParent> self = this;
 
   mozPromise->Then(
-    // Non DocGroup-version of AbstractThread::MainThread() for the task in parent.
-    AbstractThread::MainThread(),
+    // Non DocGroup-version for the task in parent.
+    GetMainThreadSerialEventTarget(),
     __func__,
     [this, self] (FlyWebPublishedServer* aServer) {
       mPublishedServer = static_cast<FlyWebPublishedServerImpl*>(aServer);
       if (mActorDestroyed) {
         mPublishedServer->Close();
         return;
       }
 
--- a/dom/flyweb/HttpServer.cpp
+++ b/dom/flyweb/HttpServer.cpp
@@ -31,20 +31,20 @@ static LazyLogModule gHttpServerLog("Htt
 #undef LOG_E
 #define LOG_E(...) MOZ_LOG(gHttpServerLog, mozilla::LogLevel::Error, (__VA_ARGS__))
 
 
 NS_IMPL_ISUPPORTS(HttpServer,
                   nsIServerSocketListener,
                   nsILocalCertGetCallback)
 
-HttpServer::HttpServer(AbstractThread* aMainThread)
+HttpServer::HttpServer(nsISerialEventTarget* aEventTarget)
   : mPort()
   , mHttps()
-  , mAbstractMainThread(aMainThread)
+  , mEventTarget(aEventTarget)
 {
 }
 
 HttpServer::~HttpServer()
 {
 }
 
 void
@@ -1251,17 +1251,17 @@ HttpServer::Connection::OnOutputStreamRe
       mOutputCopy =
         StreamCopier::Copy(mOutputBuffers[0].mStream,
                            mOutput,
                            mOutputBuffers[0].mChunked);
 
       RefPtr<Connection> self = this;
 
       mOutputCopy->
-        Then(mServer->mAbstractMainThread,
+        Then(mServer->mEventTarget,
              __func__,
              [self, this] (nsresult aStatus) {
                MOZ_ASSERT(mOutputBuffers[0].mStream);
                LOG_V("HttpServer::Connection::OnOutputStreamReady(%p) - "
                      "Sent body. Status 0x%" PRIx32,
                      this, static_cast<uint32_t>(aStatus));
 
                mOutputBuffers.RemoveElementAt(0);
--- a/dom/flyweb/HttpServer.h
+++ b/dom/flyweb/HttpServer.h
@@ -15,20 +15,19 @@
 #include "mozilla/Variant.h"
 #include "nsIRequestObserver.h"
 #include "mozilla/MozPromise.h"
 #include "nsITransportProvider.h"
 #include "nsILocalCertService.h"
 
 class nsIX509Cert;
 
-namespace mozilla {
+class nsISerialEventTarget;
 
-class AbstractThread;
-
+namespace mozilla {
 namespace dom {
 
 extern bool
 ContainsToken(const nsCString& aList, const nsCString& aToken);
 
 class InternalRequest;
 class InternalResponse;
 
@@ -42,17 +41,17 @@ public:
   virtual void OnWebSocket(InternalRequest* aConnectRequest) = 0;
   virtual void OnServerClose() = 0;
 };
 
 class HttpServer final : public nsIServerSocketListener,
                          public nsILocalCertGetCallback
 {
 public:
-  explicit HttpServer(AbstractThread* aMainThread);
+  explicit HttpServer(nsISerialEventTarget* aEventTarget);
 
   NS_DECL_ISUPPORTS
   NS_DECL_NSISERVERSOCKETLISTENER
   NS_DECL_NSILOCALCERTGETCALLBACK
 
   void Init(int32_t aPort, bool aHttps, HttpServerListener* aListener);
 
   void SendResponse(InternalRequest* aRequest, InternalResponse* aResponse);
@@ -182,15 +181,15 @@ private:
   nsCOMPtr<nsIServerSocket> mServerSocket;
   nsCOMPtr<nsIX509Cert> mCert;
 
   nsTArray<RefPtr<Connection>> mConnections;
 
   int32_t mPort;
   bool mHttps;
 
-  const RefPtr<AbstractThread> mAbstractMainThread;
+  const nsCOMPtr<nsISerialEventTarget> mEventTarget;
 };
 
 } // namespace dom
 } // namespace mozilla
 
 #endif // mozilla_dom_HttpServer_h
new file mode 100644
--- /dev/null
+++ b/dom/html/test/file_iframe_sandbox_srcdoc_allow_scripts.html
@@ -0,0 +1,1 @@
+<script>parent.parent.ok_wrapper(true, "an object inside an iframe sandboxed with allow-scripts allow-same-origin should be able to run scripts and call functions in the parent of the iframe")</script>
new file mode 100644
--- /dev/null
+++ b/dom/html/test/file_iframe_sandbox_srcdoc_no_allow_scripts.html
@@ -0,0 +1,1 @@
+<script>parent.parent.ok_wrapper(false, 'an object inside an iframe sandboxed with only allow-same-origin should not be able to run scripts')</script>
--- a/dom/html/test/mochitest.ini
+++ b/dom/html/test/mochitest.ini
@@ -151,16 +151,18 @@ support-files =
   file_iframe_sandbox_open_window_fail.html
   file_iframe_sandbox_open_window_pass.html
   file_iframe_sandbox_pass.js
   file_iframe_sandbox_redirect.html
   file_iframe_sandbox_redirect.html^headers^
   file_iframe_sandbox_redirect_target.html
   file_iframe_sandbox_refresh.html
   file_iframe_sandbox_refresh.html^headers^
+  file_iframe_sandbox_srcdoc_allow_scripts.html
+  file_iframe_sandbox_srcdoc_no_allow_scripts.html
   file_iframe_sandbox_top_navigation_fail.html
   file_iframe_sandbox_top_navigation_pass.html
   file_iframe_sandbox_window_form_fail.html
   file_iframe_sandbox_window_form_pass.html
   file_iframe_sandbox_window_navigation_fail.html
   file_iframe_sandbox_window_navigation_pass.html
   file_iframe_sandbox_window_top_navigation_pass.html
   file_iframe_sandbox_window_top_navigation_fail.html
--- a/dom/html/test/test_iframe_sandbox_inheritance.html
+++ b/dom/html/test/test_iframe_sandbox_inheritance.html
@@ -163,23 +163,23 @@ function doTest() {
   // 16) An <object> inside a <frame> inside an <iframe> sandboxed with 'allow-scripts allow-forms'
   // should be able to submit forms.
   // Done by file_iframe_sandbox_a_if15.html which is contained within file_iframe_sandbox_a_if16.html
   // which is contained within file_iframe_sandbox_a_if10.html
 
   // fails if bad
   // 17) An <object> inside an <iframe> sandboxed with 'allow-same-origin'
   // should not be able to run scripts.
-  // Done by iframe "if_no_scripts" using a data: load.
+  // Done by iframe "if_no_scripts", which loads file_iframe_sandbox_srcdoc_no_allow_scripts.html.
   testAttempted();
 
   // passes if good
   // 18) An <object> inside an <iframe> sandboxed with 'allow-scripts allow-same-origin'
   // should be able to run scripts and be same origin with this document.
-  // Done by iframe "if_scripts" using a data: load.
+  // Done by iframe "if_scripts", which loads file_iframe_sandbox_srcdoc_allow_scripts.html.
 
   // passes if good, fails if bad
   // 19) Make sure that the parent's document's sandboxing flags are copied when
   // changing the sandbox flags on an iframe inside an iframe.
   // Done in file_iframe_sandbox_a_if17.html and file_iframe_sandbox_a_if18.html
 }
 
 addLoadEvent(doTest);
@@ -189,15 +189,14 @@ addLoadEvent(doTest);
 <p id="display"></p>
 <div id="content">
 <iframe sandbox="" id="if_1" src="file_iframe_sandbox_a_if1.html" height="10" width="10"></iframe>
 <iframe sandbox="allow-scripts" id="if_3" src="file_iframe_sandbox_a_if3.html" height="10" width="10"></iframe>
 <iframe sandbox="allow-scripts allow-same-origin" id="if_5" src="file_iframe_sandbox_a_if5.html" height="10" width="10"></iframe>
 <iframe sandbox="allow-scripts allow-same-origin" id="if_8" src="file_iframe_sandbox_a_if8.html" height="10" width="10"></iframe>
 <iframe sandbox="allow-scripts allow-forms" id="if_10" src="file_iframe_sandbox_a_if10.html" height="10" width="10"></iframe>
 <iframe sandbox="allow-scripts allow-forms" id="if_13" src="file_iframe_sandbox_a_if13.html" height="10" width="10"></iframe>
-<iframe sandbox="allow-same-origin" id="if_no_scripts" src="data:text/html,<object%20data='data:text/html,<script>parent.parent.ok_wrapper(false, &quot;an object inside an iframe sandboxed with only allow-same-origin should not be able to run scripts&quot;)</script>'></object>" height="10" width="10"></iframe>
-<iframe sandbox="allow-scripts allow-same-origin" id="if_scripts" src="data:text/html,<object%20data='data:text/html,<script>parent.parent.ok_wrapper(true, &quot;an object inside an iframe sandboxed with allow-scripts allow-same-origin should be able to run scripts and call functions in the parent of the iframe&quot;)</script>'></object>" height="10" width="10"></iframe>
-<iframe sandbox="allow-same-origin" id="if_19" src="data:text/html,<iframe%20data='data:text/html,<script>parent.parent.ok_wrapper(true, &quot;an object inside an iframe sandboxed with allow-scripts allow-same-origin should be able to run scripts and call functions in the parent of the iframe&quot;)</script>'></object>" height="10" width="10"></iframe>
+<iframe sandbox="allow-same-origin" id="if_no_scripts" srcdoc="<object data='file_iframe_sandbox_srcdoc_no_allow_scripts.html'></object>" height="10" width="10"></iframe>
+<iframe sandbox="allow-scripts allow-same-origin" id="if_scripts" srcdoc="<object data='file_iframe_sandbox_srcdoc_allow_scripts.html'></object>" height="10" width="10"></iframe>
 <iframe sandbox="allow-scripts" id="if_17" src="file_iframe_sandbox_a_if17.html" height="10" width="10"></iframe>
 </div>
 </body>
 </html>
--- a/dom/interfaces/base/nsIDOMWindowUtils.idl
+++ b/dom/interfaces/base/nsIDOMWindowUtils.idl
@@ -915,17 +915,17 @@ interface nsIDOMWindowUtils : nsISupport
    * @param aLeftSize How much to expand left the rectangle
    * @param aIgnoreRootScrollFrame whether or not to ignore the root scroll
    *        frame when retrieving the element. If false, this method returns
    *        null for coordinates outside of the viewport.
    * @param aFlushLayout flushes layout if true. Otherwise, no flush occurs.
    */
   nsIDOMNodeList nodesFromRect(in float aX,
                                in float aY,
-                               in float aTopSize, 
+                               in float aTopSize,
                                in float aRightSize,
                                in float aBottomSize,
                                in float aLeftSize,
                                in boolean aIgnoreRootScrollFrame,
                                in boolean aFlushLayout);
 
 
   /**
@@ -1403,17 +1403,17 @@ interface nsIDOMWindowUtils : nsISupport
   void resumeTimeouts();
 
   /**
    * What type of layer manager the widget associated with this window is
    * using. "Basic" is unaccelerated; other types are accelerated. Throws an
    * error if there is no widget associated with this window.
    */
   readonly attribute AString layerManagerType;
-  
+
   /**
    * True if the layer manager for the widget associated with this window is
    * forwarding layers to a remote compositor, false otherwise. Throws an
    * error if there is no widget associated with this window.
    */
   readonly attribute boolean layerManagerRemote;
 
   /**
@@ -1589,17 +1589,17 @@ interface nsIDOMWindowUtils : nsISupport
 
   /**
    * Checks the layer tree for this window and returns true
    * if all layers have transforms that are translations by integers,
    * no leaf layers overlap, and the union of the leaf layers is exactly
    * the bounds of the window. Always returns true in non-DEBUG builds.
    */
   boolean leafLayersPartitionWindow();
- 
+
   /**
    * Check if any PaintedLayer painting has been done for this element,
    * clears the painted flags if they have.
    */
   boolean checkAndClearPaintedState(in nsIDOMElement aElement);
 
   /**
    * Check whether all display items of the primary frame of aElement have been
@@ -1724,17 +1724,17 @@ interface nsIDOMWindowUtils : nsISupport
 
   const unsigned long AGENT_SHEET = 0;
   const unsigned long USER_SHEET = 1;
   const unsigned long AUTHOR_SHEET = 2;
   /**
    * Synchronously loads a style sheet from |sheetURI| and adds it to the list
    * of additional style sheets of the document.
    *
-   * These additional style sheets are very much like user/agent sheets loaded 
+   * These additional style sheets are very much like user/agent sheets loaded
    * with loadAndRegisterSheet. The only difference is that they are applied only
    * on the document owned by this window.
    *
    * Sheets added via this API take effect immediately on the document.
    */
   void loadSheet(in nsIURI sheetURI, in unsigned long type);
 
   /**
@@ -1747,17 +1747,17 @@ interface nsIDOMWindowUtils : nsISupport
    *
    * Style sheets can be preloaded with nsIStyleSheetService.preloadSheet.
    *
    * Sheets added via this API take effect immediately on the document.
    */
   void addSheet(in nsIPreloadedStyleSheet sheet, in unsigned long type);
 
   /**
-   * Remove the document style sheet at |sheetURI| from the list of additional 
+   * Remove the document style sheet at |sheetURI| from the list of additional
    * style sheets of the document.  The removal takes effect immediately.
    */
   void removeSheet(in nsIURI sheetURI, in unsigned long type);
 
   /**
    * Same as the above method but allows passing the URI as a string.
    */
   void removeSheetUsingURIString(in ACString sheetURI, in unsigned long type);
@@ -1929,16 +1929,21 @@ interface nsIDOMWindowUtils : nsISupport
   void enterChaosMode();
 
   /**
    * Decrease the chaos mode activation level. See enterChaosMode().
    */
   void leaveChaosMode();
 
   /**
+   * Alerts Gecko of a device reset
+   */
+  void triggerDeviceReset();
+
+  /**
    * Returns whether the document's style set's rule processor for the
    * specified level of the cascade is shared by multiple style sets.
    * (Used by tests to ensure that certain optimizations do not regress.)
    *
    * @param aSheetType One of the nsIStyleSheetService.*_SHEET constants.
    */
   bool hasRuleProcessorUsedByMultipleStyleSets(in unsigned long aSheetType);
 
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -5373,8 +5373,19 @@ ContentParent::CanCommunicateWith(Conten
 
 mozilla::ipc::IPCResult
 ContentParent::RecvMaybeReloadPlugins()
 {
   RefPtr<nsPluginHost> pluginHost = nsPluginHost::GetInst();
   pluginHost->ReloadPlugins();
   return IPC_OK();
 }
+
+mozilla::ipc::IPCResult
+ContentParent::RecvDeviceReset()
+{
+  GPUProcessManager* pm = GPUProcessManager::Get();
+  if (pm) {
+    pm->TriggerDeviceResetForTesting();
+  }
+
+  return IPC_OK();
+}
--- a/dom/ipc/ContentParent.h
+++ b/dom/ipc/ContentParent.h
@@ -1056,16 +1056,18 @@ private:
                                                   const uint32_t& aColNumber,
                                                   const uint32_t& aFlags,
                                                   const nsCString& aCategory) override;
 
   virtual mozilla::ipc::IPCResult RecvPrivateDocShellsExist(const bool& aExist) override;
 
   virtual mozilla::ipc::IPCResult RecvFirstIdle() override;
 
+  virtual mozilla::ipc::IPCResult RecvDeviceReset() override;
+
   virtual mozilla::ipc::IPCResult RecvKeywordToURI(const nsCString& aKeyword,
                                                    nsString* aProviderName,
                                                    OptionalIPCStream* aPostData,
                                                    OptionalURIParams* aURI) override;
 
   virtual mozilla::ipc::IPCResult RecvNotifyKeywordSearchLoading(const nsString &aProvider,
                                                                  const nsString &aKeyword) override;
 
--- a/dom/ipc/PContent.ipdl
+++ b/dom/ipc/PContent.ipdl
@@ -834,16 +834,18 @@ parent:
         returns (bool showPassword);
 
     // Notify the parent of the presence or absence of private docshells
     async PrivateDocShellsExist(bool aExist);
 
     // Tell the parent that the child has gone idle for the first time.
     async FirstIdle();
 
+    async DeviceReset();
+
     sync KeywordToURI(nsCString keyword)
         returns (nsString providerName, OptionalIPCStream postData, OptionalURIParams uri);
 
     sync NotifyKeywordSearchLoading(nsString providerName, nsString keyword);
 
     async CopyFavicon(URIParams oldURI, URIParams newURI, Principal aLoadingPrincipal, bool isPrivate);
 
     // Tell the compositor to allocate a layer tree id for nested remote mozbrowsers.
--- a/dom/script/ScriptLoader.cpp
+++ b/dom/script/ScriptLoader.cpp
@@ -52,17 +52,16 @@
 #include "nsContentCreatorFunctions.h"
 #include "nsProxyRelease.h"
 #include "nsSandboxFlags.h"
 #include "nsContentTypeParser.h"
 #include "nsINetworkPredictor.h"
 #include "mozilla/dom/EncodingUtils.h"
 #include "mozilla/ConsoleReportCollector.h"
 
-#include "mozilla/AbstractThread.h"
 #include "mozilla/AsyncEventDispatcher.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/Unused.h"
 #include "nsIScriptError.h"
 #include "nsIOutputStream.h"
 
@@ -626,18 +625,18 @@ ScriptLoader::StartFetchingModuleDepende
   for (size_t i = 0; i < urls.Length(); i++) {
     RefPtr<GenericPromise> childReady =
       StartFetchingModuleAndDependencies(aRequest, urls[i]);
     importsReady.AppendElement(childReady);
   }
 
   // Wait for all imports to become ready.
   RefPtr<GenericPromise::AllPromiseType> allReady =
-    GenericPromise::All(AbstractThread::MainThread(), importsReady);
-  allReady->Then(AbstractThread::MainThread(), __func__, aRequest,
+    GenericPromise::All(GetMainThreadSerialEventTarget(), importsReady);
+  allReady->Then(GetMainThreadSerialEventTarget(), __func__, aRequest,
                  &ModuleLoadRequest::DependenciesLoaded,
                  &ModuleLoadRequest::LoadFailed);
 }
 
 RefPtr<GenericPromise>
 ScriptLoader::StartFetchingModuleAndDependencies(ModuleLoadRequest* aRequest,
                                                  nsIURI* aURI)
 {
@@ -835,17 +834,17 @@ ScriptLoader::StartLoad(ScriptLoadReques
   }
 
   if (aRequest->IsModuleRequest()) {
     // Check whether the module has been fetched or is currently being fetched,
     // and if so wait for it.
     ModuleLoadRequest* request = aRequest->AsModuleRequest();
     if (ModuleMapContainsModule(request)) {
       WaitForModuleFetch(request)
-        ->Then(AbstractThread::MainThread(), __func__, request,
+        ->Then(GetMainThreadSerialEventTarget(), __func__, request,
                &ModuleLoadRequest::ModuleLoaded,
                &ModuleLoadRequest::LoadFailed);
       return NS_OK;
     }
 
     // Otherwise put the URL in the module map and mark it as fetching.
     SetModuleFetchStarted(request);
   }
--- a/dom/security/nsContentSecurityManager.cpp
+++ b/dom/security/nsContentSecurityManager.cpp
@@ -5,16 +5,18 @@
 #include "nsILoadInfo.h"
 #include "nsContentUtils.h"
 #include "nsCORSListenerProxy.h"
 #include "nsIStreamListener.h"
 #include "nsIDocument.h"
 #include "nsMixedContentBlocker.h"
 #include "nsCDefaultURIFixup.h"
 #include "nsIURIFixup.h"
+#include "nsIImageLoadingContent.h"
+
 #include "mozilla/dom/Element.h"
 
 NS_IMPL_ISUPPORTS(nsContentSecurityManager,
                   nsIContentSecurityManager,
                   nsIChannelEventSink)
 
 static nsresult
 ValidateSecurityFlags(nsILoadInfo* aLoadInfo)
@@ -620,16 +622,18 @@ nsContentSecurityManager::CheckChannel(n
       loadInfo->MaybeIncreaseTainting(LoadTainting::Opaque);
     }
     // Please note that DoCheckLoadURIChecks should only be enforced for
     // cross origin requests. If the flag SEC_REQUIRE_CORS_DATA_INHERITS is set
     // within the loadInfo, then then CheckLoadURIWithPrincipal is performed
     // within nsCorsListenerProxy
     rv = DoCheckLoadURIChecks(uri, loadInfo);
     NS_ENSURE_SUCCESS(rv, rv);
+    // TODO: Bug 1371237
+    // consider calling SetBlockedRequest in nsContentSecurityManager::CheckChannel
   }
 
   return NS_OK;
 }
 
 // ==== nsIContentSecurityManager implementation =====
 
 NS_IMETHODIMP
--- a/dom/u2f/U2F.cpp
+++ b/dom/u2f/U2F.cpp
@@ -1,28 +1,28 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "hasht.h"
-#include "mozilla/AbstractThread.h"
 #include "mozilla/dom/CallbackFunction.h"
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/dom/CryptoBuffer.h"
 #include "mozilla/dom/NSSU2FTokenRemote.h"
 #include "mozilla/dom/U2F.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/ReentrantMonitor.h"
 #include "mozilla/SizePrintfMacros.h"
 #include "nsContentUtils.h"
 #include "nsINSSU2FToken.h"
 #include "nsNetCID.h"
 #include "nsNSSComponent.h"
+#include "nsThreadUtils.h"
 #include "nsURLParsers.h"
 #include "nsXPCOMCIDInternal.h"
 #include "pk11pub.h"
 
 using mozilla::dom::ContentChild;
 
 namespace mozilla {
 namespace dom {
@@ -160,66 +160,66 @@ U2FStatus::GetResponse()
 {
   ReentrantMonitorAutoEnter mon(mReentrantMonitor);
   MOZ_ASSERT(mIsStopped);
   return mResponse;
 }
 
 U2FTask::U2FTask(const nsAString& aOrigin, const nsAString& aAppId,
                  const Authenticator& aAuthenticator,
-                 AbstractThread* aMainThread)
+                 nsISerialEventTarget* aEventTarget)
   : mOrigin(aOrigin)
   , mAppId(aAppId)
   , mAuthenticator(aAuthenticator)
-  , mAbstractMainThread(aMainThread)
+  , mEventTarget(aEventTarget)
 {}
 
 U2FTask::~U2FTask()
 {}
 
 RefPtr<U2FPromise>
 U2FTask::Execute()
 {
   RefPtr<U2FPromise> p = mPromise.Ensure(__func__);
 
   nsCOMPtr<nsIRunnable> r(this);
 
   // TODO: Use a thread pool here, but we have to solve the PContentChild issues
   // of being in a worker thread.
-  mAbstractMainThread->Dispatch(r.forget());
+  mEventTarget->Dispatch(r.forget());
   return p;
 }
 
 U2FPrepTask::U2FPrepTask(const Authenticator& aAuthenticator,
-                         AbstractThread* aMainThread)
+                         nsISerialEventTarget* aEventTarget)
   : mAuthenticator(aAuthenticator)
-  , mAbstractMainThread(aMainThread)
+  , mEventTarget(aEventTarget)
 {}
 
 U2FPrepTask::~U2FPrepTask()
 {}
 
 RefPtr<U2FPrepPromise>
 U2FPrepTask::Execute()
 {
   RefPtr<U2FPrepPromise> p = mPromise.Ensure(__func__);
 
   nsCOMPtr<nsIRunnable> r(this);
 
   // TODO: Use a thread pool here, but we have to solve the PContentChild issues
   // of being in a worker thread.
-  mAbstractMainThread->Dispatch(r.forget());
+  mEventTarget->Dispatch(r.forget());
   return p;
 }
 
 U2FIsRegisteredTask::U2FIsRegisteredTask(const Authenticator& aAuthenticator,
                                          const LocalRegisteredKey& aRegisteredKey,
                                          const CryptoBuffer& aAppParam,
-                                         AbstractThread* aMainThread)
-  : U2FPrepTask(aAuthenticator, aMainThread)
+                                         nsISerialEventTarget* aEventTarget)
+  : U2FPrepTask(aAuthenticator, aEventTarget)
   , mRegisteredKey(aRegisteredKey)
   , mAppParam(aAppParam)
 {}
 
 U2FIsRegisteredTask::~U2FIsRegisteredTask()
 {}
 
 NS_IMETHODIMP
@@ -268,18 +268,18 @@ U2FIsRegisteredTask::Run()
 }
 
 U2FRegisterTask::U2FRegisterTask(const nsAString& aOrigin,
                                  const nsAString& aAppId,
                                  const Authenticator& aAuthenticator,
                                  const CryptoBuffer& aAppParam,
                                  const CryptoBuffer& aChallengeParam,
                                  const LocalRegisterRequest& aRegisterEntry,
-                                 AbstractThread* aMainThread)
-  : U2FTask(aOrigin, aAppId, aAuthenticator, aMainThread)
+                                 nsISerialEventTarget* aEventTarget)
+  : U2FTask(aOrigin, aAppId, aAuthenticator, aEventTarget)
   , mAppParam(aAppParam)
   , mChallengeParam(aChallengeParam)
   , mRegisterEntry(aRegisterEntry)
 {}
 
 U2FRegisterTask::~U2FRegisterTask()
 {}
 
@@ -348,18 +348,18 @@ U2FRegisterTask::Run()
 U2FSignTask::U2FSignTask(const nsAString& aOrigin,
                          const nsAString& aAppId,
                          const nsAString& aVersion,
                          const Authenticator& aAuthenticator,
                          const CryptoBuffer& aAppParam,
                          const CryptoBuffer& aChallengeParam,
                          const CryptoBuffer& aClientData,
                          const CryptoBuffer& aKeyHandle,
-                         AbstractThread* aMainThread)
-  : U2FTask(aOrigin, aAppId, aAuthenticator, aMainThread)
+                         nsISerialEventTarget* aEventTarget)
+  : U2FTask(aOrigin, aAppId, aAuthenticator, aEventTarget)
   , mVersion(aVersion)
   , mAppParam(aAppParam)
   , mChallengeParam(aChallengeParam)
   , mClientData(aClientData)
   , mKeyHandle(aKeyHandle)
 {}
 
 U2FSignTask::~U2FSignTask()
@@ -438,20 +438,20 @@ U2FSignTask::Run()
   if (NS_WARN_IF(!response.ToJSON(responseStr))) {
     return NS_ERROR_FAILURE;
   }
   mPromise.Resolve(responseStr, __func__);
   return NS_OK;
 }
 
 U2FRunnable::U2FRunnable(const nsAString& aOrigin, const nsAString& aAppId,
-                         AbstractThread* aMainThread)
+                         nsISerialEventTarget* aEventTarget)
   : mOrigin(aOrigin)
   , mAppId(aAppId)
-  , mAbstractMainThread(aMainThread)
+  , mEventTarget(aEventTarget)
 {}
 
 U2FRunnable::~U2FRunnable()
 {}
 
 // EvaluateAppIDAndRunTask determines whether the supplied FIDO AppID is valid for
 // the current FacetID, e.g., the current origin.
 // See https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-appid-and-facets.html
@@ -524,18 +524,18 @@ U2FRunnable::EvaluateAppID()
 }
 
 U2FRegisterRunnable::U2FRegisterRunnable(const nsAString& aOrigin,
                                          const nsAString& aAppId,
                                          const Sequence<RegisterRequest>& aRegisterRequests,
                                          const Sequence<RegisteredKey>& aRegisteredKeys,
                                          const Sequence<Authenticator>& aAuthenticators,
                                          U2FRegisterCallback* aCallback,
-                                         AbstractThread* aMainThread)
-  : U2FRunnable(aOrigin, aAppId, aMainThread)
+                                         nsISerialEventTarget* aEventTarget)
+  : U2FRunnable(aOrigin, aAppId, aEventTarget)
   , mAuthenticators(aAuthenticators)
   // U2FRegisterCallback does not support threadsafe refcounting, and must be
   // used and destroyed on main.
   , mCallback(new nsMainThreadPtrHolder<U2FRegisterCallback>(aCallback))
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   // The WebIDL dictionary types RegisterRequest and RegisteredKey cannot
@@ -641,25 +641,25 @@ U2FRegisterRunnable::Run()
   }
 
   // First, we must determine if any of the RegisteredKeys are already
   // registered, e.g., in the whitelist.
   for (LocalRegisteredKey key : mRegisteredKeys) {
     nsTArray<RefPtr<U2FPrepPromise>> prepPromiseList;
     for (const Authenticator& token : mAuthenticators) {
       RefPtr<U2FIsRegisteredTask> compTask =
-        new U2FIsRegisteredTask(token, key, appParam, mAbstractMainThread);
+        new U2FIsRegisteredTask(token, key, appParam, mEventTarget);
       prepPromiseList.AppendElement(compTask->Execute());
     }
 
     // Treat each call to Promise::All as a work unit, as it completes together
     status->WaitGroupAdd();
 
-    U2FPrepPromise::All(mAbstractMainThread, prepPromiseList)
-    ->Then(mAbstractMainThread, __func__,
+    U2FPrepPromise::All(mEventTarget, prepPromiseList)
+    ->Then(mEventTarget, __func__,
       [&status] (const nsTArray<Authenticator>& aTokens) {
         MOZ_LOG(gU2FLog, LogLevel::Debug,
                 ("ALL: None of the RegisteredKeys were recognized. n=%" PRIuSIZE,
                  aTokens.Length()));
 
         status->WaitGroupDone();
       },
       [&status] (ErrorCode aErrorCode) {
@@ -670,17 +670,17 @@ U2FRegisterRunnable::Run()
 
   // Wait for all the IsRegistered tasks to complete
   status->WaitGroupWait();
 
   // Check to see whether we're supposed to stop, because one of the keys was
   // recognized.
   if (status->IsStopped()) {
     status->WaitGroupAdd();
-    mAbstractMainThread->Dispatch(NS_NewRunnableFunction(
+    mEventTarget->Dispatch(NS_NewRunnableFunction(
       [&status, this] () {
         RegisterResponse response;
         response.mErrorCode.Construct(
             static_cast<uint32_t>(status->GetErrorCode()));
         SendResponse(response);
         status->WaitGroupDone();
       }
     ));
@@ -704,20 +704,20 @@ U2FRegisterRunnable::Run()
       continue;
     }
 
     for (const Authenticator& token : mAuthenticators) {
       RefPtr<U2FRegisterTask> registerTask = new U2FRegisterTask(mOrigin, mAppId,
                                                                  token, appParam,
                                                                  challengeParam,
                                                                  req,
-                                                                 mAbstractMainThread);
+                                                                 mEventTarget);
       status->WaitGroupAdd();
 
-      registerTask->Execute()->Then(mAbstractMainThread, __func__,
+      registerTask->Execute()->Then(mEventTarget, __func__,
         [&status] (nsString aResponse) {
           if (!status->IsStopped()) {
             status->Stop(ErrorCode::OK, aResponse);
           }
           status->WaitGroupDone();
         },
         [&status] (ErrorCode aErrorCode) {
           // Ignore the failing error code, as we only want the first success.
@@ -733,17 +733,17 @@ U2FRegisterRunnable::Run()
 
   // If none of the tasks completed, then nothing could satisfy.
   if (!status->IsStopped()) {
     status->Stop(ErrorCode::BAD_REQUEST);
   }
 
   // Transmit back to the JS engine from the Main Thread
   status->WaitGroupAdd();
-  mAbstractMainThread->Dispatch(NS_NewRunnableFunction(
+  mEventTarget->Dispatch(NS_NewRunnableFunction(
     [&status, this] () {
       RegisterResponse response;
       if (status->GetErrorCode() == ErrorCode::OK) {
         response.Init(status->GetResponse());
       } else {
         response.mErrorCode.Construct(
             static_cast<uint32_t>(status->GetErrorCode()));
       }
@@ -758,18 +758,18 @@ U2FRegisterRunnable::Run()
 }
 
 U2FSignRunnable::U2FSignRunnable(const nsAString& aOrigin,
                                  const nsAString& aAppId,
                                  const nsAString& aChallenge,
                                  const Sequence<RegisteredKey>& aRegisteredKeys,
                                  const Sequence<Authenticator>& aAuthenticators,
                                  U2FSignCallback* aCallback,
-                                 AbstractThread* aMainThread)
-  : U2FRunnable(aOrigin, aAppId, aMainThread)
+                                 nsISerialEventTarget* aEventTarget)
+  : U2FRunnable(aOrigin, aAppId, aEventTarget)
   , mAuthenticators(aAuthenticators)
   // U2FSignCallback does not support threadsafe refcounting, and must be used
   // and destroyed on main.
   , mCallback(new nsMainThreadPtrHolder<U2FSignCallback>(aCallback))
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   // Convert WebIDL objects to generic structs to pass between threads
@@ -886,20 +886,20 @@ U2FSignRunnable::Run()
     // We ignore mTransports, as it is intended to be used for sorting the
     // available devices by preference, but is not an exclusion factor.
 
     for (const Authenticator& token : mAuthenticators) {
       RefPtr<U2FSignTask> signTask = new U2FSignTask(mOrigin, mAppId,
                                                      key.mVersion, token,
                                                      appParam, challengeParam,
                                                      mClientData, keyHandle,
-                                                     mAbstractMainThread);
+                                                     mEventTarget);
       status->WaitGroupAdd();
 
-      signTask->Execute()->Then(mAbstractMainThread, __func__,
+      signTask->Execute()->Then(mEventTarget, __func__,
         [&status] (nsString aResponse) {
           if (!status->IsStopped()) {
             status->Stop(ErrorCode::OK, aResponse);
           }
           status->WaitGroupDone();
         },
         [&status] (ErrorCode aErrorCode) {
           // Ignore the failing error code, as we only want the first success.
@@ -915,17 +915,17 @@ U2FSignRunnable::Run()
 
   // If none of the tasks completed, then nothing could satisfy.
   if (!status->IsStopped()) {
     status->Stop(ErrorCode::DEVICE_INELIGIBLE);
   }
 
   // Transmit back to the JS engine from the Main Thread
   status->WaitGroupAdd();
-  mAbstractMainThread->Dispatch(NS_NewRunnableFunction(
+  mEventTarget->Dispatch(NS_NewRunnableFunction(
     [&status, this] () {
       SignResponse response;
       if (status->GetErrorCode() == ErrorCode::OK) {
         response.Init(status->GetResponse());
       } else {
         response.mErrorCode.Construct(
           static_cast<uint32_t>(status->GetErrorCode()));
       }
@@ -1002,17 +1002,17 @@ U2F::Init(nsPIDOMWindowInner* aParent, E
   if (Preferences::GetBool(PREF_U2F_SOFTTOKEN_ENABLED)) {
     if (!mAuthenticators.AppendElement(new NSSU2FTokenRemote(),
                                        mozilla::fallible)) {
       aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
       return;
     }
   }
 
-  mAbstractMainThread = doc->AbstractMainThreadFor(TaskCategory::Other);
+  mEventTarget = doc->EventTargetFor(TaskCategory::Other);
 
   mInitialized = true;
 }
 
 void
 U2F::Register(const nsAString& aAppId,
               const Sequence<RegisterRequest>& aRegisterRequests,
               const Sequence<RegisteredKey>& aRegisteredKeys,
@@ -1028,17 +1028,17 @@ U2F::Register(const nsAString& aAppId,
   }
 
   RefPtr<SharedThreadPool> pool = SharedThreadPool::Get(kPoolName);
   RefPtr<U2FRegisterRunnable> task = new U2FRegisterRunnable(mOrigin, aAppId,
                                                              aRegisterRequests,
                                                              aRegisteredKeys,
                                                              mAuthenticators,
                                                              &aCallback,
-                                                             mAbstractMainThread);
+                                                             mEventTarget);
   pool->Dispatch(task.forget(), NS_DISPATCH_NORMAL);
 }
 
 void
 U2F::Sign(const nsAString& aAppId,
           const nsAString& aChallenge,
           const Sequence<RegisteredKey>& aRegisteredKeys,
           U2FSignCallback& aCallback,
@@ -1051,14 +1051,14 @@ U2F::Sign(const nsAString& aAppId,
     aRv.Throw(NS_ERROR_NOT_AVAILABLE);
     return;
   }
 
   RefPtr<SharedThreadPool> pool = SharedThreadPool::Get(kPoolName);
   RefPtr<U2FSignRunnable> task = new U2FSignRunnable(mOrigin, aAppId, aChallenge,
                                                      aRegisteredKeys,
                                                      mAuthenticators, &aCallback,
-                                                     mAbstractMainThread);
+                                                     mEventTarget);
   pool->Dispatch(task.forget(), NS_DISPATCH_NORMAL);
 }
 
 } // namespace dom
 } // namespace mozilla
--- a/dom/u2f/U2F.h
+++ b/dom/u2f/U2F.h
@@ -21,20 +21,19 @@
 #include "nsIU2FToken.h"
 #include "nsNSSShutDown.h"
 #include "nsPIDOMWindow.h"
 #include "nsProxyRelease.h"
 #include "nsWrapperCache.h"
 
 #include "U2FAuthenticator.h"
 
-namespace mozilla {
+class nsISerialEventTarget;
 
-class AbstractThread;
-
+namespace mozilla {
 namespace dom {
 
 class U2FRegisterCallback;
 class U2FSignCallback;
 
 // Defined in U2FBinding.h by the U2F.webidl; their use requires a JSContext.
 struct RegisterRequest;
 struct RegisteredKey;
@@ -62,60 +61,60 @@ typedef MozPromise<Authenticator, ErrorC
 
 // U2FPrepTasks return lists of Authenticators that are OK to
 // proceed; they're useful for culling incompatible Authenticators.
 // Currently, only IsRegistered is supported.
 class U2FPrepTask : public Runnable
 {
 public:
   explicit U2FPrepTask(const Authenticator& aAuthenticator,
-                       AbstractThread* aMainThread);
+                       nsISerialEventTarget* aEventTarget);
 
   RefPtr<U2FPrepPromise> Execute();
 
 protected:
   virtual ~U2FPrepTask();
 
   Authenticator mAuthenticator;
   MozPromiseHolder<U2FPrepPromise> mPromise;
-  const RefPtr<AbstractThread> mAbstractMainThread;
+  const nsCOMPtr<nsISerialEventTarget> mEventTarget;
 };
 
 // Determine whether the provided Authenticator already knows
 // of the provided Registered Key.
 class U2FIsRegisteredTask final : public U2FPrepTask
 {
 public:
   U2FIsRegisteredTask(const Authenticator& aAuthenticator,
                       const LocalRegisteredKey& aRegisteredKey,
                       const CryptoBuffer& aAppParam,
-                      AbstractThread* aMainThread);
+                      nsISerialEventTarget* aEventTarget);
 
   NS_DECL_NSIRUNNABLE
 private:
   ~U2FIsRegisteredTask();
 
   LocalRegisteredKey mRegisteredKey;
   CryptoBuffer mAppParam;
 };
 
 class U2FTask : public Runnable
 {
 public:
   U2FTask(const nsAString& aOrigin,
           const nsAString& aAppId,
           const Authenticator& aAuthenticator,
-          AbstractThread* aMainThread);
+          nsISerialEventTarget* aEventTarget);
 
   RefPtr<U2FPromise> Execute();
 
   nsString mOrigin;
   nsString mAppId;
   Authenticator mAuthenticator;
-  const RefPtr<AbstractThread> mAbstractMainThread;
+  const nsCOMPtr<nsISerialEventTarget> mEventTarget;
 
 protected:
   virtual ~U2FTask();
 
   MozPromiseHolder<U2FPromise> mPromise;
 };
 
 // Use the provided Authenticator to Register a new scoped credential
@@ -124,17 +123,17 @@ class U2FRegisterTask final : public U2F
 {
 public:
   U2FRegisterTask(const nsAString& aOrigin,
                   const nsAString& aAppId,
                   const Authenticator& aAuthenticator,
                   const CryptoBuffer& aAppParam,
                   const CryptoBuffer& aChallengeParam,
                   const LocalRegisterRequest& aRegisterEntry,
-                  AbstractThread* aMainThread);
+                  nsISerialEventTarget* aEventTarget);
 
   NS_DECL_NSIRUNNABLE
 private:
   ~U2FRegisterTask();
 
   CryptoBuffer mAppParam;
   CryptoBuffer mChallengeParam;
   LocalRegisterRequest mRegisterEntry;
@@ -148,17 +147,17 @@ public:
   U2FSignTask(const nsAString& aOrigin,
               const nsAString& aAppId,
               const nsAString& aVersion,
               const Authenticator& aAuthenticator,
               const CryptoBuffer& aAppParam,
               const CryptoBuffer& aChallengeParam,
               const CryptoBuffer& aClientData,
               const CryptoBuffer& aKeyHandle,
-              AbstractThread* aMainThread);
+              nsISerialEventTarget* aEventTarget);
 
   NS_DECL_NSIRUNNABLE
 private:
   ~U2FSignTask();
 
   nsString mVersion;
   CryptoBuffer mAppParam;
   CryptoBuffer mChallengeParam;
@@ -198,43 +197,43 @@ private:
 
 // U2FRunnables run to completion, performing a single U2F operation such as
 // registering, or signing.
 class U2FRunnable : public Runnable
                   , public nsNSSShutDownObject
 {
 public:
   U2FRunnable(const nsAString& aOrigin, const nsAString& aAppId,
-              AbstractThread* aMainThread);
+              nsISerialEventTarget* aEventTarget);
 
   // No NSS resources to release.
   virtual
   void virtualDestroyNSSReference() override {};
 
 protected:
   virtual ~U2FRunnable();
   ErrorCode EvaluateAppID();
 
   nsString mOrigin;
   nsString mAppId;
-  const RefPtr<AbstractThread> mAbstractMainThread;
+  const nsCOMPtr<nsISerialEventTarget> mEventTarget;
 };
 
 // This U2FRunnable completes a single application-requested U2F Register
 // operation.
 class U2FRegisterRunnable : public U2FRunnable
 {
 public:
   U2FRegisterRunnable(const nsAString& aOrigin,
                       const nsAString& aAppId,
                       const Sequence<RegisterRequest>& aRegisterRequests,
                       const Sequence<RegisteredKey>& aRegisteredKeys,
                       const Sequence<Authenticator>& aAuthenticators,
                       U2FRegisterCallback* aCallback,
-                      AbstractThread* aMainThread);
+                      nsISerialEventTarget* aEventTarget);
 
   void SendResponse(const RegisterResponse& aResponse);
   void SetTimeout(const int32_t aTimeoutMillis);
 
   NS_DECL_NSIRUNNABLE
 
 private:
   ~U2FRegisterRunnable();
@@ -251,17 +250,17 @@ class U2FSignRunnable : public U2FRunnab
 {
 public:
   U2FSignRunnable(const nsAString& aOrigin,
                   const nsAString& aAppId,
                   const nsAString& aChallenge,
                   const Sequence<RegisteredKey>& aRegisteredKeys,
                   const Sequence<Authenticator>& aAuthenticators,
                   U2FSignCallback* aCallback,
-                  AbstractThread* aMainThread);
+                  nsISerialEventTarget* aEventTarget);
 
   void SendResponse(const SignResponse& aResponse);
   void SetTimeout(const int32_t aTimeoutMillis);
 
   NS_DECL_NSIRUNNABLE
 
 private:
   ~U2FSignRunnable();
@@ -317,17 +316,17 @@ public:
   virtual
   void virtualDestroyNSSReference() override {};
 
 private:
   nsCOMPtr<nsPIDOMWindowInner> mParent;
   nsString mOrigin;
   Sequence<Authenticator> mAuthenticators;
   bool mInitialized;
-  RefPtr<AbstractThread> mAbstractMainThread;
+  nsCOMPtr<nsISerialEventTarget> mEventTarget;
 
   ~U2F();
 };
 
 } // namespace dom
 } // namespace mozilla
 
 #endif // mozilla_dom_U2F_h
--- a/dom/webauthn/U2FSoftTokenManager.cpp
+++ b/dom/webauthn/U2FSoftTokenManager.cpp
@@ -1,20 +1,20 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/dom/U2FSoftTokenManager.h"
 #include "CryptoBuffer.h"
-#include "mozilla/AbstractThread.h"
 #include "mozilla/Base64.h"
 #include "mozilla/Casting.h"
 #include "nsNSSComponent.h"
+#include "nsThreadUtils.h"
 #include "pk11pub.h"
 #include "prerror.h"
 #include "secerr.h"
 #include "WebCryptoCommon.h"
 
 #define PREF_U2F_NSSTOKEN_COUNTER "security.webauth.softtoken_counter"
 
 namespace mozilla {
@@ -228,17 +228,17 @@ U2FSoftTokenManager::GetOrCreateWrapping
     MOZ_LOG(gNSSTokenLog, LogLevel::Warning,
             ("Failed to set nickname, NSS error #%d", PORT_GetError()));
     return NS_ERROR_FAILURE;
   }
 
   MOZ_LOG(gNSSTokenLog, LogLevel::Debug,
           ("Key stored, nickname set to %s.", mSecretNickname.get()));
 
-  AbstractThread::MainThread()->Dispatch(NS_NewRunnableFunction(
+  GetMainThreadEventTarget()->Dispatch(NS_NewRunnableFunction(
                                            [] () {
                                              MOZ_ASSERT(NS_IsMainThread());
                                              Preferences::SetUint(PREF_U2F_NSSTOKEN_COUNTER, 0);
                                            }));
 
   return NS_OK;
 }
 
@@ -791,17 +791,17 @@ U2FSoftTokenManager::Sign(const nsTArray
   // Increment the counter and turn it into a SECItem
   mCounter += 1;
   ScopedAutoSECItem counterItem(4);
   counterItem.data[0] = (mCounter >> 24) & 0xFF;
   counterItem.data[1] = (mCounter >> 16) & 0xFF;
   counterItem.data[2] = (mCounter >>  8) & 0xFF;
   counterItem.data[3] = (mCounter >>  0) & 0xFF;
   uint32_t counter = mCounter;
-  AbstractThread::MainThread()->Dispatch(NS_NewRunnableFunction(
+  GetMainThreadEventTarget()->Dispatch(NS_NewRunnableFunction(
                                            [counter] () {
                                              MOZ_ASSERT(NS_IsMainThread());
                                              Preferences::SetUint(PREF_U2F_NSSTOKEN_COUNTER, counter);
                                            }));
 
   // Compute the signature
   mozilla::dom::CryptoBuffer signedDataBuf;
   if (NS_WARN_IF(!signedDataBuf.SetCapacity(1 + 4 + (2 * kParamLen), mozilla::fallible))) {
--- a/dom/webauthn/WebAuthnManager.cpp
+++ b/dom/webauthn/WebAuthnManager.cpp
@@ -2,27 +2,27 @@
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "hasht.h"
 #include "nsNetCID.h"
 #include "nsICryptoHash.h"
-#include "mozilla/AbstractThread.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/dom/AuthenticatorAttestationResponse.h"
 #include "mozilla/dom/Promise.h"
 #include "mozilla/dom/WebAuthnManager.h"
 #include "mozilla/dom/WebAuthnUtil.h"
 #include "mozilla/dom/PWebAuthnTransaction.h"
 #include "mozilla/dom/WebAuthnTransactionChild.h"
 #include "mozilla/dom/WebCryptoCommon.h"
 #include "mozilla/ipc/PBackgroundChild.h"
 #include "mozilla/ipc/BackgroundChild.h"
+#include "nsThreadUtils.h"
 
 using namespace mozilla::ipc;
 
 namespace mozilla {
 namespace dom {
 
 /***********************************************************************
  * Statics
@@ -417,17 +417,17 @@ WebAuthnManager::MakeCredential(nsPIDOMW
   nsTArray<WebAuthnExtension> extensions;
 
   WebAuthnTransactionInfo info(rpIdHash,
                                clientDataHash,
                                adjustedTimeout,
                                excludeList,
                                extensions);
   RefPtr<MozPromise<nsresult, nsresult, false>> p = GetOrCreateBackgroundActor();
-  p->Then(AbstractThread::MainThread(), __func__,
+  p->Then(GetMainThreadSerialEventTarget(), __func__,
           []() {
             WebAuthnManager* mgr = WebAuthnManager::Get();
             if (!mgr) {
               return;
             }
             mgr->StartRegister();
           },
           []() {
@@ -583,17 +583,17 @@ WebAuthnManager::GetAssertion(nsPIDOMWin
   nsTArray<WebAuthnExtension> extensions;
 
   WebAuthnTransactionInfo info(rpIdHash,
                                clientDataHash,
                                adjustedTimeout,
                                allowList,
                                extensions);
   RefPtr<MozPromise<nsresult, nsresult, false>> p = GetOrCreateBackgroundActor();
-  p->Then(AbstractThread::MainThread(), __func__,
+  p->Then(GetMainThreadSerialEventTarget(), __func__,
           []() {
             WebAuthnManager* mgr = WebAuthnManager::Get();
             if (!mgr) {
               return;
             }
             mgr->StartSign();
           },
           []() {
--- a/dom/workers/ServiceWorkerUpdaterChild.cpp
+++ b/dom/workers/ServiceWorkerUpdaterChild.cpp
@@ -1,16 +1,16 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ServiceWorkerUpdaterChild.h"
-#include "mozilla/AbstractThread.h"
+#include "nsThreadUtils.h"
 
 namespace mozilla {
 namespace dom {
 namespace workers {
 
 ServiceWorkerUpdaterChild::ServiceWorkerUpdaterChild(GenericPromise* aPromise,
                                                      CancelableRunnable* aSuccessRunnable,
                                                      CancelableRunnable* aFailureRunnable)
@@ -19,17 +19,17 @@ ServiceWorkerUpdaterChild::ServiceWorker
 {
   // TODO: remove the main thread restriction after fixing bug 1364821.
   MOZ_ASSERT(NS_IsMainThread());
 
   MOZ_ASSERT(aPromise);
   MOZ_ASSERT(aSuccessRunnable);
   MOZ_ASSERT(aFailureRunnable);
 
-  aPromise->Then(AbstractThread::MainThread(), __func__,
+  aPromise->Then(GetMainThreadSerialEventTarget(), __func__,
     [this]() {
       mPromiseHolder.Complete();
       Unused << Send__delete__(this);
   }).Track(mPromiseHolder);
 }
 
 mozilla::ipc::IPCResult
 ServiceWorkerUpdaterChild::RecvProceed(const bool& aAllowed)
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -4464,33 +4464,33 @@ WorkerPrivate::WorkerPrivate(WorkerPriva
     mOnLine = aParent->OnLine();
   }
   else {
     AssertIsOnMainThread();
     RuntimeService::GetDefaultPreferences(mPreferences);
     mOnLine = !NS_IsOffline();
   }
 
-  nsCOMPtr<nsIEventTarget> target;
+  nsCOMPtr<nsISerialEventTarget> target;
 
   // A child worker just inherits the parent workers ThrottledEventQueue
   // and main thread target for now.  This is mainly due to the restriction
   // that ThrottledEventQueue can only be created on the main thread at the
   // moment.
   if (aParent) {
     mMainThreadThrottledEventQueue = aParent->mMainThreadThrottledEventQueue;
     mMainThreadEventTarget = aParent->mMainThreadEventTarget;
     return;
   }
 
   MOZ_ASSERT(NS_IsMainThread());
   target = GetWindow() ? GetWindow()->EventTargetFor(TaskCategory::Worker) : nullptr;
 
   if (!target) {
-    target = GetMainThreadEventTarget();
+    target = GetMainThreadSerialEventTarget();
     MOZ_DIAGNOSTIC_ASSERT(target);
   }
 
   // Throttle events to the main thread using a ThrottledEventQueue specific to
   // this worker thread.  This may return nullptr during shutdown.
   mMainThreadThrottledEventQueue = ThrottledEventQueue::Create(target);
 
   // If we were able to creat the throttled event queue, then use it for
--- a/editor/composer/nsEditorSpellCheck.cpp
+++ b/editor/composer/nsEditorSpellCheck.cpp
@@ -1,17 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=2 sts=2 sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include <stdlib.h>                     // for getenv
 
-#include "mozilla/AbstractThread.h"     // for AbstractThread
 #include "mozilla/Attributes.h"         // for final
 #include "mozilla/Preferences.h"        // for Preferences
 #include "mozilla/dom/Element.h"        // for Element
 #include "mozilla/dom/Selection.h"
 #include "mozilla/intl/LocaleService.h" // for retrieving app locale
 #include "mozilla/mozalloc.h"           // for operator delete, etc
 #include "nsAString.h"                  // for nsAString::IsEmpty, etc
 #include "nsComponentManagerUtils.h"    // for do_CreateInstance
@@ -30,16 +29,17 @@
 #include "nsILoadContext.h"
 #include "nsISelection.h"               // for nsISelection
 #include "nsISpellChecker.h"            // for nsISpellChecker, etc
 #include "nsISupportsBase.h"            // for nsISupports
 #include "nsISupportsUtils.h"           // for NS_ADDREF
 #include "nsITextServicesDocument.h"    // for nsITextServicesDocument
 #include "nsITextServicesFilter.h"      // for nsITextServicesFilter
 #include "nsIURI.h"                     // for nsIURI
+#include "nsThreadUtils.h"              // for GetMainThreadSerialEventTarget
 #include "nsVariant.h"                  // for nsIWritableVariant, etc
 #include "nsLiteralString.h"            // for NS_LITERAL_STRING, etc
 #include "nsMemory.h"                   // for nsMemory
 #include "nsRange.h"
 #include "nsReadableUtils.h"            // for ToNewUnicode, EmptyString, etc
 #include "nsServiceManagerUtils.h"      // for do_GetService
 #include "nsString.h"                   // for nsAutoString, nsString, etc
 #include "nsStringFwd.h"                // for nsAFlatString
@@ -837,17 +837,17 @@ nsEditorSpellCheck::DictionaryFetched(Di
     dictName.Assign(aFetcher->mDictionary);
     if (!dictName.IsEmpty()) {
       AutoTArray<nsString, 1> tryDictList;
       BuildDictionaryList(dictName, dictList, DICT_NORMAL_COMPARE, tryDictList);
 
       RefPtr<nsEditorSpellCheck> self = this;
       RefPtr<DictionaryFetcher> fetcher = aFetcher;
       mSpellChecker->SetCurrentDictionaryFromList(tryDictList)->Then(
-        AbstractThread::MainThread(),
+        GetMainThreadSerialEventTarget(),
         __func__,
         [self, fetcher]() {
 #ifdef DEBUG_DICT
           printf("***** Assigned from content preferences |%s|\n",
                  NS_ConvertUTF16toUTF8(dictName).get());
 #endif
           // We take an early exit here, so let's not forget to clear the word
           // list.
@@ -1020,17 +1020,17 @@ nsEditorSpellCheck::SetFallbackDictionar
     printf("***** Trying first of list |%s|\n",
            NS_ConvertUTF16toUTF8(dictList[0]).get());
 #endif
   }
 
   RefPtr<nsEditorSpellCheck> self = this;
   RefPtr<DictionaryFetcher> fetcher = aFetcher;
   mSpellChecker->SetCurrentDictionaryFromList(tryDictList)->Then(
-    AbstractThread::MainThread(),
+    GetMainThreadSerialEventTarget(),
     __func__,
     [self, fetcher]() {
       // If an error was thrown while setting the dictionary, just
       // fail silently so that the spellchecker dialog is allowed to come
       // up. The user can manually reset the language to their choice on
       // the dialog if it is wrong.
       self->DeleteSuggestedWordList();
       self->EndUpdateDictionary();
--- a/gfx/ipc/GPUChild.cpp
+++ b/gfx/ipc/GPUChild.cpp
@@ -197,17 +197,17 @@ GPUChild::RecvRecordChildEvents(nsTArray
   TelemetryIPC::RecordChildEvents(Telemetry::ProcessID::Gpu, aEvents);
   return IPC_OK();
 }
 
 mozilla::ipc::IPCResult
 GPUChild::RecvNotifyDeviceReset(const GPUDeviceData& aData)
 {
   gfxPlatform::GetPlatform()->ImportGPUDeviceData(aData);
-  mHost->mListener->OnProcessDeviceReset(mHost);
+  mHost->mListener->OnRemoteProcessDeviceReset(mHost);
   return IPC_OK();
 }
 
 bool
 GPUChild::SendRequestMemoryReport(const uint32_t& aGeneration,
                                   const bool& aAnonymize,
                                   const bool& aMinimizeMemoryUsage,
                                   const MaybeFileDesc& aDMDFile)
--- a/gfx/ipc/GPUProcessHost.h
+++ b/gfx/ipc/GPUProcessHost.h
@@ -38,17 +38,17 @@ public:
     {}
 
     // The GPUProcessHost has unexpectedly shutdown or had its connection
     // severed. This is not called if an error occurs after calling
     // Shutdown().
     virtual void OnProcessUnexpectedShutdown(GPUProcessHost* aHost)
     {}
 
-    virtual void OnProcessDeviceReset(GPUProcessHost* aHost)
+    virtual void OnRemoteProcessDeviceReset(GPUProcessHost* aHost)
     {}
   };
 
 public:
   explicit GPUProcessHost(Listener* listener);
   ~GPUProcessHost();
 
   // Launch the subprocess asynchronously. On failure, false is returned.
--- a/gfx/ipc/GPUProcessManager.cpp
+++ b/gfx/ipc/GPUProcessManager.cpp
@@ -349,17 +349,17 @@ GPUProcessManager::OnProcessLaunchComple
     NS_LITERAL_CSTRING("Running"));
 #endif
 }
 
 static bool
 ShouldLimitDeviceResets(uint32_t count, int32_t deltaMilliseconds)
 {
   // We decide to limit by comparing the amount of resets that have happened
-  // and time since the last reset to two prefs. 
+  // and time since the last reset to two prefs.
   int32_t timeLimit = gfxPrefs::DeviceResetThresholdMilliseconds();
   int32_t countLimit = gfxPrefs::DeviceResetLimitCount();
 
   bool hasTimeLimit = timeLimit >= 0;
   bool hasCountLimit = countLimit >= 0;
 
   bool triggeredTime = deltaMilliseconds < timeLimit;
   bool triggeredCount = count > (uint32_t)countLimit;
@@ -373,17 +373,34 @@ ShouldLimitDeviceResets(uint32_t count, 
   } else if (hasCountLimit) {
     return triggeredCount;
   }
 
   return false;
 }
 
 void
-GPUProcessManager::OnProcessDeviceReset(GPUProcessHost* aHost)
+GPUProcessManager::TriggerDeviceResetForTesting()
+{
+  if (mProcess) {
+    OnRemoteProcessDeviceReset(mProcess);
+  } else {
+    OnInProcessDeviceReset();
+  }
+}
+
+void
+GPUProcessManager::OnInProcessDeviceReset()
+{
+  RebuildInProcessSessions();
+  NotifyListenersOnCompositeDeviceReset();
+}
+
+void
+GPUProcessManager::OnRemoteProcessDeviceReset(GPUProcessHost* aHost)
 {
   // Detect whether the device is resetting too quickly or too much
   // indicating that we should give up and use software
   mDeviceResetCount++;
 
   auto newTime = TimeStamp::Now();
   auto delta = (int32_t)(newTime - mDeviceResetLastTime).ToMilliseconds();
   mDeviceResetLastTime = newTime;
@@ -392,17 +409,22 @@ GPUProcessManager::OnProcessDeviceReset(
     DestroyProcess();
     DisableGPUProcess("GPU processed experienced too many device resets");
 
     HandleProcessLost();
     return;
   }
 
   RebuildRemoteSessions();
+  NotifyListenersOnCompositeDeviceReset();
+}
 
+void
+GPUProcessManager::NotifyListenersOnCompositeDeviceReset()
+{
   for (const auto& listener : mListeners) {
     listener->OnCompositorDeviceReset();
   }
 }
 
 void
 GPUProcessManager::OnProcessUnexpectedShutdown(GPUProcessHost* aHost)
 {
@@ -490,17 +512,17 @@ GPUProcessManager::HandleProcessLost()
   //      in the same window, additional tabs will simply return the already-
   //      established compositor.
   //
   //      Finally, this step serves one other crucial function: tabs must be
   //      associated with a window compositor or else they can't forward
   //      layer transactions. So this step both ensures that a compositor
   //      exists, and that the tab can forward layers.
   //
-  //  (8) Last, if the window had no remote tabs, step (7) will not have 
+  //  (8) Last, if the window had no remote tabs, step (7) will not have
   //      applied, and the window will not have a new compositor just yet.
   //      The next refresh tick and paint will ensure that one exists, again
   //      via nsIWidget::GetLayerManager.
   RebuildRemoteSessions();
 
   // Notify content. This will ensure that each content process re-establishes
   // a connection to the compositor thread (whether it's in-process or in a
   // newly launched GPU process).
@@ -522,16 +544,33 @@ GPUProcessManager::RebuildRemoteSessions
   // Notify each widget that we have lost the GPU process. This will ensure
   // that each widget destroys its layer manager and CompositorBridgeChild.
   for (const auto& session : sessions) {
     session->NotifySessionLost();
   }
 }
 
 void
+GPUProcessManager::RebuildInProcessSessions()
+{
+  // Build a list of sessions to notify, since notification might delete
+  // entries from the list.
+  nsTArray<RefPtr<InProcessCompositorSession>> sessions;
+  for (auto& session : mInProcessSessions) {
+    sessions.AppendElement(session);
+  }
+
+  // Notify each widget that we have lost the GPU process. This will ensure
+  // that each widget destroys its layer manager and CompositorBridgeChild.
+  for (const auto& session : sessions) {
+    session->NotifySessionLost();
+  }
+}
+
+void
 GPUProcessManager::NotifyRemoteActorDestroyed(const uint64_t& aProcessToken)
 {
   if (!NS_IsMainThread()) {
     RefPtr<Runnable> task = mTaskFactory.NewRunnableMethod(
       &GPUProcessManager::NotifyRemoteActorDestroyed, aProcessToken);
     NS_DispatchToMainThread(task.forget());
     return;
   }
@@ -959,28 +998,40 @@ GPUProcessManager::EnsureVsyncIOThread()
 
 void
 GPUProcessManager::ShutdownVsyncIOThread()
 {
   mVsyncIOThread = nullptr;
 }
 
 void
-GPUProcessManager::RegisterSession(RemoteCompositorSession* aSession)
+GPUProcessManager::RegisterRemoteProcessSession(RemoteCompositorSession* aSession)
 {
   mRemoteSessions.AppendElement(aSession);
 }
 
 void
-GPUProcessManager::UnregisterSession(RemoteCompositorSession* aSession)
+GPUProcessManager::UnregisterRemoteProcessSession(RemoteCompositorSession* aSession)
 {
   mRemoteSessions.RemoveElement(aSession);
 }
 
 void
+GPUProcessManager::RegisterInProcessSession(InProcessCompositorSession* aSession)
+{
+  mInProcessSessions.AppendElement(aSession);
+}
+
+void
+GPUProcessManager::UnregisterInProcessSession(InProcessCompositorSession* aSession)
+{
+  mInProcessSessions.RemoveElement(aSession);
+}
+
+void
 GPUProcessManager::AddListener(GPUProcessListener* aListener)
 {
   mListeners.AppendElement(aListener);
 }
 
 void
 GPUProcessManager::RemoveListener(GPUProcessListener* aListener)
 {
--- a/gfx/ipc/GPUProcessManager.h
+++ b/gfx/ipc/GPUProcessManager.h
@@ -27,16 +27,17 @@ namespace layers {
 class IAPZCTreeManager;
 class CompositorOptions;
 class CompositorSession;
 class CompositorUpdateObserver;
 class PCompositorBridgeChild;
 class PCompositorManagerChild;
 class PImageBridgeChild;
 class RemoteCompositorSession;
+class InProcessCompositorSession;
 class UiCompositorControllerChild;
 } // namespace layers
 namespace widget {
 class CompositorWidget;
 } // namespace widget
 namespace dom {
 class ContentParent;
 class TabParent;
@@ -54,26 +55,28 @@ class VsyncBridgeChild;
 class VsyncIOThreadHolder;
 
 // The GPUProcessManager is a singleton responsible for creating GPU-bound
 // objects that may live in another process. Currently, it provides access
 // to the compositor via CompositorBridgeParent.
 class GPUProcessManager final : public GPUProcessHost::Listener
 {
   friend class layers::RemoteCompositorSession;
+  friend class layers::InProcessCompositorSession;
 
   typedef layers::CompositorOptions CompositorOptions;
   typedef layers::CompositorSession CompositorSession;
   typedef layers::CompositorUpdateObserver CompositorUpdateObserver;
   typedef layers::IAPZCTreeManager IAPZCTreeManager;
   typedef layers::LayerManager LayerManager;
   typedef layers::PCompositorBridgeChild PCompositorBridgeChild;
   typedef layers::PCompositorManagerChild PCompositorManagerChild;
   typedef layers::PImageBridgeChild PImageBridgeChild;
   typedef layers::RemoteCompositorSession RemoteCompositorSession;
+  typedef layers::InProcessCompositorSession InProcessCompositorSession;
   typedef layers::UiCompositorControllerChild UiCompositorControllerChild;
 
 public:
   static void Initialize();
   static void Shutdown();
   static GPUProcessManager* Get();
 
   ~GPUProcessManager();
@@ -136,17 +139,20 @@ public:
   bool AllocateAndConnectLayerTreeId(
     PCompositorBridgeChild* aCompositorBridge,
     base::ProcessId aOtherPid,
     uint64_t* aOutLayersId,
     CompositorOptions* aOutCompositorOptions);
 
   void OnProcessLaunchComplete(GPUProcessHost* aHost) override;
   void OnProcessUnexpectedShutdown(GPUProcessHost* aHost) override;
-  void OnProcessDeviceReset(GPUProcessHost* aHost) override;
+  void TriggerDeviceResetForTesting();
+  void OnInProcessDeviceReset();
+  void OnRemoteProcessDeviceReset(GPUProcessHost* aHost) override;
+  void NotifyListenersOnCompositeDeviceReset();
 
   // Notify the GPUProcessManager that a top-level PGPU protocol has been
   // terminated. This may be called from any thread.
   void NotifyRemoteActorDestroyed(const uint64_t& aProcessToken);
 
   void AddListener(GPUProcessListener* aListener);
   void RemoveListener(GPUProcessListener* aListener);
 
@@ -184,20 +190,26 @@ private:
                                 ipc::Endpoint<PImageBridgeChild>* aOutEndpoint);
   bool CreateContentVRManager(base::ProcessId aOtherProcess,
                               ipc::Endpoint<PVRManagerChild>* aOutEndpoint);
   void CreateContentVideoDecoderManager(base::ProcessId aOtherProcess,
                                         ipc::Endpoint<dom::PVideoDecoderManagerChild>* aOutEndPoint);
 
   // Called from RemoteCompositorSession. We track remote sessions so we can
   // notify their owning widgets that the session must be restarted.
-  void RegisterSession(RemoteCompositorSession* aSession);
-  void UnregisterSession(RemoteCompositorSession* aSession);
+  void RegisterRemoteProcessSession(RemoteCompositorSession* aSession);
+  void UnregisterRemoteProcessSession(RemoteCompositorSession* aSession);
+
+  // Called from InProcessCompositorSession. We track in process sessino so we can
+  // notify their owning widgets that the session must be restarted
+  void RegisterInProcessSession(InProcessCompositorSession* aSession);
+  void UnregisterInProcessSession(InProcessCompositorSession* aSession);
 
   void RebuildRemoteSessions();
+  void RebuildInProcessSessions();
 
 private:
   GPUProcessManager();
 
   // Permanently disable the GPU process and record a message why.
   void DisableGPUProcess(const char* aMessage);
 
   // Shutdown the GPU process.
@@ -248,16 +260,17 @@ private:
   ipc::TaskFactory<GPUProcessManager> mTaskFactory;
   RefPtr<VsyncIOThreadHolder> mVsyncIOThread;
   uint32_t mNextNamespace;
   uint32_t mIdNamespace;
   uint32_t mResourceId;
   uint32_t mNumProcessAttempts;
 
   nsTArray<RefPtr<RemoteCompositorSession>> mRemoteSessions;
+  nsTArray<RefPtr<InProcessCompositorSession>> mInProcessSessions;
   nsTArray<GPUProcessListener*> mListeners;
 
   uint32_t mDeviceResetCount;
   TimeStamp mDeviceResetLastTime;
 
   // Fields that are associated with the current GPU process.
   GPUProcessHost* mProcess;
   MOZ_INIT_OUTSIDE_CTOR uint64_t mProcessToken;
--- a/gfx/ipc/InProcessCompositorSession.cpp
+++ b/gfx/ipc/InProcessCompositorSession.cpp
@@ -4,31 +4,35 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "InProcessCompositorSession.h"
 
 // so we can cast an APZCTreeManager to an IAPZCTreeManager
 #include "mozilla/layers/APZCTreeManager.h"
 #include "mozilla/layers/IAPZCTreeManager.h"
+#include "nsBaseWidget.h"
 
 namespace mozilla {
 namespace layers {
 
 InProcessCompositorSession::InProcessCompositorSession(widget::CompositorWidget* aWidget,
+                                                       nsBaseWidget* baseWidget,
                                                        CompositorBridgeChild* aChild,
                                                        CompositorBridgeParent* aParent)
  : CompositorSession(aWidget->AsDelegate(), aChild, aParent->RootLayerTreeId()),
+   mWidget(baseWidget),
    mCompositorBridgeParent(aParent),
    mCompositorWidget(aWidget)
 {
+  GPUProcessManager::Get()->RegisterInProcessSession(this);
 }
 
 /* static */ RefPtr<InProcessCompositorSession>
-InProcessCompositorSession::Create(nsIWidget* aWidget,
+InProcessCompositorSession::Create(nsBaseWidget* aWidget,
                                    LayerManager* aLayerManager,
                                    const uint64_t& aRootLayerTreeId,
                                    CSSToLayoutDeviceScale aScale,
                                    const CompositorOptions& aOptions,
                                    bool aUseExternalSurfaceSize,
                                    const gfx::IntSize& aSurfaceSize,
                                    uint32_t aNamespace)
 {
@@ -43,17 +47,23 @@ InProcessCompositorSession::Create(nsIWi
   MOZ_ASSERT(parent);
   parent->InitSameProcess(widget, aRootLayerTreeId);
 
   RefPtr<CompositorBridgeChild> child =
     CompositorManagerChild::CreateSameProcessWidgetCompositorBridge(aLayerManager,
                                                                     aNamespace);
   MOZ_ASSERT(child);
 
-  return new InProcessCompositorSession(widget, child, parent);
+  return new InProcessCompositorSession(widget, aWidget, child, parent);
+}
+
+void
+InProcessCompositorSession::NotifySessionLost()
+{
+  mWidget->NotifyCompositorSessionLost(this);
 }
 
 CompositorBridgeParent*
 InProcessCompositorSession::GetInProcessBridge() const
 {
   return mCompositorBridgeParent;
 }
 
@@ -64,16 +74,22 @@ InProcessCompositorSession::SetContentCo
 }
 
 RefPtr<IAPZCTreeManager>
 InProcessCompositorSession::GetAPZCTreeManager() const
 {
   return mCompositorBridgeParent->GetAPZCTreeManager(mRootLayerTreeId);
 }
 
+nsIWidget*
+InProcessCompositorSession::GetWidget() const
+{
+  return mWidget;
+}
+
 void
 InProcessCompositorSession::Shutdown()
 {
   // Destroy will synchronously wait for the parent to acknowledge shutdown,
   // at which point CBP will defer a Release on the compositor thread. We
   // can safely release our reference now, and let the destructor run on either
   // thread.
   mCompositorBridgeChild->Destroy();
@@ -81,12 +97,13 @@ InProcessCompositorSession::Shutdown()
   mCompositorBridgeParent = nullptr;
   mCompositorWidget = nullptr;
 #if defined(MOZ_WIDGET_ANDROID)
   if (mUiCompositorControllerChild) {
     mUiCompositorControllerChild->Destroy();
     mUiCompositorControllerChild = nullptr;
   }
 #endif //defined(MOZ_WIDGET_ANDROID)
+  GPUProcessManager::Get()->UnregisterInProcessSession(this);
 }
 
 } // namespace layers
 } // namespace mozilla
--- a/gfx/ipc/InProcessCompositorSession.h
+++ b/gfx/ipc/InProcessCompositorSession.h
@@ -16,36 +16,41 @@ namespace layers {
 class CompositorOptions;
 
 // A CompositorSession where both the child and parent CompositorBridge reside
 // in the same process.
 class InProcessCompositorSession final : public CompositorSession
 {
 public:
   static RefPtr<InProcessCompositorSession> Create(
-    nsIWidget* aWidget,
+    nsBaseWidget* baseWidget,
     LayerManager* aLayerManager,
     const uint64_t& aRootLayerTreeId,
     CSSToLayoutDeviceScale aScale,
     const CompositorOptions& aOptions,
     bool aUseExternalSurfaceSize,
     const gfx::IntSize& aSurfaceSize,
     uint32_t aNamespace);
 
   CompositorBridgeParent* GetInProcessBridge() const override;
   void SetContentController(GeckoContentController* aController) override;
+  nsIWidget* GetWidget() const;
   RefPtr<IAPZCTreeManager> GetAPZCTreeManager() const override;
   void Shutdown() override;
 
+  void NotifySessionLost();
+
 private:
   InProcessCompositorSession(widget::CompositorWidget* aWidget,
+                             nsBaseWidget* baseWidget,
                              CompositorBridgeChild* aChild,
                              CompositorBridgeParent* aParent);
 
 private:
+  nsBaseWidget* mWidget;
   RefPtr<CompositorBridgeParent> mCompositorBridgeParent;
   RefPtr<CompositorWidget> mCompositorWidget;
 };
 
 } // namespace layers
 } // namespace mozilla
 
 #endif // _include_mozilla_gfx_ipc_InProcessCompositorSession_h_
--- a/gfx/ipc/RemoteCompositorSession.cpp
+++ b/gfx/ipc/RemoteCompositorSession.cpp
@@ -24,17 +24,17 @@ RemoteCompositorSession::RemoteComposito
                                                  CompositorBridgeChild* aChild,
                                                  CompositorWidgetDelegate* aWidgetDelegate,
                                                  APZCTreeManagerChild* aAPZ,
                                                  const uint64_t& aRootLayerTreeId)
  : CompositorSession(aWidgetDelegate, aChild, aRootLayerTreeId),
    mWidget(aWidget),
    mAPZ(aAPZ)
 {
-  GPUProcessManager::Get()->RegisterSession(this);
+  GPUProcessManager::Get()->RegisterRemoteProcessSession(this);
   if (mAPZ) {
     mAPZ->SetCompositorSession(this);
   }
 }
 
 RemoteCompositorSession::~RemoteCompositorSession()
 {
   // This should have been shutdown first.
@@ -45,18 +45,17 @@ RemoteCompositorSession::~RemoteComposit
 }
 
 void
 RemoteCompositorSession::NotifySessionLost()
 {
   // Re-entrancy should be impossible: when we are being notified of a lost
   // session, we have by definition not shut down yet. We will shutdown, but
   // then will be removed from the notification list.
-  MOZ_ASSERT(mWidget);
-  mWidget->NotifyRemoteCompositorSessionLost(this);
+  mWidget->NotifyCompositorSessionLost(this);
 }
 
 CompositorBridgeParent*
 RemoteCompositorSession::GetInProcessBridge() const
 {
   return nullptr;
 }
 
@@ -69,17 +68,17 @@ RemoteCompositorSession::SetContentContr
 
 GeckoContentController*
 RemoteCompositorSession::GetContentController()
 {
   return mContentController.get();
 }
 
 nsIWidget*
-RemoteCompositorSession::GetWidget()
+RemoteCompositorSession::GetWidget() const
 {
   return mWidget;
 }
 
 RefPtr<IAPZCTreeManager>
 RemoteCompositorSession::GetAPZCTreeManager() const
 {
   return mAPZ;
@@ -97,13 +96,13 @@ RemoteCompositorSession::Shutdown()
   mCompositorWidgetDelegate = nullptr;
   mWidget = nullptr;
 #if defined(MOZ_WIDGET_ANDROID)
   if (mUiCompositorControllerChild) {
     mUiCompositorControllerChild->Destroy();
     mUiCompositorControllerChild = nullptr;
   }
 #endif //defined(MOZ_WIDGET_ANDROID)
-  GPUProcessManager::Get()->UnregisterSession(this);
+  GPUProcessManager::Get()->UnregisterRemoteProcessSession(this);
 }
 
 } // namespace layers
 } // namespace mozilla
--- a/gfx/ipc/RemoteCompositorSession.h
+++ b/gfx/ipc/RemoteCompositorSession.h
@@ -21,17 +21,17 @@ public:
                           CompositorWidgetDelegate* aWidgetDelegate,
                           APZCTreeManagerChild* aAPZ,
                           const uint64_t& aRootLayerTreeId);
   ~RemoteCompositorSession() override;
 
   CompositorBridgeParent* GetInProcessBridge() const override;
   void SetContentController(GeckoContentController* aController) override;
   GeckoContentController* GetContentController();
-  nsIWidget* GetWidget();
+  nsIWidget* GetWidget() const;
   RefPtr<IAPZCTreeManager> GetAPZCTreeManager() const override;
   void Shutdown() override;
 
   void NotifySessionLost();
 
 private:
   nsBaseWidget* mWidget;
   RefPtr<APZCTreeManagerChild> mAPZ;
--- a/gfx/layers/client/ClientLayerManager.cpp
+++ b/gfx/layers/client/ClientLayerManager.cpp
@@ -112,19 +112,19 @@ ClientLayerManager::ClientLayerManager(n
 }
 
 
 ClientLayerManager::~ClientLayerManager()
 {
   mMemoryPressureObserver->Destroy();
   ClearCachedResources();
   // Stop receiveing AsyncParentMessage at Forwarder.
-  // After the call, the message is directly handled by LayerTransactionChild. 
+  // After the call, the message is directly handled by LayerTransactionChild.
   // Basically this function should be called in ShadowLayerForwarder's
-  // destructor. But when the destructor is triggered by 
+  // destructor. But when the destructor is triggered by
   // CompositorBridgeChild::Destroy(), the destructor can not handle it correctly.
   // See Bug 1000525.
   mForwarder->StopReceiveAsyncParentMessge();
   mRoot = nullptr;
 
   MOZ_COUNT_DTOR(ClientLayerManager);
 }
 
new file mode 100644
--- /dev/null
+++ b/gfx/tests/chrome/chrome.ini
@@ -0,0 +1,4 @@
+[DEFAULT]
+
+[test_device_reset.html]
+subsuite = gpu
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/gfx/tests/chrome/test_device_reset.html
@@ -0,0 +1,95 @@
+<!DOCTYPE html>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1274663
+-->
+  <head>
+    <meta charset="utf-8">
+    <title>Test device reset</title>
+    <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+    <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
+  </head>
+  <body>
+    <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1274663">Mozilla Bug 1274663</a>
+    <script>
+      var importObj = {};
+
+      var Cc = SpecialPowers.Cc;
+      var Ci = SpecialPowers.Ci;
+
+      var sysInfo = Cc["@mozilla.org/system-info;1"].getService(Ci.nsIPropertyBag2);
+      var xr = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
+
+      var windows = SpecialPowers.Services.ww.getWindowEnumerator();
+      var windowutils;
+      while (windows.hasMoreElements()) {
+        windowutils = windows.getNext().QueryInterface(Ci.nsIInterfaceRequestor)
+                                       .getInterface(Ci.nsIDOMWindowUtils);
+      }
+
+      const PAGE_WIDTH = 200;
+      const PAGE_HEIGHT = 200;
+
+      // Helper functions
+
+      function testCompositor(ctx) {
+        takeWindowSnapshot(ctx);
+        var testPassed = true;
+
+        if (!verifyCanvasRendering(ctx)) {
+          testPassed = false;
+        }
+
+        return testPassed;
+      }
+
+      function testPixel(ctx, x, y, r, g, b, a, fuzz) {
+        var data = ctx.getImageData(x, y, 1, 1);
+
+        if (Math.abs(data.data[0] - r) <= fuzz &&
+            Math.abs(data.data[1] - g) <= fuzz &&
+            Math.abs(data.data[2] - b) <= fuzz &&
+            Math.abs(data.data[3] - a) <= fuzz) {
+          return true;
+        }
+        return false;
+      }
+
+      function verifyCanvasRendering(ctx) {
+        return testPixel(ctx, 20, 20, 140, 25, 86, 255, 0);
+      }
+
+      function takeWindowSnapshot(ctx) {
+        var flags = ctx.DRAWWINDOW_DRAW_CARET | ctx.DRAWWINDOW_DRAW_VIEW | ctx.DRAWWINDOW_USE_WIDGET_LAYERS;
+        ctx.drawWindow(window, 0, 0, PAGE_WIDTH, PAGE_HEIGHT, "rgb(140,25,86)", flags);
+      }
+
+      function createCanvas() {
+        let canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
+
+        canvas.setAttribute("width", PAGE_WIDTH + "px");
+        canvas.setAttribute("height", PAGE_HEIGHT + "px");
+
+        return canvas;
+      }
+
+      // Test runner code
+      windowutils.triggerDeviceReset();
+
+      SimpleTest.waitForExplicitFinish();
+      window.addEventListener("MozAfterPaint", function paintHandle(e) {
+        runCanvasTest();
+        window.removeEventListener("MozAfterPaint", paintHandle, false);
+      });
+
+      function runCanvasTest() {
+        const canvas = createCanvas();
+        const ctx = canvas.getContext("2d");
+        document.body.appendChild(canvas);
+
+        ok(testCompositor(ctx), "Canvas did not get rendered after device reset");
+        SimpleTest.finish();
+      }
+    </script>
+  </body>
+</html>
--- a/gfx/tests/moz.build
+++ b/gfx/tests/moz.build
@@ -2,8 +2,9 @@
 # vim: set filetype=python:
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 XPCSHELL_TESTS_MANIFESTS += ['unit/xpcshell.ini']
 MOCHITEST_MANIFESTS += ['mochitest/mochitest.ini']
 BROWSER_CHROME_MANIFESTS += ['browser/browser.ini']
+MOCHITEST_CHROME_MANIFESTS += ['chrome/chrome.ini']
\ No newline at end of file
--- a/image/imgLoader.cpp
+++ b/image/imgLoader.cpp
@@ -1742,19 +1742,19 @@ imgLoader::ValidateRequestWithNewChannel
   // resulting from methods such as StartDecoding(). See bug 579122.
   req->SetNotificationsDeferred(true);
 
   // Add the proxy without notifying
   hvc->AddProxy(req);
 
   mozilla::net::PredictorLearn(aURI, aInitialDocumentURI,
                                nsINetworkPredictor::LEARN_LOAD_SUBRESOURCE, aLoadGroup);
-
   rv = newChannel->AsyncOpen2(listener);
   if (NS_WARN_IF(NS_FAILED(rv))) {
+    req->CancelAndForgetObserver(rv);
     return false;
   }
 
   req.forget(aProxyRequest);
   return true;
 }
 
 bool
--- a/netwerk/protocol/http/HttpChannelParent.cpp
+++ b/netwerk/protocol/http/HttpChannelParent.cpp
@@ -2,17 +2,16 @@
 /* vim: set sw=2 ts=8 et tw=80 : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 // HttpLog.h should generally be included first
 #include "HttpLog.h"
 
-#include "mozilla/AbstractThread.h"
 #include "mozilla/ipc/FileDescriptorSetParent.h"
 #include "mozilla/ipc/IPCStreamUtils.h"
 #include "mozilla/net/HttpChannelParent.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/TabParent.h"
 #include "mozilla/net/NeckoParent.h"
 #include "mozilla/IntegerPrintfMacros.h"
@@ -45,16 +44,17 @@
 #include "nsIIPCSerializableInputStream.h"
 #include "nsIPrompt.h"
 #include "nsIRedirectChannelRegistrar.h"
 #include "nsIWindowWatcher.h"
 #include "nsIDocument.h"
 #include "nsStreamUtils.h"
 #include "nsStringStream.h"
 #include "nsIStorageStream.h"
+#include "nsThreadUtils.h"
 #include "nsQueryObject.h"
 #include "nsIURIClassifier.h"
 
 using mozilla::BasePrincipal;
 using namespace mozilla::dom;
 using namespace mozilla::ipc;
 
 namespace mozilla {
@@ -735,17 +735,17 @@ HttpChannelParent::DoAsyncOpen(  const U
   mSuspendAfterSynthesizeResponse = aSuspendAfterSynthesizeResponse;
 
   MOZ_ASSERT(!mBgParent);
   MOZ_ASSERT(mPromise.IsEmpty());
   // Wait for HttpBackgrounChannel to continue the async open procedure.
   ++mAsyncOpenBarrier;
   RefPtr<GenericPromise> promise = WaitForBgParent();
   RefPtr<HttpChannelParent> self = this;
-  promise->Then(AbstractThread::MainThread(), __func__,
+  promise->Then(GetMainThreadSerialEventTarget(), __func__,
                 [self]() {
                   self->mRequest.Complete();
                   self->TryInvokeAsyncOpen(NS_OK);
                 },
                 [self](nsresult aStatus) {
                   self->mRequest.Complete();
                   self->TryInvokeAsyncOpen(aStatus);
                 })
@@ -817,17 +817,17 @@ HttpChannelParent::ConnectChannel(const 
     }
   }
 
   MOZ_ASSERT(!mBgParent);
   MOZ_ASSERT(mPromise.IsEmpty());
   // Waiting for background channel
   RefPtr<GenericPromise> promise = WaitForBgParent();
   RefPtr<HttpChannelParent> self = this;
-  promise->Then(AbstractThread::MainThread(), __func__,
+  promise->Then(GetMainThreadSerialEventTarget(), __func__,
                 [self]() {
                   self->mRequest.Complete();
                 },
                 [self](const nsresult& aResult) {
                   NS_ERROR("failed to establish the background channel");
                   self->mRequest.Complete();
                 })
          ->Track(mRequest);
@@ -1039,17 +1039,17 @@ HttpChannelParent::ContinueVerification(
   }
 
   // ConnectChannel must be received before Redirect2Verify.
   MOZ_ASSERT(!mPromise.IsEmpty());
 
   // Otherwise, wait for the background channel.
   RefPtr<GenericPromise> promise = WaitForBgParent();
   nsCOMPtr<nsIAsyncVerifyRedirectReadyCallback> callback = aCallback;
-  promise->Then(AbstractThread::MainThread(), __func__,
+  promise->Then(GetMainThreadSerialEventTarget(), __func__,
                 [callback]() {
                   callback->ReadyToVerify(NS_OK);
                 },
                 [callback](const nsresult& aResult) {
                   NS_ERROR("failed to establish the background channel");
                   callback->ReadyToVerify(aResult);
                 });
   return NS_OK;
--- a/netwerk/protocol/http/nsCORSListenerProxy.cpp
+++ b/netwerk/protocol/http/nsCORSListenerProxy.cpp
@@ -911,16 +911,19 @@ nsCORSListenerProxy::UpdateChannel(nsICh
   nsCOMPtr<nsIHttpChannelInternal> internal = do_QueryInterface(aChannel);
   if (internal) {
     rv = internal->SetCorsMode(nsIHttpChannelInternal::CORS_MODE_CORS);
     NS_ENSURE_SUCCESS(rv, rv);
     rv = internal->SetCorsIncludeCredentials(mWithCredentials);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
+  // TODO: Bug 1353683
+  // consider calling SetBlockedRequest in nsCORSListenerProxy::UpdateChannel
+  //
   // Check that the uri is ok to load
   rv = nsContentUtils::GetSecurityManager()->
     CheckLoadURIWithPrincipal(mRequestingPrincipal, uri,
                               nsIScriptSecurityManager::STANDARD);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (originalURI != uri) {
     rv = nsContentUtils::GetSecurityManager()->
--- a/netwerk/protocol/http/nsHttpChannel.cpp
+++ b/netwerk/protocol/http/nsHttpChannel.cpp
@@ -9161,16 +9161,26 @@ nsHttpChannel::TriggerNetwork(int32_t aT
 nsresult
 nsHttpChannel::MaybeRaceCacheWithNetwork()
 {
     // Don't trigger the network if the load flags say so.
     if (mLoadFlags & (LOAD_ONLY_FROM_CACHE | LOAD_NO_NETWORK_IO)) {
         return NS_OK;
     }
 
+    // We must not race if the channel has a failure status code.
+    if (NS_FAILED(mStatus)) {
+        return NS_OK;
+    }
+
+    // If a CORS Preflight is required we must not race.
+    if (mRequireCORSPreflight && !mIsCorsPreflightDone) {
+        return NS_OK;
+    }
+
     uint32_t threshold = mCacheOpenWithPriority ? sRCWNQueueSizePriority
                                                 : sRCWNQueueSizeNormal;
     // No need to trigger to trigger the racing, since most likely the cache
     // will be faster.
     if (mCacheQueueSizeWhenOpen < threshold) {
         return NS_OK;
     }
 
--- a/testing/marionette/accessibility.js
+++ b/testing/marionette/accessibility.js
@@ -1,16 +1,17 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
 const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
 
+Cu.import('resource://gre/modules/Services.jsm');
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Log.jsm");
 
 const logger = Log.repository.getLogger("Marionette");
 
 Cu.import("chrome://marionette/content/error.js");
 
 XPCOMUtils.defineLazyModuleGetter(
@@ -27,29 +28,16 @@ XPCOMUtils.defineLazyGetter(this, "servi
     logger.warn("Accessibility module is not present");
   } finally {
     return service;
   }
 });
 
 this.EXPORTED_SYMBOLS = ["accessibility"];
 
-/**
- * Number of attempts to get an accessible object for an element.
- * We attempt more than once because accessible tree can be out of sync
- * with the DOM tree for a short period of time.
- */
-const GET_ACCESSIBLE_ATTEMPTS = 100;
-
-/**
- * An interval between attempts to retrieve an accessible object for an
- * element.
- */
-const GET_ACCESSIBLE_ATTEMPT_INTERVAL = 10;
-
 this.accessibility = {
   get service() {
     return service;
   }
 };
 
 /**
  * Accessible states used to check element"s state from the accessiblity API
@@ -145,38 +133,57 @@ accessibility.Checks = class {
     }
 
     return new Promise((resolve, reject) => {
       if (!accessibility.service) {
         reject();
         return;
       }
 
-      let acc = accessibility.service.getAccessibleFor(element);
-      if (acc || !mustHaveAccessible) {
-        // if accessible object is found, return it;
-        // if it is not required, also resolve
-        resolve(acc);
-      } else {
-        // if we require an accessible object, we need to poll for it
-        // because accessible tree might be
-        // out of sync with DOM tree for a short time
-        let attempts = GET_ACCESSIBLE_ATTEMPTS;
-        let intervalId = setInterval(() => {
+      // First, check if accessibility is ready.
+      let docAcc = accessibility.service.getAccessibleFor(element.ownerDocument);
+      let state = {};
+      docAcc.getState(state, {});
+      if ((state.value & Ci.nsIAccessibleStates.STATE_BUSY) == 0) {
+        // Accessibility is ready, resolve immediately.
+        let acc = accessibility.service.getAccessibleFor(element);
+        if (mustHaveAccessible && !acc) {
+          reject();
+        } else {
+          resolve(acc);
+        }
+        return;
+      }
+      // Accessibility for the doc is busy, so wait for the state to change.
+      let eventObserver = {
+        observe(subject, topic, data) {
+          if (topic !== "accessible-event") {
+            return;
+          }
+
+          let event = subject.QueryInterface(Ci.nsIAccessibleEvent);
+          // If event type does not match expected type, skip the event.
+          if (event.eventType !== Ci.nsIAccessibleEvent.EVENT_STATE_CHANGE) {
+            return;
+          }
+          // If event's accessible does not match expected accessible, skip the event.
+          if (event.accessible !== docAcc) {
+            return;
+          }
+
+          Services.obs.removeObserver(this, "accessible-event");
           let acc = accessibility.service.getAccessibleFor(element);
-          if (acc || --attempts <= 0) {
-            clearInterval(intervalId);
-            if (acc) {
-              resolve(acc);
-            } else {
-              reject();
-            }
+          if (mustHaveAccessible && !acc) {
+            reject();
+          } else {
+            resolve(acc);
           }
-        }, GET_ACCESSIBLE_ATTEMPT_INTERVAL);
-      }
+        }
+      };
+      Services.obs.addObserver(eventObserver, "accessible-event");
     }).catch(() => this.error(
         "Element does not have an accessible object", element));
   };
 
   /**
    * Test if the accessible has a role that supports some arbitrary
    * action.
    *
--- a/testing/marionette/harness/marionette_harness/tests/unit/test_accessibility.py
+++ b/testing/marionette/harness/marionette_harness/tests/unit/test_accessibility.py
@@ -147,18 +147,16 @@ class TestAccessibility(MarionetteTestCa
         self.setup_accessibility(False, True)
         # No exception should be raised
         self.run_element_test(self.invalid_elementIDs, lambda button: button.click())
         # Elements are invisible
         self.run_element_test(self.falsy_elements,
                               lambda button: self.assertRaises(ElementNotInteractableException,
                                                                button.click))
 
-    @unittest.skipIf(sys.platform.startswith("linux"),
-                     "Bug 1341493 - ElementNotAccessibleException not raised")
     def test_element_visible_but_not_visible_to_accessbility(self):
         self.setup_accessibility()
         # Elements are displayed but hidden from accessibility API
         self.run_element_test(self.displayed_but_a11y_hidden_elementIDs,
                               lambda element: self.assertRaises(ElementNotAccessibleException,
                                                                 element.is_displayed))
 
     def test_element_is_visible_to_accessibility(self):
--- a/testing/marionette/harness/marionette_harness/tests/unit/unit-tests.ini
+++ b/testing/marionette/harness/marionette_harness/tests/unit/unit-tests.ini
@@ -1,15 +1,14 @@
 [test_marionette.py]
 [test_geckoinstance.py]
 [test_data_driven.py]
 [test_session.py]
 [test_capabilities.py]
 [test_accessibility.py]
-skip-if = headless # Bug 1294075 and 1341493
 [test_expectedfail.py]
 expected = fail
 [test_click.py]
 [test_click_chrome.py]
 skip-if = appname == 'fennec'
 [test_checkbox.py]
 [test_checkbox_chrome.py]
 skip-if = appname == 'fennec'
--- a/toolkit/components/telemetry/Histograms.json
+++ b/toolkit/components/telemetry/Histograms.json
@@ -12204,32 +12204,16 @@
   "GFX_CRASH": {
     "record_in_processes": ["main", "content"],
     "expires_in_version": "never",
     "kind": "enumerated",
     "n_values": 100,
     "releaseChannelCollection": "opt-out",
     "description": "Graphics Crash Reason (...)"
   },
-  "APZ_AWARE_KEY_LISTENERS": {
-    "record_in_processes": ["main", "content"],
-    "alert_emails": ["rhunt@mozilla.com"],
-    "bug_numbers": [1352654],
-    "expires_in_version": "58",
-    "kind": "boolean",
-    "description": "The percentage of pages with a non-passive key event on the path to the root scrolling element that would disable APZ key scrolling. This is tracked for non system principal windows, so it applies to toplevel windows and subframes/iframes, but not chrome windows. "
-  },
-  "APZ_AWARE_MOUSEMOVE_LISTENERS": {
-    "record_in_processes": ["main", "content"],
-    "alert_emails": ["rhunt@mozilla.com"],
-    "bug_numbers": [1352654],
-    "expires_in_version": "58",
-    "kind": "boolean",
-    "description": "The percentage of pages with a mousemove listener anywhere in the document that would disable APZ key scrolling. This is tracked for non system principal windows, so it applies to toplevel windows and subframes/iframes, but not chrome windows."
-  },
   "SCROLL_INPUT_METHODS": {
     "record_in_processes": ["main", "content", "gpu"],
     "alert_emails": ["botond@mozilla.com"],
     "bug_numbers": [1238137],
     "expires_in_version": "60",
     "kind": "enumerated",
     "n_values": 64,
     "description": "Count of scroll actions triggered by different input methods. See gfx/layers/apz/util/ScrollInputMethods.h for a list of possible values and their meanings."
--- a/toolkit/content/aboutSupport.js
+++ b/toolkit/content/aboutSupport.js
@@ -319,16 +319,27 @@ var snapshotFormatters = {
       }
 
       addRow("diagnostics", "GPUProcessPid", gpuProcessPid);
       if (gpuProcessKillButton) {
         addRow("diagnostics", "GPUProcess", [gpuProcessKillButton]);
       }
     }
 
+    if ((AppConstants.NIGHTLY_BUILD || AppConstants.MOZ_DEV_EDITION) && AppConstants.platform != "macosx") {
+      let gpuDeviceResetButton = $.new("button");
+
+      gpuDeviceResetButton.addEventListener("click", function() {
+        windowUtils.triggerDeviceReset();
+      });
+
+      gpuDeviceResetButton.textContent = strings.GetStringFromName("gpuDeviceResetButton");
+      addRow("diagnostics", "Device Reset", [gpuDeviceResetButton]);
+    }
+
     // graphics-failures-tbody tbody
     if ("failures" in data) {
       // If indices is there, it should be the same length as failures,
       // (see Troubleshoot.jsm) but we check anyway:
       if ("indices" in data && data.failures.length == data.indices.length) {
         let combined = [];
         for (let i = 0; i < data.failures.length; i++) {
           let assembled = assembleFromGraphicsFailure(i, data);
@@ -559,16 +570,17 @@ var snapshotFormatters = {
 
   javaScript: function javaScript(data) {
     $("javascript-incremental-gc").textContent = data.incrementalGCEnabled;
   },
 
   accessibility: function accessibility(data) {
     $("a11y-activated").textContent = data.isActive;
     $("a11y-force-disabled").textContent = data.forceDisabled || 0;
+    $("a11y-handler-used").textContent = data.handlerUsed;
   },
 
   libraryVersions: function libraryVersions(data) {
     let strings = stringBundle();
     let trs = [
       $.new("tr", [
         $.new("th", ""),
         $.new("th", strings.GetStringFromName("minLibVersions")),
--- a/toolkit/content/aboutSupport.xhtml
+++ b/toolkit/content/aboutSupport.xhtml
@@ -529,16 +529,26 @@
           <tr>
             <th class="column">
               &aboutSupport.a11yForceDisabled;
             </th>
 
             <td id="a11y-force-disabled">
             </td>
           </tr>
+#if defined(XP_WIN)
+          <tr>
+            <th class="column">
+              &aboutSupport.a11yHandlerUsed;
+            </th>
+
+            <td id="a11y-handler-used">
+            </td>
+          </tr>
+#endif
         </tbody>
       </table>
 
       <!-- - - - - - - - - - - - - - - - - - - - - -->
       <h2 class="major-section">
         &aboutSupport.libraryVersionsTitle;
       </h2>
 
--- a/toolkit/locales/en-US/chrome/global/aboutSupport.dtd
+++ b/toolkit/locales/en-US/chrome/global/aboutSupport.dtd
@@ -103,16 +103,17 @@ variant of aboutSupport.showDir.label. -
 <!ENTITY aboutSupport.placeDatabaseVerifyIntegrity "Verify Integrity">
 
 <!ENTITY aboutSupport.jsTitle "JavaScript">
 <!ENTITY aboutSupport.jsIncrementalGC "Incremental GC">
 
 <!ENTITY aboutSupport.a11yTitle "Accessibility">
 <!ENTITY aboutSupport.a11yActivated "Activated">
 <!ENTITY aboutSupport.a11yForceDisabled "Prevent Accessibility">
+<!ENTITY aboutSupport.a11yHandlerUsed "Accessible Handler Used">
 
 <!ENTITY aboutSupport.libraryVersionsTitle "Library Versions">
 
 <!ENTITY aboutSupport.installationHistoryTitle "Installation History">
 <!ENTITY aboutSupport.updateHistoryTitle "Update History">
 
 <!ENTITY aboutSupport.copyTextToClipboard.label "Copy text to clipboard">
 <!ENTITY aboutSupport.copyRawDataToClipboard.label "Copy raw data to clipboard">
--- a/toolkit/locales/en-US/chrome/global/aboutSupport.properties
+++ b/toolkit/locales/en-US/chrome/global/aboutSupport.properties
@@ -95,16 +95,17 @@ bugLink = bug %1$S
 # string that can be searched on DXR/MXR or grepped in the source tree.
 unknownFailure = Blocklisted; failure code %1$S
 d3d11layersCrashGuard = D3D11 Compositor
 d3d11videoCrashGuard = D3D11 Video Decoder
 d3d9videoCrashGuard = D3D9 Video Decoder
 glcontextCrashGuard = OpenGL
 resetOnNextRestart = Reset on Next Restart
 gpuProcessKillButton = Terminate GPU Process
+gpuDeviceResetButton = Trigger Device Reset
 
 minLibVersions = Expected minimum version
 loadedLibVersions = Version in use
 
 hasSeccompBPF = Seccomp-BPF (System Call Filtering)
 hasSeccompTSync = Seccomp Thread Synchronization
 hasUserNamespaces = User Namespaces
 hasPrivilegedUserNamespaces = User Namespaces for privileged processes
--- a/toolkit/modules/AppConstants.jsm
+++ b/toolkit/modules/AppConstants.jsm
@@ -178,23 +178,16 @@ this.AppConstants = Object.freeze({
 
   MOZ_CRASHREPORTER:
 #ifdef MOZ_CRASHREPORTER
   true,
 #else
   false,
 #endif
 
-  MOZ_VERIFY_MAR_SIGNATURE:
-#ifdef MOZ_VERIFY_MAR_SIGNATURE
-  true,
-#else
-  false,
-#endif
-
   MOZ_MAINTENANCE_SERVICE:
 #ifdef MOZ_MAINTENANCE_SERVICE
   true,
 #else
   false,
 #endif
 
   E10S_TESTING_ONLY:
--- a/toolkit/modules/Troubleshoot.jsm
+++ b/toolkit/modules/Troubleshoot.jsm
@@ -536,24 +536,23 @@ var dataProviders = {
                                   QueryInterface(Ci.nsIInterfaceRequestor).
                                   getInterface(Ci.nsIDOMWindowUtils).
                                   isIncrementalGCEnabled();
     done(data);
   },
 
   accessibility: function accessibility(done) {
     let data = {};
-    data.isActive = Cc["@mozilla.org/xre/app-info;1"].
-                    getService(Ci.nsIXULRuntime).
-                    accessibilityEnabled;
+    data.isActive = Services.appinfo.accessibilityEnabled;
     // eslint-disable-next-line mozilla/use-default-preference-values
     try {
       data.forceDisabled =
         Services.prefs.getIntPref("accessibility.force_disabled");
     } catch (e) {}
+    data.handlerUsed = Services.appinfo.accessibleHandlerUsed;
     done(data);
   },
 
   libraryVersions: function libraryVersions(done) {
     let data = {};
     let verInfo = Cc["@mozilla.org/security/nssversion;1"].
                   getService(Ci.nsINSSVersion);
     for (let prop in verInfo) {
--- a/toolkit/modules/tests/browser/browser_Troubleshoot.js
+++ b/toolkit/modules/tests/browser/browser_Troubleshoot.js
@@ -392,16 +392,19 @@ const SNAPSHOT_SCHEMA = {
       properties: {
         isActive: {
           required: true,
           type: "boolean",
         },
         forceDisabled: {
           type: "number",
         },
+        handlerUsed: {
+          type: "boolean",
+        },
       },
     },
     libraryVersions: {
       required: true,
       type: "object",
       properties: {
         NSPR: {
           required: true,
--- a/toolkit/mozapps/update/UpdateTelemetry.jsm
+++ b/toolkit/mozapps/update/UpdateTelemetry.jsm
@@ -171,17 +171,16 @@ this.AUSTLMY = {
   DWNLD_ERR_NO_UPDATE_PATCH: 6,
   DWNLD_ERR_PATCH_SIZE_LARGER: 8,
   DWNLD_ERR_PATCH_SIZE_NOT_EQUAL: 9,
   DWNLD_ERR_BINDING_ABORTED: 10,
   DWNLD_ERR_ABORT: 11,
   DWNLD_ERR_DOCUMENT_NOT_CACHED: 12,
   DWNLD_ERR_VERIFY_NO_REQUEST: 13,
   DWNLD_ERR_VERIFY_PATCH_SIZE_NOT_EQUAL: 14,
-  DWNLD_ERR_VERIFY_NO_HASH_MATCH: 15,
 
   /**
    * Submit a telemetry ping for the update download result code.
    *
    * @param  aIsComplete
    *         If true the histogram is for a patch type complete, if false the
    *         histogram is for a patch type partial, and when undefined the
    *         histogram is for an unknown patch type. This is used to determine
--- a/toolkit/mozapps/update/nsIUpdateService.idl
+++ b/toolkit/mozapps/update/nsIUpdateService.idl
@@ -35,27 +35,16 @@ interface nsIUpdatePatch : nsISupports
   attribute AString URL;
 
   /**
    * The final URL this patch was being downloaded from
    */
   attribute AString finalURL;
 
   /**
-   * The hash function to use when determining this file's integrity
-   */
-  attribute AString hashFunction;
-
-  /**
-   * The value of the hash function named above that should be computed if
-   * this file is not corrupt.
-   */
-  attribute AString hashValue;
-
-  /**
    * The size of this file, in bytes.
    */
   attribute unsigned long size;
 
   /**
    * The state of this patch
    */
   attribute AString state;
--- a/toolkit/mozapps/update/nsUpdateService.js
+++ b/toolkit/mozapps/update/nsUpdateService.js
@@ -1149,18 +1149,16 @@ UpdatePatch.prototype = {
   serialize: function UpdatePatch_serialize(updates) {
     var patch = updates.createElementNS(URI_UPDATE_NS, "patch");
     patch.setAttribute("type", this.type);
     patch.setAttribute("URL", this.URL);
     // finalURL is not available until after the download has started
     if (this.finalURL) {
       patch.setAttribute("finalURL", this.finalURL);
     }
-    patch.setAttribute("hashFunction", this.hashFunction);
-    patch.setAttribute("hashValue", this.hashValue);
     patch.setAttribute("size", this.size);
     if (this.selected) {
       patch.setAttribute("selected", this.selected);
     }
     patch.setAttribute("state", this.state);
 
     for (let p in this._properties) {
       if (this._properties[p].present) {
@@ -3125,59 +3123,17 @@ Downloader.prototype = {
     if (destination.fileSize != this._patch.size) {
       LOG("Downloader:_verifyDownload downloaded size != expected size.");
       AUSTLMY.pingDownloadCode(this.isCompleteUpdate,
                                AUSTLMY.DWNLD_ERR_VERIFY_PATCH_SIZE_NOT_EQUAL);
       return false;
     }
 
     LOG("Downloader:_verifyDownload downloaded size == expected size.");
-
-    // The hash check is not necessary when mar signatures are used to verify
-    // the downloaded mar file.
-    if (AppConstants.MOZ_VERIFY_MAR_SIGNATURE) {
-      return true;
-    }
-
-    let fileStream = Cc["@mozilla.org/network/file-input-stream;1"].
-                     createInstance(Ci.nsIFileInputStream);
-    fileStream.init(destination, FileUtils.MODE_RDONLY, FileUtils.PERMS_FILE, 0);
-
-    let digest;
-    try {
-      let hash = Cc["@mozilla.org/security/hash;1"].
-                 createInstance(Ci.nsICryptoHash);
-      var hashFunction = Ci.nsICryptoHash[this._patch.hashFunction.toUpperCase()];
-      if (hashFunction == undefined) {
-        throw Cr.NS_ERROR_UNEXPECTED;
-      }
-      hash.init(hashFunction);
-      hash.updateFromStream(fileStream, -1);
-      // NOTE: For now, we assume that the format of _patch.hashValue is hex
-      // encoded binary (such as what is typically output by programs like
-      // sha1sum).  In the future, this may change to base64 depending on how
-      // we choose to compute these hashes.
-      digest = binaryToHex(hash.finish(false));
-    } catch (e) {
-      LOG("Downloader:_verifyDownload - failed to compute hash of the " +
-          "downloaded update archive");
-      digest = "";
-    }
-
-    fileStream.close();
-
-    if (digest == this._patch.hashValue.toLowerCase()) {
-      LOG("Downloader:_verifyDownload hashes match.");
-      return true;
-    }
-
-    LOG("Downloader:_verifyDownload hashes do not match. ");
-    AUSTLMY.pingDownloadCode(this.isCompleteUpdate,
-                             AUSTLMY.DWNLD_ERR_VERIFY_NO_HASH_MATCH);
-    return false;
+    return true;
   },
 
   /**
    * Select the patch to use given the current state of updateDir and the given
    * set of update patches.
    * @param   update
    *          A nsIUpdate object to select a patch from
    * @param   updateDir
@@ -3399,31 +3355,25 @@ Downloader.prototype = {
    */
   onProgress: function Downloader_onProgress(request, context, progress,
                                              maxProgress) {
     LOG("Downloader:onProgress - progress: " + progress + "/" + maxProgress);
 
     if (progress > this._patch.size) {
       LOG("Downloader:onProgress - progress: " + progress +
           " is higher than patch size: " + this._patch.size);
-      // It's important that we use a different code than
-      // NS_ERROR_CORRUPTED_CONTENT so that tests can verify the difference
-      // between a hash error and a wrong download error.
       AUSTLMY.pingDownloadCode(this.isCompleteUpdate,
                                AUSTLMY.DWNLD_ERR_PATCH_SIZE_LARGER);
       this.cancel(Cr.NS_ERROR_UNEXPECTED);
       return;
     }
 
     if (maxProgress != this._patch.size) {
       LOG("Downloader:onProgress - maxProgress: " + maxProgress +
           " is not equal to expected patch size: " + this._patch.size);
-      // It's important that we use a different code than
-      // NS_ERROR_CORRUPTED_CONTENT so that tests can verify the difference
-      // between a hash error and a wrong download error.
       AUSTLMY.pingDownloadCode(this.isCompleteUpdate,
                                AUSTLMY.DWNLD_ERR_PATCH_SIZE_NOT_EQUAL);
       this.cancel(Cr.NS_ERROR_UNEXPECTED);
       return;
     }
 
     var listeners = this._listeners.concat();
     var listenerCount = listeners.length;
--- a/toolkit/mozapps/update/tests/chrome/update.sjs
+++ b/toolkit/mozapps/update/tests/chrome/update.sjs
@@ -111,28 +111,24 @@ function handleRequest(aRequest, aRespon
 
   let size;
   let patches = "";
   let url = params.badURL ? BAD_SERVICE_URL : SERVICE_URL;
   if (!params.partialPatchOnly) {
     size = SIZE_SIMPLE_MAR + (params.invalidCompleteSize ? "1" : "");
     let patchProps = {type: "complete",
                       url: url,
-                      hashFunction: "SHA512",
-                      hashValue: SHA512_HASH_SIMPLE_MAR,
                       size: size};
     patches += getRemotePatchString(patchProps);
   }
 
   if (!params.completePatchOnly) {
     size = SIZE_SIMPLE_MAR + (params.invalidPartialSize ? "1" : "");
     let patchProps = {type: "partial",
                       url: url,
-                      hashFunction: "SHA512",
-                      hashValue: SHA512_HASH_SIMPLE_MAR,
                       size: size};
     patches += getRemotePatchString(patchProps);
   }
 
   let updateProps = {};
   if (params.type) {
     updateProps.type = params.type;
   }
--- a/toolkit/mozapps/update/tests/data/sharedUpdateXML.js
+++ b/toolkit/mozapps/update/tests/data/sharedUpdateXML.js
@@ -10,26 +10,16 @@
  * used by the http server is launched with -v 170 this file must not use
  * features greater than JavaScript 1.7.
  */
 
 /* eslint-disable no-undef */
 
 const FILE_SIMPLE_MAR = "simple.mar";
 const SIZE_SIMPLE_MAR = "1031";
-const MD5_HASH_SIMPLE_MAR    = "1f8c038577bb6845d94ccec4999113ee";
-const SHA1_HASH_SIMPLE_MAR   = "5d49a672c87f10f31d7e326349564a11272a028b";
-const SHA256_HASH_SIMPLE_MAR = "1aabbed5b1dd6e16e139afc5b43d479e254e0c26" +
-                               "3c8fb9249c0a1bb93071c5fb";
-const SHA384_HASH_SIMPLE_MAR = "26615014ea034af32ef5651492d5f493f5a7a1a48522e" +
-                               "d24c366442a5ec21d5ef02e23fb58d79729b8ca2f9541" +
-                               "99dd53";
-const SHA512_HASH_SIMPLE_MAR = "922e5ae22081795f6e8d65a3c508715c9a314054179a8" +
-                               "bbfe5f50dc23919ad89888291bc0a07586ab17dd0304a" +
-                               "b5347473601127571c66f61f5080348e05c36b";
 
 const STATE_NONE            = "null";
 const STATE_DOWNLOADING     = "downloading";
 const STATE_PENDING         = "pending";
 const STATE_PENDING_SVC     = "pending-service";
 const STATE_APPLYING        = "applying";
 const STATE_APPLIED         = "applied";
 const STATE_APPLIED_SVC     = "applied-service";
@@ -162,18 +152,16 @@ function getRemotePatchString(aPatchProp
       if (gURLData) {
         return gURLData + FILE_SIMPLE_MAR;
       }
       return null;
     },
     set url(val) {
       this._url = val;
     },
-    hashFunction: "MD5",
-    hashValue: MD5_HASH_SIMPLE_MAR,
     size: SIZE_SIMPLE_MAR
   };
 
   for (let name in aPatchProps) {
     patchProps[name] = aPatchProps[name];
   }
 
   return getPatchString(patchProps) + "/>";
@@ -276,18 +264,16 @@ function getLocalUpdateString(aUpdatePro
  *         An object containing non default test values for an nsIUpdatePatch.
  *         See patchProps below for possible object names.
  * @return The string representing a patch element for a local update xml file.
  */
 function getLocalPatchString(aPatchProps) {
   const patchProps = {
     type: "complete",
     url: gURLData + FILE_SIMPLE_MAR,
-    hashFunction: "MD5",
-    hashValue: MD5_HASH_SIMPLE_MAR,
     size: SIZE_SIMPLE_MAR,
     selected: "true",
     state: STATE_SUCCEEDED
   };
 
   for (let name in aPatchProps) {
     patchProps[name] = aPatchProps[name];
   }
@@ -342,18 +328,14 @@ function getUpdateString(aUpdateProps) {
  * @param  aPatchProps (optional)
  *         An object containing non default test values for an nsIUpdatePatch.
  *         See the patchProps property names below for possible object names.
  * @return The string representing a patch element for an update xml file.
  */
 function getPatchString(aPatchProps) {
   let type = "type=\"" + aPatchProps.type + "\" ";
   let url = "URL=\"" + aPatchProps.url + "\" ";
-  let hashFunction = "hashFunction=\"" + aPatchProps.hashFunction + "\" ";
-  let hashValue = "hashValue=\"" + aPatchProps.hashValue + "\" ";
   let size = "size=\"" + aPatchProps.size + "\"";
   return "<patch " +
          type +
          url +
-         hashFunction +
-         hashValue +
          size;
 }
--- a/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js
+++ b/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js
@@ -1320,17 +1320,16 @@ function getSpecialFolderDir(aCSIDL) {
   return dir;
 }
 
 XPCOMUtils.defineLazyGetter(this, "gInstallDirPathHash", function test_gIDPH() {
   if (!IS_WIN) {
     do_throw("Windows only function called by a different platform!");
   }
 
-  // Figure out where we should check for a cached hash value
   if (!MOZ_APP_BASENAME) {
     return null;
   }
 
   let vendor = MOZ_APP_VENDOR ? MOZ_APP_VENDOR : "Mozilla";
   let appDir = getApplyDirFile(null, true);
 
   const REG_PATH = "SOFTWARE\\" + vendor + "\\" + MOZ_APP_BASENAME +
--- a/toolkit/mozapps/update/tests/unit_aus_update/downloadInterruptedRecovery.js
+++ b/toolkit/mozapps/update/tests/unit_aus_update/downloadInterruptedRecovery.js
@@ -13,18 +13,17 @@ const INC_CONTRACT_ID = "@mozilla.org/ne
 var gIncrementalDownloadErrorType = 0;
 
 var gNextRunFunc;
 var gExpectedStatusResult;
 
 function run_test() {
   setupTestCommon();
 
-  debugDump("testing mar downloads, mar hash verification, and " +
-            "mar download interrupted recovery");
+  debugDump("testing mar downloads and mar download interrupted recovery");
 
   Services.prefs.setBoolPref(PREF_APP_UPDATE_STAGING_ENABLED, false);
   start_httpserver();
   setUpdateURL(gURLData + gHTTPHandlerPath);
   standardInit();
   do_execute_soon(run_test_pt1);
 }
 
@@ -60,17 +59,17 @@ function check_test_helper_pt1_1() {
 
 function check_test_helper_pt1_2() {
   Assert.equal(gStatusResult, gExpectedStatusResult,
                "the download status result" + MSG_SHOULD_EQUAL);
   gAUS.removeDownloadListener(downloadListener);
   gNextRunFunc();
 }
 
-function setResponseBody(aHashFunction, aHashValue) {
+function setResponseBody() {
   let patches = getRemotePatchString({});
   let updates = getRemoteUpdateString({}, patches);
   gResponseBody = getRemoteUpdatesXMLString(updates);
 }
 
 function initMockIncrementalDownload() {
   let incrementalDownloadCID =
     MockRegistrar.register(INC_CONTRACT_ID, IncrementalDownload);
@@ -195,30 +194,30 @@ IncrementalDownload.prototype = {
     return this._status;
   },
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIIncrementalDownload])
 };
 
 // Test disconnecting during an update
 function run_test_pt1() {
   initMockIncrementalDownload();
-  setResponseBody("MD5", MD5_HASH_SIMPLE_MAR);
+  setResponseBody();
   run_test_helper_pt1("mar download with connection interruption",
                       Cr.NS_OK, run_test_pt2);
 }
 
 // Test disconnecting during an update
 function run_test_pt2() {
   gIncrementalDownloadErrorType = 0;
   Services.prefs.setIntPref(PREF_APP_UPDATE_SOCKET_MAXERRORS, 2);
   Services.prefs.setIntPref(PREF_APP_UPDATE_RETRYTIMEOUT, 0);
-  setResponseBody("MD5", MD5_HASH_SIMPLE_MAR);
+  setResponseBody();
   run_test_helper_pt1("mar download with connection interruption without recovery",
                       Cr.NS_ERROR_NET_RESET, run_test_pt3);
 }
 
 // Test entering offline mode while downloading
 function run_test_pt3() {
   gIncrementalDownloadErrorType = 4;
-  setResponseBody("MD5", MD5_HASH_SIMPLE_MAR);
+  setResponseBody();
   run_test_helper_pt1("mar download with offline mode",
                       Cr.NS_OK, finish_test);
 }
rename from toolkit/mozapps/update/tests/unit_aus_update/downloadAndHashCheckMar.js
rename to toolkit/mozapps/update/tests/unit_aus_update/downloadInvalidMar.js
--- a/toolkit/mozapps/update/tests/unit_aus_update/downloadAndHashCheckMar.js
+++ b/toolkit/mozapps/update/tests/unit_aus_update/downloadInvalidMar.js
@@ -9,29 +9,23 @@ var gExpectedStatusResult;
 function run_test() {
   // The network code that downloads the mar file accesses the profile to cache
   // the download, but the profile is only available after calling
   // do_get_profile in xpcshell tests. This prevents an error from being logged.
   do_get_profile();
 
   setupTestCommon();
 
-  debugDump("testing mar download and mar hash verification");
+  debugDump("testing invalid mar downloads");
 
   Services.prefs.setBoolPref(PREF_APP_UPDATE_STAGING_ENABLED, false);
   start_httpserver();
   setUpdateURL(gURLData + gHTTPHandlerPath);
   standardInit();
-  // Only perform the non hash check tests when mar signing is enabled since the
-  // update service doesn't perform hash checks when mar signing is enabled.
-  if (MOZ_VERIFY_MAR_SIGNATURE) {
-    do_execute_soon(run_test_pt11);
-  } else {
-    do_execute_soon(run_test_pt1);
-  }
+  do_execute_soon(run_test_pt1);
 }
 
 // The HttpServer must be stopped before calling do_test_finished
 function finish_test() {
   stop_httpserver(doTestFinish);
 }
 
 // Helper function for testing mar downloads that have the correct size
@@ -61,106 +55,27 @@ function check_test_helper_pt1_1() {
 
 function check_test_helper_pt1_2() {
   Assert.equal(gStatusResult, gExpectedStatusResult,
                "the download status result" + MSG_SHOULD_EQUAL);
   gAUS.removeDownloadListener(downloadListener);
   gNextRunFunc();
 }
 
-function setResponseBody(aHashFunction, aHashValue, aSize = null) {
-  let patchProps = {hashFunction: aHashFunction,
-                    hashValue: aHashValue};
-  if (aSize) {
-    patchProps.size = aSize;
-  }
-  let patches = getRemotePatchString(patchProps);
-  let updates = getRemoteUpdateString({}, patches);
-  gResponseBody = getRemoteUpdatesXMLString(updates);
-}
-
-// mar download with a valid MD5 hash
+// mar download with the mar not found
 function run_test_pt1() {
-  setResponseBody("MD5", MD5_HASH_SIMPLE_MAR);
-  run_test_helper_pt1("mar download with a valid MD5 hash",
-                      Cr.NS_OK, run_test_pt2);
-}
-
-// mar download with an invalid MD5 hash
-function run_test_pt2() {
-  setResponseBody("MD5", MD5_HASH_SIMPLE_MAR + "0");
-  run_test_helper_pt1("mar download with an invalid MD5 hash",
-                      Cr.NS_ERROR_CORRUPTED_CONTENT, run_test_pt3);
-}
-
-// mar download with a valid SHA1 hash
-function run_test_pt3() {
-  setResponseBody("SHA1", SHA1_HASH_SIMPLE_MAR);
-  run_test_helper_pt1("mar download with a valid SHA1 hash",
-                      Cr.NS_OK, run_test_pt4);
-}
-
-// mar download with an invalid SHA1 hash
-function run_test_pt4() {
-  setResponseBody("SHA1", SHA1_HASH_SIMPLE_MAR + "0");
-  run_test_helper_pt1("mar download with an invalid SHA1 hash",
-                      Cr.NS_ERROR_CORRUPTED_CONTENT, run_test_pt5);
-}
-
-// mar download with a valid SHA256 hash
-function run_test_pt5() {
-  setResponseBody("SHA256", SHA256_HASH_SIMPLE_MAR);
-  run_test_helper_pt1("mar download with a valid SHA256 hash",
-                      Cr.NS_OK, run_test_pt6);
-}
-
-// mar download with an invalid SHA256 hash
-function run_test_pt6() {
-  setResponseBody("SHA256", SHA256_HASH_SIMPLE_MAR + "0");
-  run_test_helper_pt1("mar download with an invalid SHA256 hash",
-                      Cr.NS_ERROR_CORRUPTED_CONTENT, run_test_pt7);
-}
-
-// mar download with a valid SHA384 hash
-function run_test_pt7() {
-  setResponseBody("SHA384", SHA384_HASH_SIMPLE_MAR);
-  run_test_helper_pt1("mar download with a valid SHA384 hash",
-                      Cr.NS_OK, run_test_pt8);
-}
-
-// mar download with an invalid SHA384 hash
-function run_test_pt8() {
-  setResponseBody("SHA384", SHA384_HASH_SIMPLE_MAR + "0");
-  run_test_helper_pt1("mar download with an invalid SHA384 hash",
-                      Cr.NS_ERROR_CORRUPTED_CONTENT, run_test_pt9);
-}
-
-// mar download with a valid SHA512 hash
-function run_test_pt9() {
-  setResponseBody("SHA512", SHA512_HASH_SIMPLE_MAR);
-  run_test_helper_pt1("mar download with a valid SHA512 hash",
-                      Cr.NS_OK, run_test_pt10);
-}
-
-// mar download with an invalid SHA512 hash
-function run_test_pt10() {
-  setResponseBody("SHA512", SHA512_HASH_SIMPLE_MAR + "0");
-  run_test_helper_pt1("mar download with an invalid SHA512 hash",
-                      Cr.NS_ERROR_CORRUPTED_CONTENT, run_test_pt11);
-}
-
-// mar download with the mar not found
-function run_test_pt11() {
   let patchProps = {url: gURLData + "missing.mar"};
   let patches = getRemotePatchString(patchProps);
   let updates = getRemoteUpdateString({}, patches);
   gResponseBody = getRemoteUpdatesXMLString(updates);
   run_test_helper_pt1("mar download with the mar not found",
-                      Cr.NS_ERROR_UNEXPECTED, run_test_pt12);
+                      Cr.NS_ERROR_UNEXPECTED, run_test_pt2);
 }
 
-// mar download with a valid MD5 hash but invalid file size
-function run_test_pt12() {
-  const arbitraryFileSize = 1024000;
-  setResponseBody("MD5", MD5_HASH_SIMPLE_MAR, arbitraryFileSize);
-  run_test_helper_pt1("mar download with a valid MD5 hash but invalid file size",
+// mar download with an invalid file size
+function run_test_pt2() {
+  let patchProps = {size: "1024000"};
+  let patches = getRemotePatchString(patchProps);
+  let updates = getRemoteUpdateString({}, patches);
+  gResponseBody = getRemoteUpdatesXMLString(updates);
+  run_test_helper_pt1("mar download with an invalid file size",
                       Cr.NS_ERROR_UNEXPECTED, finish_test);
 }
--- a/toolkit/mozapps/update/tests/unit_aus_update/remoteUpdateXML.js
+++ b/toolkit/mozapps/update/tests/unit_aus_update/remoteUpdateXML.js
@@ -49,24 +49,20 @@ function run_test_pt01() {
 // one update available and the update's property values
 function run_test_pt02() {
   debugDump("testing one update available and the update's property values");
   gUpdates = null;
   gUpdateCount = null;
   gCheckFunc = check_test_pt02;
   let patchProps = {type: "complete",
                     url: "http://complete/",
-                    hashFunction: "SHA1",
-                    hashValue: "98db9dad8e1d80eda7e1170d0187d6f53e477059",
                     size: "9856459"};
   let patches = getRemotePatchString(patchProps);
   patchProps = {type: "partial",
                 url: "http://partial/",
-                hashFunction: "SHA1",
-                hashValue: "e6678ca40ae7582316acdeddf3c133c9c8577de4",
                 size: "1316138"};
   patches += getRemotePatchString(patchProps);
   let updateProps = {type: "minor",
                      name: "Minor Test",
                      displayVersion: "version 2.1a1pre",
                      appVersion: "2.1a1pre",
                      buildID: "20080811053724",
                      detailsURL: "http://details/",
@@ -143,20 +139,16 @@ function check_test_pt02() {
   Assert.equal(bestUpdate.getProperty("custom2_attr"), "custom2 value",
                "the update custom2_attr property" + MSG_SHOULD_EQUAL);
 
   let patch = bestUpdate.getPatchAt(0);
   Assert.equal(patch.type, "complete",
                "the update patch type attribute" + MSG_SHOULD_EQUAL);
   Assert.equal(patch.URL, "http://complete/",
                "the update patch URL attribute" + MSG_SHOULD_EQUAL);
-  Assert.equal(patch.hashFunction, "SHA1",
-               "the update patch hashFunction attribute" + MSG_SHOULD_EQUAL);
-  Assert.equal(patch.hashValue, "98db9dad8e1d80eda7e1170d0187d6f53e477059",
-               "the update patch hashValue attribute" + MSG_SHOULD_EQUAL);
   Assert.equal(patch.size, 9856459,
                "the update patch size attribute" + MSG_SHOULD_EQUAL);
   // The value for patch.state can be the string 'null' as a valid value. This
   // is confusing if it returns null which is an invalid value since the test
   // failure output will show a failure for null == null. To lessen the
   // confusion first check that the typeof for patch.state is string.
   Assert.equal(typeof patch.state, "string",
                "the update patch state typeof value should equal |string|");
@@ -166,20 +158,16 @@ function check_test_pt02() {
             "the update patch selected attribute" + MSG_SHOULD_EQUAL);
   // XXX TODO - test nsIUpdatePatch:serialize
 
   patch = bestUpdate.getPatchAt(1);
   Assert.equal(patch.type, "partial",
                "the update patch type attribute" + MSG_SHOULD_EQUAL);
   Assert.equal(patch.URL, "http://partial/",
                "the update patch URL attribute" + MSG_SHOULD_EQUAL);
-  Assert.equal(patch.hashFunction, "SHA1",
-               "the update patch hashFunction attribute" + MSG_SHOULD_EQUAL);
-  Assert.equal(patch.hashValue, "e6678ca40ae7582316acdeddf3c133c9c8577de4",
-               "the update patch hashValue attribute" + MSG_SHOULD_EQUAL);
   Assert.equal(patch.size, 1316138,
                "the update patch size attribute" + MSG_SHOULD_EQUAL);
   Assert.equal(patch.state, STATE_NONE,
                "the update patch state attribute" + MSG_SHOULD_EQUAL);
   Assert.ok(!patch.selected,
             "the update patch selected attribute" + MSG_SHOULD_EQUAL);
   // XXX TODO - test nsIUpdatePatch:serialize
 
--- a/toolkit/mozapps/update/tests/unit_aus_update/updateManagerXML.js
+++ b/toolkit/mozapps/update/tests/unit_aus_update/updateManagerXML.js
@@ -13,18 +13,16 @@ function run_test() {
   setUpdateChannel("test_channel");
 
   // This test expects that the app.update.download.backgroundInterval
   // preference doesn't already exist.
   Services.prefs.deleteBranch("app.update.download.backgroundInterval");
 
   let patchProps = {type: "partial",
                     url: "http://partial/",
-                    hashFunction: "SHA256",
-                    hashValue: "cd43",
                     size: "86",
                     selected: "true",
                     state: STATE_PENDING};
   let patches = getLocalPatchString(patchProps);
   let updateProps = {type: "major",
                      name: "New",
                      displayVersion: "version 4",
                      appVersion: "4.0",
@@ -42,18 +40,16 @@ function run_test() {
                      custom1: "custom1_attr=\"custom1 value\"",
                      custom2: "custom2_attr=\"custom2 value\""};
   let updates = getLocalUpdateString(updateProps, patches);
   writeUpdatesToXMLFile(getLocalUpdatesXMLString(updates), true);
   writeStatusFile(STATE_SUCCEEDED);
 
   patchProps = {type: "complete",
                 url: "http://complete/",
-                hashFunction: "SHA1",
-                hashValue: "6232",
                 size: "75",
                 selected: "true",
                 state: STATE_FAILED};
   patches = getLocalPatchString(patchProps);
   updateProps = {type: "minor",
                  name: "Existing",
                  appVersion: "3.0",
                  detailsURL: "http://details2/",
@@ -115,20 +111,16 @@ function run_test() {
                "the update custom2_attr property" + MSG_SHOULD_EQUAL);
 
   debugDump("checking the activeUpdate patch properties");
   let patch = update.selectedPatch;
   Assert.equal(patch.type, "partial",
                "the update patch type attribute" + MSG_SHOULD_EQUAL);
   Assert.equal(patch.URL, "http://partial/",
                "the update patch URL attribute" + MSG_SHOULD_EQUAL);
-  Assert.equal(patch.hashFunction, "SHA256",
-               "the update patch hashFunction attribute" + MSG_SHOULD_EQUAL);
-  Assert.equal(patch.hashValue, "cd43",
-               "the update patch hashValue attribute" + MSG_SHOULD_EQUAL);
   Assert.equal(patch.size, "86",
                "the update patch size attribute" + MSG_SHOULD_EQUAL);
   Assert.ok(!!patch.selected,
             "the update patch selected attribute" + MSG_SHOULD_EQUAL);
   Assert.equal(patch.state, STATE_SUCCEEDED,
                "the update patch state attribute" + MSG_SHOULD_EQUAL);
 
   debugDump("checking the first update properties");
@@ -171,20 +163,16 @@ function run_test() {
                "the update custom4_attr property" + MSG_SHOULD_EQUAL);
 
   debugDump("checking the first update patch properties");
   patch = update.selectedPatch;
   Assert.equal(patch.type, "complete",
                "the update patch type attribute" + MSG_SHOULD_EQUAL);
   Assert.equal(patch.URL, "http://complete/",
                "the update patch URL attribute" + MSG_SHOULD_EQUAL);
-  Assert.equal(patch.hashFunction, "SHA1",
-               "the update patch hashFunction attribute" + MSG_SHOULD_EQUAL);
-  Assert.equal(patch.hashValue, "6232",
-               "the update patch hashValue attribute" + MSG_SHOULD_EQUAL);
   Assert.equal(patch.size, "75",
                "the update patch size attribute" + MSG_SHOULD_EQUAL);
   Assert.ok(!!patch.selected,
             "the update patch selected attribute" + MSG_SHOULD_EQUAL);
   Assert.equal(patch.state, STATE_FAILED,
                "the update patch state attribute" + MSG_SHOULD_EQUAL);
 
   doTestFinish();
--- a/toolkit/mozapps/update/tests/unit_aus_update/xpcshell.ini
+++ b/toolkit/mozapps/update/tests/unit_aus_update/xpcshell.ini
@@ -6,17 +6,17 @@
 tags = appupdate
 head = head_update.js
 
 [ausReadStrings.js]
 [canCheckForAndCanApplyUpdates.js]
 [urlConstruction.js]
 [updateManagerXML.js]
 [remoteUpdateXML.js]
-[downloadAndHashCheckMar.js]
+[downloadInvalidMar.js]
 [cleanupDownloadingForOlderAppVersion.js]
 [cleanupDownloadingForDifferentChannel.js]
 [cleanupDownloadingForSameVersionAndBuildID.js]
 [cleanupDownloadingIncorrectStatus.js]
 [cleanupPendingVersionFileIncorrectStatus.js]
 [cleanupSuccessLogMove.js]
 [cleanupSuccessLogsFIFO.js]
 [downloadInterruptedRecovery.js]
--- a/toolkit/xre/nsAppRunner.cpp
+++ b/toolkit/xre/nsAppRunner.cpp
@@ -116,16 +116,17 @@
 #include "nsIUUIDGenerator.h"
 #endif
 #endif
 
 #ifdef ACCESSIBILITY
 #include "nsAccessibilityService.h"
 #if defined(XP_WIN)
 #include "mozilla/a11y/Compatibility.h"
+#include "mozilla/a11y/Platform.h"
 #endif
 #endif
 
 #include "nsCRT.h"
 #include "nsCOMPtr.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsDirectoryServiceUtils.h"
 #include "nsEmbedCID.h"
@@ -964,16 +965,28 @@ nsXULAppInfo::GetAccessibilityEnabled(bo
   *aResult = GetAccService() != nullptr;
 #else
   *aResult = false;
 #endif
   return NS_OK;
 }
 
 NS_IMETHODIMP
+nsXULAppInfo::GetAccessibleHandlerUsed(bool* aResult)
+{
+#if defined(ACCESSIBILITY) && defined(XP_WIN)
+  *aResult = Preferences::GetBool("accessibility.handler.enabled", false) &&
+    a11y::IsHandlerRegistered();
+#else
+  *aResult = false;
+#endif
+  return NS_OK;
+}
+
+NS_IMETHODIMP
 nsXULAppInfo::GetIs64Bit(bool* aResult)
 {
 #ifdef HAVE_64BIT_BUILD
   *aResult = true;
 #else
   *aResult = false;
 #endif
   return NS_OK;
--- a/tools/profiler/gecko/nsProfiler.cpp
+++ b/tools/profiler/gecko/nsProfiler.cpp
@@ -15,21 +15,21 @@
 #include "mozilla/Services.h"
 #include "nsIObserverService.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsILoadContext.h"
 #include "nsIWebNavigation.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "shared-libraries.h"
 #include "js/Value.h"
-#include "mozilla/AbstractThread.h"
 #include "mozilla/ErrorResult.h"
 #include "mozilla/dom/Promise.h"
 #include "mozilla/dom/TypedArray.h"
 #include "nsLocalFile.h"
+#include "nsThreadUtils.h"
 #include "ProfilerParent.h"
 #include "platform.h"
 
 using namespace mozilla;
 
 using dom::AutoJSAPI;
 using dom::Promise;
 using std::string;
@@ -270,17 +270,17 @@ nsProfiler::GetProfileDataAsync(double a
 
   ErrorResult result;
   RefPtr<Promise> promise = Promise::Create(globalObject, result);
   if (NS_WARN_IF(result.Failed())) {
     return result.StealNSResult();
   }
 
   StartGathering(aSinceTime)->Then(
-    AbstractThread::MainThread(), __func__,
+    GetMainThreadSerialEventTarget(), __func__,
     [promise](nsCString aResult) {
       AutoJSAPI jsapi;
       if (NS_WARN_IF(!jsapi.Init(promise->GlobalJSObject()))) {
         // We're really hosed if we can't get a JS context for some reason.
         promise->MaybeReject(NS_ERROR_DOM_UNKNOWN_ERR);
         return;
       }
 
@@ -338,17 +338,17 @@ nsProfiler::GetProfileDataAsArrayBuffer(
 
   ErrorResult result;
   RefPtr<Promise> promise = Promise::Create(globalObject, result);
   if (NS_WARN_IF(result.Failed())) {
     return result.StealNSResult();
   }
 
   StartGathering(aSinceTime)->Then(
-    AbstractThread::MainThread(), __func__,
+    GetMainThreadSerialEventTarget(), __func__,
     [promise](nsCString aResult) {
       AutoJSAPI jsapi;
       if (NS_WARN_IF(!jsapi.Init(promise->GlobalJSObject()))) {
         // We're really hosed if we can't get a JS context for some reason.
         promise->MaybeReject(NS_ERROR_DOM_UNKNOWN_ERR);
         return;
       }
 
@@ -379,17 +379,17 @@ nsProfiler::DumpProfileToFileAsync(const
 
   if (!profiler_is_active()) {
     return NS_ERROR_FAILURE;
   }
 
   nsCString filename(aFilename);
 
   StartGathering(aSinceTime)->Then(
-    AbstractThread::MainThread(), __func__,
+    GetMainThreadSerialEventTarget(), __func__,
     [filename](const nsCString& aResult) {
       nsCOMPtr<nsIFile> file = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID);
       nsresult rv = file->InitWithNativePath(filename);
       if (NS_FAILED(rv)) {
         MOZ_CRASH();
       }
       nsCOMPtr<nsIFileOutputStream> of =
         do_CreateInstance("@mozilla.org/network/file-output-stream;1");
@@ -600,17 +600,17 @@ nsProfiler::StartGathering(double aSince
   // Keep the array property "processes" and the root object in mWriter open
   // until FinishGathering() is called. As profiles from the other processes
   // come in, they will be inserted and end up in the right spot.
   // FinishGathering() will close the array and the root object.
 
   mPendingProfiles = profiles.Length();
   RefPtr<nsProfiler> self = this;
   for (auto profile : profiles) {
-    profile->Then(AbstractThread::MainThread(), __func__,
+    profile->Then(GetMainThreadSerialEventTarget(), __func__,
       [self](const nsCString& aResult) {
         self->GatheredOOPProfile(aResult);
       },
       [self](ipc::PromiseRejectReason aReason) {
         self->GatheredOOPProfile(NS_LITERAL_CSTRING(""));
       });
   }
   if (!mPendingProfiles) {
deleted file mode 100644
--- a/widget/gonk/GeckoTouchDispatcher.cpp
+++ /dev/null
@@ -1,360 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 sts=2 et sw=2 tw=80: */
-/* Copyright 2014 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "FrameMetrics.h"
-#include "GeckoProfiler.h"
-#include "GeckoTouchDispatcher.h"
-#include "InputData.h"
-#include "ProfilerMarkerPayload.h"
-#include "base/basictypes.h"
-#include "gfxPrefs.h"
-#include "libui/Input.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/Mutex.h"
-#include "mozilla/TimeStamp.h"
-#include "mozilla/TouchEvents.h"
-#include "mozilla/dom/Touch.h"
-#include "mozilla/layers/APZThreadUtils.h"
-#include "mozilla/layers/CompositorBridgeParent.h"
-#include "nsAppShell.h"
-#include "nsDebug.h"
-#include "nsThreadUtils.h"
-#include "nsWindow.h"
-#include <sys/types.h>
-#include <unistd.h>
-#include <utils/Timers.h>
-
-#undef LOG
-#define LOG(args...)                                            \
-  __android_log_print(ANDROID_LOG_INFO, "Gonk" , ## args)
-
-// uncomment to print log resample data
-// #define LOG_RESAMPLE_DATA 1
-
-namespace mozilla {
-
-// Amount of time in MS before an input is considered expired.
-static const uint64_t kInputExpirationThresholdMs = 1000;
-
-static StaticRefPtr<GeckoTouchDispatcher> sTouchDispatcher;
-
-/* static */ GeckoTouchDispatcher*
-GeckoTouchDispatcher::GetInstance()
-{
-  if (!sTouchDispatcher) {
-    sTouchDispatcher = new GeckoTouchDispatcher();
-    ClearOnShutdown(&sTouchDispatcher);
-  }
-  return sTouchDispatcher;
-}
-
-GeckoTouchDispatcher::GeckoTouchDispatcher()
-  : mTouchQueueLock("GeckoTouchDispatcher::mTouchQueueLock")
-  , mHavePendingTouchMoves(false)
-  , mInflightNonMoveEvents(0)
-  , mTouchEventsFiltered(false)
-{
-  // Since GeckoTouchDispatcher is initialized when input is initialized
-  // and reads gfxPrefs, it is the first thing to touch gfxPrefs.
-  // The first thing to touch gfxPrefs MUST occur on the main thread and init
-  // the singleton
-  MOZ_ASSERT(sTouchDispatcher == nullptr);
-  MOZ_ASSERT(NS_IsMainThread());
-  gfxPrefs::GetSingleton();
-
-  mEnabledUniformityInfo = gfxPrefs::UniformityInfo();
-  mVsyncAdjust = TimeDuration::FromMilliseconds(gfxPrefs::TouchVsyncSampleAdjust());
-  mMaxPredict = TimeDuration::FromMilliseconds(gfxPrefs::TouchResampleMaxPredict());
-  mMinDelta = TimeDuration::FromMilliseconds(gfxPrefs::TouchResampleMinDelta());
-  mOldTouchThreshold = TimeDuration::FromMilliseconds(gfxPrefs::TouchResampleOldTouchThreshold());
-  mDelayedVsyncThreshold = TimeDuration::FromMilliseconds(gfxPrefs::TouchResampleVsyncDelayThreshold());
-}
-
-void
-GeckoTouchDispatcher::SetCompositorVsyncScheduler(mozilla::layers::CompositorVsyncScheduler *aObserver)
-{
-  MOZ_ASSERT(NS_IsMainThread());
-  // We assume on b2g that there is only 1 CompositorBridgeParent
-  MOZ_ASSERT(mCompositorVsyncScheduler == nullptr);
-  mCompositorVsyncScheduler = aObserver;
-}
-
-void
-GeckoTouchDispatcher::NotifyVsync(TimeStamp aVsyncTimestamp)
-{
-  layers::APZThreadUtils::AssertOnControllerThread();
-  DispatchTouchMoveEvents(aVsyncTimestamp);
-}
-
-// Touch data timestamps are in milliseconds, aEventTime is in nanoseconds
-void
-GeckoTouchDispatcher::NotifyTouch(MultiTouchInput& aTouch, TimeStamp aEventTime)
-{
-  if (mCompositorVsyncScheduler) {
-    mCompositorVsyncScheduler->SetNeedsComposite();
-  }
-
-  if (aTouch.mType == MultiTouchInput::MULTITOUCH_MOVE) {
-    MutexAutoLock lock(mTouchQueueLock);
-    if (mInflightNonMoveEvents > 0) {
-      // If we have any pending non-move events, we shouldn't resample the
-      // move events because we might end up dispatching events out of order.
-      // Instead, fall back to a non-resampling in-order dispatch until we're
-      // done processing the non-move events.
-      layers::APZThreadUtils::RunOnControllerThread(NewRunnableMethod<MultiTouchInput>(
-        this, &GeckoTouchDispatcher::DispatchTouchEvent, aTouch));
-      return;
-    }
-
-    mTouchMoveEvents.push_back(aTouch);
-    mHavePendingTouchMoves = true;
-  } else {
-    { // scope lock
-      MutexAutoLock lock(mTouchQueueLock);
-      mInflightNonMoveEvents++;
-    }
-    layers::APZThreadUtils::RunOnControllerThread(NewRunnableMethod<MultiTouchInput>(
-      this, &GeckoTouchDispatcher::DispatchTouchNonMoveEvent, aTouch));
-  }
-}
-
-void
-GeckoTouchDispatcher::DispatchTouchNonMoveEvent(MultiTouchInput aInput)
-{
-  layers::APZThreadUtils::AssertOnControllerThread();
-
-  // Flush pending touch move events, if there are any
-  // (DispatchTouchMoveEvents will check the mHavePendingTouchMoves flag and
-  // bail out if there's nothing to be done).
-  NotifyVsync(TimeStamp::Now());
-  DispatchTouchEvent(aInput);
-
-  { // scope lock
-    MutexAutoLock lock(mTouchQueueLock);
-    mInflightNonMoveEvents--;
-    MOZ_ASSERT(mInflightNonMoveEvents >= 0);
-  }
-}
-
-void
-GeckoTouchDispatcher::DispatchTouchMoveEvents(TimeStamp aVsyncTime)
-{
-  MultiTouchInput touchMove;
-
-  {
-    MutexAutoLock lock(mTouchQueueLock);
-    if (!mHavePendingTouchMoves) {
-      return;
-    }
-    mHavePendingTouchMoves = false;
-
-    int touchCount = mTouchMoveEvents.size();
-    TimeDuration vsyncTouchDiff = aVsyncTime - mTouchMoveEvents.back().mTimeStamp;
-    // The delay threshold is a positive pref, but we're testing to see if the
-    // vsync time is delayed from the touch, so add a negative sign.
-    bool isDelayedVsyncEvent = vsyncTouchDiff < -mDelayedVsyncThreshold;
-    bool isOldTouch = vsyncTouchDiff > mOldTouchThreshold;
-    bool resample = (touchCount > 1) && !isDelayedVsyncEvent && !isOldTouch;
-
-    if (!resample) {
-      touchMove = mTouchMoveEvents.back();
-      mTouchMoveEvents.clear();
-      if (!isDelayedVsyncEvent && !isOldTouch) {
-        mTouchMoveEvents.push_back(touchMove);
-      }
-    } else {
-      ResampleTouchMoves(touchMove, aVsyncTime);
-    }
-  }
-
-  DispatchTouchEvent(touchMove);
-}
-
-static int
-Interpolate(int start, int end, TimeDuration aFrameDiff, TimeDuration aTouchDiff)
-{
-  return start + (((end - start) * aFrameDiff.ToMicroseconds()) / aTouchDiff.ToMicroseconds());
-}
-
-static const SingleTouchData&
-GetTouchByID(const SingleTouchData& aCurrentTouch, MultiTouchInput& aOtherTouch)
-{
-  int32_t index = aOtherTouch.IndexOfTouch(aCurrentTouch.mIdentifier);
-  if (index < 0) {
-    // We can have situations where a previous touch event had 2 fingers
-    // and we lift 1 finger off. In those cases, we won't find the touch event
-    // with given id, so just return the current touch, which will be resampled
-    // without modification and dispatched.
-    return aCurrentTouch;
-  }
-  return aOtherTouch.mTouches[index];
-}
-
-
-// aTouchDiff is the duration between the base and current touch times
-// aFrameDiff is the duration between the base and the time we're resampling to
-static void
-ResampleTouch(MultiTouchInput& aOutTouch,
-              MultiTouchInput& aBase, MultiTouchInput& aCurrent,
-              TimeDuration aFrameDiff, TimeDuration aTouchDiff)
-{
-  aOutTouch = aCurrent;
-
-  // Make sure we only resample the correct finger.
-  for (size_t i = 0; i < aOutTouch.mTouches.Length(); i++) {
-    const SingleTouchData& current = aCurrent.mTouches[i];
-    const SingleTouchData& base = GetTouchByID(current, aBase);
-
-    const ScreenIntPoint& baseTouchPoint = base.mScreenPoint;
-    const ScreenIntPoint& currentTouchPoint = current.mScreenPoint;
-
-    ScreenIntPoint newSamplePoint;
-    newSamplePoint.x = Interpolate(baseTouchPoint.x, currentTouchPoint.x, aFrameDiff, aTouchDiff);
-    newSamplePoint.y = Interpolate(baseTouchPoint.y, currentTouchPoint.y, aFrameDiff, aTouchDiff);
-
-    aOutTouch.mTouches[i].mScreenPoint = newSamplePoint;
-
-#ifdef LOG_RESAMPLE_DATA
-    const char* type = "extrapolate";
-    if (aFrameDiff < aTouchDiff) {
-      type = "interpolate";
-    }
-
-    float alpha = aFrameDiff / aTouchDiff;
-    LOG("%s base (%d, %d), current (%d, %d) to (%d, %d) alpha %f, touch diff %d, frame diff %d\n",
-        type,
-        baseTouchPoint.x, baseTouchPoint.y,
-        currentTouchPoint.x, currentTouchPoint.y,
-        newSamplePoint.x, newSamplePoint.y,
-        alpha, (int)aTouchDiff.ToMilliseconds(), (int)aFrameDiff.ToMilliseconds());
-#endif
-  }
-}
-
-/*
- * +> Base touch (The touch before current touch)
- * |
- * |     +> Current touch (Latest touch)
- * |     |
- * |     |      +> Maximum resample time
- * |     |      |
- * +-----+------+--------------------> Time
- *    ^      ^
- *    |      |
- *    +------+--> Potential vsync events which the touches are resampled to
- *    |      |
- *    |      +> Extrapolation
- *    |
- *    +> Interpolation
- */
-
-void
-GeckoTouchDispatcher::ResampleTouchMoves(MultiTouchInput& aOutTouch, TimeStamp aVsyncTime)
-{
-  MOZ_RELEASE_ASSERT(mTouchMoveEvents.size() >= 2);
-  mTouchQueueLock.AssertCurrentThreadOwns();
-
-  MultiTouchInput currentTouch = mTouchMoveEvents.back();
-  mTouchMoveEvents.pop_back();
-  MultiTouchInput baseTouch = mTouchMoveEvents.back();
-  mTouchMoveEvents.clear();
-  mTouchMoveEvents.push_back(currentTouch);
-
-  TimeStamp sampleTime = aVsyncTime - mVsyncAdjust;
-  TimeDuration touchDiff = currentTouch.mTimeStamp - baseTouch.mTimeStamp;
-
-  if (touchDiff < mMinDelta) {
-    aOutTouch = currentTouch;
-    #ifdef LOG_RESAMPLE_DATA
-    LOG("The touches are too close, skip resampling\n");
-    #endif
-    return;
-  }
-
-  if (currentTouch.mTimeStamp < sampleTime) {
-    TimeDuration maxResampleTime = std::min(touchDiff / int64_t(2), mMaxPredict);
-    TimeStamp maxTimestamp = currentTouch.mTimeStamp + maxResampleTime;
-    if (sampleTime > maxTimestamp) {
-      sampleTime = maxTimestamp;
-      #ifdef LOG_RESAMPLE_DATA
-      LOG("Overshot extrapolation time, adjusting sample time\n");
-      #endif
-    }
-  }
-
-  ResampleTouch(aOutTouch, baseTouch, currentTouch, sampleTime - baseTouch.mTimeStamp, touchDiff);
-
-  // Both mTimeStamp and mTime are being updated to sampleTime here.
-  // mTime needs to be updated using a delta since TimeStamp doesn't
-  // provide a way to obtain a raw value.
-  aOutTouch.mTime += (sampleTime - aOutTouch.mTimeStamp).ToMilliseconds();
-  aOutTouch.mTimeStamp = sampleTime;
-}
-
-static bool
-IsExpired(const MultiTouchInput& aTouch)
-{
-  // No pending events, the filter state can be updated.
-  uint64_t timeNowMs = systemTime(SYSTEM_TIME_MONOTONIC) / 1000000;
-  return (timeNowMs - aTouch.mTime) > kInputExpirationThresholdMs;
-}
-void
-GeckoTouchDispatcher::DispatchTouchEvent(MultiTouchInput aMultiTouch)
-{
-  if ((aMultiTouch.mType == MultiTouchInput::MULTITOUCH_END ||
-       aMultiTouch.mType == MultiTouchInput::MULTITOUCH_CANCEL) &&
-      aMultiTouch.mTouches.Length() == 1) {
-    MutexAutoLock lock(mTouchQueueLock);
-    mTouchMoveEvents.clear();
-  } else if (aMultiTouch.mType == MultiTouchInput::MULTITOUCH_START &&
-             aMultiTouch.mTouches.Length() == 1) {
-    mTouchEventsFiltered = IsExpired(aMultiTouch);
-  }
-
-  if (mTouchEventsFiltered) {
-    return;
-  }
-
-  nsWindow::DispatchTouchInput(aMultiTouch);
-
-  if (mEnabledUniformityInfo && profiler_is_active()) {
-    const char* touchAction = "Invalid";
-    switch (aMultiTouch.mType) {
-      case MultiTouchInput::MULTITOUCH_START:
-        touchAction = "Touch_Event_Down";
-        break;
-      case MultiTouchInput::MULTITOUCH_MOVE:
-        touchAction = "Touch_Event_Move";
-        break;
-      case MultiTouchInput::MULTITOUCH_END:
-      case MultiTouchInput::MULTITOUCH_CANCEL:
-        touchAction = "Touch_Event_Up";
-        break;
-      case MultiTouchInput::MULTITOUCH_SENTINEL:
-        MOZ_ASSERT_UNREACHABLE("Invalid MultTouchInput.");
-        break;
-    }
-
-    const ScreenIntPoint& touchPoint = aMultiTouch.mTouches[0].mScreenPoint;
-#ifdef MOZ_GECKO_PROFILER
-    TouchDataPayload* payload = new TouchDataPayload(touchPoint);
-    PROFILER_MARKER_PAYLOAD(touchAction, payload);
-#endif
-  }
-}
-
-} // namespace mozilla
deleted file mode 100644
--- a/widget/gonk/GeckoTouchDispatcher.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 sts=2 et sw=2 tw=80: */
-/* Copyright 2014 Mozilla Foundation and Mozilla contributors
- *
- * 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.
- */
-
-#ifndef GECKO_TOUCH_INPUT_DISPATCHER_h
-#define GECKO_TOUCH_INPUT_DISPATCHER_h
-
-#include "InputData.h"
-#include "Units.h"
-#include "mozilla/Mutex.h"
-#include <vector>
-#include "mozilla/RefPtr.h"
-
-class nsIWidget;
-
-namespace mozilla {
-namespace layers {
-class CompositorVsyncScheduler;
-}
-
-// Used to resample touch events whenever a vsync event occurs. It batches
-// touch moves and on every vsync, resamples the touch position to create smooth
-// scrolls. We use the Android touch resample algorithm. It uses a combination of
-// extrapolation and interpolation. The algorithm takes the vsync time and
-// subtracts mVsyncAdjust time in ms and creates a sample time. All touch events are
-// relative to this sample time. If the last touch event occurs AFTER this
-// sample time, interpolate the last two touch events. If the last touch event occurs BEFORE
-// this sample time, we extrapolate the last two touch events to the sample
-// time. The magic numbers defined as constants are taken from android
-// InputTransport.cpp.
-class GeckoTouchDispatcher final
-{
-  NS_INLINE_DECL_THREADSAFE_REFCOUNTING(GeckoTouchDispatcher)
-
-public:
-  static GeckoTouchDispatcher* GetInstance();
-  void NotifyTouch(MultiTouchInput& aTouch, TimeStamp aEventTime);
-  void DispatchTouchEvent(MultiTouchInput aMultiTouch);
-  void DispatchTouchNonMoveEvent(MultiTouchInput aInput);
-  void DispatchTouchMoveEvents(TimeStamp aVsyncTime);
-  void NotifyVsync(TimeStamp aVsyncTimestamp);
-  void SetCompositorVsyncScheduler(layers::CompositorVsyncScheduler* aObserver);
-
-protected:
-  ~GeckoTouchDispatcher() {}
-
-private:
-  GeckoTouchDispatcher();
-  void ResampleTouchMoves(MultiTouchInput& aOutTouch, TimeStamp vsyncTime);
-  void SendTouchEvent(MultiTouchInput& aData);
-  void DispatchMouseEvent(MultiTouchInput& aMultiTouch,
-                          bool aForwardToChildren);
-
-  // mTouchQueueLock is used to protect the vector and state below
-  // as it is accessed on multiple threads.
-  Mutex mTouchQueueLock;
-  std::vector<MultiTouchInput> mTouchMoveEvents;
-  bool mHavePendingTouchMoves;
-  int mInflightNonMoveEvents;
-  // end stuff protected by mTouchQueueLock
-
-  bool mResamplingEnabled;
-  bool mTouchEventsFiltered;
-  bool mEnabledUniformityInfo;
-
-  // All times below are in nanoseconds
-  TimeDuration mVsyncAdjust;     // Time from vsync we create sample times from
-  TimeDuration mMaxPredict;      // How far into the future we're allowed to extrapolate
-  TimeDuration mMinDelta;        // Minimal time difference between touches for resampling
-
-  // Amount of time between vsync and the last event that is required before we
-  // resample
-  TimeDuration mMinResampleTime;
-
-  // Threshold if a vsync event runs too far behind touch events
-  TimeDuration mDelayedVsyncThreshold;
-
-  // How far ahead can vsync events get ahead of touch events.
-  TimeDuration mOldTouchThreshold;
-
-  RefPtr<layers::CompositorVsyncScheduler> mCompositorVsyncScheduler;
-};
-
-} // namespace mozilla
-
-#endif // GECKO_TOUCH_INPUT_DISPATCHER_h
deleted file mode 100644
--- a/widget/gonk/GfxInfo.cpp
+++ /dev/null
@@ -1,194 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "GfxInfo.h"
-
-using namespace mozilla::widget;
-
-/* GetD2DEnabled and GetDwriteEnabled shouldn't be called until after gfxPlatform initialization
- * has occurred because they depend on it for information. (See bug 591561) */
-nsresult
-GfxInfo::GetD2DEnabled(bool *aEnabled)
-{
-  return NS_ERROR_FAILURE;
-}
-
-nsresult
-GfxInfo::GetDWriteEnabled(bool *aEnabled)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetDWriteVersion(nsAString & aDwriteVersion)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetCleartypeParameters(nsAString & aCleartypeParams)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDescription(nsAString & aAdapterDescription)
-{
-  aAdapterDescription.Truncate();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDescription2(nsAString & aAdapterDescription)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterRAM(nsAString & aAdapterRAM)
-{
-  aAdapterRAM.Truncate();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterRAM2(nsAString & aAdapterRAM)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriver(nsAString & aAdapterDriver)
-{
-  aAdapterDriver.Truncate();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriver2(nsAString & aAdapterDriver)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriverVersion(nsAString & aAdapterDriverVersion)
-{
-  aAdapterDriverVersion.Truncate();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriverVersion2(nsAString & aAdapterDriverVersion)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriverDate(nsAString & aAdapterDriverDate)
-{
-  aAdapterDriverDate.Truncate();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriverDate2(nsAString & aAdapterDriverDate)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterVendorID(nsAString & aAdapterVendorID)
-{
-  aAdapterVendorID.Truncate();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterVendorID2(nsAString & aAdapterVendorID)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDeviceID(nsAString & aAdapterDeviceID)
-{
-  aAdapterDeviceID.Truncate();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDeviceID2(nsAString & aAdapterDeviceID)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterSubsysID(nsAString & aAdapterSubsysID)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterSubsysID2(nsAString & aAdapterSubsysID)
-{
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetIsGPU2Active(bool* aIsGPU2Active)
-{
-  return NS_ERROR_FAILURE;
-}
-
-const nsTArray<GfxDriverInfo>&
-GfxInfo::GetGfxDriverInfo()
-{
-  return *mDriverInfo;
-}
-
-uint32_t GfxInfo::OperatingSystemVersion()
-{
-  return 0;
-}
-
-nsresult
-GfxInfo::GetFeatureStatusImpl(int32_t /*aFeature*/,
-                              int32_t *aStatus,
-                              nsAString & /*aSuggestedDriverVersion*/,
-                              const nsTArray<GfxDriverInfo>& /*aDriverInfo*/,
-                              nsACString& aFailureId,
-                              OperatingSystem* /*aOS*/ /* = nullptr */)
-{
-  NS_ENSURE_ARG_POINTER(aStatus);
-  *aStatus = nsIGfxInfo::FEATURE_STATUS_OK;
-
-  return NS_OK;
-}
-
-#ifdef DEBUG
-
-// Implement nsIGfxInfoDebug
-
-NS_IMETHODIMP GfxInfo::SpoofVendorID(const nsAString &)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP GfxInfo::SpoofDeviceID(const nsAString &)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP GfxInfo::SpoofDriverVersion(const nsAString &)
-{
-  return NS_OK;
-}
-
-NS_IMETHODIMP GfxInfo::SpoofOSVersion(uint32_t)
-{
-  return NS_OK;
-}
-
-#endif
deleted file mode 100644
--- a/widget/gonk/GfxInfo.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/* vim: se cin sw=2 ts=2 et : */
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef __mozilla_widget_GfxInfo_h__
-#define __mozilla_widget_GfxInfo_h__
-
-#include "GfxInfoBase.h"
-#include "GfxDriverInfo.h"
-
-#include "nsString.h"
-
-namespace mozilla {
-namespace widget {
-
-class GfxInfo : public GfxInfoBase
-{
-public:
-  // We only declare the subset of nsIGfxInfo that we actually implement. The
-  // rest is brought forward from GfxInfoBase.
-  NS_IMETHOD GetD2DEnabled(bool *aD2DEnabled);
-  NS_IMETHOD GetDWriteEnabled(bool *aDWriteEnabled);
-  NS_IMETHOD GetDWriteVersion(nsAString & aDwriteVersion);
-  NS_IMETHOD GetCleartypeParameters(nsAString & aCleartypeParams);
-  NS_IMETHOD GetAdapterDescription(nsAString & aAdapterDescription);
-  NS_IMETHOD GetAdapterDriver(nsAString & aAdapterDriver);
-  NS_IMETHOD GetAdapterVendorID(nsAString & aAdapterVendorID);
-  NS_IMETHOD GetAdapterDeviceID(nsAString & aAdapterDeviceID);
-  NS_IMETHOD GetAdapterSubsysID(nsAString & aAdapterSubsysID);
-  NS_IMETHOD GetAdapterRAM(nsAString & aAdapterRAM);
-  NS_IMETHOD GetAdapterDriverVersion(nsAString & aAdapterDriverVersion);
-  NS_IMETHOD GetAdapterDriverDate(nsAString & aAdapterDriverDate);
-  NS_IMETHOD GetAdapterDescription2(nsAString & aAdapterDescription);
-  NS_IMETHOD GetAdapterDriver2(nsAString & aAdapterDriver);
-  NS_IMETHOD GetAdapterVendorID2(nsAString & aAdapterVendorID);
-  NS_IMETHOD GetAdapterDeviceID2(nsAString & aAdapterDeviceID);
-  NS_IMETHOD GetAdapterSubsysID2(nsAString & aAdapterSubsysID);
-  NS_IMETHOD GetAdapterRAM2(nsAString & aAdapterRAM);
-  NS_IMETHOD GetAdapterDriverVersion2(nsAString & aAdapterDriverVersion);
-  NS_IMETHOD GetAdapterDriverDate2(nsAString & aAdapterDriverDate);
-  NS_IMETHOD GetIsGPU2Active(bool *aIsGPU2Active);
-  using GfxInfoBase::GetFeatureStatus;
-  using GfxInfoBase::GetFeatureSuggestedDriverVersion;
-  using GfxInfoBase::GetWebGLParameter;
-
-  virtual uint32_t OperatingSystemVersion() override;
-
-#ifdef DEBUG
-  NS_DECL_NSIGFXINFODEBUG
-#endif
-
-protected:
-
-  virtual nsresult GetFeatureStatusImpl(int32_t aFeature,
-                                        int32_t *aStatus,
-                                        nsAString & aSuggestedDriverVersion,
-                                        const nsTArray<GfxDriverInfo>& aDriverInfo,
-                                        nsACString& aFailureId,
-                                        OperatingSystem* aOS = nullptr);
-  virtual const nsTArray<GfxDriverInfo>& GetGfxDriverInfo();
-};
-
-} // namespace widget
-} // namespace mozilla
-
-#endif /* __mozilla_widget_GfxInfo_h__ */
deleted file mode 100644
--- a/widget/gonk/GonkClipboardData.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "GonkClipboardData.h"
-#include "mozilla/gfx/DataSurfaceHelpers.h"
-
-namespace mozilla {
-
-void
-GonkClipboardData::SetText(const nsAString &aText)
-{
-  mPlain = aText;
-}
-
-bool
-GonkClipboardData::HasText() const
-{
-  return !mPlain.IsEmpty();
-}
-
-const nsAString&
-GonkClipboardData::GetText() const
-{
-  return mPlain;
-}
-
-void
-GonkClipboardData::SetHTML(const nsAString &aHTML)
-{
-  mHTML = aHTML;
-}
-
-bool
-GonkClipboardData::HasHTML() const
-{
-  return !mHTML.IsEmpty();
-}
-
-const nsAString&
-GonkClipboardData::GetHTML() const
-{
-  return mHTML;
-}
-
-void
-GonkClipboardData::SetImage(gfx::DataSourceSurface* aDataSource)
-{
-  // Clone a new DataSourceSurface and store it.
-  mImage = gfx::CreateDataSourceSurfaceByCloning(aDataSource);
-}
-
-bool
-GonkClipboardData::HasImage() const
-{
-  return static_cast<bool>(mImage);
-}
-
-already_AddRefed<gfx::DataSourceSurface>
-GonkClipboardData::GetImage() const
-{
-  // Return cloned DataSourceSurface.
-  RefPtr<gfx::DataSourceSurface> cloned = gfx::CreateDataSourceSurfaceByCloning(mImage);
-  return cloned.forget();
-}
-
-void
-GonkClipboardData::Clear()
-{
-  mPlain.Truncate(0);
-  mHTML.Truncate(0);
-  mImage = nullptr;
-}
-
-} // namespace mozilla
deleted file mode 100644
--- a/widget/gonk/GonkClipboardData.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef mozilla_GonkClipboardData
-#define mozilla_GonkClipboardData
-
-#include "mozilla/RefPtr.h"
-#include "nsString.h"
-
-namespace mozilla {
-
-namespace gfx {
-class DataSourceSurface;
-}
-
-class GonkClipboardData final
-{
-public:
-  explicit GonkClipboardData() = default;
-  ~GonkClipboardData() = default;
-
-  // For text/plain
-  void SetText(const nsAString &aText);
-  bool HasText() const;
-  const nsAString& GetText() const;
-
-  // For text/html
-  void SetHTML(const nsAString &aHTML);
-  bool HasHTML() const;
-  const nsAString& GetHTML() const;
-
-  // For images
-  void SetImage(gfx::DataSourceSurface* aDataSource);
-  bool HasImage() const;
-  already_AddRefed<gfx::DataSourceSurface> GetImage() const;
-
-  // For other APIs
-  void Clear();
-
-private:
-  nsAutoString mPlain;
-  nsAutoString mHTML;
-  RefPtr<gfx::DataSourceSurface> mImage;
-};
-
-} // namespace mozilla
-
-#endif // mozilla_GonkClipboardData
deleted file mode 100644
--- a/widget/gonk/GonkKeyMapping.h
+++ /dev/null
@@ -1,301 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * 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.
- */
-
-#ifndef GONKKEYMAPPING_H
-#define GONKKEYMAPPING_H
-
-#include "libui/android_keycodes.h"
-#include "mozilla/EventForwards.h"
-
-namespace mozilla {
-namespace widget {
-
-/* See libui/KeycodeLabels.h for the mapping */
-static const unsigned long kKeyMapping[] = {
-    0,
-    0, // SOFT_LEFT
-    0, // SOFT_RIGHT
-    NS_VK_HOME, // HOME
-    NS_VK_ESCAPE, // BACK
-    0, // CALL
-    NS_VK_SLEEP, // ENDCALL
-    NS_VK_0,
-    NS_VK_1,
-    NS_VK_2,
-    NS_VK_3,
-    NS_VK_4,
-    NS_VK_5,
-    NS_VK_6,
-    NS_VK_7,
-    NS_VK_8,
-    NS_VK_9,
-    NS_VK_ASTERISK,
-    NS_VK_HASH,
-    NS_VK_UP,
-    NS_VK_DOWN,
-    NS_VK_LEFT,
-    NS_VK_RIGHT,
-    NS_VK_RETURN,
-    NS_VK_VOLUME_UP,
-    NS_VK_VOLUME_DOWN,
-    NS_VK_SLEEP,     // POWER
-    NS_VK_PRINTSCREEN, // CAMERA
-    NS_VK_CLEAR,
-    NS_VK_A,
-    NS_VK_B,
-    NS_VK_C,
-    NS_VK_D,
-    NS_VK_E,
-    NS_VK_F,
-    NS_VK_G,
-    NS_VK_H,
-    NS_VK_I,
-    NS_VK_J,
-    NS_VK_K,
-    NS_VK_L,
-    NS_VK_M,
-    NS_VK_N,
-    NS_VK_O,
-    NS_VK_P,
-    NS_VK_Q,
-    NS_VK_R,
-    NS_VK_S,
-    NS_VK_T,
-    NS_VK_U,
-    NS_VK_V,
-    NS_VK_W,
-    NS_VK_X,
-    NS_VK_Y,
-    NS_VK_Z,
-    NS_VK_COMMA,
-    NS_VK_PERIOD,
-    0,
-    0,
-    0,
-    0,
-    NS_VK_TAB,
-    NS_VK_SPACE,
-    NS_VK_META, // SYM
-    0, // EXPLORER
-    0, // ENVELOPE
-    NS_VK_RETURN, // ENTER
-    NS_VK_BACK,
-    NS_VK_BACK_QUOTE, // GRAVE
-    NS_VK_HYPHEN_MINUS,
-    NS_VK_EQUALS,
-    NS_VK_OPEN_BRACKET,
-    NS_VK_CLOSE_BRACKET,
-    NS_VK_BACK_SLASH,
-    NS_VK_SEMICOLON,
-    NS_VK_QUOTE,
-    NS_VK_SLASH,
-    NS_VK_AT,
-    0, // NUM
-    NS_VK_F1, // HEADSETHOOK
-    0, // FOCUS
-    NS_VK_PLUS,
-    NS_VK_CONTEXT_MENU,
-    0, // NOTIFICATION
-    NS_VK_F5, // SEARCH
-    0, // MEDIA_PLAY_PAUSE
-    0, // MEDIA_STOP
-    0, // MEDIA_NEXT
-    0, // MEDIA_PREVIOUS
-    0, // MEDIA_REWIND
-    0, // MEDIA_FAST_FORWARD
-    0, // MUTE
-    NS_VK_PAGE_UP,
-    NS_VK_PAGE_DOWN,
-    0, // PICTSYMBOLS
-    0, // SWITCH_CHARSET
-    0, // BUTTON_A
-    0, // BUTTON_B
-    0, // BUTTON_C
-    0, // BUTTON_X
-    0, // BUTTON_Y
-    0, // BUTTON_Z
-    0, // BUTTON_L1
-    0, // BUTTON_R1
-    0, // BUTTON_L2
-    0, // BUTTON_R2
-    0, // BUTTON_THUMBL
-    0, // BUTTON_THUMBR
-    0, // BUTTON_START
-    0, // BUTTON_SELECT
-    0, // BUTTON_MODE
-    NS_VK_ESCAPE,
-    NS_VK_DELETE,
-    0, // CTRL_LEFT
-    0, // CTRL_RIGHT
-    NS_VK_CAPS_LOCK,
-    NS_VK_SCROLL_LOCK,
-    0, // META_LEFT
-    0, // META_RIGHT
-    0, // FUNCTION
-    0, // SYSRQ
-    0, // BREAK
-    NS_VK_HOME, // MOVE_HOME
-    NS_VK_END,
-    NS_VK_INSERT,
-    0, // FORWARD
-    0, // MEDIA_PLAY
-    0, // MEDIA_PAUSE
-    0, // MEDIA_CLOSE
-    0, // MEDIA_EJECT
-    0, // MEDIA_RECORD
-    NS_VK_F1,
-    NS_VK_F2,
-    NS_VK_F3,
-    NS_VK_F4,
-    NS_VK_F5,
-    NS_VK_F6,
-    NS_VK_F7,
-    NS_VK_F8,
-    NS_VK_F9,
-    NS_VK_F10,
-    NS_VK_F11,
-    NS_VK_F12,
-    NS_VK_NUM_LOCK,
-    NS_VK_NUMPAD0,
-    NS_VK_NUMPAD1,
-    NS_VK_NUMPAD2,
-    NS_VK_NUMPAD3,
-    NS_VK_NUMPAD4,
-    NS_VK_NUMPAD5,
-    NS_VK_NUMPAD6,
-    NS_VK_NUMPAD7,
-    NS_VK_NUMPAD8,
-    NS_VK_NUMPAD9,
-    NS_VK_DIVIDE,
-    NS_VK_MULTIPLY,
-    NS_VK_SUBTRACT,
-    NS_VK_ADD,
-    NS_VK_PERIOD,
-    NS_VK_COMMA,
-    NS_VK_RETURN,
-    NS_VK_EQUALS,
-    0, // NUMPAD_LEFT_PAREN
-    0, // NUMPAD_RIGHT_PAREN
-    NS_VK_VOLUME_MUTE,
-    // There are more but we don't map them
-};
-
-static KeyNameIndex GetKeyNameIndex(int aKeyCode)
-{
-    switch (aKeyCode) {
-#define NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, aKeyNameIndex) \
-    case aNativeKey: return aKeyNameIndex;
-
-#include "NativeKeyToDOMKeyName.h"
-
-#undef NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX
-
-    case AKEYCODE_0:
-    case AKEYCODE_1:
-    case AKEYCODE_2:
-    case AKEYCODE_3:
-    case AKEYCODE_4:
-    case AKEYCODE_5:
-    case AKEYCODE_6:
-    case AKEYCODE_7:
-    case AKEYCODE_8:
-    case AKEYCODE_9:
-    case AKEYCODE_STAR:
-    case AKEYCODE_POUND:
-    case AKEYCODE_A:
-    case AKEYCODE_B:
-    case AKEYCODE_C:
-    case AKEYCODE_D:
-    case AKEYCODE_E:
-    case AKEYCODE_F:
-    case AKEYCODE_G:
-    case AKEYCODE_H:
-    case AKEYCODE_I:
-    case AKEYCODE_J:
-    case AKEYCODE_K:
-    case AKEYCODE_L:
-    case AKEYCODE_M:
-    case AKEYCODE_N:
-    case AKEYCODE_O:
-    case AKEYCODE_P:
-    case AKEYCODE_Q:
-    case AKEYCODE_R:
-    case AKEYCODE_S:
-    case AKEYCODE_T:
-    case AKEYCODE_U:
-    case AKEYCODE_V:
-    case AKEYCODE_W:
-    case AKEYCODE_X:
-    case AKEYCODE_Y:
-    case AKEYCODE_Z:
-    case AKEYCODE_COMMA:
-    case AKEYCODE_PERIOD:
-    case AKEYCODE_SPACE:
-    case AKEYCODE_GRAVE:
-    case AKEYCODE_MINUS:
-    case AKEYCODE_EQUALS:
-    case AKEYCODE_LEFT_BRACKET:
-    case AKEYCODE_RIGHT_BRACKET:
-    case AKEYCODE_BACKSLASH:
-    case AKEYCODE_SEMICOLON:
-    case AKEYCODE_APOSTROPHE:
-    case AKEYCODE_SLASH:
-    case AKEYCODE_AT:
-    case AKEYCODE_PLUS:
-    case AKEYCODE_NUMPAD_0:
-    case AKEYCODE_NUMPAD_1:
-    case AKEYCODE_NUMPAD_2:
-    case AKEYCODE_NUMPAD_3:
-    case AKEYCODE_NUMPAD_4:
-    case AKEYCODE_NUMPAD_5:
-    case AKEYCODE_NUMPAD_6:
-    case AKEYCODE_NUMPAD_7:
-    case AKEYCODE_NUMPAD_8:
-    case AKEYCODE_NUMPAD_9:
-    case AKEYCODE_NUMPAD_DIVIDE:
-    case AKEYCODE_NUMPAD_MULTIPLY:
-    case AKEYCODE_NUMPAD_SUBTRACT:
-    case AKEYCODE_NUMPAD_ADD:
-    case AKEYCODE_NUMPAD_DOT:
-    case AKEYCODE_NUMPAD_COMMA:
-    case AKEYCODE_NUMPAD_EQUALS:
-    case AKEYCODE_NUMPAD_LEFT_PAREN:
-    case AKEYCODE_NUMPAD_RIGHT_PAREN:
-        return KEY_NAME_INDEX_USE_STRING;
-
-    default:
-        return KEY_NAME_INDEX_Unidentified;
-    }
-}
-
-static CodeNameIndex GetCodeNameIndex(int aScanCode)
-{
-    switch (aScanCode) {
-#define NS_NATIVE_KEY_TO_DOM_CODE_NAME_INDEX(aNativeKey, aCodeNameIndex) \
-    case aNativeKey: return aCodeNameIndex;
-
-#include "NativeKeyToDOMCodeName.h"
-
-#undef NS_NATIVE_KEY_TO_DOM_CODE_NAME_INDEX
-
-    default:
-        return CODE_NAME_INDEX_UNKNOWN;
-    }
-}
-
-} // namespace widget
-} // namespace mozilla
-
-#endif /* GONKKEYMAPPING_H */
deleted file mode 100644
--- a/widget/gonk/GonkMemoryPressureMonitoring.cpp
+++ /dev/null
@@ -1,355 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include <android/log.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <poll.h>
-#include <sys/sysinfo.h>
-
-#include "GonkMemoryPressureMonitoring.h"
-#include "mozilla/ArrayUtils.h"
-#include "mozilla/FileUtils.h"
-#include "mozilla/Monitor.h"
-#include "mozilla/Preferences.h"
-#include "mozilla/ProcessPriorityManager.h"
-#include "mozilla/Services.h"
-#include "nsIObserver.h"
-#include "nsIObserverService.h"
-#include "nsMemoryPressure.h"
-#include "nsPrintfCString.h"
-#include "nsThreadUtils.h"
-
-#define LOG(args...)  \
-  __android_log_print(ANDROID_LOG_INFO, "GonkMemoryPressure" , ## args)
-
-using namespace mozilla;
-
-namespace {
-
-/**
- * MemoryPressureWatcher watches sysfs from its own thread to notice when the
- * system is under memory pressure.  When we observe memory pressure, we use
- * MemoryPressureRunnable to notify observers that they should release memory.
- *
- * When the system is under memory pressure, we don't want to constantly fire
- * memory-pressure events.  So instead, we try to detect when sysfs indicates
- * that we're no longer under memory pressure, and only then start firing events
- * again.
- *
- * (This is a bit problematic because we can't poll() to detect when we're no
- * longer under memory pressure; instead we have to periodically read the sysfs
- * node.  If we remain under memory pressure for a long time, this means we'll
- * continue waking up to read from the node for a long time, potentially wasting
- * battery life.  Hopefully we don't hit this case in practice!  We write to
- * logcat each time we go around this loop so it's at least noticable.)
- *
- * Shutting down safely is a bit of a chore.  XPCOM won't shut down until all
- * threads exit, so we need to exit the Run() method below on shutdown.  But our
- * thread might be blocked in one of two situations: We might be poll()'ing the
- * sysfs node waiting for memory pressure to occur, or we might be asleep
- * waiting to read() the sysfs node to see if we're no longer under memory
- * pressure.
- *
- * To let us wake up from the poll(), we poll() not just the sysfs node but also
- * a pipe, which we write to on shutdown.  To let us wake up from sleeping
- * between read()s, we sleep by Wait()'ing on a monitor, which we notify on
- * shutdown.
- */
-class MemoryPressureWatcher final
-  : public nsIRunnable
-  , public nsIObserver
-{
-public:
-  MemoryPressureWatcher()
-    : mMonitor("MemoryPressureWatcher")
-    , mLowMemTriggerKB(0)
-    , mPageSize(0)
-    , mShuttingDown(false)
-    , mTriggerFd(-1)
-    , mShutdownPipeRead(-1)
-    , mShutdownPipeWrite(-1)
-  {
-  }
-
-  NS_DECL_THREADSAFE_ISUPPORTS
-
-  nsresult Init()
-  {
-    nsCOMPtr<nsIObserverService> os = services::GetObserverService();
-    NS_ENSURE_STATE(os);
-
-    // The observer service holds us alive.
-    os->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, /* ownsWeak */ false);
-
-    // Initialize the internal state
-    mPageSize = sysconf(_SC_PAGESIZE);
-    ReadPrefs();
-    nsresult rv = OpenFiles();
-    NS_ENSURE_SUCCESS(rv, rv);
-    SetLowMemTrigger(mSoftLowMemTriggerKB);
-
-    return NS_OK;
-  }
-
-  NS_IMETHOD Observe(nsISupports* aSubject, const char* aTopic,
-                     const char16_t* aData)
-  {
-    MOZ_ASSERT(strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0);
-    LOG("Observed XPCOM shutdown.");
-
-    MonitorAutoLock lock(mMonitor);
-    mShuttingDown = true;
-    mMonitor.Notify();
-
-    int rv;
-    do {
-      // Write something to the pipe; doesn't matter what.
-      uint32_t dummy = 0;
-      rv = write(mShutdownPipeWrite, &dummy, sizeof(dummy));
-    } while(rv == -1 && errno == EINTR);
-
-    return NS_OK;
-  }
-
-  NS_IMETHOD Run() override
-  {
-    MOZ_ASSERT(!NS_IsMainThread());
-
-    int triggerResetTimeout = -1;
-    bool memoryPressure;
-    nsresult rv = CheckForMemoryPressure(&memoryPressure);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    while (true) {
-      // Wait for a notification on mTriggerFd or for data to be written to
-      // mShutdownPipeWrite.  (poll(mTriggerFd, POLLPRI) blocks until we're
-      // under memory pressure or until we time out, the time out is used
-      // to adjust the trigger level after a memory pressure event.)
-      struct pollfd pollfds[2];
-      pollfds[0].fd = mTriggerFd;
-      pollfds[0].events = POLLPRI;
-      pollfds[1].fd = mShutdownPipeRead;
-      pollfds[1].events = POLLIN;
-
-      int pollRv = MOZ_TEMP_FAILURE_RETRY(
-        poll(pollfds, ArrayLength(pollfds), triggerResetTimeout)
-      );
-
-      if (pollRv == 0) {
-        // Timed out, adjust the trigger and update the timeout.
-        triggerResetTimeout = AdjustTrigger(triggerResetTimeout);
-        continue;
-      }
-
-      if (pollfds[1].revents) {
-        // Something was written to our shutdown pipe; we're outta here.
-        LOG("shutting down (1)");
-        return NS_OK;
-      }
-
-      // If pollfds[1] isn't happening, pollfds[0] ought to be!
-      if (!(pollfds[0].revents & POLLPRI)) {
-        LOG("Unexpected revents value after poll(): %d. "
-            "Shutting down GonkMemoryPressureMonitoring.", pollfds[0].revents);
-        return NS_ERROR_FAILURE;
-      }
-
-      // POLLPRI on mTriggerFd indicates that we're in a low-memory situation.
-      // We could read lowMemFd to double-check, but we've observed that the
-      // read sometimes completes after the memory-pressure event is over, so
-      // let's just believe the result of poll().
-      rv = DispatchMemoryPressure(MemPressure_New);
-      NS_ENSURE_SUCCESS(rv, rv);
-
-      // Move to the hard level if we're on the soft one.
-      if (mLowMemTriggerKB > mHardLowMemTriggerKB) {
-        SetLowMemTrigger(mHardLowMemTriggerKB);
-      }
-
-      // Manually check mTriggerFd until we observe that memory pressure is
-      // over.  We won't fire any more low-memory events until we observe that
-      // we're no longer under pressure. Instead, we fire low-memory-ongoing
-      // events, which cause processes to keep flushing caches but will not
-      // trigger expensive GCs and other attempts to save memory that are
-      // likely futile at this point.
-      do {
-        {
-          MonitorAutoLock lock(mMonitor);
-
-          // We need to check mShuttingDown before we wait here, in order to
-          // catch a shutdown signal sent after we poll()'ed mShutdownPipeRead
-          // above but before we started waiting on the monitor.  But we don't
-          // need to check after we wait, because we'll either do another
-          // iteration of this inner loop, in which case we'll check
-          // mShuttingDown, or we'll exit this loop and do another iteration
-          // of the outer loop, in which case we'll check the shutdown pipe.
-          if (mShuttingDown) {
-            LOG("shutting down (2)");
-            return NS_OK;
-          }
-          mMonitor.Wait(PR_MillisecondsToInterval(mPollMS));
-        }
-
-        LOG("Checking to see if memory pressure is over.");
-        rv = CheckForMemoryPressure(&memoryPressure);
-        NS_ENSURE_SUCCESS(rv, rv);
-
-        if (memoryPressure) {
-          rv = DispatchMemoryPressure(MemPressure_Ongoing);
-          NS_ENSURE_SUCCESS(rv, rv);
-          continue;
-        }
-      } while (false);
-
-      if (XRE_IsParentProcess()) {
-        // The main process will try to adjust the trigger.
-        triggerResetTimeout = mPollMS * 2;
-      }
-
-      LOG("Memory pressure is over.");
-    }
-
-    return NS_OK;
-  }
-
-protected:
-  ~MemoryPressureWatcher() {}
-
-private:
-  void ReadPrefs() {
-    // While we're under memory pressure, we periodically read()
-    // notify_trigger_active to try and see when we're no longer under memory
-    // pressure.  mPollMS indicates how many milliseconds we wait between those
-    // read()s.
-    Preferences::AddUintVarCache(&mPollMS,
-      "gonk.systemMemoryPressureRecoveryPollMS", /* default */ 5000);
-
-    // We have two values for the notify trigger, a soft one which is triggered
-    // before we start killing background applications and an hard one which is
-    // after we've killed background applications but before we start killing
-    // foreground ones.
-    Preferences::AddUintVarCache(&mSoftLowMemTriggerKB,
-      "gonk.notifySoftLowMemUnderKB", /* default */ 43008);
-    Preferences::AddUintVarCache(&mHardLowMemTriggerKB,
-      "gonk.notifyHardLowMemUnderKB", /* default */ 14336);
-  }
-
-  nsresult OpenFiles() {
-    mTriggerFd = open("/sys/kernel/mm/lowmemkiller/notify_trigger_active",
-                      O_RDONLY | O_CLOEXEC);
-    NS_ENSURE_STATE(mTriggerFd != -1);
-
-    int pipes[2];
-    NS_ENSURE_STATE(!pipe(pipes));
-    mShutdownPipeRead = pipes[0];
-    mShutdownPipeWrite = pipes[1];
-    return NS_OK;
-  }
-
-  /**
-   * Set the low memory trigger to the specified value, this can be done by
-   * the main process alone.
-   */
-  void SetLowMemTrigger(uint32_t aValue) {
-    if (XRE_IsParentProcess()) {
-      nsPrintfCString str("%ld", (aValue * 1024) / mPageSize);
-      if (WriteSysFile("/sys/module/lowmemorykiller/parameters/notify_trigger",
-                       str.get())) {
-        mLowMemTriggerKB = aValue;
-      }
-    }
-  }
-
-  /**
-   * Read from the trigger file descriptor and determine whether we're
-   * currently under memory pressure.
-   *
-   * We don't expect this method to block.
-   */
-  nsresult CheckForMemoryPressure(bool* aOut)
-  {
-    *aOut = false;
-
-    lseek(mTriggerFd, 0, SEEK_SET);
-
-    char buf[2];
-    int nread = MOZ_TEMP_FAILURE_RETRY(read(mTriggerFd, buf, sizeof(buf)));
-    NS_ENSURE_STATE(nread == 2);
-
-    // The notify_trigger_active sysfs node should contain either "0\n" or
-    // "1\n".  The latter indicates memory pressure.
-    *aOut = (buf[0] == '1');
-    return NS_OK;
-  }
-
-  int AdjustTrigger(int timeout)
-  {
-    if (!XRE_IsParentProcess()) {
-      return -1; // Only the main process can adjust the trigger.
-    }
-
-    struct sysinfo info;
-    int rv = sysinfo(&info);
-    if (rv < 0) {
-      return -1; // Without system information we're blind, bail out.
-    }
-
-    size_t freeMemory = (info.freeram * info.mem_unit) / 1024;
-
-    if (freeMemory > mSoftLowMemTriggerKB) {
-      SetLowMemTrigger(mSoftLowMemTriggerKB);
-      return -1; // Trigger adjusted, wait indefinitely.
-    }
-
-    // Wait again but double the duration, max once per day.
-    return std::min(86400000, timeout * 2);
-  }
-
-  /**
-   * Dispatch the specified memory pressure event. If a high-priority process is
-   * present then it's likely responding to an urgent event (an incoming call or
-   * message for example) so avoid wasting CPU time responding to low-memory
-   * events.
-   */
-  nsresult DispatchMemoryPressure(MemoryPressureState state)
-  {
-    return NS_DispatchMemoryPressure(state);
-  }
-
-  Monitor mMonitor;
-  uint32_t mPollMS; // Ongoing pressure poll delay
-  uint32_t mSoftLowMemTriggerKB; // Soft memory pressure level
-  uint32_t mHardLowMemTriggerKB; // Hard memory pressure level
-  uint32_t mLowMemTriggerKB; // Current value of the trigger
-  size_t mPageSize;
-  bool mShuttingDown;
-
-  ScopedClose mTriggerFd;
-  ScopedClose mShutdownPipeRead;
-  ScopedClose mShutdownPipeWrite;
-};
-
-NS_IMPL_ISUPPORTS(MemoryPressureWatcher, nsIRunnable, nsIObserver);
-
-} // namespace
-
-namespace mozilla {
-
-void
-InitGonkMemoryPressureMonitoring()
-{
-  // memoryPressureWatcher is held alive by the observer service.
-  RefPtr<MemoryPressureWatcher> memoryPressureWatcher =
-    new MemoryPressureWatcher();
-  NS_ENSURE_SUCCESS_VOID(memoryPressureWatcher->Init());
-
-  nsCOMPtr<nsIThread> thread;
-  NS_NewNamedThread("MemoryPressure", getter_AddRefs(thread),
-                    memoryPressureWatcher);
-}
-
-} // namespace mozilla
deleted file mode 100644
--- a/widget/gonk/GonkMemoryPressureMonitoring.h
+++ /dev/null
@@ -1,14 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#ifndef mozilla_GonkMemoryPressureMonitoring_h_
-#define mozilla_GonkMemoryPressureMonitoring_h_
-
-namespace mozilla {
-void InitGonkMemoryPressureMonitoring();
-}
-
-#endif /* mozilla_GonkMemoryPressureMonitoring_h_ */
deleted file mode 100644
--- a/widget/gonk/GonkPermission.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2012 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "GonkPermission.h"
-#include <binder/IPCThreadState.h>
-#include <binder/ProcessState.h>
-#include <binder/IServiceManager.h>
-#include <binder/IPermissionController.h>
-
-#ifndef HAVE_ANDROID_OS
-#define HAVE_ANDROID_OS 1
-#endif
-#include <private/android_filesystem_config.h>
-
-#include "mozilla/dom/ContentParent.h"
-#include "mozilla/dom/TabParent.h"
-#include "mozilla/SyncRunnable.h"
-#include "nsThreadUtils.h"
-
-#undef LOG
-#include <android/log.h>
-#undef ALOGE
-#define ALOGE(args...)  __android_log_print(ANDROID_LOG_ERROR, "gonkperm" , ## args)
-
-using namespace android;
-using namespace mozilla;
-
-bool
-GonkPermissionService::checkPermission(const String16& permission, int32_t pid,
-                                     int32_t uid)
-{
-  // root can do anything.
-  if (0 == uid) {
-    return true;
-  }
-
-  String8 perm8(permission);
-
-  // Some ril implementations need android.permission.MODIFY_AUDIO_SETTINGS
-  if ((uid == AID_SYSTEM || uid == AID_RADIO || uid == AID_BLUETOOTH) &&
-      perm8 == "android.permission.MODIFY_AUDIO_SETTINGS") {
-    return true;
-  }
-
-  // No other permissions apply to non-app processes.
-  if (uid < AID_APP) {
-    ALOGE("%s for pid=%d,uid=%d denied: not an app",
-      String8(permission).string(), pid, uid);
-    return false;
-  }
-
-  // Only these permissions can be granted to apps through this service.
-  if (perm8 != "android.permission.CAMERA" &&
-    perm8 != "android.permission.RECORD_AUDIO") {
-    ALOGE("%s for pid=%d,uid=%d denied: unsupported permission",
-      String8(permission).string(), pid, uid);
-    return false;
-  }
-
-  // Users granted the permission through a prompt dialog.
-  // Before permission managment of gUM is done, app cannot remember the
-  // permission.
-  PermissionGrant permGrant(perm8.string(), pid);
-  if (nsTArray<PermissionGrant>::NoIndex != mGrantArray.IndexOf(permGrant)) {
-    mGrantArray.RemoveElement(permGrant);
-  }
-
-  return true;
-}
-
-static GonkPermissionService* gGonkPermissionService = NULL;
-
-/* static */
-void
-GonkPermissionService::instantiate()
-{
-  defaultServiceManager()->addService(String16(getServiceName()),
-    GetInstance());
-}
-
-/* static */
-GonkPermissionService*
-GonkPermissionService::GetInstance()
-{
-  if (!gGonkPermissionService) {
-    gGonkPermissionService = new GonkPermissionService();
-  }
-  return gGonkPermissionService;
-}
-
-void
-GonkPermissionService::addGrantInfo(const char* permission, int32_t pid)
-{
-  mGrantArray.AppendElement(PermissionGrant(permission, pid));
-}
deleted file mode 100644
--- a/widget/gonk/GonkPermission.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2012 Mozilla Foundation
- *
- * 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.
- */
-#ifndef GONKPERMISSION_H
-#define GONKPERMISSION_H
-
-#include <binder/BinderService.h>
-#include "nsString.h"
-#include "nsTArray.h"
-
-namespace mozilla {
-class PermissionGrant
-{
-public:
-  PermissionGrant(const char* perm, int32_t p) : mPid(p)
-  {
-    mPermission.Assign(perm);
-  }
-
-  PermissionGrant(const nsACString& permission, int32_t pid) : mPid(pid),
-    mPermission(permission)
-  {
-  }
-
-  bool operator==(const PermissionGrant& other) const
-  {
-    return (mPid == other.pid() && mPermission.Equals(other.permission()));
-  }
-
-  int32_t pid() const
-  {
-    return mPid;
-  }
-
-  const nsACString& permission() const
-  {
-    return mPermission;
-  }
-
-private:
-  int32_t mPid;
-  nsCString mPermission;
-};
-
-class PermissionGrant;
-
-class GonkPermissionService :
-  public android::BinderService<GonkPermissionService>,
-  public android::BnPermissionController
-{
-public:
-  virtual ~GonkPermissionService() {}
-  static GonkPermissionService* GetInstance();
-  static const char *getServiceName() {
-    return "permission";
-  }
-
-  static void instantiate();
-
-  virtual android::status_t dump(int fd, const android::Vector<android::String16>& args) {
-    return android::NO_ERROR;
-  }
-  virtual bool checkPermission(const android::String16& permission, int32_t pid,
-      int32_t uid);
-
-  void addGrantInfo(const char* permission, int32_t pid);
-private:
-  GonkPermissionService(): android::BnPermissionController() {}
-  nsTArray<PermissionGrant> mGrantArray;
-};
-
-} // namespace mozilla
-
-#endif // GONKPERMISSION_H
deleted file mode 100644
--- a/widget/gonk/HwcComposer2D.cpp
+++ /dev/null
@@ -1,971 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:set ts=4 sw=4 sts=4 et: */
-/*
- * Copyright (c) 2012, 2013 The Linux Foundation. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <android/log.h>
-#include <string.h>
-
-#include "gfxPrefs.h"
-#include "ImageLayers.h"
-#include "libdisplay/GonkDisplay.h"
-#include "HwcComposer2D.h"
-#include "LayerScope.h"
-#include "Units.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/layers/CompositorBridgeParent.h"
-#include "mozilla/layers/LayerManagerComposite.h"
-#include "mozilla/layers/PLayerTransaction.h"
-#include "mozilla/layers/ShadowLayerUtilsGralloc.h"
-#include "mozilla/layers/TextureHostOGL.h"  // for TextureHostOGL
-#include "mozilla/StaticPtr.h"
-#include "nsThreadUtils.h"
-#include "cutils/properties.h"
-#include "gfx2DGlue.h"
-#include "gfxPlatform.h"
-#include "VsyncSource.h"
-#include "nsScreenManagerGonk.h"
-#include "nsWindow.h"
-
-#if ANDROID_VERSION >= 17
-#include "libdisplay/DisplaySurface.h"
-#endif
-
-#ifdef LOG_TAG
-#undef LOG_TAG
-#endif
-#define LOG_TAG "HWComposer"
-
-/*
- * By default the debug message of hwcomposer (LOG_DEBUG level) are undefined,
- * but can be enabled by uncommenting HWC_DEBUG below.
- */
-//#define HWC_DEBUG
-
-#ifdef HWC_DEBUG
-#define LOGD(args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, ## args)
-#else
-#define LOGD(args...) ((void)0)
-#endif
-
-#define LOGI(args...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, ## args)
-#define LOGE(args...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, ## args)
-
-#define LAYER_COUNT_INCREMENTS 5
-
-using namespace android;
-using namespace mozilla::gfx;
-using namespace mozilla::layers;
-
-namespace mozilla {
-
-static void
-HookInvalidate(const struct hwc_procs* aProcs)
-{
-    HwcComposer2D::GetInstance()->Invalidate();
-}
-
-static void
-HookVsync(const struct hwc_procs* aProcs, int aDisplay,
-          int64_t aTimestamp)
-{
-    HwcComposer2D::GetInstance()->Vsync(aDisplay, aTimestamp);
-}
-
-static void
-HookHotplug(const struct hwc_procs* aProcs, int aDisplay,
-            int aConnected)
-{
-    HwcComposer2D::GetInstance()->Hotplug(aDisplay, aConnected);
-}
-
-static StaticRefPtr<HwcComposer2D> sInstance;
-
-HwcComposer2D::HwcComposer2D()
-    : mList(nullptr)
-    , mMaxLayerCount(0)
-    , mColorFill(false)
-    , mRBSwapSupport(false)
-    , mPrepared(false)
-    , mHasHWVsync(false)
-    , mLock("mozilla.HwcComposer2D.mLock")
-{
-    mHal = HwcHALBase::CreateHwcHAL();
-    if (!mHal->HasHwc()) {
-        LOGD("no hwc support");
-        return;
-    }
-
-    RegisterHwcEventCallback();
-
-    nsIntSize screenSize;
-
-    GonkDisplay::NativeData data = GetGonkDisplay()->GetNativeData(GonkDisplay::DISPLAY_PRIMARY);
-    ANativeWindow *win = data.mNativeWindow.get();
-    win->query(win, NATIVE_WINDOW_WIDTH, &screenSize.width);
-    win->query(win, NATIVE_WINDOW_HEIGHT, &screenSize.height);
-    mScreenRect = gfx::IntRect(gfx::IntPoint(0, 0), screenSize);
-
-    mColorFill = mHal->Query(HwcHALBase::QueryType::COLOR_FILL);
-    mRBSwapSupport = mHal->Query(HwcHALBase::QueryType::RB_SWAP);
-}
-
-HwcComposer2D::~HwcComposer2D()
-{
-    free(mList);
-}
-
-HwcComposer2D*
-HwcComposer2D::GetInstance()
-{
-    if (!sInstance) {
-#ifdef HWC_DEBUG
-        // Make sure only create once
-        static int timesCreated = 0;
-        ++timesCreated;
-        MOZ_ASSERT(timesCreated == 1);
-#endif
-        LOGI("Creating new instance");
-        sInstance = new HwcComposer2D();
-
-        // If anyone uses the compositor thread to create HwcComposer2D,
-        // we just skip this function.
-        // If ClearOnShutdown() can handle objects in other threads
-        // in the future, we can remove this check.
-        if (NS_IsMainThread()) {
-            // If we create HwcComposer2D by the main thread, we can use
-            // ClearOnShutdown() to make sure it will be nullified properly.
-            ClearOnShutdown(&sInstance);
-        }
-    }
-    return sInstance;
-}
-
-bool
-HwcComposer2D::EnableVsync(bool aEnable)
-{
-    MOZ_ASSERT(NS_IsMainThread());
-    if (!mHasHWVsync) {
-        return false;
-    }
-    return mHal->EnableVsync(aEnable) && aEnable;
-}
-
-bool
-HwcComposer2D::RegisterHwcEventCallback()
-{
-    const HwcHALProcs_t cHWCProcs = {
-        &HookInvalidate,    // 1st: void (*invalidate)(...)
-        &HookVsync,         // 2nd: void (*vsync)(...)
-        &HookHotplug        // 3rd: void (*hotplug)(...)
-    };
-    mHasHWVsync = mHal->RegisterHwcEventCallback(cHWCProcs);
-    return mHasHWVsync;
-}
-
-void
-HwcComposer2D::Vsync(int aDisplay, nsecs_t aVsyncTimestamp)
-{
-    // Only support hardware vsync on kitkat, L and up due to inaccurate timings
-    // with JellyBean.
-#if (ANDROID_VERSION == 19 || ANDROID_VERSION >= 21)
-    TimeStamp vsyncTime = mozilla::TimeStamp::FromSystemTime(aVsyncTimestamp);
-    gfxPlatform::GetPlatform()->GetHardwareVsync()->GetGlobalDisplay().NotifyVsync(vsyncTime);
-#else
-    // If this device doesn't support vsync, this function should not be used.
-    MOZ_ASSERT(false);
-#endif
-}
-
-// Called on the "invalidator" thread (run from HAL).
-void
-HwcComposer2D::Invalidate()
-{
-    if (!mHal->HasHwc()) {
-        LOGE("HwcComposer2D::Invalidate failed!");
-        return;
-    }
-
-    MutexAutoLock lock(mLock);
-    if (mCompositorBridgeParent) {
-        mCompositorBridgeParent->ScheduleRenderOnCompositorThread();
-    }
-}
-
-namespace {
-class HotplugEvent : public Runnable {
-public:
-    HotplugEvent(GonkDisplay::DisplayType aType, bool aConnected)
-        : mType(aType)
-        , mConnected(aConnected)
-    {
-    }
-
-    NS_IMETHOD Run() override
-    {
-        RefPtr<nsScreenManagerGonk> screenManager =
-            nsScreenManagerGonk::GetInstance();
-        if (mConnected) {
-            screenManager->AddScreen(mType);
-        } else {
-            screenManager->RemoveScreen(mType);
-        }
-        return NS_OK;
-    }
-private:
-    GonkDisplay::DisplayType mType;
-    bool mConnected;
-};
-} // namespace
-
-void
-HwcComposer2D::Hotplug(int aDisplay, int aConnected)
-{
-    NS_DispatchToMainThread(new HotplugEvent(GonkDisplay::DISPLAY_EXTERNAL,
-                                             aConnected));
-}
-
-void
-HwcComposer2D::SetCompositorBridgeParent(CompositorBridgeParent* aCompositorBridgeParent)
-{
-    MutexAutoLock lock(mLock);
-    mCompositorBridgeParent = aCompositorBridgeParent;
-}
-
-bool
-HwcComposer2D::ReallocLayerList()
-{
-    int size = sizeof(HwcList) +
-        ((mMaxLayerCount + LAYER_COUNT_INCREMENTS) * sizeof(HwcLayer));
-
-    HwcList* listrealloc = (HwcList*)realloc(mList, size);
-
-    if (!listrealloc) {
-        return false;
-    }
-
-    if (!mList) {
-        //first alloc, initialize
-        listrealloc->numHwLayers = 0;
-        listrealloc->flags = 0;
-    }
-
-    mList = listrealloc;
-    mMaxLayerCount += LAYER_COUNT_INCREMENTS;
-    return true;
-}
-
-bool
-HwcComposer2D::PrepareLayerList(Layer* aLayer,
-                                const nsIntRect& aClip,
-                                const Matrix& aParentTransform,
-                                bool aFindSidebandStreams)
-{
-    // NB: we fall off this path whenever there are container layers
-    // that require intermediate surfaces.  That means all the
-    // GetEffective*() coordinates are relative to the framebuffer.
-
-    bool fillColor = false;
-
-    const nsIntRegion visibleRegion = aLayer->GetLocalVisibleRegion().ToUnknownRegion();
-    if (visibleRegion.IsEmpty()) {
-        return true;
-    }
-
-    uint8_t opacity = std::min(0xFF, (int)(aLayer->GetEffectiveOpacity() * 256.0));
-    if (opacity == 0) {
-        LOGD("%s Layer has zero opacity; skipping", aLayer->Name());
-        return true;
-    }
-
-    if (!mHal->SupportTransparency() && opacity < 0xFF && !aFindSidebandStreams) {
-        LOGD("%s Layer has planar semitransparency which is unsupported by hwcomposer", aLayer->Name());
-        return false;
-    }
-
-    if (aLayer->GetMaskLayer() && !aFindSidebandStreams) {
-        LOGD("%s Layer has MaskLayer which is unsupported by hwcomposer", aLayer->Name());
-        return false;
-    }
-
-    nsIntRect clip;
-    nsIntRect layerClip = aLayer->GetLocalClipRect().valueOr(ParentLayerIntRect()).ToUnknownRect();
-    nsIntRect* layerClipPtr = aLayer->GetLocalClipRect() ? &layerClip : nullptr;
-    if (!HwcUtils::CalculateClipRect(aParentTransform,
-                                     layerClipPtr,
-                                     aClip,
-                                     &clip))
-    {
-        LOGD("%s Clip rect is empty. Skip layer", aLayer->Name());
-        return true;
-    }
-
-    // HWC supports only the following 2D transformations:
-    //
-    // Scaling via the sourceCrop and displayFrame in HwcLayer
-    // Translation via the sourceCrop and displayFrame in HwcLayer
-    // Rotation (in square angles only) via the HWC_TRANSFORM_ROT_* flags
-    // Reflection (horizontal and vertical) via the HWC_TRANSFORM_FLIP_* flags
-    //
-    // A 2D transform with PreservesAxisAlignedRectangles() has all the attributes
-    // above
-    Matrix layerTransform;
-    if (!aLayer->GetEffectiveTransform().Is2D(&layerTransform) ||
-        !layerTransform.PreservesAxisAlignedRectangles()) {
-        LOGD("Layer EffectiveTransform has a 3D transform or a non-square angle rotation");
-        return false;
-    }
-
-    Matrix layerBufferTransform;
-    if (!aLayer->GetEffectiveTransformForBuffer().Is2D(&layerBufferTransform) ||
-        !layerBufferTransform.PreservesAxisAlignedRectangles()) {
-        LOGD("Layer EffectiveTransformForBuffer has a 3D transform or a non-square angle rotation");
-      return false;
-    }
-
-    if (ContainerLayer* container = aLayer->AsContainerLayer()) {
-        if (container->UseIntermediateSurface() && !aFindSidebandStreams) {
-            LOGD("Container layer needs intermediate surface");
-            return false;
-        }
-        AutoTArray<Layer*, 12> children;
-        container->SortChildrenBy3DZOrder(children);
-
-        for (uint32_t i = 0; i < children.Length(); i++) {
-            if (!PrepareLayerList(children[i], clip, layerTransform, aFindSidebandStreams) &&
-                !aFindSidebandStreams) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    LayerRenderState state = aLayer->GetRenderState();
-
-#if ANDROID_VERSION >= 21
-    if (!state.GetGrallocBuffer() && !state.GetSidebandStream().IsValid()) {
-#else
-    if (!state.GetGrallocBuffer()) {
-#endif
-        if (aLayer->AsColorLayer() && mColorFill) {
-            fillColor = true;
-        } else {
-            LOGD("%s Layer doesn't have a gralloc buffer", aLayer->Name());
-            return false;
-        }
-    }
-
-    nsIntRect visibleRect = visibleRegion.GetBounds();
-
-    nsIntRect bufferRect;
-    if (fillColor) {
-        bufferRect = nsIntRect(visibleRect);
-    } else {
-        nsIntRect layerRect;
-        if (state.mHasOwnOffset) {
-            bufferRect = nsIntRect(state.mOffset.x, state.mOffset.y,
-                                   state.mSize.width, state.mSize.height);
-            layerRect = bufferRect;
-        } else {
-            //Since the buffer doesn't have its own offset, assign the whole
-            //surface size as its buffer bounds
-            bufferRect = nsIntRect(0, 0, state.mSize.width, state.mSize.height);
-            layerRect = bufferRect;
-            if (aLayer->GetType() == Layer::TYPE_IMAGE) {
-                ImageLayer* imageLayer = static_cast<ImageLayer*>(aLayer);
-                if(imageLayer->GetScaleMode() != ScaleMode::SCALE_NONE) {
-                  layerRect = nsIntRect(0, 0, imageLayer->GetScaleToSize().width, imageLayer->GetScaleToSize().height);
-                }
-            }
-        }
-        // In some cases the visible rect assigned to the layer can be larger
-        // than the layer's surface, e.g., an ImageLayer with a small Image
-        // in it.
-        visibleRect.IntersectRect(visibleRect, layerRect);
-    }
-
-    // Buffer rotation is not to be confused with the angled rotation done by a transform matrix
-    // It's a fancy PaintedLayer feature used for scrolling
-    if (state.BufferRotated()) {
-        LOGD("%s Layer has a rotated buffer", aLayer->Name());
-        return false;
-    }
-
-    const bool needsYFlip = state.OriginBottomLeft() ? true
-                                                     : false;
-
-    hwc_rect_t sourceCrop, displayFrame;
-    if(!HwcUtils::PrepareLayerRects(visibleRect,
-                          layerTransform,
-                          layerBufferTransform,
-                          clip,
-                          bufferRect,
-                          needsYFlip,
-                          &(sourceCrop),
-                          &(displayFrame)))
-    {
-        return true;
-    }
-
-    // OK!  We can compose this layer with hwc.
-    int current = mList ? mList->numHwLayers : 0;
-
-    // Do not compose any layer below full-screen Opaque layer
-    // Note: It can be generalized to non-fullscreen Opaque layers.
-    bool isOpaque = opacity == 0xFF &&
-        (state.mFlags & LayerRenderStateFlags::OPAQUE);
-    // Currently we perform opacity calculation using the *bounds* of the layer.
-    // We can only make this assumption if we're not dealing with a complex visible region.
-    bool isSimpleVisibleRegion = visibleRegion.Contains(visibleRect);
-    if (current && isOpaque && isSimpleVisibleRegion) {
-        nsIntRect displayRect = nsIntRect(displayFrame.left, displayFrame.top,
-            displayFrame.right - displayFrame.left, displayFrame.bottom - displayFrame.top);
-        if (displayRect.Contains(mScreenRect)) {
-            // In z-order, all previous layers are below
-            // the current layer. We can ignore them now.
-            mList->numHwLayers = current = 0;
-            mHwcLayerMap.Clear();
-        }
-    }
-
-    if (!mList || current >= mMaxLayerCount) {
-        if (!ReallocLayerList() || current >= mMaxLayerCount) {
-            LOGE("PrepareLayerList failed! Could not increase the maximum layer count");
-            return false;
-        }
-    }
-
-    HwcLayer& hwcLayer = mList->hwLayers[current];
-    hwcLayer.displayFrame = displayFrame;
-    mHal->SetCrop(hwcLayer, sourceCrop);
-    buffer_handle_t handle = nullptr;
-#if ANDROID_VERSION >= 21
-    if (state.GetSidebandStream().IsValid()) {
-        handle = state.GetSidebandStream().GetRawNativeHandle();
-    } else if (state.GetGrallocBuffer()) {
-        handle = state.GetGrallocBuffer()->getNativeBuffer()->handle;
-    }
-#else
-    if (state.GetGrallocBuffer()) {
-        handle = state.GetGrallocBuffer()->getNativeBuffer()->handle;
-    }
-#endif
-    hwcLayer.handle = handle;
-
-    hwcLayer.flags = 0;
-    hwcLayer.hints = 0;
-    hwcLayer.blending = isOpaque ? HWC_BLENDING_NONE : HWC_BLENDING_PREMULT;
-#if ANDROID_VERSION >= 17
-    hwcLayer.compositionType = HWC_FRAMEBUFFER;
-#if ANDROID_VERSION >= 21
-    if (state.GetSidebandStream().IsValid()) {
-        hwcLayer.compositionType = HWC_SIDEBAND;
-    }
-#endif
-    hwcLayer.acquireFenceFd = -1;
-    hwcLayer.releaseFenceFd = -1;
-#if ANDROID_VERSION >= 18
-    hwcLayer.planeAlpha = opacity;
-#endif
-#else
-    hwcLayer.compositionType = HwcUtils::HWC_USE_COPYBIT;
-#endif
-
-    if (!fillColor) {
-        if (state.FormatRBSwapped()) {
-            if (!mRBSwapSupport) {
-                LOGD("No R/B swap support in H/W Composer");
-                return false;
-            }
-            hwcLayer.flags |= HwcUtils::HWC_FORMAT_RB_SWAP;
-        }
-
-        // Translation and scaling have been addressed in PrepareLayerRects().
-        // Given the above and that we checked for PreservesAxisAlignedRectangles()
-        // the only possible transformations left to address are
-        // square angle rotation and horizontal/vertical reflection.
-        //
-        // The rotation and reflection permutations total 16 but can be
-        // reduced to 8 transformations after eliminating redundancies.
-        //
-        // All matrices represented here are in the form
-        //
-        // | xx  xy |
-        // | yx  yy |
-        //
-        // And ignore scaling.
-        //
-        // Reflection is applied before rotation
-        gfx::Matrix rotation = layerTransform;
-        // Compute fuzzy zero like PreservesAxisAlignedRectangles()
-        if (fabs(rotation._11) < 1e-6) {
-            if (rotation._21 < 0) {
-                if (rotation._12 > 0) {
-                    // 90 degree rotation
-                    //
-                    // |  0  -1  |
-                    // |  1   0  |
-                    //
-                    hwcLayer.transform = HWC_TRANSFORM_ROT_90;
-                    LOGD("Layer rotated 90 degrees");
-                }
-                else {
-                    // Horizontal reflection then 90 degree rotation
-                    //
-                    // |  0  -1  | | -1   0  | = |  0  -1  |
-                    // |  1   0  | |  0   1  |   | -1   0  |
-                    //
-                    // same as vertical reflection then 270 degree rotation
-                    //
-                    // |  0   1  | |  1   0  | = |  0  -1  |
-                    // | -1   0  | |  0  -1  |   | -1   0  |
-                    //
-                    hwcLayer.transform = HWC_TRANSFORM_ROT_90 | HWC_TRANSFORM_FLIP_H;
-                    LOGD("Layer vertically reflected then rotated 270 degrees");
-                }
-            } else {
-                if (rotation._12 < 0) {
-                    // 270 degree rotation
-                    //
-                    // |  0   1  |
-                    // | -1   0  |
-                    //
-                    hwcLayer.transform = HWC_TRANSFORM_ROT_270;
-                    LOGD("Layer rotated 270 degrees");
-                }
-                else {
-                    // Vertical reflection then 90 degree rotation
-                    //
-                    // |  0   1  | | -1   0  | = |  0   1  |
-                    // | -1   0  | |  0   1  |   |  1   0  |
-                    //
-                    // Same as horizontal reflection then 270 degree rotation
-                    //
-                    // |  0  -1  | |  1   0  | = |  0   1  |
-                    // |  1   0  | |  0  -1  |   |  1   0  |
-                    //
-                    hwcLayer.transform = HWC_TRANSFORM_ROT_90 | HWC_TRANSFORM_FLIP_V;
-                    LOGD("Layer horizontally reflected then rotated 270 degrees");
-                }
-            }
-        } else if (rotation._11 < 0) {
-            if (rotation._22 > 0) {
-                // Horizontal reflection
-                //
-                // | -1   0  |
-                // |  0   1  |
-                //
-                hwcLayer.transform = HWC_TRANSFORM_FLIP_H;
-                LOGD("Layer rotated 180 degrees");
-            }
-            else {
-                // 180 degree rotation
-                //
-                // | -1   0  |
-                // |  0  -1  |
-                //
-                // Same as horizontal and vertical reflection
-                //
-                // | -1   0  | |  1   0  | = | -1   0  |
-                // |  0   1  | |  0  -1  |   |  0  -1  |
-                //
-                hwcLayer.transform = HWC_TRANSFORM_ROT_180;
-                LOGD("Layer rotated 180 degrees");
-            }
-        } else {
-            if (rotation._22 < 0) {
-                // Vertical reflection
-                //
-                // |  1   0  |
-                // |  0  -1  |
-                //
-                hwcLayer.transform = HWC_TRANSFORM_FLIP_V;
-                LOGD("Layer rotated 180 degrees");
-            }
-            else {
-                // No rotation or reflection
-                //
-                // |  1   0  |
-                // |  0   1  |
-                //
-                hwcLayer.transform = 0;
-            }
-        }
-
-        const bool needsYFlip = state.OriginBottomLeft() ? true
-                                                         : false;
-
-        if (needsYFlip) {
-           // Invert vertical reflection flag if it was already set
-           hwcLayer.transform ^= HWC_TRANSFORM_FLIP_V;
-        }
-        hwc_region_t region;
-        if (visibleRegion.GetNumRects() > 1) {
-            mVisibleRegions.push_back(HwcUtils::RectVector());
-            HwcUtils::RectVector* visibleRects = &(mVisibleRegions.back());
-            bool isVisible = false;
-            if(!HwcUtils::PrepareVisibleRegion(visibleRegion,
-                                     layerTransform,
-                                     layerBufferTransform,
-                                     clip,
-                                     bufferRect,
-                                     visibleRects,
-                                     isVisible)) {
-                LOGD("A region of layer is too small to be rendered by HWC");
-                return false;
-            }
-            if (!isVisible) {
-                // Layer is not visible, no need to render it
-                return true;
-            }
-            region.numRects = visibleRects->size();
-            region.rects = &((*visibleRects)[0]);
-        } else {
-            region.numRects = 1;
-            region.rects = &(hwcLayer.displayFrame);
-        }
-        hwcLayer.visibleRegionScreen = region;
-    } else {
-        hwcLayer.flags |= HwcUtils::HWC_COLOR_FILL;
-        ColorLayer* colorLayer = aLayer->AsColorLayer();
-        if (colorLayer->GetColor().a < 1.0) {
-            LOGD("Color layer has semitransparency which is unsupported");
-            return false;
-        }
-        hwcLayer.transform = colorLayer->GetColor().ToABGR();
-    }
-
-#if ANDROID_VERSION >= 21
-    if (aFindSidebandStreams && hwcLayer.compositionType == HWC_SIDEBAND) {
-        mCachedSidebandLayers.AppendElement(hwcLayer);
-    }
-#endif
-
-    mHwcLayerMap.AppendElement(static_cast<LayerComposite*>(aLayer->ImplData()));
-    mList->numHwLayers++;
-    return true;
-}
-
-
-#if ANDROID_VERSION >= 17
-bool
-HwcComposer2D::TryHwComposition(nsScreenGonk* aScreen)
-{
-    DisplaySurface* dispSurface = aScreen->GetDisplaySurface();
-
-    if (!(dispSurface && dispSurface->lastHandle)) {
-        LOGD("H/W Composition failed. DispSurface not initialized.");
-        return false;
-    }
-
-    // Add FB layer
-    int idx = mList->numHwLayers++;
-    if (idx >= mMaxLayerCount) {
-        if (!ReallocLayerList() || idx >= mMaxLayerCount) {
-            LOGE("TryHwComposition failed! Could not add FB layer");
-            return false;
-        }
-    }
-
-    Prepare(dispSurface->lastHandle, -1, aScreen);
-
-    /* Possible composition paths, after hwc prepare:
-    1. GPU Composition
-    2. BLIT Composition
-    3. Full OVERLAY Composition
-    4. Partial OVERLAY Composition (GPU + OVERLAY) */
-
-    bool gpuComposite = false;
-    bool blitComposite = false;
-    bool overlayComposite = true;
-
-    for (int j=0; j < idx; j++) {
-        if (mList->hwLayers[j].compositionType == HWC_FRAMEBUFFER ||
-            mList->hwLayers[j].compositionType == HWC_BLIT) {
-            // Full OVERLAY composition is not possible on this frame
-            // It is either GPU / BLIT / partial OVERLAY composition.
-            overlayComposite = false;
-            break;
-        }
-    }
-
-    if (!overlayComposite) {
-        for (int k=0; k < idx; k++) {
-            switch (mList->hwLayers[k].compositionType) {
-                case HWC_FRAMEBUFFER:
-                    gpuComposite = true;
-                    break;
-                case HWC_BLIT:
-                    blitComposite = true;
-                    break;
-#if ANDROID_VERSION >= 21
-                case HWC_SIDEBAND:
-#endif
-                case HWC_OVERLAY: {
-                    // HWC will compose HWC_OVERLAY layers in partial
-                    // Overlay Composition, set layer composition flag
-                    // on mapped LayerComposite to skip GPU composition
-                    mHwcLayerMap[k]->SetLayerComposited(true);
-
-                    uint8_t opacity = std::min(0xFF, (int)(mHwcLayerMap[k]->GetLayer()->GetEffectiveOpacity() * 256.0));
-                    if ((mList->hwLayers[k].hints & HWC_HINT_CLEAR_FB) &&
-                        (opacity == 0xFF)) {
-                        // Clear visible rect on FB with transparent pixels.
-                        hwc_rect_t r = mList->hwLayers[k].displayFrame;
-                        mHwcLayerMap[k]->SetClearRect(nsIntRect(r.left, r.top,
-                                                                r.right - r.left,
-                                                                r.bottom - r.top));
-                    }
-                    break;
-                }
-                default:
-                    break;
-            }
-        }
-
-        if (gpuComposite) {
-            // GPU or partial OVERLAY Composition
-            return false;
-        } else if (blitComposite) {
-            // BLIT Composition, flip DispSurface target
-            GetGonkDisplay()->UpdateDispSurface(aScreen->GetEGLDisplay(), aScreen->GetEGLSurface());
-            DisplaySurface* dispSurface = aScreen->GetDisplaySurface();
-            if (!dispSurface) {
-                LOGE("H/W Composition failed. NULL DispSurface.");
-                return false;
-            }
-            mList->hwLayers[idx].handle = dispSurface->lastHandle;
-            mList->hwLayers[idx].acquireFenceFd = dispSurface->GetPrevDispAcquireFd();
-        }
-    }
-
-    // BLIT or full OVERLAY Composition
-    return Commit(aScreen);
-}
-
-bool
-HwcComposer2D::Render(nsIWidget* aWidget)
-{
-    nsScreenGonk* screen = static_cast<nsWindow*>(aWidget)->GetScreen();
-
-    // HWC module does not exist or mList is not created yet.
-    if (!mHal->HasHwc() || !mList) {
-        return GetGonkDisplay()->SwapBuffers(screen->GetEGLDisplay(), screen->GetEGLSurface());
-    } else if (!mList && !ReallocLayerList()) {
-        LOGE("Cannot realloc layer list");
-        return false;
-    }
-
-    DisplaySurface* dispSurface = screen->GetDisplaySurface();
-    if (!dispSurface) {
-        LOGE("H/W Composition failed. DispSurface not initialized.");
-        return false;
-    }
-
-    if (mPrepared) {
-        // No mHwc prepare, if already prepared in current draw cycle
-        mList->hwLayers[mList->numHwLayers - 1].handle = dispSurface->lastHandle;
-        mList->hwLayers[mList->numHwLayers - 1].acquireFenceFd = dispSurface->GetPrevDispAcquireFd();
-    } else {
-        // Update screen rect to handle a case that TryRenderWithHwc() is not called.
-        mScreenRect = screen->GetNaturalBounds().ToUnknownRect();
-
-        mList->flags = HWC_GEOMETRY_CHANGED;
-        mList->numHwLayers = 2;
-        mList->hwLayers[0].hints = 0;
-        mList->hwLayers[0].compositionType = HWC_FRAMEBUFFER;
-        mList->hwLayers[0].flags = HWC_SKIP_LAYER;
-        mList->hwLayers[0].backgroundColor = {0};
-        mList->hwLayers[0].acquireFenceFd = -1;
-        mList->hwLayers[0].releaseFenceFd = -1;
-        mList->hwLayers[0].displayFrame = {0, 0, mScreenRect.width, mScreenRect.height};
-
-#if ANDROID_VERSION >= 21
-        // Prepare layers for sideband streams
-        const uint32_t len = mCachedSidebandLayers.Length();
-        for (uint32_t i = 0; i < len; ++i) {
-            ++mList->numHwLayers;
-            mList->hwLayers[i+1] = mCachedSidebandLayers[i];
-        }
-#endif
-        Prepare(dispSurface->lastHandle, dispSurface->GetPrevDispAcquireFd(), screen);
-    }
-
-    // GPU or partial HWC Composition
-    return Commit(screen);
-}
-
-void
-HwcComposer2D::Prepare(buffer_handle_t dispHandle, int fence, nsScreenGonk* screen)
-{
-    if (mPrepared) {
-        LOGE("Multiple hwc prepare calls!");
-    }
-    hwc_rect_t dispRect = {0, 0, mScreenRect.width, mScreenRect.height};
-    mHal->Prepare(mList, screen->GetDisplayType(), dispRect, dispHandle, fence);
-    mPrepared = true;
-}
-
-bool
-HwcComposer2D::Commit(nsScreenGonk* aScreen)
-{
-    for (uint32_t j=0; j < (mList->numHwLayers - 1); j++) {
-        mList->hwLayers[j].acquireFenceFd = -1;
-        if (mHwcLayerMap.IsEmpty() ||
-            (mList->hwLayers[j].compositionType == HWC_FRAMEBUFFER)) {
-            continue;
-        }
-        LayerRenderState state = mHwcLayerMap[j]->GetLayer()->GetRenderState();
-        if (!state.mTexture) {
-            continue;
-        }
-        FenceHandle fence = state.mTexture->GetAndResetAcquireFenceHandle();
-        if (fence.IsValid()) {
-            RefPtr<FenceHandle::FdObj> fdObj = fence.GetAndResetFdObj();
-            mList->hwLayers[j].acquireFenceFd = fdObj->GetAndResetFd();
-        }
-    }
-
-    int err = mHal->Set(mList, aScreen->GetDisplayType());
-
-    mPrevRetireFence.TransferToAnotherFenceHandle(mPrevDisplayFence);
-
-    for (uint32_t j=0; j < (mList->numHwLayers - 1); j++) {
-        if (mList->hwLayers[j].releaseFenceFd >= 0) {
-            int fd = mList->hwLayers[j].releaseFenceFd;
-            mList->hwLayers[j].releaseFenceFd = -1;
-            RefPtr<FenceHandle::FdObj> fdObj = new FenceHandle::FdObj(fd);
-            FenceHandle fence(fdObj);
-
-            LayerRenderState state = mHwcLayerMap[j]->GetLayer()->GetRenderState();
-            if (!state.mTexture) {
-                continue;
-            }
-            state.mTexture->SetReleaseFenceHandle(fence);
-        }
-    }
-
-    if (mList->retireFenceFd >= 0) {
-        mPrevRetireFence = FenceHandle(new FenceHandle::FdObj(mList->retireFenceFd));
-    }
-
-    // Set DisplaySurface layer fence
-    DisplaySurface* displaySurface = aScreen->GetDisplaySurface();
-    displaySurface->setReleaseFenceFd(mList->hwLayers[mList->numHwLayers - 1].releaseFenceFd);
-    mList->hwLayers[mList->numHwLayers - 1].releaseFenceFd = -1;
-
-    mPrepared = false;
-    return !err;
-}
-#else
-bool
-HwcComposer2D::TryHwComposition(nsScreenGonk* aScreen)
-{
-    mHal->SetEGLInfo(aScreen->GetEGLDisplay(), aScreen->GetEGLSurface());
-    return !mHal->Set(mList, aScreen->GetDisplayType());
-}
-
-bool
-HwcComposer2D::Render(nsIWidget* aWidget)
-{
-    nsScreenGonk* screen = static_cast<nsWindow*>(aWidget)->GetScreen();
-    return GetGonkDisplay()->SwapBuffers(screen->GetEGLDisplay(), screen->GetEGLSurface());
-}
-#endif
-
-bool
-HwcComposer2D::TryRenderWithHwc(Layer* aRoot,
-                                nsIWidget* aWidget,
-                                bool aGeometryChanged,
-                                bool aHasImageHostOverlays)
-{
-    if (!mHal->HasHwc()) {
-        return false;
-    }
-
-    nsScreenGonk* screen = static_cast<nsWindow*>(aWidget)->GetScreen();
-
-    if (mList) {
-        mList->flags = mHal->GetGeometryChangedFlag(aGeometryChanged);
-        mList->numHwLayers = 0;
-        mHwcLayerMap.Clear();
-    }
-
-    if (mPrepared) {
-        mHal->ResetHwc();
-        mPrepared = false;
-    }
-
-    // XXX: The clear() below means all rect vectors will be have to be
-    // reallocated. We may want to avoid this if possible
-    mVisibleRegions.clear();
-
-    mScreenRect = screen->GetNaturalBounds().ToUnknownRect();
-    MOZ_ASSERT(mHwcLayerMap.IsEmpty());
-    mCachedSidebandLayers.Clear();
-    if (!PrepareLayerList(aRoot,
-                          mScreenRect,
-                          gfx::Matrix(),
-                          /* aFindSidebandStreams */ false))
-    {
-        mHwcLayerMap.Clear();
-        LOGD("Render aborted. Fallback to GPU Composition");
-        if (aHasImageHostOverlays) {
-            LOGD("Prepare layers of SidebandStreams");
-            // Failed to create a layer list for hwc. But we need the list
-            // only for handling sideband streams. Traverse layer tree without
-            // some early returns to make sure we can find all the layers.
-            // It is the best wrong thing that we can do.
-            PrepareLayerList(aRoot,
-                             mScreenRect,
-                             gfx::Matrix(),
-                             /* aFindSidebandStreams */ true);
-            // Reset mPrepared to false, since we already fell back to
-            // gpu composition.
-            mPrepared = false;
-        }
-        return false;
-    }
-
-    // Send data to LayerScope for debugging
-    SendtoLayerScope();
-
-    if (!TryHwComposition(screen)) {
-        LOGD("Full HWC Composition failed. Fallback to GPU Composition or partial OVERLAY Composition");
-        LayerScope::CleanLayer();
-        return false;
-    }
-
-    LOGD("Frame rendered");
-    return true;
-}
-
-void
-HwcComposer2D::SendtoLayerScope()
-{
-    if (!LayerScope::CheckSendable()) {
-        return;
-    }
-
-    const int len = mList->numHwLayers;
-    for (int i = 0; i < len; ++i) {
-        LayerComposite* layer = mHwcLayerMap[i];
-        const hwc_rect_t r = mList->hwLayers[i].displayFrame;
-        LayerScope::SendLayer(layer, r.right - r.left, r.bottom - r.top);
-    }
-}
-
-} // namespace mozilla
deleted file mode 100644
--- a/widget/gonk/HwcComposer2D.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:set ts=4 sw=4 sts=4 et: */
-/*
- * Copyright (c) 2012, The Linux Foundation. All rights reserved.
- *
- * 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.
- */
-
-#ifndef mozilla_HwcComposer2D
-#define mozilla_HwcComposer2D
-
-#include "Composer2D.h"
-#include "hwchal/HwcHALBase.h"              // for HwcHAL
-#include "HwcUtils.h"                       // for RectVector
-#include "Layers.h"
-#include "mozilla/Mutex.h"
-#include "mozilla/layers/FenceUtils.h"      // for FenceHandle
-#include "mozilla/UniquePtr.h"              // for HwcHAL
-
-#include <vector>
-#include <list>
-
-#include <utils/Timers.h>
-
-class nsScreenGonk;
-
-namespace mozilla {
-
-namespace gl {
-    class GLContext;
-}
-
-namespace layers {
-class CompositorBridgeParent;
-class Layer;
-}
-
-/*
- * HwcComposer2D provides a way for gecko to render frames
- * using hwcomposer.h in the AOSP HAL.
- *
- * hwcomposer.h defines an interface for display composition
- * using dedicated hardware. This hardware is usually faster
- * or more power efficient than the GPU. However, in exchange
- * for better performance, generality has to be sacrificed:
- * no 3d transforms, no intermediate surfaces, no special shader effects,
- * and loss of other goodies depending on the platform.
- *
- * In general, when hwc is enabled gecko tries to compose
- * its frames using HwcComposer2D first. Then if HwcComposer2D is
- * unable to compose a frame then it falls back to compose it
- * using the GPU with OpenGL.
- *
- */
-class HwcComposer2D : public mozilla::layers::Composer2D {
-public:
-    HwcComposer2D();
-    virtual ~HwcComposer2D();
-
-    static HwcComposer2D* GetInstance();
-
-    // Returns TRUE if the container has been succesfully rendered
-    // Returns FALSE if the container cannot be fully rendered
-    // by this composer so nothing was rendered at all
-    virtual bool TryRenderWithHwc(layers::Layer* aRoot,
-                                  nsIWidget* aWidget,
-                                  bool aGeometryChanged,
-                                  bool aHasImageHostOverlays) override;
-
-    virtual bool Render(nsIWidget* aWidget) override;
-
-    virtual bool HasHwc() override { return mHal->HasHwc(); }
-
-    bool EnableVsync(bool aEnable);
-    bool RegisterHwcEventCallback();
-    void Vsync(int aDisplay, int64_t aTimestamp);
-    void Invalidate();
-    void Hotplug(int aDisplay, int aConnected);
-    void SetCompositorBridgeParent(layers::CompositorBridgeParent* aCompositorBridgeParent);
-
-private:
-    void Reset();
-    void Prepare(buffer_handle_t dispHandle, int fence, nsScreenGonk* screen);
-    bool Commit(nsScreenGonk* aScreen);
-    bool TryHwComposition(nsScreenGonk* aScreen);
-    bool ReallocLayerList();
-    bool PrepareLayerList(layers::Layer* aContainer, const nsIntRect& aClip,
-          const gfx::Matrix& aParentTransform,
-          bool aFindSidebandStreams);
-    void SendtoLayerScope();
-
-    UniquePtr<HwcHALBase>   mHal;
-    HwcList*                mList;
-    nsIntRect               mScreenRect;
-    int                     mMaxLayerCount;
-    bool                    mColorFill;
-    bool                    mRBSwapSupport;
-    //Holds all the dynamically allocated RectVectors needed
-    //to render the current frame
-    std::list<HwcUtils::RectVector>   mVisibleRegions;
-    layers::FenceHandle mPrevRetireFence;
-    layers::FenceHandle mPrevDisplayFence;
-    nsTArray<HwcLayer>      mCachedSidebandLayers;
-    nsTArray<layers::LayerComposite*> mHwcLayerMap;
-    bool                    mPrepared;
-    bool                    mHasHWVsync;
-    layers::CompositorBridgeParent* mCompositorBridgeParent;
-    Mutex mLock;
-};
-
-} // namespace mozilla
-
-#endif // mozilla_HwcComposer2D
deleted file mode 100644
--- a/widget/gonk/HwcUtils.cpp
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (c) 2013 The Linux Foundation. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <android/log.h>
-#include "HwcUtils.h"
-#include "gfxUtils.h"
-#include "gfx2DGlue.h"
-
-#define LOG_TAG "HwcUtils"
-
-#if (LOG_NDEBUG == 0)
-#define LOGD(args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, ## args)
-#else
-#define LOGD(args...) ((void)0)
-#endif
-
-#define LOGE(args...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, ## args)
-
-
-namespace mozilla {
-
-/* Utility functions for HwcComposer */
-
-
-
-/* static */ bool
-HwcUtils::PrepareLayerRects(nsIntRect aVisible,
-                            const gfx::Matrix& aLayerTransform,
-                            const gfx::Matrix& aLayerBufferTransform,
-                            nsIntRect aClip, nsIntRect aBufferRect,
-                            bool aYFlipped,
-                            hwc_rect_t* aSourceCrop, hwc_rect_t* aVisibleRegionScreen) {
-
-    gfxMatrix aTransform = gfx::ThebesMatrix(aLayerTransform);
-    gfxRect visibleRect(ThebesRect(aVisible));
-    gfxRect clip(ThebesRect(aClip));
-    gfxRect visibleRectScreen = aTransform.TransformBounds(visibleRect);
-    // |clip| is guaranteed to be integer
-    visibleRectScreen.IntersectRect(visibleRectScreen, clip);
-
-    if (visibleRectScreen.IsEmpty()) {
-        return false;
-    }
-
-    gfxMatrix inverse = gfx::ThebesMatrix(aLayerBufferTransform);
-    inverse.Invert();
-    gfxRect crop = inverse.TransformBounds(visibleRectScreen);
-
-    //clip to buffer size
-    crop.IntersectRect(crop, ThebesRect(aBufferRect));
-    crop.Round();
-
-    if (crop.IsEmpty()) {
-        return false;
-    }
-
-    //propagate buffer clipping back to visible rect
-    gfxMatrix layerBufferTransform = gfx::ThebesMatrix(aLayerBufferTransform);
-    visibleRectScreen = layerBufferTransform.TransformBounds(crop);
-    visibleRectScreen.Round();
-
-    // Map from layer space to buffer space
-    crop -= aBufferRect.TopLeft();
-    if (aYFlipped) {
-        crop.y = aBufferRect.height - (crop.y + crop.height);
-    }
-
-    aSourceCrop->left = crop.x;
-    aSourceCrop->top  = crop.y;
-    aSourceCrop->right  = crop.x + crop.width;
-    aSourceCrop->bottom = crop.y + crop.height;
-
-    aVisibleRegionScreen->left = visibleRectScreen.x;
-    aVisibleRegionScreen->top  = visibleRectScreen.y;
-    aVisibleRegionScreen->right  = visibleRectScreen.x + visibleRectScreen.width;
-    aVisibleRegionScreen->bottom = visibleRectScreen.y + visibleRectScreen.height;
-
-    return true;
-}
-
-/* static */ bool
-HwcUtils::PrepareVisibleRegion(const nsIntRegion& aVisible,
-                               const gfx::Matrix& aLayerTransform,
-                               const gfx::Matrix& aLayerBufferTransform,
-                               nsIntRect aClip, nsIntRect aBufferRect,
-                               RectVector* aVisibleRegionScreen,
-                               bool& aIsVisible) {
-    const float MIN_SRC_WIDTH = 2.f;
-    const float MIN_SRC_HEIGHT = 2.f;
-
-    gfxMatrix layerTransform = gfx::ThebesMatrix(aLayerTransform);
-    gfxMatrix layerBufferTransform = gfx::ThebesMatrix(aLayerBufferTransform);
-    gfxRect bufferRect =
-        layerBufferTransform.TransformBounds(ThebesRect(aBufferRect));
-    gfxMatrix inverse = gfx::ThebesMatrix(aLayerBufferTransform);
-    inverse.Invert();
-    aIsVisible = false;
-
-    for (auto iter = aVisible.RectIter(); !iter.Done(); iter.Next()) {
-        gfxRect screenRect =
-          layerTransform.TransformBounds(ThebesRect(iter.Get()));
-        screenRect.IntersectRect(screenRect, bufferRect);
-        screenRect.IntersectRect(screenRect, ThebesRect(aClip));
-        screenRect.Round();
-        if (screenRect.IsEmpty()) {
-            continue;
-        }
-
-        hwc_rect_t visibleRectScreen;
-        visibleRectScreen.left = screenRect.x;
-        visibleRectScreen.top  = screenRect.y;
-        visibleRectScreen.right  = screenRect.XMost();
-        visibleRectScreen.bottom = screenRect.YMost();
-
-        gfxRect srcCrop = inverse.TransformBounds(screenRect);
-        // When src crop is very small, HWC could not render correctly in some cases.
-        // See Bug 1169093
-        if(srcCrop.Width() < MIN_SRC_WIDTH || srcCrop.Height() < MIN_SRC_HEIGHT) {
-            return false;
-        }
-
-        aVisibleRegionScreen->push_back(visibleRectScreen);
-        aIsVisible = true;
-    }
-
-    return true;
-}
-
-/* static */ bool
-HwcUtils::CalculateClipRect(const gfx::Matrix& transform,
-                            const nsIntRect* aLayerClip,
-                            nsIntRect aParentClip, nsIntRect* aRenderClip) {
-
-    gfxMatrix aTransform = gfx::ThebesMatrix(transform);
-    *aRenderClip = aParentClip;
-
-    if (!aLayerClip) {
-        return true;
-    }
-
-    if (aLayerClip->IsEmpty()) {
-        return false;
-    }
-
-    nsIntRect clip = *aLayerClip;
-
-    gfxRect r = ThebesRect(clip);
-    gfxRect trClip = aTransform.TransformBounds(r);
-    trClip.Round();
-    gfxUtils::GfxRectToIntRect(trClip, &clip);
-
-    aRenderClip->IntersectRect(*aRenderClip, clip);
-    return true;
-}
-
-} // namespace mozilla
deleted file mode 100644
--- a/widget/gonk/HwcUtils.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (c) 2013, The Linux Foundation. All rights reserved.
- *
- * 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.
- */
-
-#ifndef mozilla_HwcUtils
-#define mozilla_HwcUtils
-
-#include "Layers.h"
-#include <vector>
-#include "hardware/hwcomposer.h"
-
-namespace mozilla {
-
-namespace gfx {
-class Matrix;
-}
-
-class HwcUtils {
-public:
-
-enum {
-    HWC_USE_GPU = HWC_FRAMEBUFFER,
-    HWC_USE_OVERLAY = HWC_OVERLAY,
-    HWC_USE_COPYBIT
-};
-
-// HWC layer flags
-enum {
-    // Draw a solid color rectangle
-    // The color should be set on the transform member of the hwc_layer_t struct
-    // The expected format is a 32 bit ABGR with 8 bits per component
-    HWC_COLOR_FILL = 0x8,
-    // Swap the RB pixels of gralloc buffer, like RGBA<->BGRA or RGBX<->BGRX
-    // The flag will be set inside LayerRenderState
-    HWC_FORMAT_RB_SWAP = 0x40
-};
-
-typedef std::vector<hwc_rect_t> RectVector;
-
-/* Utility functions - implemented in HwcUtils.cpp */
-
-/**
- * Calculates the layer's clipping rectangle
- *
- * @param aTransform Input. A transformation matrix
- *        It transforms the clip rect to screen space
- * @param aLayerClip Input. The layer's internal clipping rectangle.
- *        This may be NULL which means the layer has no internal clipping
- *        The origin is the top-left corner of the layer
- * @param aParentClip Input. The parent layer's rendering clipping rectangle
- *        The origin is the top-left corner of the screen
- * @param aRenderClip Output. The layer's rendering clipping rectangle
- *        The origin is the top-left corner of the screen
- * @return true if the layer should be rendered.
- *         false if the layer can be skipped
- */
-static bool CalculateClipRect(const gfx::Matrix& aTransform,
-                              const nsIntRect* aLayerClip,
-                              nsIntRect aParentClip, nsIntRect* aRenderClip);
-
-
-/**
- * Prepares hwc layer visible region required for hwc composition
- *
- * @param aVisible Input. Layer's unclipped visible region
- *        The origin is the top-left corner of the layer
- * @param aLayerTransform Input. Layer's transformation matrix
- *        It transforms from layer space to screen space
- * @param aLayerBufferTransform Input. Layer buffer's transformation matrix
- *        It transforms from layer buffer's space to screen space
- * @param aClip Input. A clipping rectangle.
- *        The origin is the top-left corner of the screen
- * @param aBufferRect Input. The layer's buffer bounds
- *        The origin is the top-left corner of the layer
- * @param aVisibleRegionScreen Output. Visible region in screen space.
- *        The origin is the top-left corner of the screen
- * @param aIsVisible Output. true if region is visible
- *        false if region is not visible
- * @return true if region can be rendered by HWC.
- *         false if region should not be rendered by HWC
- */
-static bool PrepareVisibleRegion(const nsIntRegion& aVisible,
-                                 const gfx::Matrix& aLayerTransform,
-                                 const gfx::Matrix& aLayerBufferTransform,
-                                 nsIntRect aClip, nsIntRect aBufferRect,
-                                 RectVector* aVisibleRegionScreen,
-                                 bool& aIsVisible);
-
-
-/**
- * Sets hwc layer rectangles required for hwc composition
- *
- * @param aVisible Input. Layer's unclipped visible rectangle
- *        The origin is the top-left corner of the layer
- * @param aLayerTransform Input. Layer's transformation matrix
- *        It transforms from layer space to screen space
- * @param aLayerBufferTransform Input. Layer buffer's transformation matrix
- *        It transforms from layer buffer's space to screen space
- * @param aClip Input. A clipping rectangle.
- *        The origin is the top-left corner of the screen
- * @param aBufferRect Input. The layer's buffer bounds
- *        The origin is the top-left corner of the layer
- * @param aYFlipped Input. true if the buffer is rendered as Y flipped
- * @param aSurceCrop Output. Area of the source to consider,
- *        the origin is the top-left corner of the buffer
- * @param aVisibleRegionScreen Output. Visible region in screen space.
- *        The origin is the top-left corner of the screen
- * @return true if the layer should be rendered.
- *         false if the layer can be skipped
- */
-static bool PrepareLayerRects(nsIntRect aVisible,
-                              const gfx::Matrix& aLayerTransform,
-                              const gfx::Matrix& aLayerBufferTransform,
-                              nsIntRect aClip, nsIntRect aBufferRect,
-                              bool aYFlipped,
-                              hwc_rect_t* aSourceCrop,
-                              hwc_rect_t* aVisibleRegionScreen);
-
-};
-
-} // namespace mozilla
-
-#endif // mozilla_HwcUtils
deleted file mode 100644
--- a/widget/gonk/ProcessOrientation.cpp
+++ /dev/null
@@ -1,518 +0,0 @@
-/*
- * Copyright (c) 2013, Linux Foundation. All rights reserved
- *
- * 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.
- */
-
-#include "base/basictypes.h"
-#include "mozilla/Hal.h"
-#include "mozilla/Unused.h"
-#include "nsIScreen.h"
-#include "nsIScreenManager.h"
-#include "ProcessOrientation.h"
-#include "mozilla/HalSensor.h"
-#include "math.h"
-#include "limits.h"
-#include "android/log.h"
-
-#if 0
-#define LOGD(args...)  __android_log_print(ANDROID_LOG_DEBUG, "ProcessOrientation" , ## args)
-#else
-#define LOGD(args...)
-#endif
-
-namespace mozilla {
-
-// We work with all angles in degrees in this class.
-#define RADIANS_TO_DEGREES (180/M_PI)
-
-// Number of nanoseconds per millisecond.
-#define NANOS_PER_MS 1000000
-
-// Indices into SensorEvent.values for the accelerometer sensor.
-#define ACCELEROMETER_DATA_X 0
-#define ACCELEROMETER_DATA_Y 1
-#define ACCELEROMETER_DATA_Z 2
-
-// The minimum amount of time that a predicted rotation must be stable before
-// it is accepted as a valid rotation proposal. This value can be quite small
-// because the low-pass filter already suppresses most of the noise so we're
-// really just looking for quick confirmation that the last few samples are in
-// agreement as to the desired orientation.
-#define PROPOSAL_SETTLE_TIME_NANOS (40*NANOS_PER_MS)
-
-// The minimum amount of time that must have elapsed since the device last
-// exited the flat state (time since it was picked up) before the proposed
-// rotation can change.
-#define PROPOSAL_MIN_TIME_SINCE_FLAT_ENDED_NANOS (500*NANOS_PER_MS)
-
-// The minimum amount of time that must have elapsed since the device stopped
-// swinging (time since device appeared to be in the process of being put down
-// or put away into a pocket) before the proposed rotation can change.
-#define PROPOSAL_MIN_TIME_SINCE_SWING_ENDED_NANOS (300*NANOS_PER_MS)
-
-// The minimum amount of time that must have elapsed since the device stopped
-// undergoing external acceleration before the proposed rotation can change.
-#define PROPOSAL_MIN_TIME_SINCE_ACCELERATION_ENDED_NANOS (500*NANOS_PER_MS)
-
-// If the tilt angle remains greater than the specified angle for a minimum of
-// the specified time, then the device is deemed to be lying flat
-// (just chillin' on a table).
-#define FLAT_ANGLE 75
-#define FLAT_TIME_NANOS (1000*NANOS_PER_MS)
-
-// If the tilt angle has increased by at least delta degrees within the
-// specified amount of time, then the device is deemed to be swinging away
-// from the user down towards flat (tilt = 90).
-#define SWING_AWAY_ANGLE_DELTA 20
-#define SWING_TIME_NANOS (300*NANOS_PER_MS)
-
-// The maximum sample inter-arrival time in milliseconds. If the acceleration
-// samples are further apart than this amount in time, we reset the state of
-// the low-pass filter and orientation properties.  This helps to handle
-// boundary conditions when the device is turned on, wakes from suspend or
-// there is a significant gap in samples.
-#define MAX_FILTER_DELTA_TIME_NANOS (1000*NANOS_PER_MS)
-
-// The acceleration filter time constant.
-//
-// This time constant is used to tune the acceleration filter such that
-// impulses and vibrational noise (think car dock) is suppressed before we try
-// to calculate the tilt and orientation angles.
-//
-// The filter time constant is related to the filter cutoff frequency, which
-// is the frequency at which signals are attenuated by 3dB (half the passband
-// power). Each successive octave beyond this frequency is attenuated by an
-// additional 6dB.
-//
-// Given a time constant t in seconds, the filter cutoff frequency Fc in Hertz
-// is given by Fc = 1 / (2pi * t).
-//
-// The higher the time constant, the lower the cutoff frequency, so more noise
-// will be suppressed.
-//
-// Filtering adds latency proportional the time constant (inversely
-// proportional to the cutoff frequency) so we don't want to make the time
-// constant too large or we can lose responsiveness.  Likewise we don't want
-// to make it too small or we do a poor job suppressing acceleration spikes.
-// Empirically, 100ms seems to be too small and 500ms is too large. Android
-// default is 200.
-#define FILTER_TIME_CONSTANT_MS 200.0f
-
-// State for orientation detection. Thresholds for minimum and maximum
-// allowable deviation from gravity.
-//
-// If the device is undergoing external acceleration (being bumped, in a car
-// that is turning around a corner or a plane taking off) then the magnitude
-// may be substantially more or less than gravity.  This can skew our
-// orientation detection by making us think that up is pointed in a different
-// direction.
-//
-// Conversely, if the device is in freefall, then there will be no gravity to
-// measure at all.  This is problematic because we cannot detect the orientation
-// without gravity to tell us which way is up. A magnitude near 0 produces
-// singularities in the tilt and orientation calculations.
-//
-// In both cases, we postpone choosing an orientation.
-//
-// However, we need to tolerate some acceleration because the angular momentum
-// of turning the device can skew the observed acceleration for a short period
-// of time.
-#define NEAR_ZERO_MAGNITUDE 1 // m/s^2
-#define ACCELERATION_TOLERANCE 4 // m/s^2
-#define STANDARD_GRAVITY 9.80665f
-#define MIN_ACCELERATION_MAGNITUDE (STANDARD_GRAVITY-ACCELERATION_TOLERANCE)
-#define MAX_ACCELERATION_MAGNITUDE (STANDARD_GRAVITY+ACCELERATION_TOLERANCE)
-
-// Maximum absolute tilt angle at which to consider orientation data. Beyond
-// this (i.e. when screen is facing the sky or ground), we completely ignore
-// orientation data.
-#define MAX_TILT 75
-
-// The gap angle in degrees between adjacent orientation angles for
-// hysteresis.This creates a "dead zone" between the current orientation and a
-// proposed adjacent orientation. No orientation proposal is made when the
-// orientation angle is within the gap between the current orientation and the
-// adjacent orientation.
-#define ADJACENT_ORIENTATION_ANGLE_GAP 45
-
-const int
-ProcessOrientation::tiltTolerance[][4] = {
-  {-25, 70}, // ROTATION_0
-  {-25, 65}, // ROTATION_90
-  {-25, 60}, // ROTATION_180
-  {-25, 65}  // ROTATION_270
-};
-
-int
-ProcessOrientation::GetProposedRotation()
-{
-  return mProposedRotation;
-}
-
-int
-ProcessOrientation::OnSensorChanged(const SensorData& event,
-                                    int deviceCurrentRotation)
-{
-  // The vector given in the SensorEvent points straight up (towards the sky)
-  // under ideal conditions (the phone is not accelerating). I'll call this up
-  // vector elsewhere.
-  const InfallibleTArray<float>& values = event.values();
-  float x = values[ACCELEROMETER_DATA_X];
-  float y = values[ACCELEROMETER_DATA_Y];
-  float z = values[ACCELEROMETER_DATA_Z];
-
-  LOGD
-    ("ProcessOrientation: Raw acceleration vector: x = %f, y = %f, z = %f,"
-     "magnitude = %f\n", x, y, z, sqrt(x * x + y * y + z * z));
-  // Apply a low-pass filter to the acceleration up vector in cartesian space.
-  // Reset the orientation listener state if the samples are too far apart in
-  // time or when we see values of (0, 0, 0) which indicates that we polled the
-  // accelerometer too soon after turning it on and we don't have any data yet.
-  const int64_t now = (int64_t) event.timestamp();
-  const int64_t then = mLastFilteredTimestampNanos;
-  const float timeDeltaMS = (now - then) * 0.000001f;
-  bool skipSample = false;
-  if (now < then
-      || now > then + MAX_FILTER_DELTA_TIME_NANOS
-      || (x == 0 && y == 0 && z == 0)) {
-    LOGD
-      ("ProcessOrientation: Resetting orientation listener.");
-    Reset();
-    skipSample = true;
-  } else {
-    const float alpha = timeDeltaMS / (FILTER_TIME_CONSTANT_MS + timeDeltaMS);
-    x = alpha * (x - mLastFilteredX) + mLastFilteredX;
-    y = alpha * (y - mLastFilteredY) + mLastFilteredY;
-    z = alpha * (z - mLastFilteredZ) + mLastFilteredZ;
-    LOGD
-      ("ProcessOrientation: Filtered acceleration vector: x=%f, y=%f, z=%f,"
-       "magnitude=%f", z, y, z, sqrt(x * x + y * y + z * z));
-    skipSample = false;
-  }
-  mLastFilteredTimestampNanos = now;
-  mLastFilteredX = x;
-  mLastFilteredY = y;
-  mLastFilteredZ = z;
-
-  bool isAccelerating = false;
-  bool isFlat = false;
-  bool isSwinging = false;
-  if (skipSample) {
-    return -1;
-  }
-
-  // Calculate the magnitude of the acceleration vector.
-  const float magnitude = sqrt(x * x + y * y + z * z);
-  if (magnitude < NEAR_ZERO_MAGNITUDE) {
-    LOGD
-      ("ProcessOrientation: Ignoring sensor data, magnitude too close to"
-       " zero.");
-    ClearPredictedRotation();
-  } else {
-    // Determine whether the device appears to be undergoing external
-    // acceleration.
-    if (this->IsAccelerating(magnitude)) {
-      isAccelerating = true;
-      mAccelerationTimestampNanos = now;
-    }
-    // Calculate the tilt angle. This is the angle between the up vector and
-    // the x-y plane (the plane of the screen) in a range of [-90, 90]
-    // degrees.
-    //   -90 degrees: screen horizontal and facing the ground (overhead)
-    //     0 degrees: screen vertical
-    //    90 degrees: screen horizontal and facing the sky (on table)
-    const int tiltAngle =
-      static_cast<int>(roundf(asin(z / magnitude) * RADIANS_TO_DEGREES));
-    AddTiltHistoryEntry(now, tiltAngle);
-
-    // Determine whether the device appears to be flat or swinging.
-    if (this->IsFlat(now)) {
-      isFlat = true;
-      mFlatTimestampNanos = now;
-    }
-    if (this->IsSwinging(now, tiltAngle)) {
-      isSwinging = true;
-      mSwingTimestampNanos = now;
-    }
-    // If the tilt angle is too close to horizontal then we cannot determine
-    // the orientation angle of the screen.
-    if (abs(tiltAngle) > MAX_TILT) {
-      LOGD
-        ("ProcessOrientation: Ignoring sensor data, tilt angle too high:"
-         " tiltAngle=%d", tiltAngle);
-      ClearPredictedRotation();
-    } else {
-      // Calculate the orientation angle.
-      // This is the angle between the x-y projection of the up vector onto
-      // the +y-axis, increasing clockwise in a range of [0, 360] degrees.
-      int orientationAngle =
-        static_cast<int>(roundf(-atan2f(-x, y) * RADIANS_TO_DEGREES));
-      if (orientationAngle < 0) {
-        // atan2 returns [-180, 180]; normalize to [0, 360]
-        orientationAngle += 360;
-      }
-      // Find the nearest rotation.
-      int nearestRotation = (orientationAngle + 45) / 90;
-      if (nearestRotation == 4) {
-        nearestRotation = 0;
-      }
-      // Determine the predicted orientation.
-      if (IsTiltAngleAcceptable(nearestRotation, tiltAngle)
-          &&
-          IsOrientationAngleAcceptable
-          (nearestRotation, orientationAngle, deviceCurrentRotation)) {
-        UpdatePredictedRotation(now, nearestRotation);
-        LOGD
-          ("ProcessOrientation: Predicted: tiltAngle=%d, orientationAngle=%d,"
-           " predictedRotation=%d, predictedRotationAgeMS=%f",
-           tiltAngle,
-           orientationAngle,
-           mPredictedRotation,
-           ((now - mPredictedRotationTimestampNanos) * 0.000001f));
-      } else {
-        LOGD
-          ("ProcessOrientation: Ignoring sensor data, no predicted rotation:"
-           " tiltAngle=%d, orientationAngle=%d",
-           tiltAngle,
-           orientationAngle);
-        ClearPredictedRotation();
-      }
-    }
-  }
-
-  // Determine new proposed rotation.
-  const int oldProposedRotation = mProposedRotation;
-  if (mPredictedRotation < 0 || IsPredictedRotationAcceptable(now)) {
-    mProposedRotation = mPredictedRotation;
-  }
-  // Write final statistics about where we are in the orientation detection
-  // process.
-  LOGD
-    ("ProcessOrientation: Result: oldProposedRotation=%d,currentRotation=%d, "
-     "proposedRotation=%d, predictedRotation=%d, timeDeltaMS=%f, "
-     "isAccelerating=%d, isFlat=%d, isSwinging=%d, timeUntilSettledMS=%f, "
-     "timeUntilAccelerationDelayExpiredMS=%f, timeUntilFlatDelayExpiredMS=%f, "
-     "timeUntilSwingDelayExpiredMS=%f",
-     oldProposedRotation,
-     deviceCurrentRotation, mProposedRotation,
-     mPredictedRotation, timeDeltaMS, isAccelerating, isFlat,
-     isSwinging, RemainingMS(now,
-                             mPredictedRotationTimestampNanos +
-                             PROPOSAL_SETTLE_TIME_NANOS),
-     RemainingMS(now,
-                 mAccelerationTimestampNanos +
-                 PROPOSAL_MIN_TIME_SINCE_ACCELERATION_ENDED_NANOS),
-     RemainingMS(now,
-                 mFlatTimestampNanos +
-                 PROPOSAL_MIN_TIME_SINCE