Backed out 7 changesets (bug 907585, bug 873351, bug 864485) for making phones unbootable.
authorRyan VanderMeulen <ryanvm@gmail.com>
Fri, 06 Sep 2013 17:28:10 -0400
changeset 158898 dc4758d44b11816832b1bb0d7e5e81cbe35bc149
parent 158897 742dd2b24c3e5ff3fa62b39be65fcaf9b88bc310
child 158899 b917d0b96b6fcd5a74b11e7f6b14e6e33e579b23
push id2961
push userlsblakk@mozilla.com
push dateMon, 28 Oct 2013 21:59:28 +0000
treeherdermozilla-beta@73ef4f13486f [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
bugs907585, 873351, 864485
milestone26.0a1
backs out001a849303ded1b8efafdf75b66fb9b51aa54ee8
8020b30136185269fd2ba61b3dc16f060a549c5a
9039460e09c58ce94e85865eca87c8cb3699700d
9464e393a501faa53f29ccf77f35cb03305ae75f
d6920653de69f76ef3cdda22835a42d65b903e18
20ef446b27cd6b4826c72d5e0edddc35199325a3
e27c780e1ef5b269c664c3b3f894df83c01063bd
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Backed out 7 changesets (bug 907585, bug 873351, bug 864485) for making phones unbootable. Backed out changeset 001a849303de (bug 873351) Backed out changeset 8020b3013618 (bug 907585) Backed out changeset 9039460e09c5 (bug 907585) Backed out changeset 9464e393a501 (bug 907585) Backed out changeset d6920653de69 (bug 864485) Backed out changeset 20ef446b27cd (bug 864485) Backed out changeset e27c780e1ef5 (bug 864485)
b2g/installer/package-manifest.in
browser/installer/package-manifest.in
dom/base/Navigator.cpp
dom/bindings/Bindings.conf
dom/bluetooth/BluetoothHfpManager.cpp
dom/bluetooth/BluetoothTelephonyListener.cpp
dom/dom-config.mk
dom/ipc/ContentChild.cpp
dom/ipc/ContentChild.h
dom/ipc/ContentParent.cpp
dom/ipc/ContentParent.h
dom/ipc/PContent.ipdl
dom/mobilemessage/interfaces/moz.build
dom/mobilemessage/interfaces/nsIRilSmsService.idl
dom/mobilemessage/interfaces/nsISmsService.idl
dom/mobilemessage/src/Makefile.in
dom/mobilemessage/src/SmsServicesFactory.cpp
dom/mobilemessage/src/android/SmsService.cpp
dom/mobilemessage/src/fallback/SmsService.cpp
dom/mobilemessage/src/gonk/SmsService.cpp
dom/mobilemessage/src/gonk/SmsService.h
dom/mobilemessage/src/gonk/SmsService.js
dom/mobilemessage/src/gonk/SmsService.manifest
dom/mobilemessage/src/ipc/SmsIPCService.cpp
dom/mobilemessage/src/moz.build
dom/moz.build
dom/system/gonk/Makefile.in
dom/system/gonk/RILContentHelper.js
dom/system/gonk/RadioInterfaceLayer.js
dom/system/gonk/RilMessageManager.jsm
dom/system/gonk/moz.build
dom/system/gonk/nsIRadioInterfaceLayer.idl
dom/telephony/CallEvent.cpp
dom/telephony/Makefile.in
dom/telephony/Telephony.cpp
dom/telephony/TelephonyCall.cpp
dom/telephony/TelephonyCallGroup.cpp
dom/telephony/TelephonyFactory.cpp
dom/telephony/TelephonyFactory.h
dom/telephony/gonk/TelephonyProvider.js
dom/telephony/gonk/TelephonyProvider.manifest
dom/telephony/ipc/PTelephony.ipdl
dom/telephony/ipc/PTelephonyRequest.ipdl
dom/telephony/ipc/TelephonyChild.cpp
dom/telephony/ipc/TelephonyChild.h
dom/telephony/ipc/TelephonyIPCProvider.cpp
dom/telephony/ipc/TelephonyIPCProvider.h
dom/telephony/ipc/TelephonyParent.cpp
dom/telephony/ipc/TelephonyParent.h
dom/telephony/ipc/TelephonyTypes.ipdlh
dom/telephony/moz.build
dom/telephony/nsIGonkTelephonyProvider.idl
dom/telephony/nsITelephonyProvider.idl
dom/tests/mochitest/general/test_interfaces.html
dom/webidl/WebIDL.mk
layout/build/Makefile.in
layout/build/nsLayoutModule.cpp
--- a/b2g/installer/package-manifest.in
+++ b/b2g/installer/package-manifest.in
@@ -159,16 +159,17 @@
 @BINPATH@/components/docshell.xpt
 @BINPATH@/components/dom.xpt
 @BINPATH@/components/dom_activities.xpt
 @BINPATH@/components/dom_apps.xpt
 @BINPATH@/components/dom_audiochannel.xpt
 @BINPATH@/components/dom_base.xpt
 @BINPATH@/components/dom_system.xpt
 #ifdef MOZ_B2G_RIL
+@BINPATH@/components/dom_telephony.xpt
 @BINPATH@/components/dom_voicemail.xpt
 @BINPATH@/components/dom_wifi.xpt
 @BINPATH@/components/dom_system_gonk.xpt
 @BINPATH@/components/dom_icc.xpt
 @BINPATH@/components/dom_cellbroadcast.xpt
 @BINPATH@/components/dom_wappush.xpt
 #endif
 #ifdef MOZ_B2G_BT
@@ -197,17 +198,16 @@
 @BINPATH@/components/dom_quota.xpt
 @BINPATH@/components/dom_range.xpt
 @BINPATH@/components/dom_settings.xpt
 @BINPATH@/components/dom_permissionsettings.xpt
 @BINPATH@/components/dom_sidebar.xpt
 @BINPATH@/components/dom_mobilemessage.xpt
 @BINPATH@/components/dom_storage.xpt
 @BINPATH@/components/dom_stylesheets.xpt
-@BINPATH@/components/dom_telephony.xpt
 @BINPATH@/components/dom_threads.xpt
 @BINPATH@/components/dom_traversal.xpt
 @BINPATH@/components/dom_views.xpt
 #ifdef MOZ_WEBSPEECH
 @BINPATH@/components/dom_webspeechrecognition.xpt
 #endif
 @BINPATH@/components/dom_xbl.xpt
 @BINPATH@/components/dom_xpath.xpt
@@ -455,31 +455,27 @@
 @BINPATH@/components/SettingsService.manifest
 #ifdef MOZ_B2G_RIL
 @BINPATH@/components/NetworkManager.manifest
 @BINPATH@/components/NetworkManager.js
 @BINPATH@/components/RadioInterfaceLayer.manifest
 @BINPATH@/components/RadioInterfaceLayer.js
 @BINPATH@/components/MmsService.manifest
 @BINPATH@/components/MmsService.js
-@BINPATH@/components/SmsService.manifest
-@BINPATH@/components/SmsService.js
 @BINPATH@/components/RILContentHelper.js
 @BINPATH@/components/MobileMessageDatabaseService.manifest
 @BINPATH@/components/MobileMessageDatabaseService.js
 @BINPATH@/components/WifiWorker.js
 @BINPATH@/components/WifiWorker.manifest
 @BINPATH@/components/DOMWifiManager.js
 @BINPATH@/components/DOMWifiManager.manifest
 @BINPATH@/components/NetworkStatsManager.js
 @BINPATH@/components/NetworkStatsManager.manifest
 @BINPATH@/components/NetworkInterfaceListService.manifest
 @BINPATH@/components/NetworkInterfaceListService.js
-@BINPATH@/components/TelephonyProvider.manifest
-@BINPATH@/components/TelephonyProvider.js
 #endif
 #ifdef MOZ_ENABLE_DBUS
 @BINPATH@/components/@DLL_PREFIX@dbusservice@DLL_SUFFIX@
 #endif
 @BINPATH@/components/nsINIProcessor.manifest
 @BINPATH@/components/nsINIProcessor.js
 @BINPATH@/components/nsPrompter.manifest
 @BINPATH@/components/nsPrompter.js
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -171,16 +171,17 @@
 @BINPATH@/components/cookie.xpt
 @BINPATH@/components/directory.xpt
 @BINPATH@/components/docshell.xpt
 @BINPATH@/components/dom.xpt
 @BINPATH@/components/dom_apps.xpt
 @BINPATH@/components/dom_base.xpt
 @BINPATH@/components/dom_system.xpt
 #ifdef MOZ_B2G_RIL
+@BINPATH@/components/dom_telephony.xpt
 @BINPATH@/components/dom_voicemail.xpt
 @BINPATH@/components/dom_wifi.xpt
 @BINPATH@/components/dom_system_gonk.xpt
 @BINPATH@/components/dom_icc.xpt
 @BINPATH@/components/dom_wappush.xpt
 #endif
 #ifdef MOZ_B2G_BT
 @BINPATH@/components/dom_bluetooth.xpt
@@ -206,17 +207,16 @@
 @BINPATH@/components/dom_quota.xpt
 @BINPATH@/components/dom_range.xpt
 @BINPATH@/components/dom_settings.xpt
 @BINPATH@/components/dom_permissionsettings.xpt
 @BINPATH@/components/dom_sidebar.xpt
 @BINPATH@/components/dom_mobilemessage.xpt
 @BINPATH@/components/dom_storage.xpt
 @BINPATH@/components/dom_stylesheets.xpt
-@BINPATH@/components/dom_telephony.xpt
 @BINPATH@/components/dom_traversal.xpt
 #ifdef MOZ_WEBSPEECH
 @BINPATH@/components/dom_webspeechrecognition.xpt
 #endif
 @BINPATH@/components/dom_xbl.xpt
 @BINPATH@/components/dom_xpath.xpt
 @BINPATH@/components/dom_xul.xpt
 #ifdef MOZ_GAMEPAD
@@ -441,18 +441,16 @@
 @BINPATH@/components/contentSecurityPolicy.js
 @BINPATH@/components/contentAreaDropListener.manifest
 @BINPATH@/components/contentAreaDropListener.js
 #ifdef MOZ_B2G_RIL
 @BINPATH@/components/RadioInterfaceLayer.manifest
 @BINPATH@/components/RadioInterfaceLayer.js
 @BINPATH@/components/MmsService.manifest
 @BINPATH@/components/MmsService.js
-@BINPATH@/components/SmsService.manifest
-@BINPATH@/components/SmsService.js
 @BINPATH@/components/RILContentHelper.js
 @BINPATH@/components/MobileMessageDatabaseService.manifest
 @BINPATH@/components/MobileMessageDatabaseService.js
 @BINPATH@/components/WifiWorker.js
 @BINPATH@/components/WifiWorker.manifest
 @BINPATH@/components/DOMWifiManager.js
 @BINPATH@/components/DOMWifiManager.manifest
 #endif
--- a/dom/base/Navigator.cpp
+++ b/dom/base/Navigator.cpp
@@ -49,17 +49,17 @@
 #include "TimeManager.h"
 #include "DeviceStorage.h"
 #include "nsIDOMNavigatorSystemMessages.h"
 
 #ifdef MOZ_MEDIA_NAVIGATOR
 #include "MediaManager.h"
 #endif
 #ifdef MOZ_B2G_RIL
-#include "mozilla/dom/telephony/Telephony.h"
+#include "Telephony.h"
 #endif
 #ifdef MOZ_B2G_BT
 #include "BluetoothManager.h"
 #endif
 #include "DOMCameraManager.h"
 
 #ifdef MOZ_AUDIO_CHANNEL_MANAGER
 #include "AudioChannelManager.h"
--- a/dom/bindings/Bindings.conf
+++ b/dom/bindings/Bindings.conf
@@ -163,22 +163,22 @@ DOMInterfaces = {
 
 'BluetoothManager': {
     'nativeType': 'mozilla::dom::bluetooth::BluetoothManager',
     'headerFile': 'BluetoothManager.h'
 },
 
 'CallEvent': {
     'nativeType': 'mozilla::dom::telephony::CallEvent',
-    'headerFile': 'mozilla/dom/telephony/CallEvent.h',
+    'headerFile': 'CallEvent.h',
 },
 
 'CallsList': {
     'nativeType': 'mozilla::dom::telephony::CallsList',
-    'headerFile': 'mozilla/dom/telephony/CallsList.h',
+    'headerFile': 'CallsList.h',
 },
 
 'CameraControl': {
     'nativeType': 'mozilla::nsDOMCameraControl',
     'headerFile': 'DOMCameraControl.h',
     'binaryNames': {
         "release": "ReleaseHardware"
     }
@@ -1157,27 +1157,27 @@ DOMInterfaces = {
 },
 
 'SVGZoomAndPan' : {
     'concrete': False,
 },
 
 'Telephony' : {
     'nativeType': 'mozilla::dom::telephony::Telephony',
-    'headerFile': 'mozilla/dom/telephony/Telephony.h',
+    'headerFile': 'Telephony.h',
 },
 
 'TelephonyCall' : {
     'nativeType': 'mozilla::dom::telephony::TelephonyCall',
-    'headerFile': 'mozilla/dom/telephony/TelephonyCall.h',
+    'headerFile': 'TelephonyCall.h',
 },
 
 'TelephonyCallGroup' : {
     'nativeType': 'mozilla::dom::telephony::TelephonyCallGroup',
-    'headerFile': 'mozilla/dom/telephony/TelephonyCallGroup.h',
+    'headerFile': 'TelephonyCallGroup.h',
 },
 
 'Text': {
     # Total hack to allow binding code to realize that nsTextNode can
     # in fact be cast to Text.
     'headerFile': 'nsTextNode.h',
 },
 
--- a/dom/bluetooth/BluetoothHfpManager.cpp
+++ b/dom/bluetooth/BluetoothHfpManager.cpp
@@ -1478,17 +1478,17 @@ BluetoothHfpManager::OnSocketConnectSucc
     MOZ_ASSERT(!mSocket);
     mHeadsetSocket.swap(mSocket);
 
     mHandsfreeSocket->Disconnect();
     mHandsfreeSocket = nullptr;
   }
 
   nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
+    do_GetService(NS_RILCONTENTHELPER_CONTRACTID);
   NS_ENSURE_TRUE_VOID(provider);
   provider->EnumerateCalls(mListener->GetListener());
 
   mFirstCKPD = true;
 
   // Cache device path for NotifySettings() since we can't get socket address
   // when a headset disconnect with us
   mSocket->GetAddress(mDeviceAddress);
--- a/dom/bluetooth/BluetoothTelephonyListener.cpp
+++ b/dom/bluetooth/BluetoothTelephonyListener.cpp
@@ -56,21 +56,23 @@ TelephonyListener::EnumerateCallStateCom
 
 NS_IMETHODIMP
 TelephonyListener::EnumerateCallState(uint32_t aCallIndex,
                                       uint16_t aCallState,
                                       const nsAString_internal& aNumber,
                                       bool aIsActive,
                                       bool aIsOutgoing,
                                       bool aIsEmergency,
-                                      bool aIsConference)
+                                      bool aIsConference,
+                                      bool* aResult)
 {
   BluetoothHfpManager* hfp = BluetoothHfpManager::Get();
   hfp->HandleCallStateChanged(aCallIndex, aCallState, EmptyString(), aNumber,
                               aIsOutgoing, false);
+  *aResult = true;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TelephonyListener::SupplementaryServiceNotification(int32_t aCallIndex,
                                                     uint16_t aNotification)
 {
   return NS_OK;
@@ -110,33 +112,33 @@ BluetoothTelephonyListener::BluetoothTel
 {
   mTelephonyListener = new TelephonyListener();
 }
 
 bool
 BluetoothTelephonyListener::StartListening()
 {
   nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
+    do_GetService(NS_RILCONTENTHELPER_CONTRACTID);
   NS_ENSURE_TRUE(provider, false);
 
-  nsresult rv = provider->RegisterListener(mTelephonyListener);
+  nsresult rv = provider->RegisterTelephonyMsg(mTelephonyListener);
   NS_ENSURE_SUCCESS(rv, false);
 
   return true;
 }
 
 bool
 BluetoothTelephonyListener::StopListening()
 {
   nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
+    do_GetService(NS_RILCONTENTHELPER_CONTRACTID);
   NS_ENSURE_TRUE(provider, false);
 
-  nsresult rv = provider->UnregisterListener(mTelephonyListener);
+  nsresult rv = provider->UnregisterTelephonyMsg(mTelephonyListener);
 
   return NS_FAILED(rv) ? false : true;
 }
 
 nsITelephonyListener*
 BluetoothTelephonyListener::GetListener()
 {
   return mTelephonyListener;
--- a/dom/dom-config.mk
+++ b/dom/dom-config.mk
@@ -35,16 +35,17 @@ DOM_SRCDIRS = \
   layout/xul/base/src \
   layout/xul/tree \
   dom/camera \
   $(NULL)
 
 ifdef MOZ_B2G_RIL
 DOM_SRCDIRS += \
   dom/system/gonk \
+  dom/telephony \
   dom/wifi \
   dom/icc/src \
   $(NULL)
 endif
 
 ifdef MOZ_B2G_FM
 DOM_SRCDIRS += \
   dom/fmradio \
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -91,17 +91,16 @@
 #endif
 
 #ifdef ACCESSIBILITY
 #include "nsIAccessibilityService.h"
 #endif
 
 #include "mozilla/dom/indexedDB/PIndexedDBChild.h"
 #include "mozilla/dom/mobilemessage/SmsChild.h"
-#include "mozilla/dom/telephony/TelephonyChild.h"
 #include "mozilla/dom/devicestorage/DeviceStorageRequestChild.h"
 #include "mozilla/dom/bluetooth/PBluetoothChild.h"
 #include "mozilla/dom/PFMRadioChild.h"
 #include "mozilla/ipc/InputStreamUtils.h"
 
 #ifdef MOZ_WEBSPEECH
 #include "mozilla/dom/PSpeechSynthesisChild.h"
 #endif
@@ -122,17 +121,16 @@
 using namespace base;
 using namespace mozilla;
 using namespace mozilla::docshell;
 using namespace mozilla::dom::bluetooth;
 using namespace mozilla::dom::devicestorage;
 using namespace mozilla::dom::ipc;
 using namespace mozilla::dom::mobilemessage;
 using namespace mozilla::dom::indexedDB;
-using namespace mozilla::dom::telephony;
 using namespace mozilla::hal_sandbox;
 using namespace mozilla::ipc;
 using namespace mozilla::layers;
 using namespace mozilla::net;
 using namespace mozilla::jsipc;
 #if defined(MOZ_WIDGET_GONK)
 using namespace mozilla::system;
 #endif
@@ -916,29 +914,16 @@ ContentChild::AllocPSmsChild()
 
 bool
 ContentChild::DeallocPSmsChild(PSmsChild* aSms)
 {
     delete aSms;
     return true;
 }
 
-PTelephonyChild*
-ContentChild::AllocPTelephonyChild()
-{
-    MOZ_CRASH("No one should be allocating PTelephonyChild actors");
-}
-
-bool
-ContentChild::DeallocPTelephonyChild(PTelephonyChild* aActor)
-{
-    delete aActor;
-    return true;
-}
-
 PStorageChild*
 ContentChild::AllocPStorageChild()
 {
     NS_NOTREACHED("We should never be manually allocating PStorageChild actors");
     return nullptr;
 }
 
 bool
--- a/dom/ipc/ContentChild.h
+++ b/dom/ipc/ContentChild.h
@@ -147,19 +147,16 @@ public:
             const bool& aForceSave,
             const int64_t& aContentLength,
             const OptionalURIParams& aReferrer);
     virtual bool DeallocPExternalHelperAppChild(PExternalHelperAppChild *aService);
 
     virtual PSmsChild* AllocPSmsChild();
     virtual bool DeallocPSmsChild(PSmsChild*);
 
-    virtual PTelephonyChild* AllocPTelephonyChild();
-    virtual bool DeallocPTelephonyChild(PTelephonyChild*);
-
     virtual PStorageChild* AllocPStorageChild();
     virtual bool DeallocPStorageChild(PStorageChild* aActor);
 
     virtual PBluetoothChild* AllocPBluetoothChild();
     virtual bool DeallocPBluetoothChild(PBluetoothChild* aActor);
 
     virtual PFMRadioChild* AllocPFMRadioChild();
     virtual bool DeallocPFMRadioChild(PFMRadioChild* aActor);
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -29,17 +29,16 @@
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/ExternalHelperAppParent.h"
 #include "mozilla/dom/PMemoryReportRequestParent.h"
 #include "mozilla/dom/power/PowerManagerService.h"
 #include "mozilla/dom/DOMStorageIPC.h"
 #include "mozilla/dom/bluetooth/PBluetoothParent.h"
 #include "mozilla/dom/PFMRadioParent.h"
 #include "mozilla/dom/devicestorage/DeviceStorageRequestParent.h"
-#include "mozilla/dom/telephony/TelephonyParent.h"
 #include "SmsParent.h"
 #include "mozilla/Hal.h"
 #include "mozilla/hal_sandbox/PHalParent.h"
 #include "mozilla/ipc/TestShellParent.h"
 #include "mozilla/ipc/InputStreamUtils.h"
 #include "mozilla/layers/CompositorParent.h"
 #include "mozilla/layers/ImageBridgeParent.h"
 #include "mozilla/net/NeckoParent.h"
@@ -143,17 +142,16 @@ static const char* sClipboardTextFlavors
 
 using base::ChildPrivileges;
 using base::KillProcess;
 using namespace mozilla::dom::bluetooth;
 using namespace mozilla::dom::devicestorage;
 using namespace mozilla::dom::indexedDB;
 using namespace mozilla::dom::power;
 using namespace mozilla::dom::mobilemessage;
-using namespace mozilla::dom::telephony;
 using namespace mozilla::hal;
 using namespace mozilla::idl;
 using namespace mozilla::ipc;
 using namespace mozilla::layers;
 using namespace mozilla::net;
 using namespace mozilla::jsipc;
 
 namespace mozilla {
@@ -2241,35 +2239,16 @@ ContentParent::AllocPSmsParent()
 
 bool
 ContentParent::DeallocPSmsParent(PSmsParent* aSms)
 {
     static_cast<SmsParent*>(aSms)->Release();
     return true;
 }
 
-PTelephonyParent*
-ContentParent::AllocPTelephonyParent()
-{
-    if (!AssertAppProcessPermission(this, "telephony")) {
-        return nullptr;
-    }
-
-    TelephonyParent* actor = new TelephonyParent();
-    NS_ADDREF(actor);
-    return actor;
-}
-
-bool
-ContentParent::DeallocPTelephonyParent(PTelephonyParent* aActor)
-{
-    static_cast<TelephonyParent*>(aActor)->Release();
-    return true;
-}
-
 PStorageParent*
 ContentParent::AllocPStorageParent()
 {
     return new DOMStorageDBParent();
 }
 
 bool
 ContentParent::DeallocPStorageParent(PStorageParent* aActor)
--- a/dom/ipc/ContentParent.h
+++ b/dom/ipc/ContentParent.h
@@ -316,19 +316,16 @@ private:
             const bool& aForceSave,
             const int64_t& aContentLength,
             const OptionalURIParams& aReferrer);
     virtual bool DeallocPExternalHelperAppParent(PExternalHelperAppParent* aService);
 
     virtual PSmsParent* AllocPSmsParent();
     virtual bool DeallocPSmsParent(PSmsParent*);
 
-    virtual PTelephonyParent* AllocPTelephonyParent();
-    virtual bool DeallocPTelephonyParent(PTelephonyParent*);
-
     virtual PStorageParent* AllocPStorageParent();
     virtual bool DeallocPStorageParent(PStorageParent* aActor);
 
     virtual PBluetoothParent* AllocPBluetoothParent();
     virtual bool DeallocPBluetoothParent(PBluetoothParent* aActor);
     virtual bool RecvPBluetoothConstructor(PBluetoothParent* aActor);
 
     virtual PFMRadioParent* AllocPFMRadioParent();
--- a/dom/ipc/PContent.ipdl
+++ b/dom/ipc/PContent.ipdl
@@ -15,17 +15,16 @@ include protocol PFMRadio;
 include protocol PHal;
 include protocol PImageBridge;
 include protocol PIndexedDB;
 include protocol PMemoryReportRequest;
 include protocol PNecko;
 include protocol PSms;
 include protocol PSpeechSynthesis;
 include protocol PStorage;
-include protocol PTelephony;
 include protocol PTestShell;
 include protocol PJavaScript;
 include DOMTypes;
 include JavaScriptTypes;
 include InputStreamParams;
 include PTabContext;
 include URIParams;
 
@@ -193,17 +192,16 @@ rpc protocol PContent
     manages PFMRadio;
     manages PHal;
     manages PIndexedDB;
     manages PMemoryReportRequest;
     manages PNecko;
     manages PSms;
     manages PSpeechSynthesis;
     manages PStorage;
-    manages PTelephony;
     manages PTestShell;
     manages PJavaScript;
 
 both:
     // Depending on exactly how the new browser is being created, it might be
     // created from either the child or parent process!
     //
     // The child creates the PBrowser as part of
@@ -350,18 +348,16 @@ parent:
     PNecko();
 
     PSms();
 
     PSpeechSynthesis();
 
     PStorage();
 
-    PTelephony();
-
     PBluetooth();
 
     PFMRadio();
 
     // Services remoting
 
     async StartVisitedQuery(URIParams uri);
     async VisitURI(URIParams uri, OptionalURIParams referrer, uint32_t flags);
--- a/dom/mobilemessage/interfaces/moz.build
+++ b/dom/mobilemessage/interfaces/moz.build
@@ -20,13 +20,12 @@ XPIDL_SOURCES += [
     'nsIMobileMessageService.idl',
     'nsISmsService.idl',
     'nsIWapPushApplication.idl',
 ]
 
 if CONFIG['MOZ_B2G_RIL']:
     XPIDL_SOURCES += [
         'nsIRilMobileMessageDatabaseService.idl',
-        'nsIRilSmsService.idl',
     ]
 
 XPIDL_MODULE = 'dom_mobilemessage'
 
deleted file mode 100644
--- a/dom/mobilemessage/interfaces/nsIRilSmsService.idl
+++ /dev/null
@@ -1,11 +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 "nsISmsService.idl"
-
-[scriptable, uuid(f216903c-bdf5-4988-b894-f62fd91df114)]
-interface nsIRilSmsService : nsISmsService
-{
-  void notifyMessageReceived(in jsval message);
-};
--- a/dom/mobilemessage/interfaces/nsISmsService.idl
+++ b/dom/mobilemessage/interfaces/nsISmsService.idl
@@ -8,24 +8,25 @@ interface nsIDOMMozSmsMessage;
 interface nsIDOMMozSmsSegmentInfo;
 interface nsIMobileMessageCallback;
 
 %{C++
 #define SMS_SERVICE_CID { 0xbada3cb8, 0xa568, 0x4dff, { 0xb5, 0x43, 0x52, 0xbb, 0xb3, 0x14, 0x31, 0x21 } }
 #define SMS_SERVICE_CONTRACTID "@mozilla.org/sms/smsservice;1"
 %}
 
-[scriptable, uuid(7ef8e361-9db6-46ed-badc-2901e1049e5d)]
+[scriptable, builtinclass, uuid(0f3f75ec-00dd-11e3-87ac-0b1d5c79afdf)]
 interface nsISmsService : nsISupports
 {
   boolean hasSupport();
 
   void getSegmentInfoForText(in DOMString text,
                              in nsIMobileMessageCallback request);
 
   void send(in DOMString number,
             in DOMString message,
             in boolean silent,
             in nsIMobileMessageCallback request);
 
+  boolean isSilentNumber(in DOMString number);
   void addSilentNumber(in DOMString number);
   void removeSilentNumber(in DOMString number);
 };
--- a/dom/mobilemessage/src/Makefile.in
+++ b/dom/mobilemessage/src/Makefile.in
@@ -21,10 +21,17 @@ LOCAL_INCLUDES = \
   -I$(topsrcdir)/content/events/src \
   -I$(topsrcdir)/dom/base \
   $(NULL)
 
 # Add VPATH to LOCAL_INCLUDES so we are going to include the correct backend
 # subdirectory (and the ipc one).
 LOCAL_INCLUDES += $(VPATH:%=-I%)
 
+ifdef MOZ_B2G_RIL
+LOCAL_INCLUDES += \
+  -I$(topsrcdir)/dom/telephony \
+  -I$(topsrcdir)/dom/system/gonk \
+  $(NULL)
+endif
+
 include $(topsrcdir)/config/rules.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
--- a/dom/mobilemessage/src/SmsServicesFactory.cpp
+++ b/dom/mobilemessage/src/SmsServicesFactory.cpp
@@ -1,60 +1,53 @@
 /* -*- 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 "SmsServicesFactory.h"
 #include "nsXULAppAPI.h"
+#include "SmsService.h"
 #include "SmsIPCService.h"
 #ifndef MOZ_B2G_RIL
 #include "MobileMessageDatabaseService.h"
 #include "MmsService.h"
-#include "SmsService.h"
 #endif
 #include "nsServiceManagerUtils.h"
 
 #define RIL_MMSSERVICE_CONTRACTID "@mozilla.org/mms/rilmmsservice;1"
-#define RIL_MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID \
-  "@mozilla.org/mobilemessage/rilmobilemessagedatabaseservice;1"
-#define RIL_SMSSERVICE_CONTRACTID "@mozilla.org/sms/rilsmsservice;1"
+#define RIL_MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID "@mozilla.org/mobilemessage/rilmobilemessagedatabaseservice;1"
 
 namespace mozilla {
 namespace dom {
 namespace mobilemessage {
 
 /* static */ already_AddRefed<nsISmsService>
 SmsServicesFactory::CreateSmsService()
 {
   nsCOMPtr<nsISmsService> smsService;
 
   if (XRE_GetProcessType() == GeckoProcessType_Content) {
     smsService = new SmsIPCService();
   } else {
-#ifdef MOZ_B2G_RIL
-    smsService = do_GetService(RIL_SMSSERVICE_CONTRACTID);
-#else
     smsService = new SmsService();
-#endif
   }
 
   return smsService.forget();
 }
 
 /* static */ already_AddRefed<nsIMobileMessageDatabaseService>
 SmsServicesFactory::CreateMobileMessageDatabaseService()
 {
   nsCOMPtr<nsIMobileMessageDatabaseService> mobileMessageDBService;
   if (XRE_GetProcessType() == GeckoProcessType_Content) {
     mobileMessageDBService = new SmsIPCService();
   } else {
 #ifdef MOZ_B2G_RIL
-    mobileMessageDBService =
-      do_GetService(RIL_MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
+    mobileMessageDBService = do_GetService(RIL_MOBILE_MESSAGE_DATABASE_SERVICE_CONTRACTID);
 #else
     mobileMessageDBService = new MobileMessageDatabaseService();
 #endif
   }
 
   return mobileMessageDBService.forget();
 }
 
--- a/dom/mobilemessage/src/android/SmsService.cpp
+++ b/dom/mobilemessage/src/android/SmsService.cpp
@@ -46,16 +46,24 @@ SmsService::Send(const nsAString& aNumbe
     return NS_OK;
   }
 
   AndroidBridge::Bridge()->SendMessage(aNumber, aMessage, aRequest);
   return NS_OK;
 }
 
 NS_IMETHODIMP
+SmsService::IsSilentNumber(const nsAString& aNumber,
+                           bool*            aIsSilent)
+{
+  NS_NOTYETIMPLEMENTED("Implement me!");
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
 SmsService::AddSilentNumber(const nsAString& aNumber)
 {
   NS_NOTYETIMPLEMENTED("Implement me!");
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 NS_IMETHODIMP
 SmsService::RemoveSilentNumber(const nsAString& aNumber)
--- a/dom/mobilemessage/src/fallback/SmsService.cpp
+++ b/dom/mobilemessage/src/fallback/SmsService.cpp
@@ -35,16 +35,24 @@ SmsService::Send(const nsAString& aNumbe
                  const bool       aSilent,
                  nsIMobileMessageCallback* aRequest)
 {
   NS_ERROR("We should not be here!");
   return NS_ERROR_FAILURE;
 }
 
 NS_IMETHODIMP
+SmsService::IsSilentNumber(const nsAString& aNumber,
+                           bool*            aIsSilent)
+{
+  NS_ERROR("We should not be here!");
+  return NS_ERROR_FAILURE;
+}
+
+NS_IMETHODIMP
 SmsService::AddSilentNumber(const nsAString& aNumber)
 {
   NS_ERROR("We should not be here!");
   return NS_ERROR_FAILURE;
 }
 
 NS_IMETHODIMP
 SmsService::RemoveSilentNumber(const nsAString& aNumber)
new file mode 100644
--- /dev/null
+++ b/dom/mobilemessage/src/gonk/SmsService.cpp
@@ -0,0 +1,85 @@
+/* -*- 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 "SmsMessage.h"
+#include "SmsService.h"
+#include "jsapi.h"
+#include "SmsSegmentInfo.h"
+
+namespace mozilla {
+namespace dom {
+namespace mobilemessage {
+
+NS_IMPL_ISUPPORTS1(SmsService, nsISmsService)
+
+SmsService::SmsService()
+{
+  nsCOMPtr<nsIRadioInterfaceLayer> ril = do_GetService("@mozilla.org/ril;1");
+  if (ril) {
+    ril->GetRadioInterface(0, getter_AddRefs(mRadioInterface));
+  }
+  NS_WARN_IF_FALSE(mRadioInterface, "This shouldn't fail!");
+}
+
+NS_IMETHODIMP
+SmsService::HasSupport(bool* aHasSupport)
+{
+  *aHasSupport = true;
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+SmsService::GetSegmentInfoForText(const nsAString& aText,
+                                  nsIMobileMessageCallback* aRequest)
+{
+  NS_ENSURE_TRUE(mRadioInterface, NS_ERROR_FAILURE);
+
+  return mRadioInterface->GetSegmentInfoForText(aText, aRequest);
+}
+
+NS_IMETHODIMP
+SmsService::Send(const nsAString& aNumber,
+                 const nsAString& aMessage,
+                 const bool       aSilent,
+                 nsIMobileMessageCallback* aRequest)
+{
+  NS_ENSURE_TRUE(mRadioInterface, NS_ERROR_FAILURE);
+
+  return mRadioInterface->SendSMS(aNumber, aMessage, aSilent, aRequest);
+}
+
+NS_IMETHODIMP
+SmsService::IsSilentNumber(const nsAString& aNumber,
+                           bool*            aIsSilent)
+{
+  *aIsSilent = mSilentNumbers.Contains(aNumber);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+SmsService::AddSilentNumber(const nsAString& aNumber)
+{
+  if (mSilentNumbers.Contains(aNumber)) {
+    return NS_ERROR_UNEXPECTED;
+  }
+
+  NS_ENSURE_TRUE(mSilentNumbers.AppendElement(aNumber), NS_ERROR_FAILURE);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+SmsService::RemoveSilentNumber(const nsAString& aNumber)
+{
+  if (!mSilentNumbers.Contains(aNumber)) {
+    return NS_ERROR_INVALID_ARG;
+  }
+
+  NS_ENSURE_TRUE(mSilentNumbers.RemoveElement(aNumber), NS_ERROR_FAILURE);
+  return NS_OK;
+}
+
+} // namespace mobilemessage
+} // namespace dom
+} // namespace mozilla
new file mode 100644
--- /dev/null
+++ b/dom/mobilemessage/src/gonk/SmsService.h
@@ -0,0 +1,35 @@
+/* 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_dom_mobilemessage_SmsService_h
+#define mozilla_dom_mobilemessage_SmsService_h
+
+#include "nsISmsService.h"
+#include "nsCOMPtr.h"
+#include "nsIRadioInterfaceLayer.h"
+#include "nsTArray.h"
+#include "nsString.h"
+
+namespace mozilla {
+namespace dom {
+namespace mobilemessage {
+
+class SmsService : public nsISmsService
+{
+public:
+  NS_DECL_ISUPPORTS
+  NS_DECL_NSISMSSERVICE
+  SmsService();
+
+protected:
+  // TODO: Bug 854326 - B2G Multi-SIM: support multiple SIM cards for SMS/MMS
+  nsCOMPtr<nsIRadioInterface> mRadioInterface;
+  nsTArray<nsString> mSilentNumbers;
+};
+
+} // namespace mobilemessage
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_mobilemessage_SmsService_h
deleted file mode 100644
--- a/dom/mobilemessage/src/gonk/SmsService.js
+++ /dev/null
@@ -1,1015 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: sw=2 ts=2 sts=2 et filetype=javascript
- * 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, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-var RIL = {};
-Cu.import("resource://gre/modules/ril_consts.js", RIL);
-
-const RIL_SMSSERVICE_CONTRACTID = "@mozilla.org/sms/rilsmsservice;1";
-const RIL_SMSSERVICE_CID =
-  Components.ID("{46a9ed78-3574-40a1-9f12-ea179942d67f}");
-
-const DELIVERY_STATE_RECEIVED = "received";
-const DELIVERY_STATE_SENDING  = "sending";
-const DELIVERY_STATE_SENT     = "sent";
-const DELIVERY_STATE_ERROR    = "error";
-
-// Observer topics to send.
-const kSmsReceivedObserverTopic          = "sms-received";
-const kSmsSendingObserverTopic           = "sms-sending";
-const kSmsSentObserverTopic              = "sms-sent";
-const kSmsFailedObserverTopic            = "sms-failed";
-const kSmsDeliverySuccessObserverTopic   = "sms-delivery-success";
-const kSmsDeliveryErrorObserverTopic     = "sms-delivery-error";
-const kSilentSmsReceivedObserverTopic    = "silent-sms-received";
-
-// Observer topics to watch.
-const kPrefenceChangedObserverTopic = "nsPref:changed";
-const kXpcomShutdownObserverTopic   = "xpcom-shutdown";
-
-// Preference keys.
-const kPrefKeyRilDebuggingEnabled = "ril.debugging.enabled";
-
-// TODO: Bug 815526 - [meta] B2G RIL: deprecate RILContentHelper
-XPCOMUtils.defineLazyServiceGetter(this, "gIccProvider",
-                                   "@mozilla.org/ril/content-helper;1",
-                                   "nsIIccProvider");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageDatabaseService",
-                                   "@mozilla.org/mobilemessage/rilmobilemessagedatabaseservice;1",
-                                   "nsIRilMobileMessageDatabaseService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageService",
-                                   "@mozilla.org/mobilemessage/mobilemessageservice;1",
-                                   "nsIMobileMessageService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSystemMessenger",
-                                   "@mozilla.org/system-message-internal;1",
-                                   "nsISystemMessagesInternal");
-
-XPCOMUtils.defineLazyGetter(this, "gRadioInterface", function () {
-  let ril = Cc["@mozilla.org/ril;1"].getService(Ci.nsIRadioInterfaceLayer);
-  // TODO: Bug 854326 - B2G Multi-SIM: support multiple SIM cards for SMS/MMS
-  return ril.getRadioInterface(0);
-});
-
-XPCOMUtils.defineLazyGetter(this, "gPhoneNumberUtils", function () {
-  let ns = {};
-  Cu.import("resource://gre/modules/PhoneNumberUtils.jsm", ns);
-  return ns.PhoneNumberUtils;
-});
-
-XPCOMUtils.defineLazyGetter(this, "WAP", function () {
-  let WAP = {};
-  Cu.import("resource://gre/modules/WapPushManager.js", WAP);
-  return WAP;
-});
-
-// TODO: Bug 833229 - B2G RIL: use ipdl as IPC in MozVoicemail
-XPCOMUtils.defineLazyGetter(this, "gMessageManager", function () {
-  let ns = {};
-  Cu.import("resource://gre/modules/RilMessageManager.jsm", ns);
-  return ns.RilMessageManager;
-});
-
-let DEBUG;
-function debug(s) {
-  dump("SmsService: " + s + "\n");
-}
-
-/**
- * SmsService
- */
-function SmsService() {
-  this._updateDebugFlag();
-
-  this.silentNumbers = [];
-
-  this.portAddressedSmsApps = {};
-  this.portAddressedSmsApps[WAP.WDP_PORT_PUSH] =
-    this._handleSmsWdpPortPush.bind(this);
-
-  Services.obs.addObserver(this, kPrefenceChangedObserverTopic, false);
-  Services.obs.addObserver(this, kXpcomShutdownObserverTopic, false);
-}
-SmsService.prototype = {
-
-  classID: RIL_SMSSERVICE_CID,
-  classInfo: XPCOMUtils.generateCI({classID: RIL_SMSSERVICE_CID,
-                                    contractID: RIL_SMSSERVICE_CONTRACTID,
-                                    classDescription: "SmsService",
-                                    interfaces: [Ci.nsIRilSmsService,
-                                                 Ci.nsISmsService],
-                                    flags: Ci.nsIClassInfo.SINGLETON}),
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
-                                         Ci.nsIRilSmsService,
-                                         Ci.nsISmsService]),
-
-  /**
-   * List of tuples of national language identifier pairs.
-   *
-   * TODO: Support static/runtime settings, see bug 733331.
-   */
-  enabledGsmTableTuples: [
-    [RIL.PDU_NL_IDENTIFIER_DEFAULT, RIL.PDU_NL_IDENTIFIER_DEFAULT],
-  ],
-
-  /**
-   * Use 16-bit reference number for concatenated outgoint messages.
-   *
-   * TODO: Support static/runtime settings, see bug 733331.
-   */
-  segmentRef16Bit: false,
-
-  /**
-   * Get valid SMS concatenation reference number.
-   */
-  segmentRef: 0,
-  get nextSegmentRef() {
-    let ref = this.segmentRef++;
-
-    this.segmentRef %= (this.segmentRef16Bit ? 65535 : 255);
-
-    // 0 is not a valid SMS concatenation reference number.
-    return ref + 1;
-  },
-
-  statusReportPendingMessageIds: null,
-
-  portAddressedSmsApps: null,
-
-  silentNumbers: null,
-
-  _updateDebugFlag: function _updateDebugFlag() {
-    try {
-      DEBUG = RIL.DEBUG_RIL ||
-              Services.prefs.getBoolPref("ril.debugging.enabled");
-    } catch (e) {}
-  },
-
-  _getStrict7BitEncoding: function _getStrict7BitEncoding() {
-    try {
-      return Services.prefs.getBoolPref("dom.sms.strict7BitEncoding");
-    } catch (e) {
-      return false;
-    }
-  },
-
-  _getRequestStatusReport: function _getRequestStatusReport() {
-    try {
-      return Services.prefs.getBoolPref("dom.sms.requestStatusReport");
-    } catch (e) {
-      return true;
-    }
-  },
-
-  _getMsisdn: function _getMsisdn() {
-    let iccInfo = gIccProvider.iccInfo;
-    if (!iccInfo) {
-      return null;
-    }
-
-    let number;
-    if (iccInfo.iccType == "ruim") {
-      let cdmaIccInfo = iccInfo.QueryInterface(Ci.nsIDOMMozCdmaIccInfo);
-      number = cdmaIccInfo.mdn;
-    } else {
-      let gsmIccInfo = iccInfo.QueryInterface(Ci.nsIDOMMozGsmIccInfo);
-      number = gsmIccInfo.msisdn;
-    }
-
-    // Workaround an xpconnect issue with undefined string objects.
-    // See bug 808220
-    if (number === undefined || number === "undefined") {
-      return null;
-    }
-    return number;
-  },
-
-  /**
-   * Calculate encoded length using specified locking/single shift table
-   *
-   * @param text
-   *        text string to be encoded.
-   * @param langTable
-   *        locking shift table string.
-   * @param langShiftTable
-   *        single shift table string.
-   * @param strict7BitEncoding
-   *        Optional. Enable Latin characters replacement with corresponding
-   *        ones in GSM SMS 7-bit default alphabet.
-   *
-   * @return encoded length in septets.
-   *
-   * @note that the algorithm used in this function must match exactly with
-   * GsmPDUHelper#writeStringAsSeptets.
-   */
-  _countGsm7BitSeptets: function _countGsm7BitSeptets(text,
-                                                      langTable,
-                                                      langShiftTable,
-                                                      strict7BitEncoding) {
-    let length = 0;
-    for (let msgIndex = 0; msgIndex < text.length; msgIndex++) {
-      let c = text.charAt(msgIndex);
-      if (strict7BitEncoding) {
-        c = RIL.GSM_SMS_STRICT_7BIT_CHARMAP[c] || c;
-      }
-
-      let septet = langTable.indexOf(c);
-
-      // According to 3GPP TS 23.038, section 6.1.1 General notes, "The
-      // characters marked '1)' are not used but are displayed as a space."
-      if (septet == RIL.PDU_NL_EXTENDED_ESCAPE) {
-        continue;
-      }
-
-      if (septet >= 0) {
-        length++;
-        continue;
-      }
-
-      septet = langShiftTable.indexOf(c);
-      if (septet < 0) {
-        if (!strict7BitEncoding) {
-          return -1;
-        }
-
-        // Bug 816082, when strict7BitEncoding is enabled, we should replace
-        // characters that can't be encoded with GSM 7-Bit alphabets with '*'.
-        c = '*';
-        if (langTable.indexOf(c) >= 0) {
-          length++;
-        } else if (langShiftTable.indexOf(c) >= 0) {
-          length += 2;
-        } else {
-          // We can't even encode a '*' character with current configuration.
-          return -1;
-        }
-
-        continue;
-      }
-
-      // According to 3GPP TS 23.038 B.2, "This code represents a control
-      // character and therefore must not be used for language specific
-      // characters."
-      if (septet == RIL.PDU_NL_RESERVED_CONTROL) {
-        continue;
-      }
-
-      // The character is not found in locking shfit table, but could be
-      // encoded as <escape><char> with single shift table. Note that it's
-      // still possible for septet to has the value of PDU_NL_EXTENDED_ESCAPE,
-      // but we can display it as a space in this case as said in previous
-      // comment.
-      length += 2;
-    }
-
-    return length;
-  },
-
-  /**
-   * Calculate user data length of specified text string encoded in GSM 7Bit
-   * alphabets.
-   *
-   * @param text
-   *        a text string to be encoded.
-   * @param strict7BitEncoding
-   *        Optional. Enable Latin characters replacement with corresponding
-   *        ones in GSM SMS 7-bit default alphabet.
-   *
-   * @return null or an options object with attributes `dcs`,
-   *         `userDataHeaderLength`, `encodedFullBodyLength`, `langIndex`,
-   *         `langShiftIndex`, `segmentMaxSeq` set.
-   *
-   * @see #_calculateUserDataLength().
-   */
-  _calculateUserDataLength7Bit: function _calculateUserDataLength7Bit(text,
-                                                                      strict7BitEncoding) {
-    let options = null;
-    let minUserDataSeptets = Number.MAX_VALUE;
-    for (let i = 0; i < this.enabledGsmTableTuples.length; i++) {
-      let [langIndex, langShiftIndex] = this.enabledGsmTableTuples[i];
-
-      const langTable = RIL.PDU_NL_LOCKING_SHIFT_TABLES[langIndex];
-      const langShiftTable = RIL.PDU_NL_SINGLE_SHIFT_TABLES[langShiftIndex];
-
-      let bodySeptets = this._countGsm7BitSeptets(text,
-                                                  langTable,
-                                                  langShiftTable,
-                                                  strict7BitEncoding);
-      if (bodySeptets < 0) {
-        continue;
-      }
-
-      let headerLen = 0;
-      if (langIndex != RIL.PDU_NL_IDENTIFIER_DEFAULT) {
-        headerLen += 3; // IEI + len + langIndex
-      }
-      if (langShiftIndex != RIL.PDU_NL_IDENTIFIER_DEFAULT) {
-        headerLen += 3; // IEI + len + langShiftIndex
-      }
-
-      // Calculate full user data length, note the extra byte is for header len
-      let headerSeptets = Math.ceil((headerLen ? headerLen + 1 : 0) * 8 / 7);
-      let segmentSeptets = RIL.PDU_MAX_USER_DATA_7BIT;
-      if ((bodySeptets + headerSeptets) > segmentSeptets) {
-        headerLen += this.segmentRef16Bit ? 6 : 5;
-        headerSeptets = Math.ceil((headerLen + 1) * 8 / 7);
-        segmentSeptets -= headerSeptets;
-      }
-
-      let segments = Math.ceil(bodySeptets / segmentSeptets);
-      let userDataSeptets = bodySeptets + headerSeptets * segments;
-      if (userDataSeptets >= minUserDataSeptets) {
-        continue;
-      }
-
-      minUserDataSeptets = userDataSeptets;
-
-      options = {
-        dcs: RIL.PDU_DCS_MSG_CODING_7BITS_ALPHABET,
-        encodedFullBodyLength: bodySeptets,
-        userDataHeaderLength: headerLen,
-        langIndex: langIndex,
-        langShiftIndex: langShiftIndex,
-        segmentMaxSeq: segments,
-        segmentChars: segmentSeptets,
-      };
-    }
-
-    return options;
-  },
-
-  /**
-   * Calculate user data length of specified text string encoded in UCS2.
-   *
-   * @param text
-   *        a text string to be encoded.
-   *
-   * @return an options object with attributes `dcs`, `userDataHeaderLength`,
-   *         `encodedFullBodyLength`, `segmentMaxSeq` set.
-   *
-   * @see #_calculateUserDataLength().
-   */
-  _calculateUserDataLengthUCS2: function _calculateUserDataLengthUCS2(text) {
-    let bodyChars = text.length;
-    let headerLen = 0;
-    let headerChars = Math.ceil((headerLen ? headerLen + 1 : 0) / 2);
-    let segmentChars = RIL.PDU_MAX_USER_DATA_UCS2;
-    if ((bodyChars + headerChars) > segmentChars) {
-      headerLen += this.segmentRef16Bit ? 6 : 5;
-      headerChars = Math.ceil((headerLen + 1) / 2);
-      segmentChars -= headerChars;
-    }
-
-    let segments = Math.ceil(bodyChars / segmentChars);
-
-    return {
-      dcs: RIL.PDU_DCS_MSG_CODING_16BITS_ALPHABET,
-      encodedFullBodyLength: bodyChars * 2,
-      userDataHeaderLength: headerLen,
-      segmentMaxSeq: segments,
-      segmentChars: segmentChars,
-    };
-  },
-
-  /**
-   * Calculate user data length and its encoding.
-   *
-   * @param text
-   *        a text string to be encoded.
-   * @param strict7BitEncoding
-   *        Optional. Enable Latin characters replacement with corresponding
-   *        ones in GSM SMS 7-bit default alphabet.
-   *
-   * @return an options object with some or all of following attributes set:
-   *
-   * @param dcs
-   *        Data coding scheme. One of the PDU_DCS_MSG_CODING_*BITS_ALPHABET
-   *        constants.
-   * @param userDataHeaderLength
-   *        Length of embedded user data header, in bytes. The whole header
-   *        size will be userDataHeaderLength + 1; 0 for no header.
-   * @param encodedFullBodyLength
-   *        Length of the text body when encoded with the given DCS. For
-   *        UCS2, in bytes; for 7-bit, in septets.
-   * @param langIndex
-   *        Table index used for normal 7-bit encoded character lookup.
-   * @param langShiftIndex
-   *        Table index used for escaped 7-bit encoded character lookup.
-   * @param segmentMaxSeq
-   *        Max sequence number of a multi-part messages, or 1 for single one.
-   *        This number might not be accurate for a multi-part text until
-   *        it's processed by #_fragmentText() again.
-   */
-  _calculateUserDataLength: function _calculateUserDataLength(text,
-                                                              strict7BitEncoding) {
-    let options = this._calculateUserDataLength7Bit(text, strict7BitEncoding);
-    if (!options) {
-      options = this._calculateUserDataLengthUCS2(text);
-    }
-
-    if (DEBUG) debug("_calculateUserDataLength: " + JSON.stringify(options));
-    return options;
-  },
-
-  /**
-   * Fragment GSM 7-Bit encodable string for transmission.
-   *
-   * @param text
-   *        text string to be fragmented.
-   * @param langTable
-   *        locking shift table string.
-   * @param langShiftTable
-   *        single shift table string.
-   * @param segmentSeptets
-   *        Number of available spetets per segment.
-   * @param strict7BitEncoding
-   *        Optional. Enable Latin characters replacement with corresponding
-   *        ones in GSM SMS 7-bit default alphabet.
-   *
-   * @return an array of objects. See #_fragmentText() for detailed definition.
-   */
-  _fragmentText7Bit: function _fragmentText7Bit(text, langTable, langShiftTable,
-                                                segmentSeptets,
-                                                strict7BitEncoding) {
-    let ret = [];
-    let body = "", len = 0;
-    for (let i = 0, inc = 0; i < text.length; i++) {
-      let c = text.charAt(i);
-      if (strict7BitEncoding) {
-        c = RIL.GSM_SMS_STRICT_7BIT_CHARMAP[c] || c;
-      }
-
-      let septet = langTable.indexOf(c);
-      if (septet == RIL.PDU_NL_EXTENDED_ESCAPE) {
-        continue;
-      }
-
-      if (septet >= 0) {
-        inc = 1;
-      } else {
-        septet = langShiftTable.indexOf(c);
-        if (septet == RIL.PDU_NL_RESERVED_CONTROL) {
-          continue;
-        }
-
-        inc = 2;
-        if (septet < 0) {
-          if (!strict7BitEncoding) {
-            throw new Error("Given text cannot be encoded with GSM 7-bit Alphabet!");
-          }
-
-          // Bug 816082, when strict7BitEncoding is enabled, we should replace
-          // characters that can't be encoded with GSM 7-Bit alphabets with '*'.
-          c = '*';
-          if (langTable.indexOf(c) >= 0) {
-            inc = 1;
-          }
-        }
-      }
-
-      if ((len + inc) > segmentSeptets) {
-        ret.push({
-          body: body,
-          encodedBodyLength: len,
-        });
-        body = c;
-        len = inc;
-      } else {
-        body += c;
-        len += inc;
-      }
-    }
-
-    if (len) {
-      ret.push({
-        body: body,
-        encodedBodyLength: len,
-      });
-    }
-
-    return ret;
-  },
-
-  /**
-   * Fragment UCS2 encodable string for transmission.
-   *
-   * @param text
-   *        text string to be fragmented.
-   * @param segmentChars
-   *        Number of available characters per segment.
-   *
-   * @return an array of objects. See #_fragmentText() for detailed definition.
-   */
-  _fragmentTextUCS2: function _fragmentTextUCS2(text, segmentChars) {
-    let ret = [];
-    for (let offset = 0; offset < text.length; offset += segmentChars) {
-      let str = text.substr(offset, segmentChars);
-      ret.push({
-        body: str,
-        encodedBodyLength: str.length * 2,
-      });
-    }
-
-    return ret;
-  },
-
-  /**
-   * Fragment string for transmission.
-   *
-   * Fragment input text string into an array of objects that contains
-   * attributes `body`, substring for this segment, `encodedBodyLength`,
-   * length of the encoded segment body in septets.
-   *
-   * @param text
-   *        Text string to be fragmented.
-   * @param options
-   *        Optional pre-calculated option object. The output array will be
-   *        stored at options.segments if there are multiple segments.
-   * @param strict7BitEncoding
-   *        Optional. Enable Latin characters replacement with corresponding
-   *        ones in GSM SMS 7-bit default alphabet.
-   *
-   * @return Populated options object.
-   */
-  _fragmentText: function _fragmentText(text, options, strict7BitEncoding) {
-    if (!options) {
-      options = this._calculateUserDataLength(text, strict7BitEncoding);
-    }
-
-    if (options.dcs == RIL.PDU_DCS_MSG_CODING_7BITS_ALPHABET) {
-      const langTable = RIL.PDU_NL_LOCKING_SHIFT_TABLES[options.langIndex];
-      const langShiftTable = RIL.PDU_NL_SINGLE_SHIFT_TABLES[options.langShiftIndex];
-      options.segments = this._fragmentText7Bit(text,
-                                                langTable, langShiftTable,
-                                                options.segmentChars,
-                                                strict7BitEncoding);
-    } else {
-      options.segments = this._fragmentTextUCS2(text,
-                                                options.segmentChars);
-    }
-
-    // Re-sync options.segmentMaxSeq with actual length of returning array.
-    options.segmentMaxSeq = options.segments.length;
-
-    return options;
-  },
-
-  /**
-   * A helper to broadcast the system message to launch registered apps
-   * like Costcontrol, Notification and Message app... etc.
-   *
-   * @param aName
-   *        The system message name.
-   * @param aDomMessage
-   *        The nsIDOMMozSmsMessage object.
-   */
-  _broadcastSystemMessage: function _broadcastSystemMessage(aName, aDomMessage) {
-    if (DEBUG) debug("Broadcasting the SMS system message: " + aName);
-
-    // Sadly we cannot directly broadcast the aDomMessage object
-    // because the system message mechamism will rewrap the object
-    // based on the content window, which needs to know the properties.
-    gSystemMessenger.broadcastMessage(aName, {
-      type:           aDomMessage.type,
-      id:             aDomMessage.id,
-      threadId:       aDomMessage.threadId,
-      delivery:       aDomMessage.delivery,
-      deliveryStatus: aDomMessage.deliveryStatus,
-      sender:         aDomMessage.sender,
-      receiver:       aDomMessage.receiver,
-      body:           aDomMessage.body,
-      messageClass:   aDomMessage.messageClass,
-      timestamp:      aDomMessage.timestamp,
-      read:           aDomMessage.read
-    });
-  },
-
-  /**
-   * Handle WDP port push PDU. Constructor WDP bearer information and deliver
-   * to WapPushManager.
-   *
-   * @param message
-   *        A SMS message.
-   */
-  _handleSmsWdpPortPush: function _handleSmsWdpPortPush(message) {
-    if (message.encoding != RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
-      if (DEBUG) {
-        debug("Got port addressed SMS but not encoded in 8-bit alphabet." +
-              " Drop!");
-      }
-      return;
-    }
-
-    let options = {
-      bearer: WAP.WDP_BEARER_GSM_SMS_GSM_MSISDN,
-      sourceAddress: message.sender,
-      sourcePort: message.header.originatorPort,
-      destinationAddress: this.rilContext.iccInfo.msisdn,
-      destinationPort: message.header.destinationPort,
-    };
-    WAP.WapPushManager.receiveWdpPDU(message.fullData, message.fullData.length,
-                                     0, options);
-  },
-
-  _isSilentNumber: function _isSilentNumber(number) {
-    return this.silentNumbers.indexOf(number) >= 0;
-  },
-
-  /**
-   * nsISmsService methods.
-   */
-
-  // TODO: Bug 859616 - WebSMS: return undefined if the API is unsupported on
-  // the platform, not null
-  hasSupport: function hasSupport() {
-    return true;
-  },
-
-  getSegmentInfoForText: function getSegmentInfoForText(text, request) {
-    let strict7BitEncoding = this._getStrict7BitEncoding();
-
-    let options = this._fragmentText(text, null, strict7BitEncoding);
-    let charsInLastSegment;
-    if (options.segmentMaxSeq) {
-      let lastSegment = options.segments[options.segmentMaxSeq - 1];
-      charsInLastSegment = lastSegment.encodedBodyLength;
-      if (options.dcs == RIL.PDU_DCS_MSG_CODING_16BITS_ALPHABET) {
-        // In UCS2 encoding, encodedBodyLength is in octets.
-        charsInLastSegment /= 2;
-      }
-    } else {
-      charsInLastSegment = 0;
-    }
-
-    let result = gMobileMessageService
-                 .createSmsSegmentInfo(options.segmentMaxSeq,
-                                       options.segmentChars,
-                                       options.segmentChars - charsInLastSegment);
-    request.notifySegmentInfoForTextGot(result);
-  },
-
-  send: function send(number, text, silent, request) {
-    let strict7BitEncoding = this._getStrict7BitEncoding();
-    let requestStatusReport = this._getRequestStatusReport();
-
-    let options = this._fragmentText(text, null, strict7BitEncoding);
-    options.number = gPhoneNumberUtils.normalize(number);
-    options.requestStatusReport = requestStatusReport && !silent;
-    if (options.segmentMaxSeq > 1) {
-      options.segmentRef16Bit = this.segmentRef16Bit;
-      options.segmentRef = this.nextSegmentRef;
-    }
-
-    let notifyResult = (function notifyResult(rv, domMessage) {
-      // TODO bug 832140 handle !Components.isSuccessCode(rv)
-      if (!silent) {
-        Services.obs.notifyObservers(domMessage, kSmsSendingObserverTopic, null);
-      }
-
-      // If the radio is disabled or the SIM card is not ready, just directly
-      // return with the corresponding error code.
-      let errorCode;
-      if (!gPhoneNumberUtils.isPlainPhoneNumber(options.number)) {
-        if (DEBUG) debug("Error! Address is invalid when sending SMS: " +
-                              options.number);
-        errorCode = Ci.nsIMobileMessageCallback.INVALID_ADDRESS_ERROR;
-      } else if (gRadioInterface.rilContext.radioState !=
-                 RIL.GECKO_RADIOSTATE_READY) {
-        if (DEBUG) debug("Error! Radio is disabled when sending SMS.");
-        errorCode = Ci.nsIMobileMessageCallback.RADIO_DISABLED_ERROR;
-      } else if (gRadioInterface.rilContext.cardState !=
-                 RIL.GECKO_CARDSTATE_READY) {
-        if (DEBUG) debug("Error! SIM card is not ready when sending SMS.");
-        errorCode = Ci.nsIMobileMessageCallback.NO_SIM_CARD_ERROR;
-      }
-      if (errorCode) {
-        if (silent) {
-          request.notifySendMessageFailed(errorCode);
-          return;
-        }
-
-        gMobileMessageDatabaseService
-          .setMessageDeliveryByMessageId(domMessage.id,
-                                         null,
-                                         DELIVERY_STATE_ERROR,
-                                         RIL.GECKO_SMS_DELIVERY_STATUS_ERROR,
-                                         null,
-                                         function notifyResult(rv, domMessage) {
-          // TODO bug 832140 handle !Components.isSuccessCode(rv)
-          request.notifySendMessageFailed(errorCode);
-          Services.obs.notifyObservers(domMessage, kSmsFailedObserverTopic, null);
-        });
-        return;
-      }
-
-      // Keep current SMS message info for sent/delivered notifications
-      let context = {
-        request: request,
-        sms: domMessage,
-        requestStatusReport: options.requestStatusReport,
-        silent: silent
-      };
-
-      // This is the entry point starting to send SMS.
-      gRadioInterface.sendWorkerMessage("sendSMS", options,
-                                        (function(context, response) {
-        if (response.errorMsg) {
-          // Failed to send SMS out.
-          let error = Ci.nsIMobileMessageCallback.UNKNOWN_ERROR;
-          switch (response.errorMsg) {
-            case RIL.ERROR_RADIO_NOT_AVAILABLE:
-              error = Ci.nsIMobileMessageCallback.NO_SIGNAL_ERROR;
-              break;
-          }
-
-          if (context.silent) {
-            context.request.notifySendMessageFailed(error);
-            return false;
-          }
-
-          gMobileMessageDatabaseService
-            .setMessageDeliveryByMessageId(context.sms.id,
-                                           null,
-                                           DELIVERY_STATE_ERROR,
-                                           RIL.GECKO_SMS_DELIVERY_STATUS_ERROR,
-                                           null,
-                                           function notifyResult(rv, domMessage) {
-            // TODO bug 832140 handle !Components.isSuccessCode(rv)
-            context.request.notifySendMessageFailed(error);
-            Services.obs.notifyObservers(domMessage, kSmsFailedObserverTopic, null);
-          });
-          return false;
-        } // End of send failure.
-
-        if (response.deliveryStatus) {
-          // Message delivery.
-          gMobileMessageDatabaseService
-            .setMessageDeliveryByMessageId(context.sms.id,
-                                           null,
-                                           context.sms.delivery,
-                                           response.deliveryStatus,
-                                           null,
-                                           function notifyResult(rv, domMessage) {
-            // TODO bug 832140 handle !Components.isSuccessCode(rv)
-            let topic = (response.deliveryStatus == RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS)
-                        ? kSmsDeliverySuccessObserverTopic
-                        : kSmsDeliveryErrorObserverTopic;
-            Services.obs.notifyObservers(domMessage, topic, null);
-          });
-
-          // Send transaction has ended completely.
-          return false;
-        } // End of message delivery.
-
-        // Message sent.
-        if (context.silent) {
-          // There is no way to modify nsIDOMMozSmsMessage attributes as they are
-          // read only so we just create a new sms instance to send along with
-          // the notification.
-          let sms = context.sms;
-          context.request.notifyMessageSent(
-            gMobileMessageService.createSmsMessage(sms.id,
-                                                   sms.threadId,
-                                                   DELIVERY_STATE_SENT,
-                                                   sms.deliveryStatus,
-                                                   sms.sender,
-                                                   sms.receiver,
-                                                   sms.body,
-                                                   sms.messageClass,
-                                                   sms.timestamp,
-                                                   sms.read));
-          // We don't wait for SMS-DELIVER-REPORT for silent one.
-          return false;
-        }
-
-        gMobileMessageDatabaseService
-          .setMessageDeliveryByMessageId(context.sms.id,
-                                         null,
-                                         DELIVERY_STATE_SENT,
-                                         context.sms.deliveryStatus,
-                                         null,
-                                         (function notifyResult(rv, domMessage) {
-          // TODO bug 832140 handle !Components.isSuccessCode(rv)
-          this._broadcastSystemMessage("sms-sent", domMessage);
-
-          if (context.requestStatusReport) {
-            context.sms = domMessage;
-          }
-
-          context.request.notifyMessageSent(domMessage);
-          Services.obs.notifyObservers(domMessage, kSmsSentObserverTopic, null);
-        }).bind(this));
-
-        // Only keep current context if we have requested for delivery report.
-        return context.requestStatusReport;
-      }).bind(this, context)); // End of |sendWorkerMessage| callback.
-    }).bind(this); // End of DB saveSendingMessage callback.
-
-    let sendingMessage = {
-      type: "sms",
-      sender: this._getMsisdn(),
-      receiver: number,
-      body: text,
-      deliveryStatusRequested: options.requestStatusReport,
-      timestamp: Date.now()
-    };
-
-    if (silent) {
-      let deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_PENDING;
-      let delivery = DELIVERY_STATE_SENDING;
-      let domMessage =
-        gMobileMessageService.createSmsMessage(-1, // id
-                                               0,  // threadId
-                                               delivery,
-                                               deliveryStatus,
-                                               sendingMessage.sender,
-                                               sendingMessage.receiver,
-                                               sendingMessage.body,
-                                               "normal", // message class
-                                               sendingMessage.timestamp,
-                                               false);
-      notifyResult(Cr.NS_OK, domMessage);
-      return;
-    }
-
-    let id = gMobileMessageDatabaseService.saveSendingMessage(
-      sendingMessage, notifyResult);
-  },
-
-  addSilentNumber: function addSilentNumber(number) {
-    if (this._isSilentNumber(number)) {
-      throw Cr.NS_ERROR_UNEXPECTED;
-    }
-
-    this.silentNumbers.push(number);
-  },
-
-  removeSilentNumber: function removeSilentNumber(number) {
-    let index = this.silentNumbers.indexOf(number);
-    if (index < 0) {
-      throw Cr.NS_ERROR_INVALID_ARG;
-    }
-
-    this.silentNumbers.splice(index, 1);
-  },
-
-  /**
-   * nsIRilSmsService methods.
-   */
-
-  notifyMessageReceived: function notifyMessageReceived(message) {
-    if (DEBUG) debug("notifyMessageReceived: " + JSON.stringify(message));
-
-    // FIXME: Bug 737202 - Typed arrays become normal arrays when sent to/from workers
-    if (message.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
-      message.fullData = new Uint8Array(message.fullData);
-    }
-
-    // Dispatch to registered handler if application port addressing is
-    // available. Note that the destination port can possibly be zero when
-    // representing a UDP/TCP port.
-    if (message.header && message.header.destinationPort != null) {
-      let handler = this.portAddressedSmsApps[message.header.destinationPort];
-      if (handler) {
-        handler(message);
-      }
-      gRadioInterface.sendWorkerMessage("ackSMS", { result: RIL.PDU_FCS_OK });
-      return;
-    }
-
-    if (message.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
-      // Don't know how to handle binary data yet.
-      gRadioInterface.sendWorkerMessage("ackSMS", { result: RIL.PDU_FCS_OK });
-      return;
-    }
-
-    message.type = "sms";
-    message.sender = message.sender || null;
-    message.receiver = this._getMsisdn();
-    message.body = message.fullBody = message.fullBody || null;
-    message.timestamp = Date.now();
-
-    if (this._isSilentNumber(message.sender)) {
-      message.id = -1;
-      message.threadId = 0;
-      message.delivery = DELIVERY_STATE_RECEIVED;
-      message.deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS;
-      message.read = false;
-
-      let domMessage =
-        gMobileMessageService.createSmsMessage(message.id,
-                                               message.threadId,
-                                               message.delivery,
-                                               message.deliveryStatus,
-                                               message.sender,
-                                               message.receiver,
-                                               message.body,
-                                               message.messageClass,
-                                               message.timestamp,
-                                               message.read);
-
-      Services.obs.notifyObservers(domMessage,
-                                   kSilentSmsReceivedObserverTopic,
-                                   null);
-      gRadioInterface.sendWorkerMessage("ackSMS", { result: RIL.PDU_FCS_OK });
-      return;
-    }
-
-    // TODO: Bug #768441
-    // For now we don't store indicators persistently. When the mwi.discard
-    // flag is false, we'll need to persist the indicator to EFmwis.
-    // See TS 23.040 9.2.3.24.2
-
-    let mwi = message.mwi;
-    if (mwi) {
-      mwi.returnNumber = message.sender;
-      mwi.returnMessage = message.fullBody;
-      // TODO: Bug 833229 - B2G RIL: use ipdl as IPC in MozVoicemail
-      gMessageManager.sendVoicemailMessage("RIL:VoicemailNotification",
-                                           this.clientId, mwi);
-      gRadioInterface.sendWorkerMessage("ackSMS", { result: RIL.PDU_FCS_OK });
-      return;
-    }
-
-    let notifyReceived = function notifyReceived(rv, domMessage) {
-      let success = Components.isSuccessCode(rv);
-
-      // Acknowledge the reception of the SMS.
-      gRadioInterface.sendWorkerMessage("ackSMS", {
-        result: (success ? RIL.PDU_FCS_OK
-                         : RIL.PDU_FCS_MEMORY_CAPACITY_EXCEEDED)
-      });
-
-      if (!success) {
-        // At this point we could send a message to content to notify the user
-        // that storing an incoming SMS failed, most likely due to a full disk.
-        if (DEBUG) {
-          debug("Could not store SMS " + message.id + ", error code " + rv);
-        }
-        return;
-      }
-
-      this._broadcastSystemMessage("sms-received", domMessage);
-      Services.obs.notifyObservers(domMessage, kSmsReceivedObserverTopic, null);
-    }.bind(this);
-
-    if (message.messageClass == RIL.GECKO_SMS_MESSAGE_CLASSES[RIL.PDU_DCS_MSG_CLASS_0]) {
-      message.id = -1;
-      message.threadId = 0;
-      message.delivery = DELIVERY_STATE_RECEIVED;
-      message.deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS;
-      message.read = false;
-
-      let domMessage =
-        gMobileMessageService.createSmsMessage(message.id,
-                                               message.threadId,
-                                               message.delivery,
-                                               message.deliveryStatus,
-                                               message.sender,
-                                               message.receiver,
-                                               message.body,
-                                               message.messageClass,
-                                               message.timestamp,
-                                               message.read);
-
-      notifyReceived(Cr.NS_OK, domMessage);
-      return;
-    }
-
-    message.id =
-      gMobileMessageDatabaseService.saveReceivedMessage(message,
-                                                        notifyReceived);
-  },
-
-  /**
-   * nsIObserver methods.
-   */
-
-  observe: function observe(subject, topic, data) {
-    switch (topic) {
-      case kPrefenceChangedObserverTopic:
-        if (data === "ril.debugging.enabled") {
-          this._updateDebugFlag();
-        }
-        break;
-
-      case kXpcomShutdownObserverTopic:
-        Services.obs.removeObserver(this, kPrefenceChangedObserverTopic);
-        Services.obs.removeObserver(this, kXpcomShutdownObserverTopic);
-        break;
-    }
-  }
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([SmsService]);
deleted file mode 100644
--- a/dom/mobilemessage/src/gonk/SmsService.manifest
+++ /dev/null
@@ -1,3 +0,0 @@
-# SmsService.js
-component {46a9ed78-3574-40a1-9f12-ea179942d67f} SmsService.js
-contract @mozilla.org/sms/rilsmsservice;1 {46a9ed78-3574-40a1-9f12-ea179942d67f}
--- a/dom/mobilemessage/src/ipc/SmsIPCService.cpp
+++ b/dom/mobilemessage/src/ipc/SmsIPCService.cpp
@@ -111,16 +111,24 @@ SmsIPCService::Send(const nsAString& aNu
 {
   return SendRequest(SendMessageRequest(SendSmsMessageRequest(nsString(aNumber),
                                                               nsString(aMessage),
                                                               aSilent)),
                      aRequest);
 }
 
 NS_IMETHODIMP
+SmsIPCService::IsSilentNumber(const nsAString& aNumber,
+                              bool*            aIsSilent)
+{
+  NS_ERROR("We should not be here!");
+  return NS_ERROR_FAILURE;
+}
+
+NS_IMETHODIMP
 SmsIPCService::AddSilentNumber(const nsAString& aNumber)
 {
   PSmsChild* smsChild = GetSmsChild();
   NS_ENSURE_TRUE(smsChild, NS_ERROR_FAILURE);
 
   smsChild->SendAddSilentNumber(nsString(aNumber));
   return NS_OK;
 }
--- a/dom/mobilemessage/src/moz.build
+++ b/dom/mobilemessage/src/moz.build
@@ -31,17 +31,16 @@ if CONFIG['MOZ_B2G_RIL']:
 else:
     EXPORTS.mozilla.dom.mobilemessage += [
         "%s/%s" % (mmsdir, 'MmsService.h'),
         "%s/%s" % (mmsdir, 'MobileMessageDatabaseService.h'),
     ]
     CPP_SOURCES += [
         'MobileMessageDatabaseService.cpp',
         'MmsService.cpp',
-        'SmsService.cpp',
     ]
 
 EXPORTS.mozilla.dom += [
     'MmsMessage.h',
     'MobileMessageManager.h',
     'SmsFilter.h',
     'SmsMessage.h',
     'SmsSegmentInfo.h',
@@ -56,27 +55,26 @@ CPP_SOURCES += [
     'MobileMessageService.cpp',
     'MobileMessageThread.cpp',
     'SmsChild.cpp',
     'SmsFilter.cpp',
     'SmsIPCService.cpp',
     'SmsMessage.cpp',
     'SmsParent.cpp',
     'SmsSegmentInfo.cpp',
+    'SmsService.cpp',
     'SmsServicesFactory.cpp',
 ]
 
 if CONFIG['MOZ_B2G_RIL']:
     EXTRA_COMPONENTS += [
         'gonk/MmsService.js',
         'gonk/MmsService.manifest',
         'gonk/MobileMessageDatabaseService.js',
         'gonk/MobileMessageDatabaseService.manifest',
-        'gonk/SmsService.js',
-        'gonk/SmsService.manifest',
     ]
 
 IPDL_SOURCES += [
     'ipc/PMobileMessageCursor.ipdl',
     'ipc/PSms.ipdl',
     'ipc/PSmsRequest.ipdl',
     'ipc/SmsTypes.ipdlh',
 ]
--- a/dom/moz.build
+++ b/dom/moz.build
@@ -67,25 +67,25 @@ PARALLEL_DIRS += [
     'indexedDB',
     'system',
     'ipc',
     'identity',
     'workers',
     'camera',
     'audiochannel',
     'promise',
-    'wappush',
-    'telephony',
+    'wappush'
 ]
 
 if CONFIG['OS_ARCH'] == 'WINNT':
     PARALLEL_DIRS += ['plugins/ipc/hangui']
 
 if CONFIG['MOZ_B2G_RIL']:
     PARALLEL_DIRS += [
+        'telephony',
         'wifi',
         'icc',
         'cellbroadcast',
         'voicemail',
     ]
 
 if CONFIG['MOZ_PAY']:
     PARALLEL_DIRS += ['payment']
--- a/dom/system/gonk/Makefile.in
+++ b/dom/system/gonk/Makefile.in
@@ -12,16 +12,17 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
 include $(topsrcdir)/dom/dom-config.mk
 
 LOCAL_INCLUDES = \
   -I$(topsrcdir)/dom/base \
   -I$(topsrcdir)/dom/src/geolocation \
+  -I$(topsrcdir)/dom/telephony \
   -I$(topsrcdir)/dom/wifi \
   -I$(topsrcdir)/dom/bluetooth \
   -I$(topsrcdir)/content/events/src \
   $(NULL)
 
 # TODO: Bug 908038, move this to moz.build
 WORKER_FILES := worker_buf.js \
   $(NULL)
--- a/dom/system/gonk/RILContentHelper.js
+++ b/dom/system/gonk/RILContentHelper.js
@@ -66,23 +66,27 @@ const CELLBROADCASTETWSINFO_CID =
 const DOMMMIERROR_CID =
   Components.ID("{6b204c42-7928-4e71-89ad-f90cd82aff96}");
 
 const RIL_IPC_MSG_NAMES = [
   "RIL:CardStateChanged",
   "RIL:IccInfoChanged",
   "RIL:VoiceInfoChanged",
   "RIL:DataInfoChanged",
+  "RIL:EnumerateCalls",
   "RIL:GetAvailableNetworks",
   "RIL:NetworkSelectionModeChanged",
   "RIL:SelectNetwork",
   "RIL:SelectNetworkAuto",
+  "RIL:CallStateChanged",
   "RIL:EmergencyCbModeChanged",
   "RIL:VoicemailNotification",
   "RIL:VoicemailInfoChanged",
+  "RIL:CallError",
+  "RIL:SuppSvcNotification",
   "RIL:CardLockResult",
   "RIL:CardLockRetryCount",
   "RIL:USSDReceived",
   "RIL:SendMMI",
   "RIL:CancelMMI",
   "RIL:StkCommand",
   "RIL:StkSessionEnd",
   "RIL:DataError",
@@ -99,26 +103,32 @@ const RIL_IPC_MSG_NAMES = [
   "RIL:CfStateChanged",
   "RIL:IccOpenChannel",
   "RIL:IccCloseChannel",
   "RIL:IccExchangeAPDU",
   "RIL:ReadIccContacts",
   "RIL:UpdateIccContact",
   "RIL:SetRoamingPreference",
   "RIL:GetRoamingPreference",
+  "RIL:CdmaCallWaiting",
   "RIL:ExitEmergencyCbMode",
   "RIL:SetVoicePrivacyMode",
   "RIL:GetVoicePrivacyMode",
+  "RIL:ConferenceCallStateChanged",
   "RIL:OtaStatusChanged"
 ];
 
 XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
                                    "@mozilla.org/childprocessmessagemanager;1",
                                    "nsISyncMessageSender");
 
+XPCOMUtils.defineLazyServiceGetter(this, "gUUIDGenerator",
+                                   "@mozilla.org/uuid-generator;1",
+                                   "nsIUUIDGenerator");
+
 function MobileIccCardLockResult(options) {
   this.lockType = options.lockType;
   this.enabled = options.enabled;
   this.retryCount = options.retryCount;
   this.success = options.success;
 }
 MobileIccCardLockResult.prototype = {
   __exposedProps__ : {lockType: 'r',
@@ -434,25 +444,27 @@ function RILContentHelper() {
 }
 
 RILContentHelper.prototype = {
   __proto__: DOMRequestIpcHelper.prototype,
 
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIMobileConnectionProvider,
                                          Ci.nsICellBroadcastProvider,
                                          Ci.nsIVoicemailProvider,
+                                         Ci.nsITelephonyProvider,
                                          Ci.nsIIccProvider,
                                          Ci.nsIObserver,
                                          Ci.nsISupportsWeakReference]),
   classID:   RILCONTENTHELPER_CID,
   classInfo: XPCOMUtils.generateCI({classID: RILCONTENTHELPER_CID,
                                     classDescription: "RILContentHelper",
                                     interfaces: [Ci.nsIMobileConnectionProvider,
                                                  Ci.nsICellBroadcastProvider,
                                                  Ci.nsIVoicemailProvider,
+                                                 Ci.nsITelephonyProvider,
                                                  Ci.nsIIccProvider]}),
 
   // An utility function to copy objects.
   updateInfo: function updateInfo(srcInfo, destInfo) {
     for (let key in srcInfo) {
       destInfo[key] = srcInfo[key];
     }
   },
@@ -1264,19 +1276,21 @@ RILContentHelper.prototype = {
         requestId: requestId,
       }
     });
 
     return request;
   },
 
   _mobileConnectionListeners: null,
+  _telephonyListeners: null,
   _cellBroadcastListeners: null,
   _voicemailListeners: null,
   _iccListeners: null,
+  _enumerateTelephonyCallbacks: null,
 
   voicemailStatus: null,
 
   getVoicemailInfo: function getVoicemailInfo() {
     // Get voicemail infomation by IPC only on first time.
     this.getVoicemailInfo = function getVoicemailInfo() {
       return this.voicemailInfo;
     };
@@ -1328,16 +1342,34 @@ RILContentHelper.prototype = {
     this.registerListener("_mobileConnectionListeners", listener);
     cpmm.sendAsyncMessage("RIL:RegisterMobileConnectionMsg");
   },
 
   unregisterMobileConnectionMsg: function unregisteMobileConnectionMsg(listener) {
     this.unregisterListener("_mobileConnectionListeners", listener);
   },
 
+  registerTelephonyMsg: function registerTelephonyMsg(listener) {
+    debug("Registering for telephony-related messages");
+    this.registerListener("_telephonyListeners", listener);
+    cpmm.sendAsyncMessage("RIL:RegisterTelephonyMsg");
+  },
+
+  unregisterTelephonyMsg: function unregisteTelephonyMsg(listener) {
+    this.unregisterListener("_telephonyListeners", listener);
+
+    // We also need to make sure the listener is removed from
+    // _enumerateTelephonyCallbacks.
+    let index = this._enumerateTelephonyCallbacks.indexOf(listener);
+    if (index != -1) {
+      this._enumerateTelephonyCallbacks.splice(index, 1);
+      if (DEBUG) debug("Unregistered enumerateTelephony callback: " + listener);
+    }
+  },
+
   registerVoicemailMsg: function registerVoicemailMsg(listener) {
     debug("Registering for voicemail-related messages");
     this.registerListener("_voicemailListeners", listener);
     cpmm.sendAsyncMessage("RIL:RegisterVoicemailMsg");
   },
 
   unregisterVoicemailMsg: function unregisteVoicemailMsg(listener) {
     this.unregisterListener("_voicemailListeners", listener);
@@ -1358,16 +1390,145 @@ RILContentHelper.prototype = {
     this.registerListener("_iccListeners", listener);
     cpmm.sendAsyncMessage("RIL:RegisterIccMsg");
   },
 
   unregisterIccMsg: function unregisterIccMsg(listener) {
     this.unregisterListener("_iccListeners", listener);
   },
 
+  enumerateCalls: function enumerateCalls(callback) {
+    debug("Requesting enumeration of calls for callback: " + callback);
+    // We need 'requestId' to meet the 'RILContentHelper <--> RadioInterfaceLayer'
+    // protocol.
+    let requestId = this._getRandomId();
+    cpmm.sendAsyncMessage("RIL:EnumerateCalls", {
+      clientId: 0,
+      data: {
+        requestId: requestId
+      }
+    });
+    if (!this._enumerateTelephonyCallbacks) {
+      this._enumerateTelephonyCallbacks = [];
+    }
+    this._enumerateTelephonyCallbacks.push(callback);
+  },
+
+  startTone: function startTone(dtmfChar) {
+    debug("Sending Tone for " + dtmfChar);
+    cpmm.sendAsyncMessage("RIL:StartTone", {
+      clientId: 0,
+      data: dtmfChar
+    });
+  },
+
+  stopTone: function stopTone() {
+    debug("Stopping Tone");
+    cpmm.sendAsyncMessage("RIL:StopTone", {clientId: 0});
+  },
+
+  dial: function dial(number) {
+    debug("Dialing " + number);
+    cpmm.sendAsyncMessage("RIL:Dial", {
+      clientId: 0,
+      data: number
+    });
+  },
+
+  dialEmergency: function dialEmergency(number) {
+    debug("Dialing emergency " + number);
+    cpmm.sendAsyncMessage("RIL:DialEmergency", {
+      clientId: 0,
+      data: number
+    });
+  },
+
+  hangUp: function hangUp(callIndex) {
+    debug("Hanging up call no. " + callIndex);
+    cpmm.sendAsyncMessage("RIL:HangUp", {
+      clientId: 0,
+      data: callIndex
+    });
+  },
+
+  answerCall: function answerCall(callIndex) {
+    cpmm.sendAsyncMessage("RIL:AnswerCall", {
+      clientId: 0,
+      data: callIndex
+    });
+  },
+
+  rejectCall: function rejectCall(callIndex) {
+    cpmm.sendAsyncMessage("RIL:RejectCall", {
+      clientId: 0,
+      data: callIndex
+    });
+  },
+
+  holdCall: function holdCall(callIndex) {
+    cpmm.sendAsyncMessage("RIL:HoldCall", {
+      clientId: 0,
+      data: callIndex
+    });
+  },
+
+  resumeCall: function resumeCall(callIndex) {
+    cpmm.sendAsyncMessage("RIL:ResumeCall", {
+      clientId: 0,
+      data: callIndex
+    });
+  },
+
+  conferenceCall: function conferenceCall() {
+    cpmm.sendAsyncMessage("RIL:ConferenceCall", {
+      clientId: 0
+    });
+  },
+
+  separateCall: function separateCall(callIndex) {
+    cpmm.sendAsyncMessage("RIL:SeparateCall", {
+      clientId: 0,
+      data: callIndex
+    });
+  },
+
+  holdConference: function holdConference() {
+    cpmm.sendAsyncMessage("RIL:HoldConference", {
+      clientId: 0
+    });
+  },
+
+  resumeConference: function resumeConference() {
+    cpmm.sendAsyncMessage("RIL:ResumeConference", {
+      clientId: 0
+    });
+  },
+
+  get microphoneMuted() {
+    return cpmm.sendSyncMessage("RIL:GetMicrophoneMuted", {clientId: 0})[0];
+  },
+
+  set microphoneMuted(value) {
+    cpmm.sendAsyncMessage("RIL:SetMicrophoneMuted", {
+      clientId: 0,
+      data: value
+    });
+  },
+
+  get speakerEnabled() {
+    return cpmm.sendSyncMessage("RIL:GetSpeakerEnabled", {clientId: 0})[0];
+  },
+
+  set speakerEnabled(value) {
+    cpmm.sendAsyncMessage("RIL:SetSpeakerEnabled", {
+      clientId: 0,
+      data: value
+    });
+  },
+
   // nsIObserver
 
   observe: function observe(subject, topic, data) {
     if (topic == "xpcom-shutdown") {
       this.destroyDOMRequestHelper();
       Services.obs.removeObserver(this, "xpcom-shutdown");
     }
   },
@@ -1454,30 +1615,62 @@ RILContentHelper.prototype = {
                            "notifyDataChanged",
                            null);
         break;
       case "RIL:OtaStatusChanged":
         this._deliverEvent("_mobileConnectionListeners",
                            "notifyOtaStatusChanged",
                            [msg.json.data]);
         break;
+      case "RIL:EnumerateCalls":
+        this.handleEnumerateCalls(msg.json.calls);
+        break;
       case "RIL:GetAvailableNetworks":
         this.handleGetAvailableNetworks(msg.json);
         break;
       case "RIL:NetworkSelectionModeChanged":
         this.rilContext.networkSelectionMode = msg.json.data.mode;
         break;
       case "RIL:SelectNetwork":
         this.handleSelectNetwork(msg.json,
                                  RIL.GECKO_NETWORK_SELECTION_MANUAL);
         break;
       case "RIL:SelectNetworkAuto":
         this.handleSelectNetwork(msg.json,
                                  RIL.GECKO_NETWORK_SELECTION_AUTOMATIC);
         break;
+      case "RIL:CallStateChanged": {
+        let data = msg.json.data;
+        this._deliverEvent("_telephonyListeners",
+                           "callStateChanged",
+                           [data.callIndex, data.state,
+                            data.number, data.isActive,
+                            data.isOutgoing, data.isEmergency,
+                            data.isConference]);
+        break;
+      }
+      case "RIL:ConferenceCallStateChanged": {
+        let data = msg.json.data;
+        this._deliverEvent("_telephonyListeners",
+                           "conferenceCallStateChanged",
+                           [data]);
+        break;
+      }
+      case "RIL:CallError": {
+        let data = msg.json.data;
+        this._deliverEvent("_telephonyListeners",
+                           "notifyError",
+                           [data.callIndex, data.errorMsg]);
+        break;
+      }
+      case "RIL:SuppSvcNotification":
+        this._deliverEvent("_telephonyListeners",
+                           "supplementaryServiceNotification",
+                           [msg.json.callIndex, msg.json.notification]);
+        break;
       case "RIL:VoicemailNotification":
         this.handleVoicemailNotification(msg.json.data);
         break;
       case "RIL:VoicemailInfoChanged":
         this.updateInfo(msg.json.data, this.voicemailInfo);
         break;
       case "RIL:CardLockResult":
         if (msg.json.success) {
@@ -1588,16 +1781,21 @@ RILContentHelper.prototype = {
       }
       case "RIL:SetRoamingPreference":
         this.handleSimpleRequest(msg.json.requestId, msg.json.errorMsg, null);
         break;
       case "RIL:GetRoamingPreference":
         this.handleSimpleRequest(msg.json.requestId, msg.json.errorMsg,
                                  msg.json.mode);
         break;
+      case "RIL:CdmaCallWaiting":
+        this._deliverEvent("_telephonyListeners",
+                           "notifyCdmaCallWaiting",
+                           [msg.json.data]);
+        break;
       case "RIL:ExitEmergencyCbMode":
         this.handleExitEmergencyCbMode(msg.json);
         break;
       case "RIL:EmergencyCbModeChanged":
         let data = msg.json.data;
         this._deliverEvent("_mobileConnectionListeners",
                            "notifyEmergencyCbModeChanged",
                            [data.active, data.timeoutMs]);
@@ -1607,16 +1805,45 @@ RILContentHelper.prototype = {
         break;
       case "RIL:GetVoicePrivacyMode":
         this.handleSimpleRequest(msg.json.requestId, msg.json.errorMsg,
                                  msg.json.enabled);
         break;
     }
   },
 
+  handleEnumerateCalls: function handleEnumerateCalls(calls) {
+    debug("handleEnumerateCalls: " + JSON.stringify(calls));
+    let callback = this._enumerateTelephonyCallbacks.shift();
+    if (!calls.length) {
+      callback.enumerateCallStateComplete();
+      return;
+    }
+
+    for (let i in calls) {
+      let call = calls[i];
+      let keepGoing;
+      try {
+        keepGoing =
+          callback.enumerateCallState(call.callIndex, call.state, call.number,
+                                      call.isActive, call.isOutgoing,
+                                      call.isEmergency, call.isConference);
+      } catch (e) {
+        debug("callback handler for 'enumerateCallState' threw an " +
+              " exception: " + e);
+        keepGoing = true;
+      }
+      if (!keepGoing) {
+        break;
+      }
+    }
+
+    callback.enumerateCallStateComplete();
+  },
+
   handleSimpleRequest: function handleSimpleRequest(requestId, errorMsg, result) {
     if (errorMsg) {
       this.fireRequestError(requestId, errorMsg);
     } else {
       this.fireRequestSuccess(requestId, result);
     }
   },
 
@@ -1819,16 +2046,20 @@ RILContentHelper.prototype = {
       let mmiError = new this._window.DOMMMIError(result.serviceCode,
                                                   message.errorMsg,
                                                   null,
                                                   result.additionalInformation);
       Services.DOMRequest.fireDetailedError(request, mmiError);
     }
   },
 
+  _getRandomId: function _getRandomId() {
+    return gUUIDGenerator.generateUUID().toString();
+  },
+
   _deliverEvent: function _deliverEvent(listenerType, name, args) {
     let thisListeners = this[listenerType];
     if (!thisListeners) {
       return;
     }
 
     let listeners = thisListeners.slice();
     for (let listener of listeners) {
--- a/dom/system/gonk/RadioInterfaceLayer.js
+++ b/dom/system/gonk/RadioInterfaceLayer.js
@@ -41,37 +41,76 @@ function debug(s) {
 
 const RADIOINTERFACELAYER_CID =
   Components.ID("{2d831c8d-6017-435b-a80c-e5d422810cea}");
 const RADIOINTERFACE_CID =
   Components.ID("{6a7c91f0-a2b3-4193-8562-8969296c0b54}");
 const RILNETWORKINTERFACE_CID =
   Components.ID("{3bdd52a9-3965-4130-b569-0ac5afed045e}");
 
+const nsIAudioManager = Ci.nsIAudioManager;
+const nsITelephonyProvider = Ci.nsITelephonyProvider;
+
 const kNetworkInterfaceStateChangedTopic = "network-interface-state-changed";
+const kSmsReceivedObserverTopic          = "sms-received";
+const kSilentSmsReceivedObserverTopic    = "silent-sms-received";
+const kSmsSendingObserverTopic           = "sms-sending";
+const kSmsSentObserverTopic              = "sms-sent";
+const kSmsFailedObserverTopic            = "sms-failed";
+const kSmsDeliverySuccessObserverTopic   = "sms-delivery-success";
+const kSmsDeliveryErrorObserverTopic     = "sms-delivery-error";
 const kMozSettingsChangedObserverTopic   = "mozsettings-changed";
 const kSysMsgListenerReadyObserverTopic  = "system-message-listener-ready";
 const kSysClockChangeObserverTopic       = "system-clock-change";
 const kScreenStateChangedTopic           = "screen-state-changed";
 const kTimeNitzAutomaticUpdateEnabled    = "time.nitz.automatic-update.enabled";
 const kTimeNitzAvailable                 = "time.nitz.available";
 const kCellBroadcastSearchList           = "ril.cellbroadcast.searchlist";
 const kCellBroadcastDisabled             = "ril.cellbroadcast.disabled";
 const kPrefenceChangedObserverTopic      = "nsPref:changed";
 const kClirModePreference                = "ril.clirMode";
 
-const RADIO_POWER_OFF_TIMEOUT = 30000;
+const DOM_MOBILE_MESSAGE_DELIVERY_RECEIVED = "received";
+const DOM_MOBILE_MESSAGE_DELIVERY_SENDING  = "sending";
+const DOM_MOBILE_MESSAGE_DELIVERY_SENT     = "sent";
+const DOM_MOBILE_MESSAGE_DELIVERY_ERROR    = "error";
+
+const CALL_WAKELOCK_TIMEOUT              = 5000;
+const RADIO_POWER_OFF_TIMEOUT            = 30000;
+
+const RIL_IPC_TELEPHONY_MSG_NAMES = [
+  "RIL:EnumerateCalls",
+  "RIL:GetMicrophoneMuted",
+  "RIL:SetMicrophoneMuted",
+  "RIL:GetSpeakerEnabled",
+  "RIL:SetSpeakerEnabled",
+  "RIL:StartTone",
+  "RIL:StopTone",
+  "RIL:Dial",
+  "RIL:DialEmergency",
+  "RIL:HangUp",
+  "RIL:AnswerCall",
+  "RIL:RejectCall",
+  "RIL:HoldCall",
+  "RIL:ResumeCall",
+  "RIL:RegisterTelephonyMsg",
+  "RIL:ConferenceCall",
+  "RIL:SeparateCall",
+  "RIL:HoldConference",
+  "RIL:ResumeConference"
+];
 
 const RIL_IPC_MOBILECONNECTION_MSG_NAMES = [
   "RIL:GetRilContext",
   "RIL:GetAvailableNetworks",
   "RIL:SelectNetwork",
   "RIL:SelectNetworkAuto",
   "RIL:SendMMI",
   "RIL:CancelMMI",
+  "RIL:RegisterMobileConnectionMsg",
   "RIL:SetCallForwardingOption",
   "RIL:GetCallForwardingOption",
   "RIL:SetCallBarringOption",
   "RIL:GetCallBarringOption",
   "RIL:ChangeCallBarringPassword",
   "RIL:SetCallWaitingOption",
   "RIL:GetCallWaitingOption",
   "RIL:SetCallingLineIdRestriction",
@@ -91,26 +130,48 @@ const RIL_IPC_ICCMANAGER_MSG_NAMES = [
   "RIL:GetCardLockState",
   "RIL:UnlockCardLock",
   "RIL:SetCardLock",
   "RIL:GetCardLockRetryCount",
   "RIL:IccOpenChannel",
   "RIL:IccExchangeAPDU",
   "RIL:IccCloseChannel",
   "RIL:ReadIccContacts",
-  "RIL:UpdateIccContact"
+  "RIL:UpdateIccContact",
+  "RIL:RegisterIccMsg"
 ];
 
 const RIL_IPC_VOICEMAIL_MSG_NAMES = [
+  "RIL:RegisterVoicemailMsg",
   "RIL:GetVoicemailInfo"
 ];
 
+const RIL_IPC_CELLBROADCAST_MSG_NAMES = [
+  "RIL:RegisterCellBroadcastMsg"
+];
+
+XPCOMUtils.defineLazyServiceGetter(this, "gPowerManagerService",
+                                   "@mozilla.org/power/powermanagerservice;1",
+                                   "nsIPowerManagerService");
+
+XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageService",
+                                   "@mozilla.org/mobilemessage/mobilemessageservice;1",
+                                   "nsIMobileMessageService");
+
 XPCOMUtils.defineLazyServiceGetter(this, "gSmsService",
-                                   "@mozilla.org/sms/rilsmsservice;1",
-                                   "nsIRilSmsService");
+                                   "@mozilla.org/sms/smsservice;1",
+                                   "nsISmsService");
+
+XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageDatabaseService",
+                                   "@mozilla.org/mobilemessage/rilmobilemessagedatabaseservice;1",
+                                   "nsIRilMobileMessageDatabaseService");
+
+XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
+                                   "@mozilla.org/parentprocessmessagemanager;1",
+                                   "nsIMessageBroadcaster");
 
 XPCOMUtils.defineLazyServiceGetter(this, "gSettingsService",
                                    "@mozilla.org/settingsService;1",
                                    "nsISettingsService");
 
 XPCOMUtils.defineLazyServiceGetter(this, "gSystemMessenger",
                                    "@mozilla.org/system-message-internal;1",
                                    "nsISystemMessagesInternal");
@@ -122,37 +183,386 @@ XPCOMUtils.defineLazyServiceGetter(this,
 XPCOMUtils.defineLazyServiceGetter(this, "gTimeService",
                                    "@mozilla.org/time/timeservice;1",
                                    "nsITimeService");
 
 XPCOMUtils.defineLazyServiceGetter(this, "gSystemWorkerManager",
                                    "@mozilla.org/telephony/system-worker-manager;1",
                                    "nsISystemWorkerManager");
 
-XPCOMUtils.defineLazyServiceGetter(this, "gTelephonyProvider",
-                                   "@mozilla.org/telephony/telephonyprovider;1",
-                                   "nsIGonkTelephonyProvider");
+XPCOMUtils.defineLazyGetter(this, "WAP", function () {
+  let wap = {};
+  Cu.import("resource://gre/modules/WapPushManager.js", wap);
+  return wap;
+});
+
+XPCOMUtils.defineLazyGetter(this, "PhoneNumberUtils", function () {
+  let ns = {};
+  Cu.import("resource://gre/modules/PhoneNumberUtils.jsm", ns);
+  return ns.PhoneNumberUtils;
+});
+
+function convertRILCallState(state) {
+  switch (state) {
+    case RIL.CALL_STATE_ACTIVE:
+      return nsITelephonyProvider.CALL_STATE_CONNECTED;
+    case RIL.CALL_STATE_HOLDING:
+      return nsITelephonyProvider.CALL_STATE_HELD;
+    case RIL.CALL_STATE_DIALING:
+      return nsITelephonyProvider.CALL_STATE_DIALING;
+    case RIL.CALL_STATE_ALERTING:
+      return nsITelephonyProvider.CALL_STATE_ALERTING;
+    case RIL.CALL_STATE_INCOMING:
+    case RIL.CALL_STATE_WAITING:
+      return nsITelephonyProvider.CALL_STATE_INCOMING;
+    default:
+      throw new Error("Unknown rilCallState: " + state);
+  }
+}
+
+function convertRILSuppSvcNotification(notification) {
+  switch (notification) {
+    case RIL.GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD:
+      return nsITelephonyProvider.NOTIFICATION_REMOTE_HELD;
+    case RIL.GECKO_SUPP_SVC_NOTIFICATION_REMOTE_RESUMED:
+      return nsITelephonyProvider.NOTIFICATION_REMOTE_RESUMED;
+    default:
+      throw new Error("Unknown rilSuppSvcNotification: " + notification);
+  }
+}
+
+/**
+ * Fake nsIAudioManager implementation so that we can run the telephony
+ * code in a non-Gonk build.
+ */
+let FakeAudioManager = {
+  microphoneMuted: false,
+  masterVolume: 1.0,
+  masterMuted: false,
+  phoneState: nsIAudioManager.PHONE_STATE_CURRENT,
+  _forceForUse: {},
+  setForceForUse: function setForceForUse(usage, force) {
+    this._forceForUse[usage] = force;
+  },
+  getForceForUse: function setForceForUse(usage) {
+    return this._forceForUse[usage] || nsIAudioManager.FORCE_NONE;
+  }
+};
+
+XPCOMUtils.defineLazyGetter(this, "gAudioManager", function getAudioManager() {
+  try {
+    return Cc["@mozilla.org/telephony/audiomanager;1"]
+             .getService(nsIAudioManager);
+  } catch (ex) {
+    //TODO on the phone this should not fall back as silently.
+    if (DEBUG) debug("Using fake audio manager.");
+    return FakeAudioManager;
+  }
+});
 
 XPCOMUtils.defineLazyGetter(this, "gMessageManager", function () {
-  let ns = {};
-  Cu.import("resource://gre/modules/RilMessageManager.jsm", ns);
-  return ns.RilMessageManager;
+  return {
+    QueryInterface: XPCOMUtils.generateQI([Ci.nsIMessageListener,
+                                           Ci.nsIObserver]),
+
+    ril: null,
+
+    // Manage message targets in terms of topic. Only the authorized and
+    // registered contents can receive related messages.
+    targetsByTopic: {},
+    topics: [],
+
+    targetMessageQueue: [],
+    ready: false,
+
+    init: function init(ril) {
+      this.ril = ril;
+
+      Services.obs.addObserver(this, "xpcom-shutdown", false);
+      Services.obs.addObserver(this, kSysMsgListenerReadyObserverTopic, false);
+      this._registerMessageListeners();
+    },
+
+    _shutdown: function _shutdown() {
+      this.ril = null;
+
+      Services.obs.removeObserver(this, "xpcom-shutdown");
+      this._unregisterMessageListeners();
+    },
+
+    _registerMessageListeners: function _registerMessageListeners() {
+      ppmm.addMessageListener("child-process-shutdown", this);
+      for (let msgname of RIL_IPC_TELEPHONY_MSG_NAMES) {
+        ppmm.addMessageListener(msgname, this);
+      }
+      for (let msgname of RIL_IPC_MOBILECONNECTION_MSG_NAMES) {
+        ppmm.addMessageListener(msgname, this);
+      }
+      for (let msgName of RIL_IPC_ICCMANAGER_MSG_NAMES) {
+        ppmm.addMessageListener(msgName, this);
+      }
+      for (let msgname of RIL_IPC_VOICEMAIL_MSG_NAMES) {
+        ppmm.addMessageListener(msgname, this);
+      }
+      for (let msgname of RIL_IPC_CELLBROADCAST_MSG_NAMES) {
+        ppmm.addMessageListener(msgname, this);
+      }
+    },
+
+    _unregisterMessageListeners: function _unregisterMessageListeners() {
+      ppmm.removeMessageListener("child-process-shutdown", this);
+      for (let msgname of RIL_IPC_TELEPHONY_MSG_NAMES) {
+        ppmm.removeMessageListener(msgname, this);
+      }
+      for (let msgname of RIL_IPC_MOBILECONNECTION_MSG_NAMES) {
+        ppmm.removeMessageListener(msgname, this);
+      }
+      for (let msgName of RIL_IPC_ICCMANAGER_MSG_NAMES) {
+        ppmm.removeMessageListener(msgName, this);
+      }
+      for (let msgname of RIL_IPC_VOICEMAIL_MSG_NAMES) {
+        ppmm.removeMessageListener(msgname, this);
+      }
+      for (let msgname of RIL_IPC_CELLBROADCAST_MSG_NAMES) {
+        ppmm.removeMessageListener(msgname, this);
+      }
+      ppmm = null;
+    },
+
+    _registerMessageTarget: function _registerMessageTarget(topic, target) {
+      let targets = this.targetsByTopic[topic];
+      if (!targets) {
+        targets = this.targetsByTopic[topic] = [];
+        let list = this.topics;
+        if (list.indexOf(topic) == -1) {
+          list.push(topic);
+        }
+      }
+
+      if (targets.indexOf(target) != -1) {
+        if (DEBUG) debug("Already registered this target!");
+        return;
+      }
+
+      targets.push(target);
+      if (DEBUG) debug("Registered " + topic + " target: " + target);
+    },
+
+    _unregisterMessageTarget: function _unregisterMessageTarget(topic, target) {
+      if (topic == null) {
+        // Unregister the target for every topic when no topic is specified.
+        for (let type of this.topics) {
+          this._unregisterMessageTarget(type, target);
+        }
+        return;
+      }
+
+      // Unregister the target for a specified topic.
+      let targets = this.targetsByTopic[topic];
+      if (!targets) {
+        return;
+      }
+
+      let index = targets.indexOf(target);
+      if (index != -1) {
+        targets.splice(index, 1);
+        if (DEBUG) debug("Unregistered " + topic + " target: " + target);
+      }
+    },
+
+    _enqueueTargetMessage: function _enqueueTargetMessage(topic, message, options) {
+      let msg = { topic : topic,
+                  message : message,
+                  options : options };
+      // Remove previous queued message of same message type, only one message
+      // per message type is allowed in queue.
+      let messageQueue = this.targetMessageQueue;
+      for(let i = 0; i < messageQueue.length; i++) {
+        if (messageQueue[i].message === message) {
+          messageQueue.splice(i, 1);
+          break;
+        }
+      }
+
+      messageQueue.push(msg);
+    },
+
+    _sendTargetMessage: function _sendTargetMessage(topic, message, options) {
+      if (!this.ready) {
+        this._enqueueTargetMessage(topic, message, options);
+        return;
+      }
+
+      let targets = this.targetsByTopic[topic];
+      if (!targets) {
+        return;
+      }
+
+      for (let target of targets) {
+        target.sendAsyncMessage(message, options);
+      }
+    },
+
+    _resendQueuedTargetMessage: function _resendQueuedTargetMessage() {
+      this.ready = true;
+
+      // Here uses this._sendTargetMessage() to resend message, which will
+      // enqueue message if listener is not ready.
+      // So only resend after listener is ready, or it will cause infinate loop and
+      // hang the system.
+
+      // Dequeue and resend messages.
+      for each (let msg in this.targetMessageQueue) {
+        this._sendTargetMessage(msg.topic, msg.message, msg.options);
+      }
+      this.targetMessageQueue = null;
+    },
+
+    /**
+     * nsIMessageListener interface methods.
+     */
+
+    receiveMessage: function receiveMessage(msg) {
+      if (DEBUG) debug("Received '" + msg.name + "' message from content process");
+      if (msg.name == "child-process-shutdown") {
+        // By the time we receive child-process-shutdown, the child process has
+        // already forgotten its permissions so we need to unregister the target
+        // for every permission.
+        this._unregisterMessageTarget(null, msg.target);
+        return;
+      }
+
+      if (RIL_IPC_TELEPHONY_MSG_NAMES.indexOf(msg.name) != -1) {
+        if (!msg.target.assertPermission("telephony")) {
+          if (DEBUG) {
+            debug("Telephony message " + msg.name +
+                  " from a content process with no 'telephony' privileges.");
+          }
+          return null;
+        }
+      } else if (RIL_IPC_MOBILECONNECTION_MSG_NAMES.indexOf(msg.name) != -1) {
+        if (!msg.target.assertPermission("mobileconnection")) {
+          if (DEBUG) {
+            debug("MobileConnection message " + msg.name +
+                  " from a content process with no 'mobileconnection' privileges.");
+          }
+          return null;
+        }
+      } else if (RIL_IPC_ICCMANAGER_MSG_NAMES.indexOf(msg.name) != -1) {
+        if (!msg.target.assertPermission("mobileconnection")) {
+          if (DEBUG) {
+            debug("IccManager message " + msg.name +
+                  " from a content process with no 'mobileconnection' privileges.");
+          }
+          return null;
+        }
+      } else if (RIL_IPC_VOICEMAIL_MSG_NAMES.indexOf(msg.name) != -1) {
+        if (!msg.target.assertPermission("voicemail")) {
+          if (DEBUG) {
+            debug("Voicemail message " + msg.name +
+                  " from a content process with no 'voicemail' privileges.");
+          }
+          return null;
+        }
+      } else if (RIL_IPC_CELLBROADCAST_MSG_NAMES.indexOf(msg.name) != -1) {
+        if (!msg.target.assertPermission("cellbroadcast")) {
+          if (DEBUG) {
+            debug("Cell Broadcast message " + msg.name +
+                  " from a content process with no 'cellbroadcast' privileges.");
+          }
+          return null;
+        }
+      } else {
+        if (DEBUG) debug("Ignoring unknown message type: " + msg.name);
+        return null;
+      }
+
+      switch (msg.name) {
+        case "RIL:RegisterTelephonyMsg":
+          this._registerMessageTarget("telephony", msg.target);
+          return;
+        case "RIL:RegisterMobileConnectionMsg":
+          this._registerMessageTarget("mobileconnection", msg.target);
+          return;
+        case "RIL:RegisterIccMsg":
+          this._registerMessageTarget("icc", msg.target);
+          return;
+        case "RIL:RegisterVoicemailMsg":
+          this._registerMessageTarget("voicemail", msg.target);
+          return;
+        case "RIL:RegisterCellBroadcastMsg":
+          this._registerMessageTarget("cellbroadcast", msg.target);
+          return;
+      }
+
+      let clientId = msg.json.clientId || 0;
+      let radioInterface = this.ril.getRadioInterface(clientId);
+      if (!radioInterface) {
+        if (DEBUG) debug("No such radio interface: " + clientId);
+        return null;
+      }
+
+      return radioInterface.receiveMessage(msg);
+    },
+
+    /**
+     * nsIObserver interface methods.
+     */
+
+    observe: function observe(subject, topic, data) {
+      switch (topic) {
+        case kSysMsgListenerReadyObserverTopic:
+          Services.obs.removeObserver(this, kSysMsgListenerReadyObserverTopic);
+          this._resendQueuedTargetMessage();
+          break;
+        case "xpcom-shutdown":
+          this._shutdown();
+          break;
+      }
+    },
+
+    sendTelephonyMessage: function sendTelephonyMessage(message, clientId, data) {
+      this._sendTargetMessage("telephony", message, {
+        clientId: clientId,
+        data: data
+      });
+    },
+
+    sendMobileConnectionMessage: function sendMobileConnectionMessage(message, clientId, data) {
+      this._sendTargetMessage("mobileconnection", message, {
+        clientId: clientId,
+        data: data
+      });
+    },
+
+    sendVoicemailMessage: function sendVoicemailMessage(message, clientId, data) {
+      this._sendTargetMessage("voicemail", message, {
+        clientId: clientId,
+        data: data
+      });
+    },
+
+    sendCellBroadcastMessage: function sendCellBroadcastMessage(message, clientId, data) {
+      this._sendTargetMessage("cellbroadcast", message, {
+        clientId: clientId,
+        data: data
+      });
+    },
+
+    sendIccMessage: function sendIccMessage(message, clientId, data) {
+      this._sendTargetMessage("icc", message, {
+        clientId: clientId,
+        data: data
+      });
+    }
+  };
 });
 
 function RadioInterfaceLayer() {
-  let callback = this._receiveMessage.bind(this);
-  gMessageManager.registerMessageListeners("icc",
-                                           RIL_IPC_ICCMANAGER_MSG_NAMES,
-                                           callback);
-  gMessageManager.registerMessageListeners("mobileconnection",
-                                           RIL_IPC_MOBILECONNECTION_MSG_NAMES,
-                                           callback);
-  gMessageManager.registerMessageListeners("voicemail",
-                                           RIL_IPC_VOICEMAIL_MSG_NAMES,
-                                           callback);
+  gMessageManager.init(this);
 
   let options = {
     debug: debugPref,
     cellBroadcastDisabled: false,
     clirMode: RIL.CLIR_DEFAULT
   };
 
   try {
@@ -177,27 +587,16 @@ RadioInterfaceLayer.prototype = {
   classID:   RADIOINTERFACELAYER_CID,
   classInfo: XPCOMUtils.generateCI({classID: RADIOINTERFACELAYER_CID,
                                     classDescription: "RadioInterfaceLayer",
                                     interfaces: [Ci.nsIRadioInterfaceLayer]}),
 
   QueryInterface: XPCOMUtils.generateQI([Ci.nsIRadioInterfaceLayer,
                                          Ci.nsIObserver]),
 
-  _receiveMessage: function _receiveMessage(topic, msg) {
-    let clientId = msg.json.clientId || 0;
-    let radioInterface = this.getRadioInterface(clientId);
-    if (!radioInterface) {
-      if (DEBUG) debug("No such radio interface: " + clientId);
-      return null;
-    }
-
-    return radioInterface.receiveMessage(msg);
-  },
-
   /**
    * nsIObserver interface methods.
    */
 
   observe: function observe(subject, topic, data) {
     // Nothing to do now. Just for profile-after-change.
   },
 
@@ -426,16 +825,19 @@ function RadioInterface(options) {
 
   Services.obs.addObserver(this, "xpcom-shutdown", false);
   Services.obs.addObserver(this, kMozSettingsChangedObserverTopic, false);
   Services.obs.addObserver(this, kSysMsgListenerReadyObserverTopic, false);
   Services.obs.addObserver(this, kSysClockChangeObserverTopic, false);
   Services.obs.addObserver(this, kScreenStateChangedTopic, false);
 
   Services.prefs.addObserver(kCellBroadcastDisabled, this, false);
+
+  this.portAddressedSmsApps = {};
+  this.portAddressedSmsApps[WAP.WDP_PORT_PUSH] = this.handleSmsWdpPortPush.bind(this);
 }
 RadioInterface.prototype = {
 
   classID:   RADIOINTERFACE_CID,
   classInfo: XPCOMUtils.generateCI({classID: RADIOINTERFACE_CID,
                                     classDescription: "RadioInterface",
                                     interfaces: [Ci.nsIRadioInterface]}),
 
@@ -487,16 +889,71 @@ RadioInterface.prototype = {
   /**
    * Process a message from the content process.
    */
   receiveMessage: function receiveMessage(msg) {
     switch (msg.name) {
       case "RIL:GetRilContext":
         // This message is sync.
         return this.rilContext;
+      case "RIL:EnumerateCalls":
+        this.enumerateCalls(msg.target, msg.json.data);
+        break;
+      case "RIL:GetMicrophoneMuted":
+        // This message is sync.
+        return this.microphoneMuted;
+      case "RIL:SetMicrophoneMuted":
+        this.microphoneMuted = msg.json.data;
+        break;
+      case "RIL:GetSpeakerEnabled":
+        // This message is sync.
+        return this.speakerEnabled;
+      case "RIL:SetSpeakerEnabled":
+        this.speakerEnabled = msg.json.data;
+        break;
+      case "RIL:StartTone":
+        this.workerMessenger.send("startTone", { dtmfChar: msg.json.data });
+        break;
+      case "RIL:StopTone":
+        this.workerMessenger.send("stopTone");
+        break;
+      case "RIL:Dial":
+        this.dial(msg.json.data);
+        break;
+      case "RIL:DialEmergency":
+        this.dialEmergency(msg.json.data);
+        break;
+      case "RIL:HangUp":
+        this.workerMessenger.send("hangUp", { callIndex: msg.json.data });
+        break;
+      case "RIL:AnswerCall":
+        this.workerMessenger.send("answerCall", { callIndex: msg.json.data });
+        break;
+      case "RIL:RejectCall":
+        this.workerMessenger.send("rejectCall", { callIndex: msg.json.data });
+        break;
+      case "RIL:HoldCall":
+        this.workerMessenger.send("holdCall", { callIndex: msg.json.data });
+        break;
+      case "RIL:ResumeCall":
+        this.workerMessenger.send("resumeCall", { callIndex: msg.json.data });
+        break;
+      case "RIL:ConferenceCall":
+        this.workerMessenger.send("conferenceCall");
+        break;
+      case "RIL:SeparateCall":
+        this.workerMessenger.send("separateCall",
+                                  { callIndex: msg.json.data });
+        break;
+      case "RIL:HoldConference":
+        this.workerMessenger.send("holdConference");
+        break;
+      case "RIL:ResumeConference":
+        this.workerMessenger.send("resumeConference");
+        break;
       case "RIL:GetAvailableNetworks":
         this.workerMessenger.sendWithIPCMessage(msg, "getAvailableNetworks");
         break;
       case "RIL:SelectNetwork":
         this.workerMessenger.sendWithIPCMessage(msg, "selectNetwork");
         break;
       case "RIL:SelectNetworkAuto":
         this.workerMessenger.sendWithIPCMessage(msg, "selectNetworkAuto");
@@ -596,36 +1053,38 @@ RadioInterface.prototype = {
         this.workerMessenger.sendWithIPCMessage(msg, "queryVoicePrivacyMode");
         break;
     }
   },
 
   handleUnsolicitedWorkerMessage: function handleUnsolicitedWorkerMessage(message) {
     switch (message.rilMessageType) {
       case "callRing":
-        gTelephonyProvider.notifyCallRing();
+        this.handleCallRing();
         break;
       case "callStateChange":
-        gTelephonyProvider.notifyCallStateChanged(message.call);
+        // This one will handle its own notifications.
+        this.handleCallStateChange(message.call);
         break;
       case "callDisconnected":
-        gTelephonyProvider.notifyCallDisconnected(message.call);
+        // This one will handle its own notifications.
+        this.handleCallDisconnected(message.call);
         break;
       case "conferenceCallStateChanged":
-        gTelephonyProvider.notifyConferenceCallStateChanged(message.state);
+        this.handleConferenceCallStateChanged(message.state);
         break;
       case "cdmaCallWaiting":
-        gTelephonyProvider.notifyCdmaCallWaiting(message.number);
+        gMessageManager.sendTelephonyMessage("RIL:CdmaCallWaiting",
+                                             this.clientId, message.number);
         break;
       case "callError":
-        gTelephonyProvider.notifyCallError(message.callIndex, message.errorMsg);
+        this.handleCallError(message);
         break;
       case "suppSvcNotification":
-        gTelephonyProvider.notifySupplementaryService(message.callIndex,
-                                                      message.notification);
+        this.handleSuppSvcNotification(message);
         break;
       case "emergencyCbModeChange":
         this.handleEmergencyCbModeChange(message);
         break;
       case "networkinfochanged":
         this.updateNetworkInfo(message);
         break;
       case "networkselectionmodechange":
@@ -653,18 +1112,21 @@ RadioInterface.prototype = {
         this.handleRadioStateChange(message);
         break;
       case "cardstatechange":
         this.rilContext.cardState = message.cardState;
         gMessageManager.sendIccMessage("RIL:CardStateChanged",
                                        this.clientId, message);
         break;
       case "sms-received":
-        gSmsService.notifyMessageReceived(message);
-        break;
+        let ackOk = this.handleSmsReceived(message);
+        if (ackOk) {
+          this.workerMessenger.send("ackSMS", { result: RIL.PDU_FCS_OK });
+        }
+        return;
       case "cellbroadcast-received":
         message.timestamp = Date.now();
         gMessageManager.sendCellBroadcastMessage("RIL:CellBroadcastReceived",
                                                  this.clientId, message);
         break;
       case "datacallstatechange":
         this.handleDataCallState(message);
         break;
@@ -701,16 +1163,28 @@ RadioInterface.prototype = {
         this.handleExitEmergencyCbMode(message);
         break;
       default:
         throw new Error("Don't know about this message type: " +
                         message.rilMessageType);
     }
   },
 
+  getMsisdn: function getMsisdn() {
+    let iccInfo = this.rilContext.iccInfo;
+    let number = iccInfo ? iccInfo.msisdn : null;
+
+    // Workaround an xpconnect issue with undefined string objects.
+    // See bug 808220
+    if (number === undefined || number === "undefined") {
+      return null;
+    }
+    return number;
+  },
+
   updateNetworkInfo: function updateNetworkInfo(message) {
     let voiceMessage = message[RIL.NETWORK_INFO_VOICE_REGISTRATION_STATE];
     let dataMessage = message[RIL.NETWORK_INFO_DATA_REGISTRATION_STATE];
     let operatorMessage = message[RIL.NETWORK_INFO_OPERATOR];
     let selectionMessage = message[RIL.NETWORK_INFO_NETWORK_SELECTION_MODE];
     let signalMessage = message[RIL.NETWORK_INFO_SIGNAL];
 
     // Batch the *InfoChanged messages together
@@ -1249,16 +1723,175 @@ RadioInterface.prototype = {
       return;
     }
 
     if (DEBUG) this.debug("Data call settings: connect data call.");
     this.setupDataCallByType("default");
   },
 
   /**
+   * Track the active call and update the audio system as its state changes.
+   */
+  _activeCall: null,
+  updateCallAudioState: function updateCallAudioState(options) {
+    if (options.conferenceState === nsITelephonyProvider.CALL_STATE_CONNECTED) {
+      gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_IN_CALL;
+      if (this.speakerEnabled) {
+        gAudioManager.setForceForUse(nsIAudioManager.USE_COMMUNICATION,
+                                     nsIAudioManager.FORCE_SPEAKER);
+      }
+      return;
+    }
+    if (options.conferenceState === nsITelephonyProvider.CALL_STATE_UNKNOWN ||
+        options.conferenceState === nsITelephonyProvider.CALL_STATE_HELD) {
+      if (!this._activeCall) {
+        gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_NORMAL;
+      }
+      return;
+    }
+
+    if (!options.call) {
+      return;
+    }
+
+    if (options.call.isConference) {
+      if (this._activeCall && this._activeCall.callIndex == options.call.callIndex) {
+        this._activeCall = null;
+      }
+      return;
+    }
+
+    let call = options.call;
+    switch (call.state) {
+      case nsITelephonyProvider.CALL_STATE_DIALING: // Fall through...
+      case nsITelephonyProvider.CALL_STATE_ALERTING:
+      case nsITelephonyProvider.CALL_STATE_CONNECTED:
+        call.isActive = true;
+        this._activeCall = call;
+        gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_IN_CALL;
+        if (this.speakerEnabled) {
+          gAudioManager.setForceForUse(nsIAudioManager.USE_COMMUNICATION,
+                                       nsIAudioManager.FORCE_SPEAKER);
+        }
+        if (DEBUG) {
+          this.debug("Active call, put audio system into PHONE_STATE_IN_CALL: "
+                     + gAudioManager.phoneState);
+        }
+        break;
+      case nsITelephonyProvider.CALL_STATE_INCOMING:
+        call.isActive = false;
+        if (!this._activeCall) {
+          // We can change the phone state into RINGTONE only when there's
+          // no active call.
+          gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_RINGTONE;
+          if (DEBUG) {
+            this.debug("Incoming call, put audio system into " +
+                       "PHONE_STATE_RINGTONE: " + gAudioManager.phoneState);
+          }
+        }
+        break;
+      case nsITelephonyProvider.CALL_STATE_HELD: // Fall through...
+      case nsITelephonyProvider.CALL_STATE_DISCONNECTED:
+        call.isActive = false;
+        if (this._activeCall &&
+            this._activeCall.callIndex == call.callIndex) {
+          // Previously active call is not active now.
+          this._activeCall = null;
+        }
+
+        if (!this._activeCall) {
+          // No active call. Disable the audio.
+          gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_NORMAL;
+          if (DEBUG) {
+            this.debug("No active call, put audio system into " +
+                       "PHONE_STATE_NORMAL: " + gAudioManager.phoneState);
+          }
+        }
+        break;
+    }
+  },
+
+  _callRingWakeLock: null,
+  _callRingWakeLockTimer: null,
+  _cancelCallRingWakeLockTimer: function _cancelCallRingWakeLockTimer() {
+    if (this._callRingWakeLockTimer) {
+      this._callRingWakeLockTimer.cancel();
+    }
+    if (this._callRingWakeLock) {
+      this._callRingWakeLock.unlock();
+      this._callRingWakeLock = null;
+    }
+  },
+
+  /**
+   * Handle an incoming call.
+   *
+   * Not much is known about this call at this point, but it's enough
+   * to start bringing up the Phone app already.
+   */
+  handleCallRing: function handleCallRing() {
+    if (!this._callRingWakeLock) {
+      this._callRingWakeLock = gPowerManagerService.newWakeLock("cpu");
+    }
+    if (!this._callRingWakeLockTimer) {
+      this._callRingWakeLockTimer =
+        Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+    }
+    this._callRingWakeLockTimer
+        .initWithCallback(this._cancelCallRingWakeLockTimer.bind(this),
+                          CALL_WAKELOCK_TIMEOUT, Ci.nsITimer.TYPE_ONE_SHOT);
+
+    gSystemMessenger.broadcastMessage("telephony-new-call", {});
+  },
+
+  /**
+   * Handle call state changes by updating our current state and the audio
+   * system.
+   */
+  handleCallStateChange: function handleCallStateChange(call) {
+    if (DEBUG) this.debug("handleCallStateChange: " + JSON.stringify(call));
+    call.state = convertRILCallState(call.state);
+
+    if (call.state == nsITelephonyProvider.CALL_STATE_DIALING) {
+      gSystemMessenger.broadcastMessage("telephony-new-call", {});
+    }
+    this.updateCallAudioState({call: call});
+    gMessageManager.sendTelephonyMessage("RIL:CallStateChanged",
+                                         this.clientId, call);
+  },
+
+  /**
+   * Handle call disconnects by updating our current state and the audio system.
+   */
+  handleCallDisconnected: function handleCallDisconnected(call) {
+    if (DEBUG) this.debug("handleCallDisconnected: " + JSON.stringify(call));
+    call.state = nsITelephonyProvider.CALL_STATE_DISCONNECTED;
+    let duration = ("started" in call && typeof call.started == "number") ?
+      new Date().getTime() - call.started : 0;
+    let data = {
+      number: call.number,
+      duration: duration,
+      direction: call.isOutgoing ? "outgoing" : "incoming"
+    };
+    gSystemMessenger.broadcastMessage("telephony-call-ended", data);
+    this.updateCallAudioState({call: call});
+    gMessageManager.sendTelephonyMessage("RIL:CallStateChanged",
+                                         this.clientId, call);
+  },
+
+  handleConferenceCallStateChanged: function handleConferenceCallStateChanged(state) {
+    debug("handleConferenceCallStateChanged: " + state);
+    state = state != null ? convertRILCallState(state) :
+                            nsITelephonyProvider.CALL_STATE_UNKNOWN;
+    this.updateCallAudioState({conferenceState: state});
+    gMessageManager.sendTelephonyMessage("RIL:ConferenceCallStateChanged",
+                                         this.clientId, state);
+  },
+
+  /**
    * Update network selection mode
    */
   updateNetworkSelectionMode: function updateNetworkSelectionMode(message) {
     if (DEBUG) this.debug("updateNetworkSelectionMode: " + JSON.stringify(message));
     this.rilContext.networkSelectionMode = message.mode;
     gMessageManager.sendMobileConnectionMessage("RIL:NetworkSelectionModeChanged",
                                                 this.clientId, message);
   },
@@ -1268,16 +1901,211 @@ RadioInterface.prototype = {
    */
   handleEmergencyCbModeChange: function handleEmergencyCbModeChange(message) {
     if (DEBUG) this.debug("handleEmergencyCbModeChange: " + JSON.stringify(message));
     gMessageManager.sendMobileConnectionMessage("RIL:EmergencyCbModeChanged",
                                                 this.clientId, message);
   },
 
   /**
+   * Handle call error.
+   */
+  handleCallError: function handleCallError(message) {
+    gMessageManager.sendTelephonyMessage("RIL:CallError",
+                                         this.clientId, message);
+  },
+
+  /**
+   * Handle supplementary service notification.
+   */
+  handleSuppSvcNotification: function handleSuppSvcNotification(message) {
+    message.notification = convertRILSuppSvcNotification(message.notification);
+    gMessageManager.sendTelephonyMessage("RIL:SuppSvcNotification",
+                                         this.clientId, message);
+  },
+
+  /**
+   * Handle WDP port push PDU. Constructor WDP bearer information and deliver
+   * to WapPushManager.
+   *
+   * @param message
+   *        A SMS message.
+   */
+  handleSmsWdpPortPush: function handleSmsWdpPortPush(message) {
+    if (message.encoding != RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
+      if (DEBUG) {
+        this.debug("Got port addressed SMS but not encoded in 8-bit alphabet." +
+                   " Drop!");
+      }
+      return;
+    }
+
+    let options = {
+      bearer: WAP.WDP_BEARER_GSM_SMS_GSM_MSISDN,
+      sourceAddress: message.sender,
+      sourcePort: message.header.originatorPort,
+      destinationAddress: this.rilContext.iccInfo.msisdn,
+      destinationPort: message.header.destinationPort,
+    };
+    WAP.WapPushManager.receiveWdpPDU(message.fullData, message.fullData.length,
+                                     0, options);
+  },
+
+  /**
+   * A helper to broadcast the system message to launch registered apps
+   * like Costcontrol, Notification and Message app... etc.
+   *
+   * @param aName
+   *        The system message name.
+   * @param aDomMessage
+   *        The nsIDOMMozSmsMessage object.
+   */
+  broadcastSmsSystemMessage: function broadcastSmsSystemMessage(aName, aDomMessage) {
+    if (DEBUG) this.debug("Broadcasting the SMS system message: " + aName);
+
+    // Sadly we cannot directly broadcast the aDomMessage object
+    // because the system message mechamism will rewrap the object
+    // based on the content window, which needs to know the properties.
+    gSystemMessenger.broadcastMessage(aName, {
+      type:           aDomMessage.type,
+      id:             aDomMessage.id,
+      threadId:       aDomMessage.threadId,
+      delivery:       aDomMessage.delivery,
+      deliveryStatus: aDomMessage.deliveryStatus,
+      sender:         aDomMessage.sender,
+      receiver:       aDomMessage.receiver,
+      body:           aDomMessage.body,
+      messageClass:   aDomMessage.messageClass,
+      timestamp:      aDomMessage.timestamp,
+      read:           aDomMessage.read
+    });
+  },
+
+  portAddressedSmsApps: null,
+  handleSmsReceived: function handleSmsReceived(message) {
+    if (DEBUG) this.debug("handleSmsReceived: " + JSON.stringify(message));
+
+    // FIXME: Bug 737202 - Typed arrays become normal arrays when sent to/from workers
+    if (message.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
+      message.fullData = new Uint8Array(message.fullData);
+    }
+
+    // Dispatch to registered handler if application port addressing is
+    // available. Note that the destination port can possibly be zero when
+    // representing a UDP/TCP port.
+    if (message.header && message.header.destinationPort != null) {
+      let handler = this.portAddressedSmsApps[message.header.destinationPort];
+      if (handler) {
+        handler(message);
+      }
+      return true;
+    }
+
+    if (message.encoding == RIL.PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
+      // Don't know how to handle binary data yet.
+      return true;
+    }
+
+    message.type = "sms";
+    message.sender = message.sender || null;
+    message.receiver = this.getMsisdn();
+    message.body = message.fullBody = message.fullBody || null;
+    message.timestamp = Date.now();
+
+    if (gSmsService.isSilentNumber(message.sender)) {
+      message.id = -1;
+      message.threadId = 0;
+      message.delivery = DOM_MOBILE_MESSAGE_DELIVERY_RECEIVED;
+      message.deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS;
+      message.read = false;
+
+      let domMessage =
+        gMobileMessageService.createSmsMessage(message.id,
+                                               message.threadId,
+                                               message.delivery,
+                                               message.deliveryStatus,
+                                               message.sender,
+                                               message.receiver,
+                                               message.body,
+                                               message.messageClass,
+                                               message.timestamp,
+                                               message.read);
+
+      Services.obs.notifyObservers(domMessage,
+                                   kSilentSmsReceivedObserverTopic,
+                                   null);
+      return true;
+    }
+
+    // TODO: Bug #768441
+    // For now we don't store indicators persistently. When the mwi.discard
+    // flag is false, we'll need to persist the indicator to EFmwis.
+    // See TS 23.040 9.2.3.24.2
+
+    let mwi = message.mwi;
+    if (mwi) {
+      mwi.returnNumber = message.sender;
+      mwi.returnMessage = message.fullBody;
+      gMessageManager.sendVoicemailMessage("RIL:VoicemailNotification",
+                                           this.clientId, mwi);
+      return true;
+    }
+
+    let notifyReceived = function notifyReceived(rv, domMessage) {
+      let success = Components.isSuccessCode(rv);
+
+      // Acknowledge the reception of the SMS.
+      this.workerMessenger.send("ackSMS", {
+        result: (success ? RIL.PDU_FCS_OK
+                         : RIL.PDU_FCS_MEMORY_CAPACITY_EXCEEDED)
+      });
+
+      if (!success) {
+        // At this point we could send a message to content to notify the user
+        // that storing an incoming SMS failed, most likely due to a full disk.
+        if (DEBUG) {
+          this.debug("Could not store SMS " + message.id + ", error code " + rv);
+        }
+        return;
+      }
+
+      this.broadcastSmsSystemMessage("sms-received", domMessage);
+      Services.obs.notifyObservers(domMessage, kSmsReceivedObserverTopic, null);
+    }.bind(this);
+
+    if (message.messageClass != RIL.GECKO_SMS_MESSAGE_CLASSES[RIL.PDU_DCS_MSG_CLASS_0]) {
+      message.id = gMobileMessageDatabaseService.saveReceivedMessage(message,
+                                                                     notifyReceived);
+    } else {
+      message.id = -1;
+      message.threadId = 0;
+      message.delivery = DOM_MOBILE_MESSAGE_DELIVERY_RECEIVED;
+      message.deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS;
+      message.read = false;
+
+      let domMessage =
+        gMobileMessageService.createSmsMessage(message.id,
+                                               message.threadId,
+                                               message.delivery,
+                                               message.deliveryStatus,
+                                               message.sender,
+                                               message.receiver,
+                                               message.body,
+                                               message.messageClass,
+                                               message.timestamp,
+                                               message.read);
+
+      notifyReceived(Cr.NS_OK, domMessage);
+    }
+
+    // SMS ACK will be sent in notifyReceived. Return false here.
+    return false;
+  },
+
+  /**
    * Handle data call state changes.
    */
   handleDataCallState: function handleDataCallState(datacall) {
     let data = this.rilContext.data;
     let apnSetting = this.apnSettings.byType.default;
     let dataCallConnected =
         (datacall.state == RIL.GECKO_NETWORK_STATE_CONNECTED);
     if (apnSetting && datacall.ifname) {
@@ -1476,16 +2304,18 @@ RadioInterface.prototype = {
           try {
             value = Services.prefs.getBoolPref(kCellBroadcastDisabled);
           } catch(e) {}
           this.workerMessenger.send("setCellBroadcastDisabled",
                                     { disabled: value });
         }
         break;
       case "xpcom-shutdown":
+        // Cancel the timer for the call-ring wake lock.
+        this._cancelCallRingWakeLockTimer();
         // Shutdown all RIL network interfaces
         for each (let apnSetting in this.apnSettings.byAPN) {
           if (apnSetting.iface) {
             apnSetting.iface.shutdown();
           }
         }
         Services.obs.removeObserver(this, "xpcom-shutdown");
         Services.obs.removeObserver(this, kMozSettingsChangedObserverTopic);
@@ -1625,16 +2455,66 @@ RadioInterface.prototype = {
     if (DEBUG) this.debug("Setting radio power to " + value);
     this.workerMessenger.send("setRadioPower", { on: value });
   },
 
   rilContext: null,
 
   // Handle phone functions of nsIRILContentHelper
 
+  enumerateCalls: function enumerateCalls(target, message) {
+    if (DEBUG) this.debug("Requesting enumeration of calls for callback");
+    this.workerMessenger.send("enumerateCalls", message, (function(response) {
+      for (let call of response.calls) {
+        call.state = convertRILCallState(call.state);
+        call.isActive = this._activeCall ?
+          call.callIndex == this._activeCall.callIndex : false;
+      }
+      target.sendAsyncMessage("RIL:EnumerateCalls", response);
+      return false;
+    }).bind(this));
+  },
+
+  _validateNumber: function _validateNumber(number) {
+    // note: isPlainPhoneNumber also accepts USSD and SS numbers
+    if (PhoneNumberUtils.isPlainPhoneNumber(number)) {
+      return true;
+    }
+
+    this.handleCallError({
+      callIndex: -1,
+      errorMsg: RIL.RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[RIL.CALL_FAIL_UNOBTAINABLE_NUMBER]
+    });
+    if (DEBUG) {
+      this.debug("Number '" + number + "' doesn't seem to be a viable number." +
+                 " Drop.");
+    }
+
+    return false;
+  },
+
+  dial: function dial(number) {
+    if (DEBUG) this.debug("Dialing " + number);
+    number = PhoneNumberUtils.normalize(number);
+    if (this._validateNumber(number)) {
+      this.workerMessenger.send("dial", { number: number,
+                                          isDialEmergency: false });
+    }
+  },
+
+  dialEmergency: function dialEmergency(number) {
+    if (DEBUG) this.debug("Dialing emergency " + number);
+    // we don't try to be too clever here, as the phone is probably in the
+    // locked state. Let's just check if it's a number without normalizing
+    if (this._validateNumber(number)) {
+      this.workerMessenger.send("dial", { number: number,
+                                          isDialEmergency: true });
+    }
+  },
+
   _sendCfStateChanged: function _sendCfStateChanged(message) {
     gMessageManager.sendMobileConnectionMessage("RIL:CfStateChanged",
                                                 this.clientId, message);
   },
 
   _updateCallingLineIdRestrictionPref:
     function _updateCallingLineIdRestrictionPref(mode) {
     try {
@@ -1679,16 +2559,664 @@ RadioInterface.prototype = {
       if (response.success) {
         this._updateCallingLineIdRestrictionPref(response.clirMode);
       }
       target.sendAsyncMessage("RIL:SetCallingLineIdRestriction", response);
       return false;
     }).bind(this));
   },
 
+  get microphoneMuted() {
+    return gAudioManager.microphoneMuted;
+  },
+  set microphoneMuted(value) {
+    if (value == this.microphoneMuted) {
+      return;
+    }
+    gAudioManager.microphoneMuted = value;
+
+    if (!this._activeCall) {
+      gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_NORMAL;
+    }
+  },
+
+  get speakerEnabled() {
+    return (gAudioManager.getForceForUse(nsIAudioManager.USE_COMMUNICATION) ==
+            nsIAudioManager.FORCE_SPEAKER);
+  },
+  set speakerEnabled(value) {
+    if (value == this.speakerEnabled) {
+      return;
+    }
+    let force = value ? nsIAudioManager.FORCE_SPEAKER :
+                        nsIAudioManager.FORCE_NONE;
+    gAudioManager.setForceForUse(nsIAudioManager.USE_COMMUNICATION, force);
+
+    if (!this._activeCall) {
+      gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_NORMAL;
+    }
+  },
+
+  /**
+   * List of tuples of national language identifier pairs.
+   *
+   * TODO: Support static/runtime settings, see bug 733331.
+   */
+  enabledGsmTableTuples: [
+    [RIL.PDU_NL_IDENTIFIER_DEFAULT, RIL.PDU_NL_IDENTIFIER_DEFAULT],
+  ],
+
+  /**
+   * Use 16-bit reference number for concatenated outgoint messages.
+   *
+   * TODO: Support static/runtime settings, see bug 733331.
+   */
+  segmentRef16Bit: false,
+
+  /**
+   * Get valid SMS concatenation reference number.
+   */
+  _segmentRef: 0,
+  get nextSegmentRef() {
+    let ref = this._segmentRef++;
+
+    this._segmentRef %= (this.segmentRef16Bit ? 65535 : 255);
+
+    // 0 is not a valid SMS concatenation reference number.
+    return ref + 1;
+  },
+
+  /**
+   * Calculate encoded length using specified locking/single shift table
+   *
+   * @param message
+   *        message string to be encoded.
+   * @param langTable
+   *        locking shift table string.
+   * @param langShiftTable
+   *        single shift table string.
+   * @param strict7BitEncoding
+   *        Optional. Enable Latin characters replacement with corresponding
+   *        ones in GSM SMS 7-bit default alphabet.
+   *
+   * @return encoded length in septets.
+   *
+   * @note that the algorithm used in this function must match exactly with
+   * GsmPDUHelper#writeStringAsSeptets.
+   */
+  _countGsm7BitSeptets: function _countGsm7BitSeptets(message, langTable, langShiftTable, strict7BitEncoding) {
+    let length = 0;
+    for (let msgIndex = 0; msgIndex < message.length; msgIndex++) {
+      let c = message.charAt(msgIndex);
+      if (strict7BitEncoding) {
+        c = RIL.GSM_SMS_STRICT_7BIT_CHARMAP[c] || c;
+      }
+
+      let septet = langTable.indexOf(c);
+
+      // According to 3GPP TS 23.038, section 6.1.1 General notes, "The
+      // characters marked '1)' are not used but are displayed as a space."
+      if (septet == RIL.PDU_NL_EXTENDED_ESCAPE) {
+        continue;
+      }
+
+      if (septet >= 0) {
+        length++;
+        continue;
+      }
+
+      septet = langShiftTable.indexOf(c);
+      if (septet < 0) {
+        if (!strict7BitEncoding) {
+          return -1;
+        }
+
+        // Bug 816082, when strict7BitEncoding is enabled, we should replace
+        // characters that can't be encoded with GSM 7-Bit alphabets with '*'.
+        c = '*';
+        if (langTable.indexOf(c) >= 0) {
+          length++;
+        } else if (langShiftTable.indexOf(c) >= 0) {
+          length += 2;
+        } else {
+          // We can't even encode a '*' character with current configuration.
+          return -1;
+        }
+
+        continue;
+      }
+
+      // According to 3GPP TS 23.038 B.2, "This code represents a control
+      // character and therefore must not be used for language specific
+      // characters."
+      if (septet == RIL.PDU_NL_RESERVED_CONTROL) {
+        continue;
+      }
+
+      // The character is not found in locking shfit table, but could be
+      // encoded as <escape><char> with single shift table. Note that it's
+      // still possible for septet to has the value of PDU_NL_EXTENDED_ESCAPE,
+      // but we can display it as a space in this case as said in previous
+      // comment.
+      length += 2;
+    }
+
+    return length;
+  },
+
+  /**
+   * Calculate user data length of specified message string encoded in GSM 7Bit
+   * alphabets.
+   *
+   * @param message
+   *        a message string to be encoded.
+   * @param strict7BitEncoding
+   *        Optional. Enable Latin characters replacement with corresponding
+   *        ones in GSM SMS 7-bit default alphabet.
+   *
+   * @return null or an options object with attributes `dcs`,
+   *         `userDataHeaderLength`, `encodedFullBodyLength`, `langIndex`,
+   *         `langShiftIndex`, `segmentMaxSeq` set.
+   *
+   * @see #_calculateUserDataLength().
+   */
+  _calculateUserDataLength7Bit: function _calculateUserDataLength7Bit(message, strict7BitEncoding) {
+    let options = null;
+    let minUserDataSeptets = Number.MAX_VALUE;
+    for (let i = 0; i < this.enabledGsmTableTuples.length; i++) {
+      let [langIndex, langShiftIndex] = this.enabledGsmTableTuples[i];
+
+      const langTable = RIL.PDU_NL_LOCKING_SHIFT_TABLES[langIndex];
+      const langShiftTable = RIL.PDU_NL_SINGLE_SHIFT_TABLES[langShiftIndex];
+
+      let bodySeptets = this._countGsm7BitSeptets(message,
+                                                  langTable,
+                                                  langShiftTable,
+                                                  strict7BitEncoding);
+      if (bodySeptets < 0) {
+        continue;
+      }
+
+      let headerLen = 0;
+      if (langIndex != RIL.PDU_NL_IDENTIFIER_DEFAULT) {
+        headerLen += 3; // IEI + len + langIndex
+      }
+      if (langShiftIndex != RIL.PDU_NL_IDENTIFIER_DEFAULT) {
+        headerLen += 3; // IEI + len + langShiftIndex
+      }
+
+      // Calculate full user data length, note the extra byte is for header len
+      let headerSeptets = Math.ceil((headerLen ? headerLen + 1 : 0) * 8 / 7);
+      let segmentSeptets = RIL.PDU_MAX_USER_DATA_7BIT;
+      if ((bodySeptets + headerSeptets) > segmentSeptets) {
+        headerLen += this.segmentRef16Bit ? 6 : 5;
+        headerSeptets = Math.ceil((headerLen + 1) * 8 / 7);
+        segmentSeptets -= headerSeptets;
+      }
+
+      let segments = Math.ceil(bodySeptets / segmentSeptets);
+      let userDataSeptets = bodySeptets + headerSeptets * segments;
+      if (userDataSeptets >= minUserDataSeptets) {
+        continue;
+      }
+
+      minUserDataSeptets = userDataSeptets;
+
+      options = {
+        dcs: RIL.PDU_DCS_MSG_CODING_7BITS_ALPHABET,
+        encodedFullBodyLength: bodySeptets,
+        userDataHeaderLength: headerLen,
+        langIndex: langIndex,
+        langShiftIndex: langShiftIndex,
+        segmentMaxSeq: segments,
+        segmentChars: segmentSeptets,
+      };
+    }
+
+    return options;
+  },
+
+  /**
+   * Calculate user data length of specified message string encoded in UCS2.
+   *
+   * @param message
+   *        a message string to be encoded.
+   *
+   * @return an options object with attributes `dcs`, `userDataHeaderLength`,
+   *         `encodedFullBodyLength`, `segmentMaxSeq` set.
+   *
+   * @see #_calculateUserDataLength().
+   */
+  _calculateUserDataLengthUCS2: function _calculateUserDataLengthUCS2(message) {
+    let bodyChars = message.length;
+    let headerLen = 0;
+    let headerChars = Math.ceil((headerLen ? headerLen + 1 : 0) / 2);
+    let segmentChars = RIL.PDU_MAX_USER_DATA_UCS2;
+    if ((bodyChars + headerChars) > segmentChars) {
+      headerLen += this.segmentRef16Bit ? 6 : 5;
+      headerChars = Math.ceil((headerLen + 1) / 2);
+      segmentChars -= headerChars;
+    }
+
+    let segments = Math.ceil(bodyChars / segmentChars);
+
+    return {
+      dcs: RIL.PDU_DCS_MSG_CODING_16BITS_ALPHABET,
+      encodedFullBodyLength: bodyChars * 2,
+      userDataHeaderLength: headerLen,
+      segmentMaxSeq: segments,
+      segmentChars: segmentChars,
+    };
+  },
+
+  /**
+   * Calculate user data length and its encoding.
+   *
+   * @param message
+   *        a message string to be encoded.
+   * @param strict7BitEncoding
+   *        Optional. Enable Latin characters replacement with corresponding
+   *        ones in GSM SMS 7-bit default alphabet.
+   *
+   * @return an options object with some or all of following attributes set:
+   *
+   * @param dcs
+   *        Data coding scheme. One of the PDU_DCS_MSG_CODING_*BITS_ALPHABET
+   *        constants.
+   * @param userDataHeaderLength
+   *        Length of embedded user data header, in bytes. The whole header
+   *        size will be userDataHeaderLength + 1; 0 for no header.
+   * @param encodedFullBodyLength
+   *        Length of the message body when encoded with the given DCS. For
+   *        UCS2, in bytes; for 7-bit, in septets.
+   * @param langIndex
+   *        Table index used for normal 7-bit encoded character lookup.
+   * @param langShiftIndex
+   *        Table index used for escaped 7-bit encoded character lookup.
+   * @param segmentMaxSeq
+   *        Max sequence number of a multi-part messages, or 1 for single one.
+   *        This number might not be accurate for a multi-part message until
+   *        it's processed by #_fragmentText() again.
+   */
+  _calculateUserDataLength: function _calculateUserDataLength(message, strict7BitEncoding) {
+    let options = this._calculateUserDataLength7Bit(message, strict7BitEncoding);
+    if (!options) {
+      options = this._calculateUserDataLengthUCS2(message);
+    }
+
+    if (DEBUG) this.debug("_calculateUserDataLength: " + JSON.stringify(options));
+    return options;
+  },
+
+  /**
+   * Fragment GSM 7-Bit encodable string for transmission.
+   *
+   * @param text
+   *        text string to be fragmented.
+   * @param langTable
+   *        locking shift table string.
+   * @param langShiftTable
+   *        single shift table string.
+   * @param segmentSeptets
+   *        Number of available spetets per segment.
+   * @param strict7BitEncoding
+   *        Optional. Enable Latin characters replacement with corresponding
+   *        ones in GSM SMS 7-bit default alphabet.
+   *
+   * @return an array of objects. See #_fragmentText() for detailed definition.
+   */
+  _fragmentText7Bit: function _fragmentText7Bit(text, langTable, langShiftTable, segmentSeptets, strict7BitEncoding) {
+    let ret = [];
+    let body = "", len = 0;
+    for (let i = 0, inc = 0; i < text.length; i++) {
+      let c = text.charAt(i);
+      if (strict7BitEncoding) {
+        c = RIL.GSM_SMS_STRICT_7BIT_CHARMAP[c] || c;
+      }
+
+      let septet = langTable.indexOf(c);
+      if (septet == RIL.PDU_NL_EXTENDED_ESCAPE) {
+        continue;
+      }
+
+      if (septet >= 0) {
+        inc = 1;
+      } else {
+        septet = langShiftTable.indexOf(c);
+        if (septet == RIL.PDU_NL_RESERVED_CONTROL) {
+          continue;
+        }
+
+        inc = 2;
+        if (septet < 0) {
+          if (!strict7BitEncoding) {
+            throw new Error("Given text cannot be encoded with GSM 7-bit Alphabet!");
+          }
+
+          // Bug 816082, when strict7BitEncoding is enabled, we should replace
+          // characters that can't be encoded with GSM 7-Bit alphabets with '*'.
+          c = '*';
+          if (langTable.indexOf(c) >= 0) {
+            inc = 1;
+          }
+        }
+      }
+
+      if ((len + inc) > segmentSeptets) {
+        ret.push({
+          body: body,
+          encodedBodyLength: len,
+        });
+        body = c;
+        len = inc;
+      } else {
+        body += c;
+        len += inc;
+      }
+    }
+
+    if (len) {
+      ret.push({
+        body: body,
+        encodedBodyLength: len,
+      });
+    }
+
+    return ret;
+  },
+
+  /**
+   * Fragment UCS2 encodable string for transmission.
+   *
+   * @param text
+   *        text string to be fragmented.
+   * @param segmentChars
+   *        Number of available characters per segment.
+   *
+   * @return an array of objects. See #_fragmentText() for detailed definition.
+   */
+  _fragmentTextUCS2: function _fragmentTextUCS2(text, segmentChars) {
+    let ret = [];
+    for (let offset = 0; offset < text.length; offset += segmentChars) {
+      let str = text.substr(offset, segmentChars);
+      ret.push({
+        body: str,
+        encodedBodyLength: str.length * 2,
+      });
+    }
+
+    return ret;
+  },
+
+  /**
+   * Fragment string for transmission.
+   *
+   * Fragment input text string into an array of objects that contains
+   * attributes `body`, substring for this segment, `encodedBodyLength`,
+   * length of the encoded segment body in septets.
+   *
+   * @param text
+   *        Text string to be fragmented.
+   * @param options
+   *        Optional pre-calculated option object. The output array will be
+   *        stored at options.segments if there are multiple segments.
+   * @param strict7BitEncoding
+   *        Optional. Enable Latin characters replacement with corresponding
+   *        ones in GSM SMS 7-bit default alphabet.
+   *
+   * @return Populated options object.
+   */
+  _fragmentText: function _fragmentText(text, options, strict7BitEncoding) {
+    if (!options) {
+      options = this._calculateUserDataLength(text, strict7BitEncoding);
+    }
+
+    if (options.dcs == RIL.PDU_DCS_MSG_CODING_7BITS_ALPHABET) {
+      const langTable = RIL.PDU_NL_LOCKING_SHIFT_TABLES[options.langIndex];
+      const langShiftTable = RIL.PDU_NL_SINGLE_SHIFT_TABLES[options.langShiftIndex];
+      options.segments = this._fragmentText7Bit(text,
+                                                langTable, langShiftTable,
+                                                options.segmentChars,
+                                                strict7BitEncoding);
+    } else {
+      options.segments = this._fragmentTextUCS2(text,
+                                                options.segmentChars);
+    }
+
+    // Re-sync options.segmentMaxSeq with actual length of returning array.
+    options.segmentMaxSeq = options.segments.length;
+
+    return options;
+  },
+
+  getSegmentInfoForText: function getSegmentInfoForText(text, request) {
+    let strict7BitEncoding;
+    try {
+      strict7BitEncoding = Services.prefs.getBoolPref("dom.sms.strict7BitEncoding");
+    } catch (e) {
+      strict7BitEncoding = false;
+    }
+
+    let options = this._fragmentText(text, null, strict7BitEncoding);
+    let charsInLastSegment;
+    if (options.segmentMaxSeq) {
+      let lastSegment = options.segments[options.segmentMaxSeq - 1];
+      charsInLastSegment = lastSegment.encodedBodyLength;
+      if (options.dcs == RIL.PDU_DCS_MSG_CODING_16BITS_ALPHABET) {
+        // In UCS2 encoding, encodedBodyLength is in octets.
+        charsInLastSegment /= 2;
+      }
+    } else {
+      charsInLastSegment = 0;
+    }
+
+    let result = gMobileMessageService
+                 .createSmsSegmentInfo(options.segmentMaxSeq,
+                                       options.segmentChars,
+                                       options.segmentChars - charsInLastSegment);
+    request.notifySegmentInfoForTextGot(result);
+  },
+
+  sendSMS: function sendSMS(number, message, silent, request) {
+    let strict7BitEncoding;
+    try {
+      strict7BitEncoding = Services.prefs.getBoolPref("dom.sms.strict7BitEncoding");
+    } catch (e) {
+      strict7BitEncoding = false;
+    }
+
+    let options = this._fragmentText(message, null, strict7BitEncoding);
+    options.number = PhoneNumberUtils.normalize(number);
+    let requestStatusReport;
+    try {
+      requestStatusReport =
+        Services.prefs.getBoolPref("dom.sms.requestStatusReport");
+    } catch (e) {
+      requestStatusReport = true;
+    }
+    options.requestStatusReport = requestStatusReport && !silent;
+    if (options.segmentMaxSeq > 1) {
+      options.segmentRef16Bit = this.segmentRef16Bit;
+      options.segmentRef = this.nextSegmentRef;
+    }
+
+    let notifyResult = (function notifyResult(rv, domMessage) {
+      // TODO bug 832140 handle !Components.isSuccessCode(rv)
+      if (!silent) {
+        Services.obs.notifyObservers(domMessage, kSmsSendingObserverTopic, null);
+      }
+
+      // If the radio is disabled or the SIM card is not ready, just directly
+      // return with the corresponding error code.
+      let errorCode;
+      if (!PhoneNumberUtils.isPlainPhoneNumber(options.number)) {
+        if (DEBUG) this.debug("Error! Address is invalid when sending SMS: " +
+                              options.number);
+        errorCode = Ci.nsIMobileMessageCallback.INVALID_ADDRESS_ERROR;
+      } else if (!this._radioEnabled) {
+        if (DEBUG) this.debug("Error! Radio is disabled when sending SMS.");
+        errorCode = Ci.nsIMobileMessageCallback.RADIO_DISABLED_ERROR;
+      } else if (this.rilContext.cardState != "ready") {
+        if (DEBUG) this.debug("Error! SIM card is not ready when sending SMS.");
+        errorCode = Ci.nsIMobileMessageCallback.NO_SIM_CARD_ERROR;
+      }
+      if (errorCode) {
+        if (silent) {
+          request.notifySendMessageFailed(errorCode);
+          return;
+        }
+
+        gMobileMessageDatabaseService
+          .setMessageDeliveryByMessageId(domMessage.id,
+                                         null,
+                                         DOM_MOBILE_MESSAGE_DELIVERY_ERROR,
+                                         RIL.GECKO_SMS_DELIVERY_STATUS_ERROR,
+                                         null,
+                                         function notifyResult(rv, domMessage) {
+          // TODO bug 832140 handle !Components.isSuccessCode(rv)
+          request.notifySendMessageFailed(errorCode);
+          Services.obs.notifyObservers(domMessage, kSmsFailedObserverTopic, null);
+        });
+        return;
+      }
+
+      // Keep current SMS message info for sent/delivered notifications
+      let context = {
+        request: request,
+        sms: domMessage,
+        requestStatusReport: options.requestStatusReport,
+        silent: silent
+      };
+
+      // This is the entry point starting to send SMS.
+      this.workerMessenger.send("sendSMS", options,
+                                (function(context, response) {
+        if (response.errorMsg) {
+          // Failed to send SMS out.
+          let error = Ci.nsIMobileMessageCallback.UNKNOWN_ERROR;
+          switch (response.errorMsg) {
+            case RIL.ERROR_RADIO_NOT_AVAILABLE:
+              error = Ci.nsIMobileMessageCallback.NO_SIGNAL_ERROR;
+              break;
+          }
+
+          if (context.silent) {
+            context.request.notifySendMessageFailed(error);
+            return false;
+          }
+
+          gMobileMessageDatabaseService
+            .setMessageDeliveryByMessageId(context.sms.id,
+                                           null,
+                                           DOM_MOBILE_MESSAGE_DELIVERY_ERROR,
+                                           RIL.GECKO_SMS_DELIVERY_STATUS_ERROR,
+                                           null,
+                                           function notifyResult(rv, domMessage) {
+            // TODO bug 832140 handle !Components.isSuccessCode(rv)
+            context.request.notifySendMessageFailed(error);
+            Services.obs.notifyObservers(domMessage, kSmsFailedObserverTopic, null);
+          });
+          return false;
+        } // End of send failure.
+
+        if (response.deliveryStatus) {
+          // Message delivery.
+          gMobileMessageDatabaseService
+            .setMessageDeliveryByMessageId(context.sms.id,
+                                           null,
+                                           context.sms.delivery,
+                                           response.deliveryStatus,
+                                           null,
+                                           function notifyResult(rv, domMessage) {
+            // TODO bug 832140 handle !Components.isSuccessCode(rv)
+            let topic = (response.deliveryStatus == RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS)
+                        ? kSmsDeliverySuccessObserverTopic
+                        : kSmsDeliveryErrorObserverTopic;
+            Services.obs.notifyObservers(domMessage, topic, null);
+          });
+
+          // Send transaction has ended completely.
+          return false;
+        } // End of message delivery.
+
+        // Message sent.
+        if (context.silent) {
+          // There is no way to modify nsIDOMMozSmsMessage attributes as they are
+          // read only so we just create a new sms instance to send along with
+          // the notification.
+          let sms = context.sms;
+          context.request.notifyMessageSent(
+            gMobileMessageService.createSmsMessage(sms.id,
+                                                   sms.threadId,
+                                                   DOM_MOBILE_MESSAGE_DELIVERY_SENT,
+                                                   sms.deliveryStatus,
+                                                   sms.sender,
+                                                   sms.receiver,
+                                                   sms.body,
+                                                   sms.messageClass,
+                                                   sms.timestamp,
+                                                   sms.read));
+          // We don't wait for SMS-DELIVER-REPORT for silent one.
+          return false;
+        }
+
+        gMobileMessageDatabaseService
+          .setMessageDeliveryByMessageId(context.sms.id,
+                                         null,
+                                         DOM_MOBILE_MESSAGE_DELIVERY_SENT,
+                                         context.sms.deliveryStatus,
+                                         null,
+                                         (function notifyResult(rv, domMessage) {
+          // TODO bug 832140 handle !Components.isSuccessCode(rv)
+          this.broadcastSmsSystemMessage("sms-sent", domMessage);
+
+          if (context.requestStatusReport) {
+            context.sms = domMessage;
+          }
+
+          context.request.notifyMessageSent(domMessage);
+          Services.obs.notifyObservers(domMessage, kSmsSentObserverTopic, null);
+        }).bind(this));
+
+        // Only keep current context if we have requested for delivery report.
+        return context.requestStatusReport;
+      }).bind(this, context)); // End of |workerMessenger.send| callback.
+    }).bind(this); // End of DB saveSendingMessage callback.
+
+    let sendingMessage = {
+      type: "sms",
+      sender: this.getMsisdn(),
+      receiver: number,
+      body: message,
+      deliveryStatusRequested: options.requestStatusReport,
+      timestamp: Date.now()
+    };
+
+    if (silent) {
+      let deliveryStatus = RIL.GECKO_SMS_DELIVERY_STATUS_PENDING;
+      let delivery = DOM_MOBILE_MESSAGE_DELIVERY_SENDING;
+      let domMessage =
+        gMobileMessageService.createSmsMessage(-1, // id
+                                               0,  // threadId
+                                               delivery,
+                                               deliveryStatus,
+                                               sendingMessage.sender,
+                                               sendingMessage.receiver,
+                                               sendingMessage.body,
+                                               "normal", // message class
+                                               sendingMessage.timestamp,
+                                               false);
+      notifyResult(Cr.NS_OK, domMessage);
+      return;
+    }
+
+    let id = gMobileMessageDatabaseService.saveSendingMessage(
+      sendingMessage, notifyResult);
+  },
+
   registerDataCallCallback: function registerDataCallCallback(callback) {
     if (this._datacall_callbacks) {
       if (this._datacall_callbacks.indexOf(callback) != -1) {
         throw new Error("Already registered this callback!");
       }
     } else {
       this._datacall_callbacks = [];
     }
@@ -1829,23 +3357,16 @@ RadioInterface.prototype = {
                                                  chappap: chappap,
                                                  pdptype: pdptype });
   },
 
   deactivateDataCall: function deactivateDataCall(cid, reason) {
     this.workerMessenger.send("deactivateDataCall", { cid: cid,
                                                       reason: reason });
   },
-
-  sendWorkerMessage: function sendWorkerMessage(rilMessageType, message,
-                                                callback) {
-    this.workerMessenger.send(rilMessageType, message, function (response) {
-      return callback.handleResponse(response);
-    });
-  }
 };
 
 function RILNetworkInterface(radioInterface, apnSetting) {
   this.radioInterface = radioInterface;
   this.apnSetting = apnSetting;
 
   this.connectedTypes = [];
 }
deleted file mode 100644
--- a/dom/system/gonk/RilMessageManager.jsm
+++ /dev/null
@@ -1,330 +0,0 @@
-/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* 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, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
-                                   "@mozilla.org/parentprocessmessagemanager;1",
-                                   "nsIMessageBroadcaster");
-
-// Observer topics.
-const kPrefenceChangedObserverTopic     = "nsPref:changed";
-const kSysMsgListenerReadyObserverTopic = "system-message-listener-ready";
-const kXpcomShutdownObserverTopic       = "xpcom-shutdown";
-
-// Preference keys.
-const kPrefKeyRilDebuggingEnabled = "ril.debugging.enabled";
-
-// Frame message names.
-const kMsgNameChildProcessShutdown = "child-process-shutdown";
-
-let DEBUG;
-function debug(s) {
-  dump("RilMessageManager: " + s + "\n");
-}
-
-this.RilMessageManager = {
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsIMessageListener,
-                                         Ci.nsIObserver]),
-
-  topicRegistrationNames: {
-    cellbroadcast:    "RIL:RegisterCellBroadcastMsg",
-    icc:              "RIL:RegisterIccMsg",
-    mobileconnection: "RIL:RegisterMobileConnectionMsg",
-    voicemail:        "RIL:RegisterVoicemailMsg",
-  },
-
-  /**
-   * this.callbacksByName[< A string message name>] = {
-   *   topic:    <A string topic>,
-   *   callback: <A callback that accepts two parameters -- topic and msg>,
-   * }
-   */
-  callbacksByName: {},
-
-  // Manage message targets in terms of topic. Only the authorized and
-  // registered contents can receive related messages.
-  targetsByTopic: {},
-  topics: [],
-
-  targetMessageQueue: [],
-  ready: false,
-
-  _init: function _init() {
-    this._updateDebugFlag();
-
-    Services.obs.addObserver(this, kPrefenceChangedObserverTopic, false);
-    Services.obs.addObserver(this, kSysMsgListenerReadyObserverTopic, false);
-    Services.obs.addObserver(this, kXpcomShutdownObserverTopic, false);
-
-    ppmm.addMessageListener(kMsgNameChildProcessShutdown, this);
-
-    let callback = this._registerMessageTarget.bind(this);
-    for (let topic in this.topicRegistrationNames) {
-      let name = this.topicRegistrationNames[topic];
-      this.registerMessageListeners(topic, [name], callback);
-    }
-  },
-
-  _shutdown: function _shutdown() {
-    if (!this.ready) {
-      Services.obs.removeObserver(this, kSysMsgListenerReadyObserverTopic);
-    }
-    Services.obs.removeObserver(this, kPrefenceChangedObserverTopic);
-    Services.obs.removeObserver(this, kXpcomShutdownObserverTopic);
-
-    for (let name in this.callbacksByName) {
-      ppmm.removeMessageListener(name, this);
-    }
-    this.callbacksByName = null;
-
-    ppmm.removeMessageListener(kMsgNameChildProcessShutdown, this);
-    ppmm = null;
-
-    this.targetsByTopic = null;
-    this.targetMessageQueue = null;
-  },
-
-  _registerMessageTarget: function _registerMessageTarget(topic, msg) {
-    let targets = this.targetsByTopic[topic];
-    if (!targets) {
-      targets = this.targetsByTopic[topic] = [];
-      let list = this.topics;
-      if (list.indexOf(topic) == -1) {
-        list.push(topic);
-      }
-    }
-
-    let target = msg.target;
-    if (targets.indexOf(target) != -1) {
-      if (DEBUG) debug("Already registered this target!");
-      return;
-    }
-
-    targets.push(target);
-    if (DEBUG) debug("Registered " + topic + " target: " + target);
-  },
-
-  _unregisterMessageTarget: function _unregisterMessageTarget(topic, target) {
-    if (topic == null) {
-      // Unregister the target for every topic when no topic is specified.
-      for (let type of this.topics) {
-        this._unregisterMessageTarget(type, target);
-      }
-      return;
-    }
-
-    // Unregister the target for a specified topic.
-    let targets = this.targetsByTopic[topic];
-    if (!targets) {
-      return;
-    }
-
-    let index = targets.indexOf(target);
-    if (index != -1) {
-      targets.splice(index, 1);
-      if (DEBUG) debug("Unregistered " + topic + " target: " + target);
-    }
-  },
-
-  _enqueueTargetMessage: function _enqueueTargetMessage(topic, name, options) {
-    let msg = { topic : topic,
-                name : name,
-                options : options };
-    // Remove previous queued message of same message name, only one message
-    // per message name is allowed in queue.
-    let messageQueue = this.targetMessageQueue;
-    for (let i = 0; i < messageQueue.length; i++) {
-      if (messageQueue[i].name === name) {
-        messageQueue.splice(i, 1);
-        break;
-      }
-    }
-
-    messageQueue.push(msg);
-  },
-
-  _sendTargetMessage: function _sendTargetMessage(topic, name, options) {
-    if (!this.ready) {
-      this._enqueueTargetMessage(topic, name, options);
-      return;
-    }
-
-    let targets = this.targetsByTopic[topic];
-    if (!targets) {
-      return;
-    }
-
-    for (let target of targets) {
-      target.sendAsyncMessage(name, options);
-    }
-  },
-
-  _resendQueuedTargetMessage: function _resendQueuedTargetMessage() {
-    // Here uses this._sendTargetMessage() to resend message, which will
-    // enqueue message if listener is not ready.  So only resend after listener
-    // is ready, or it will cause infinate loop and hang the system.
-
-    // Dequeue and resend messages.
-    for (let msg of this.targetMessageQueue) {
-      this._sendTargetMessage(msg.topic, msg.name, msg.options);
-    }
-    this.targetMessageQueue = null;
-  },
-
-  _updateDebugFlag: function _updateDebugFlag() {
-    try {
-      DEBUG = RIL.DEBUG_RIL ||
-              Services.prefs.getBoolPref(kPrefKeyRilDebuggingEnabled);
-    } catch(e) {}
-  },
-
-  /**
-   * nsIMessageListener interface methods.
-   */
-
-  receiveMessage: function receiveMessage(msg) {
-    if (DEBUG) {
-      debug("Received '" + msg.name + "' message from content process");
-    }
-
-    if (msg.name == kMsgNameChildProcessShutdown) {
-      // By the time we receive child-process-shutdown, the child process has
-      // already forgotten its permissions so we need to unregister the target
-      // for every permission.
-      this._unregisterMessageTarget(null, msg.target);
-      return;
-    }
-
-    let entry = this.callbacksByName[msg.name];
-    if (!entry) {
-      if (DEBUG) debug("Ignoring unknown message type: " + msg.name);
-      return null;
-    }
-
-    if (entry.topic && !msg.target.assertPermission(entry.topic)) {
-      if (DEBUG) {
-        debug("Message " + msg.name + " from a content process with no '" +
-              entry.topic + "' privileges.");
-      }
-      return null;
-    }
-
-    return entry.callback(entry.topic, msg);
-  },
-
-  /**
-   * nsIObserver interface methods.
-   */
-
-  observe: function observe(subject, topic, data) {
-    switch (topic) {
-      case kSysMsgListenerReadyObserverTopic:
-        this.ready = true;
-        Services.obs.removeObserver(this, kSysMsgListenerReadyObserverTopic);
-
-        this._resendQueuedTargetMessage();
-        break;
-
-      case kPrefenceChangedObserverTopic:
-        if (data === kPrefKeyRilDebuggingEnabled) {
-          this._updateDebugFlag();
-        }
-        break;
-
-      case kXpcomShutdownObserverTopic:
-        this._shutdown();
-        break;
-    }
-  },
-
-  /**
-   * Public methods.
-   */
-
-  /**
-   * @param topic
-   *        A string for the topic of the registrating names. Also the
-   *        permission to listen messages of these names.
-   * @param names
-   *        An array of string message names to listen.
-   * @param callback
-   *        A callback that accepts two parameters -- topic and msg.
-   */
-  registerMessageListeners: function registerMessageListeners(topic, names,
-                                                              callback) {
-    for (let name of names) {
-      if (this.callbacksByName[name]) {
-        if (DEBUG) {
-          debug("Message name '" + name + "' was already registered. Ignored.");
-        }
-        continue;
-      }
-
-      this.callbacksByName[name] = { topic: topic, callback: callback };
-      ppmm.addMessageListener(name, this);
-    }
-  },
-
-  /**
-   * Remove all listening names with specified callback.
-   *
-   * @param callback
-   *        The callback previously registered for messages.
-   */
-  unregisterMessageListeners: function unregisterMessageListeners(callback) {
-    let remains = {};
-    for (let name in this.callbacksByName) {
-      let entry = this.callbacksByName[name];
-      if (entry.callback != callback) {
-        remains[name] = entry;
-      } else {
-        ppmm.removeMessageListener(name, this);
-      }
-    }
-    this.callbacksByName = remains;
-  },
-
-  sendMobileConnectionMessage: function sendMobileConnectionMessage(name,
-                                                                    clientId,
-                                                                    data) {
-    this._sendTargetMessage("mobileconnection", name, {
-      clientId: clientId,
-      data: data
-    });
-  },
-
-  sendVoicemailMessage: function sendVoicemailMessage(name, clientId, data) {
-    this._sendTargetMessage("voicemail", name, {
-      clientId: clientId,
-      data: data
-    });
-  },
-
-  sendCellBroadcastMessage: function sendCellBroadcastMessage(name, clientId,
-                                                              data) {
-    this._sendTargetMessage("cellbroadcast", name, {
-      clientId: clientId,
-      data: data
-    });
-  },
-
-  sendIccMessage: function sendIccMessage(name, clientId, data) {
-    this._sendTargetMessage("icc", name, {
-      clientId: clientId,
-      data: data
-    });
-  }
-};
-
-RilMessageManager._init();
-
-this.EXPORTED_SYMBOLS = ["RilMessageManager"];
--- a/dom/system/gonk/moz.build
+++ b/dom/system/gonk/moz.build
@@ -69,17 +69,16 @@ EXTRA_COMPONENTS += [
     'NetworkManager.js',
     'NetworkManager.manifest',
     'RILContentHelper.js',
     'RadioInterfaceLayer.js',
     'RadioInterfaceLayer.manifest',
 ]
 
 EXTRA_JS_MODULES += [
-    'RilMessageManager.jsm',
     'net_worker.js',
     'ril_consts.js',
     'ril_worker.js',
     'systemlibs.js',
 ]
 
 FAIL_ON_WARNINGS = True
 
--- a/dom/system/gonk/nsIRadioInterfaceLayer.idl
+++ b/dom/system/gonk/nsIRadioInterfaceLayer.idl
@@ -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/. */
 
 #include "nsISupports.idl"
 
 interface nsIDOMMozIccInfo;
 interface nsIDOMMozMobileConnectionInfo;
+interface nsIMobileMessageCallback;
 
 [scriptable, uuid(1e602d20-d066-4399-8997-daf36b3158ef)]
 interface nsIRILDataCallInfo : nsISupports
 {
   /**
    * Current data call state, one of the
    * nsINetworkInterface::NETWORK_STATE_* constants.
    */
@@ -72,42 +73,43 @@ interface nsIRilContext : nsISupports
 
   readonly attribute nsIDOMMozIccInfo iccInfo;
 
   readonly attribute nsIDOMMozMobileConnectionInfo voice;
 
   readonly attribute nsIDOMMozMobileConnectionInfo data;
 };
 
-[scriptable, function, uuid(3bc96351-53b0-47a1-a888-c74c64b60f25)]
-interface nsIRilSendWorkerMessageCallback : nsISupports
-{
-  boolean handleResponse(in jsval response);
-};
-
-[scriptable, uuid(b1af7aad-6547-427c-a878-e2ebf98a14d6)]
+[scriptable, uuid(a50d65aa-00da-11e3-b954-7bfb233d98fc)]
 interface nsIRadioInterface : nsISupports
 {
   readonly attribute nsIRilContext rilContext;
 
   /**
    * PDP APIs
    */
   void setupDataCallByType(in DOMString apntype);
   void deactivateDataCallByType(in DOMString apntype);
   long getDataCallStateByType(in DOMString apntype);
 
   void registerDataCallCallback(in nsIRILDataCallback callback);
   void unregisterDataCallCallback(in nsIRILDataCallback callback);
 
   void updateRILNetworkInterface();
 
-  void sendWorkerMessage(in DOMString type,
-              [optional] in jsval message,
-              [optional] in nsIRilSendWorkerMessageCallback callback);
+  /**
+   * SMS-related functionality.
+   */
+  void getSegmentInfoForText(in DOMString text,
+                             in nsIMobileMessageCallback request);
+
+  void sendSMS(in DOMString number,
+               in DOMString message,
+               in boolean silent,
+               in nsIMobileMessageCallback request);
 };
 
 [scriptable, uuid(44b03951-1444-4c03-bd37-0bcb3a01b56f)]
 interface nsIRadioInterfaceLayer : nsISupports
 {
   readonly attribute unsigned long numRadioInterfaces;
 
   nsIRadioInterface getRadioInterface(in long clientId);
--- a/dom/telephony/CallEvent.cpp
+++ b/dom/telephony/CallEvent.cpp
@@ -6,17 +6,16 @@
 
 #include "CallEvent.h"
 #include "mozilla/dom/CallEventBinding.h"
 
 #include "TelephonyCall.h"
 
 USING_TELEPHONY_NAMESPACE
 using namespace mozilla::dom;
-using mozilla::ErrorResult;
 
 /* static */
 already_AddRefed<CallEvent>
 CallEvent::Create(EventTarget* aOwner, const nsAString& aType,
                   TelephonyCall* aCall, bool aCanBubble,
                   bool aCancelable)
 {
   nsRefPtr<CallEvent> event = new CallEvent(aOwner, nullptr, nullptr);
--- a/dom/telephony/Makefile.in
+++ b/dom/telephony/Makefile.in
@@ -1,7 +1,5 @@
 # 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 $(topsrcdir)/dom/dom-config.mk
-include $(topsrcdir)/config/rules.mk
-include $(topsrcdir)/ipc/chromium/chromium-config.mk
--- a/dom/telephony/Telephony.cpp
+++ b/dom/telephony/Telephony.cpp
@@ -19,19 +19,20 @@
 #include "nsServiceManagerUtils.h"
 #include "nsThreadUtils.h"
 
 #include "CallEvent.h"
 #include "CallsList.h"
 #include "TelephonyCall.h"
 #include "TelephonyCallGroup.h"
 
+#define NS_RILCONTENTHELPER_CONTRACTID "@mozilla.org/ril/content-helper;1"
+
 USING_TELEPHONY_NAMESPACE
 using namespace mozilla::dom;
-using mozilla::ErrorResult;
 
 namespace {
 
 typedef nsAutoTArray<Telephony*, 2> TelephonyList;
 
 TelephonyList* gTelephonyList;
 
 } // anonymous namespace
@@ -45,18 +46,16 @@ public:
   NS_FORWARD_SAFE_NSITELEPHONYLISTENER(mTelephony)
 
   Listener(Telephony* aTelephony)
     : mTelephony(aTelephony)
   {
     MOZ_ASSERT(mTelephony);
   }
 
-  virtual ~Listener() {}
-
   void
   Disconnect()
   {
     MOZ_ASSERT(mTelephony);
     mTelephony = nullptr;
   }
 };
 
@@ -107,17 +106,17 @@ Telephony::~Telephony()
 
 void
 Telephony::Shutdown()
 {
   if (mListener) {
     mListener->Disconnect();
 
     if (mProvider) {
-      mProvider->UnregisterListener(mListener);
+      mProvider->UnregisterTelephonyMsg(mListener);
       mProvider = nullptr;
     }
 
     mListener = nullptr;
   }
 }
 
 JSObject*
@@ -128,17 +127,17 @@ Telephony::WrapObject(JSContext* aCx, JS
 
 // static
 already_AddRefed<Telephony>
 Telephony::Create(nsPIDOMWindow* aOwner, ErrorResult& aRv)
 {
   NS_ASSERTION(aOwner, "Null owner!");
 
   nsCOMPtr<nsITelephonyProvider> ril =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
+    do_GetService(NS_RILCONTENTHELPER_CONTRACTID);
   if (!ril) {
     aRv.Throw(NS_ERROR_UNEXPECTED);
     return nullptr;
   }
 
   nsCOMPtr<nsIScriptGlobalObject> sgo = do_QueryInterface(aOwner);
   if (!sgo) {
     aRv.Throw(NS_ERROR_UNEXPECTED);
@@ -161,17 +160,17 @@ Telephony::Create(nsPIDOMWindow* aOwner,
   telephony->mGroup = TelephonyCallGroup::Create(telephony);
 
   nsresult rv = ril->EnumerateCalls(telephony->mListener);
   if (NS_FAILED(rv)) {
     aRv.Throw(rv);
     return nullptr;
   }
 
-  rv = ril->RegisterListener(telephony->mListener);
+  rv = ril->RegisterTelephonyMsg(telephony->mListener);
   if (NS_FAILED(rv)) {
     aRv.Throw(rv);
     return nullptr;
   }
 
   return telephony.forget();
 }
 
@@ -218,17 +217,22 @@ Telephony::DialInternal(bool isEmergency
       // One call has been dialed already and we only support one outgoing call
       // at a time.
       NS_WARNING("Only permitted to dial one call at a time!");
       aRv.Throw(NS_ERROR_NOT_AVAILABLE);
       return nullptr;
     }
   }
 
-  nsresult rv = mProvider->Dial(aNumber, isEmergency);
+  nsresult rv;
+  if (isEmergency) {
+    rv = mProvider->DialEmergency(aNumber);
+  } else {
+    rv = mProvider->Dial(aNumber);
+  }
   if (NS_FAILED(rv)) {
     aRv.Throw(rv);
     return nullptr;
   }
 
   nsRefPtr<TelephonyCall> call = CreateNewDialingCall(aNumber);
 
   // Notify other telephony objects that we just dialed.
@@ -582,45 +586,48 @@ Telephony::EnumerateCallStateComplete()
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 Telephony::EnumerateCallState(uint32_t aCallIndex, uint16_t aCallState,
                               const nsAString& aNumber, bool aIsActive,
                               bool aIsOutgoing, bool aIsEmergency,
-                              bool aIsConference)
+                              bool aIsConference, bool* aContinue)
 {
   nsRefPtr<TelephonyCall> call;
 
   // We request calls enumeration in constructor, and the asynchronous result
   // will be sent back through the callback function EnumerateCallState().
   // However, it is likely to have call state changes, i.e. CallStateChanged()
   // being called, before the enumeration result comes back. We'd make sure
   // we don't somehow add duplicates due to the race condition.
   call = aIsConference ? mGroup->GetCall(aCallIndex) : GetCall(aCallIndex);
   if (call) {
     // We have the call either in mCalls or in mGroup. Skip it.
+    *aContinue = true;
     return NS_OK;
   }
 
   if (MoveCall(aCallIndex, aIsConference)) {
+    *aContinue = true;
     return NS_OK;
   }
 
   // Didn't know anything about this call before now.
 
   call = TelephonyCall::Create(this, aNumber, aCallState, aCallIndex,
                                aIsEmergency, aIsConference);
   NS_ASSERTION(call, "This should never fail!");
 
   NS_ASSERTION(aIsConference ? mGroup->CallsArray().Contains(call) :
                                mCalls.Contains(call),
                "Should have auto-added new call!");
 
+  *aContinue = true;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 Telephony::SupplementaryServiceNotification(int32_t aCallIndex,
                                             uint16_t aNotification)
 {
   nsRefPtr<TelephonyCall> associatedCall;
--- a/dom/telephony/TelephonyCall.cpp
+++ b/dom/telephony/TelephonyCall.cpp
@@ -10,17 +10,16 @@
 #include "mozilla/dom/DOMError.h"
 
 #include "CallEvent.h"
 #include "Telephony.h"
 #include "TelephonyCallGroup.h"
 
 USING_TELEPHONY_NAMESPACE
 using namespace mozilla::dom;
-using mozilla::ErrorResult;
 
 // static
 already_AddRefed<TelephonyCall>
 TelephonyCall::Create(Telephony* aTelephony, const nsAString& aNumber,
                       uint16_t aCallState, uint32_t aCallIndex,
                       bool aEmergency, bool aIsConference)
 {
   NS_ASSERTION(aTelephony, "Null pointer!");
--- a/dom/telephony/TelephonyCallGroup.cpp
+++ b/dom/telephony/TelephonyCallGroup.cpp
@@ -8,17 +8,16 @@
 #include "mozilla/dom/TelephonyCallGroupBinding.h"
 
 #include "CallEvent.h"
 #include "CallsList.h"
 #include "Telephony.h"
 
 USING_TELEPHONY_NAMESPACE
 using namespace mozilla::dom;
-using mozilla::ErrorResult;
 
 TelephonyCallGroup::TelephonyCallGroup()
 : mCallState(nsITelephonyProvider::CALL_STATE_UNKNOWN)
 {
   SetIsDOMBinding();
 }
 
 TelephonyCallGroup::~TelephonyCallGroup()
deleted file mode 100644
--- a/dom/telephony/TelephonyFactory.cpp
+++ /dev/null
@@ -1,30 +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 "mozilla/dom/telephony/TelephonyFactory.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsIGonkTelephonyProvider.h"
-#endif
-#include "nsServiceManagerUtils.h"
-#include "nsXULAppAPI.h"
-#include "ipc/TelephonyIPCProvider.h"
-
-USING_TELEPHONY_NAMESPACE
-
-/* static */ already_AddRefed<nsITelephonyProvider>
-TelephonyFactory::CreateTelephonyProvider()
-{
-  nsCOMPtr<nsITelephonyProvider> provider;
-
-  if (XRE_GetProcessType() == GeckoProcessType_Content) {
-    provider = new TelephonyIPCProvider();
-#ifdef MOZ_WIDGET_GONK
-  } else {
-    provider = do_CreateInstance(GONK_TELEPHONY_PROVIDER_CONTRACTID);
-#endif
-  }
-
-  return provider.forget();
-}
deleted file mode 100644
--- a/dom/telephony/TelephonyFactory.h
+++ /dev/null
@@ -1,24 +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/. */
-
-#ifndef mozilla_dom_telephony_TelephonyFactory_h
-#define mozilla_dom_telephony_TelephonyFactory_h
-
-#include "nsCOMPtr.h"
-#include "mozilla/dom/telephony/TelephonyCommon.h"
-
-class nsITelephonyProvider;
-
-BEGIN_TELEPHONY_NAMESPACE
-
-class TelephonyFactory
-{
-public:
-  static already_AddRefed<nsITelephonyProvider> CreateTelephonyProvider();
-};
-
-END_TELEPHONY_NAMESPACE
-
-#endif // mozilla_dom_telephony_TelephonyFactory_h
deleted file mode 100644
--- a/dom/telephony/gonk/TelephonyProvider.js
+++ /dev/null
@@ -1,525 +0,0 @@
-/* -*- Mode: js; 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/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-var RIL = {};
-Cu.import("resource://gre/modules/ril_consts.js", RIL);
-
-const GONK_TELEPHONYPROVIDER_CONTRACTID =
-  "@mozilla.org/telephony/gonktelephonyprovider;1";
-const GONK_TELEPHONYPROVIDER_CID =
-  Components.ID("{67d26434-d063-4d28-9f48-5b3189788155}");
-
-const kPrefenceChangedObserverTopic = "nsPref:changed";
-const kXpcomShutdownObserverTopic   = "xpcom-shutdown";
-
-const nsIAudioManager = Ci.nsIAudioManager;
-const nsITelephonyProvider = Ci.nsITelephonyProvider;
-
-const CALL_WAKELOCK_TIMEOUT = 5000;
-
-let DEBUG;
-function debug(s) {
-  dump("TelephonyProvider: " + s + "\n");
-}
-
-XPCOMUtils.defineLazyGetter(this, "gAudioManager", function getAudioManager() {
-  try {
-    return Cc["@mozilla.org/telephony/audiomanager;1"]
-             .getService(nsIAudioManager);
-  } catch (ex) {
-    //TODO on the phone this should not fall back as silently.
-
-    // Fake nsIAudioManager implementation so that we can run the telephony
-    // code in a non-Gonk build.
-    if (DEBUG) debug("Using fake audio manager.");
-    return {
-      microphoneMuted: false,
-      masterVolume: 1.0,
-      masterMuted: false,
-      phoneState: nsIAudioManager.PHONE_STATE_CURRENT,
-      _forceForUse: {},
-
-      setForceForUse: function setForceForUse(usage, force) {
-        this._forceForUse[usage] = force;
-      },
-
-      getForceForUse: function setForceForUse(usage) {
-        return this._forceForUse[usage] || nsIAudioManager.FORCE_NONE;
-      }
-    };
-  }
-});
-
-XPCOMUtils.defineLazyServiceGetter(this, "gPowerManagerService",
-                                   "@mozilla.org/power/powermanagerservice;1",
-                                   "nsIPowerManagerService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSystemMessenger",
-                                   "@mozilla.org/system-message-internal;1",
-                                   "nsISystemMessagesInternal");
-
-XPCOMUtils.defineLazyGetter(this, "gRadioInterface", function () {
-  let ril = Cc["@mozilla.org/ril;1"].getService(Ci["nsIRadioInterfaceLayer"]);
-  // TODO: Bug 854326 - B2G Multi-SIM: support multiple SIM cards for SMS/MMS
-  return ril.getRadioInterface(0);
-});
-
-XPCOMUtils.defineLazyGetter(this, "gPhoneNumberUtils", function () {
-  let ns = {};
-  Cu.import("resource://gre/modules/PhoneNumberUtils.jsm", ns);
-  return ns.PhoneNumberUtils;
-});
-
-function TelephonyProvider() {
-  this._listeners = [];
-
-  this._updateDebugFlag();
-
-  Services.obs.addObserver(this, kPrefenceChangedObserverTopic, false);
-  Services.obs.addObserver(this, kXpcomShutdownObserverTopic, false);
-}
-TelephonyProvider.prototype = {
-  classID: GONK_TELEPHONYPROVIDER_CID,
-  classInfo: XPCOMUtils.generateCI({classID: GONK_TELEPHONYPROVIDER_CID,
-                                    contractID: GONK_TELEPHONYPROVIDER_CONTRACTID,
-                                    classDescription: "TelephonyProvider",
-                                    interfaces: [Ci.nsITelephonyProvider,
-                                                 Ci.nsIGonkTelephonyProvider],
-                                    flags: Ci.nsIClassInfo.SINGLETON}),
-  QueryInterface: XPCOMUtils.generateQI([Ci.nsITelephonyProvider,
-                                         Ci.nsIGonkTelephonyProvider,
-                                         Ci.nsIObserver]),
-
-  _callRingWakeLock: null,
-  _callRingWakeLockTimer: null,
-  _cancelCallRingWakeLockTimer: function _cancelCallRingWakeLockTimer() {
-    if (this._callRingWakeLockTimer) {
-      this._callRingWakeLockTimer.cancel();
-    }
-    if (this._callRingWakeLock) {
-      this._callRingWakeLock.unlock();
-      this._callRingWakeLock = null;
-    }
-  },
-
-  // An array of nsITelephonyListener instances.
-  _listeners: null,
-  _notifyAllListeners: function _notifyAllListeners(aMethodName, aArgs) {
-    let listeners = this._listeners.slice();
-    for (let listener of listeners) {
-      if (this._listeners.indexOf(listener) == -1) {
-        // Listener has been unregistered in previous run.
-        continue;
-      }
-
-      let handler = listener[aMethodName];
-      try {
-        handler.apply(listener, aArgs);
-      } catch (e) {
-        debug("listener for " + aMethodName + " threw an exception: " + e);
-      }
-    }
-  },
-
-  /**
-   * Track the active call and update the audio system as its state changes.
-   */
-  _activeCall: null,
-  _updateCallAudioState: function _updateCallAudioState(aCall,
-                                                        aConferenceState) {
-    if (aConferenceState === nsITelephonyProvider.CALL_STATE_CONNECTED) {
-      gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_IN_CALL;
-      if (this.speakerEnabled) {
-        gAudioManager.setForceForUse(nsIAudioManager.USE_COMMUNICATION,
-                                     nsIAudioManager.FORCE_SPEAKER);
-      }
-      return;
-    }
-    if (aConferenceState === nsITelephonyProvider.CALL_STATE_UNKNOWN ||
-        aConferenceState === nsITelephonyProvider.CALL_STATE_HELD) {
-      if (!this._activeCall) {
-        gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_NORMAL;
-      }
-      return;
-    }
-
-    if (!aCall) {
-      return;
-    }
-
-    if (aCall.isConference) {
-      if (this._activeCall && this._activeCall.callIndex == aCall.callIndex) {
-        this._activeCall = null;
-      }
-      return;
-    }
-
-    switch (aCall.state) {
-      case nsITelephonyProvider.CALL_STATE_DIALING: // Fall through...
-      case nsITelephonyProvider.CALL_STATE_ALERTING:
-      case nsITelephonyProvider.CALL_STATE_CONNECTED:
-        aCall.isActive = true;
-        this._activeCall = aCall;
-        gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_IN_CALL;
-        if (this.speakerEnabled) {
-          gAudioManager.setForceForUse(nsIAudioManager.USE_COMMUNICATION,
-                                       nsIAudioManager.FORCE_SPEAKER);
-        }
-        if (DEBUG) {
-          debug("Active call, put audio system into PHONE_STATE_IN_CALL: " +
-                gAudioManager.phoneState);
-        }
-        break;
-
-      case nsITelephonyProvider.CALL_STATE_INCOMING:
-        aCall.isActive = false;
-        if (!this._activeCall) {
-          // We can change the phone state into RINGTONE only when there's
-          // no active call.
-          gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_RINGTONE;
-          if (DEBUG) {
-            debug("Incoming call, put audio system into PHONE_STATE_RINGTONE: " +
-                  gAudioManager.phoneState);
-          }
-        }
-        break;
-
-      case nsITelephonyProvider.CALL_STATE_HELD: // Fall through...
-      case nsITelephonyProvider.CALL_STATE_DISCONNECTED:
-        aCall.isActive = false;
-        if (this._activeCall &&
-            this._activeCall.callIndex == aCall.callIndex) {
-          // Previously active call is not active now.
-          this._activeCall = null;
-        }
-
-        if (!this._activeCall) {
-          // No active call. Disable the audio.
-          gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_NORMAL;
-          if (DEBUG) {
-            debug("No active call, put audio system into PHONE_STATE_NORMAL: " +
-                  gAudioManager.phoneState);
-          }
-        }
-        break;
-    }
-  },
-
-  _convertRILCallState: function _convertRILCallState(aState) {
-    switch (aState) {
-      case RIL.CALL_STATE_ACTIVE:
-        return nsITelephonyProvider.CALL_STATE_CONNECTED;
-      case RIL.CALL_STATE_HOLDING:
-        return nsITelephonyProvider.CALL_STATE_HELD;
-      case RIL.CALL_STATE_DIALING:
-        return nsITelephonyProvider.CALL_STATE_DIALING;
-      case RIL.CALL_STATE_ALERTING:
-        return nsITelephonyProvider.CALL_STATE_ALERTING;
-      case RIL.CALL_STATE_INCOMING:
-      case RIL.CALL_STATE_WAITING:
-        return nsITelephonyProvider.CALL_STATE_INCOMING;
-      default:
-        throw new Error("Unknown rilCallState: " + aState);
-    }
-  },
-
-  _convertRILSuppSvcNotification: function _convertRILSuppSvcNotification(aNotification) {
-    switch (aNotification) {
-      case RIL.GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD:
-        return nsITelephonyProvider.NOTIFICATION_REMOTE_HELD;
-      case RIL.GECKO_SUPP_SVC_NOTIFICATION_REMOTE_RESUMED:
-        return nsITelephonyProvider.NOTIFICATION_REMOTE_RESUMED;
-      default:
-        throw new Error("Unknown rilSuppSvcNotification: " + aNotification);
-    }
-  },
-
-  _validateNumber: function _validateNumber(aNumber) {
-    // note: isPlainPhoneNumber also accepts USSD and SS numbers
-    if (gPhoneNumberUtils.isPlainPhoneNumber(aNumber)) {
-      return true;
-    }
-
-    let errorMsg = RIL.RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[RIL.CALL_FAIL_UNOBTAINABLE_NUMBER];
-    let currentThread = Services.tm.currentThread;
-    currentThread.dispatch(this.notifyCallError.bind(this, -1, errorMsg),
-                           Ci.nsIThread.DISPATCH_NORMAL);
-    if (DEBUG) {
-      debug("Number '" + aNumber + "' doesn't seem to be a viable number. Drop.");
-    }
-
-    return false;
-  },
-
-  _updateDebugFlag: function _updateDebugFlag() {
-    try {
-      DEBUG = RIL.DEBUG_RIL ||
-              Services.prefs.getBoolPref("ril.debugging.enabled");
-    } catch (e) {}
-  },
-
-  /**
-   * nsITelephonyProvider interface.
-   */
-
-  registerListener: function(aListener) {
-    if (this._listeners.indexOf(aListener) >= 0) {
-      throw Cr.NS_ERROR_UNEXPECTED;
-    }
-
-    this._listeners.push(aListener);
-  },
-
-  unregisterListener: function(aListener) {
-    let index = this._listeners.indexOf(aListener);
-    if (index < 0) {
-      throw Cr.NS_ERROR_UNEXPECTED;
-    }
-
-    this._listeners.splice(index, 1);
-  },
-
-  enumerateCalls: function(aListener) {
-    if (DEBUG) debug("Requesting enumeration of calls for callback");
-    gRadioInterface.sendWorkerMessage("enumerateCalls", null,
-                                      (function(response) {
-      for (let call of response.calls) {
-        call.state = this._convertRILCallState(call.state);
-        call.isActive = this._activeCall ?
-          (call.callIndex == this._activeCall.callIndex) : false;
-
-        aListener.enumerateCallState(call.callIndex, call.state, call.number,
-                                     call.isActive, call.isOutgoing,
-                                     call.isEmergency, call.isConference);
-      }
-      aListener.enumerateCallStateComplete();
-
-      return false;
-    }).bind(this));
-  },
-
-  dial: function(aNumber, aIsEmergency) {
-    if (DEBUG) debug("Dialing " + (aIsEmergency ? "emergency " : "") + aNumber);
-    // we don't try to be too clever here, as the phone is probably in the
-    // locked state. Let's just check if it's a number without normalizing
-    if (!aIsEmergency) {
-      aNumber = gPhoneNumberUtils.normalize(aNumber);
-    }
-    if (this._validateNumber(aNumber)) {
-      gRadioInterface.sendWorkerMessage("dial", { number: aNumber,
-                                                  isDialEmergency: aIsEmergency });
-    }
-  },
-
-  hangUp: function(aCallIndex) {
-    gRadioInterface.sendWorkerMessage("hangUp", { callIndex: aCallIndex });
-  },
-
-  startTone: function(aDtmfChar) {
-    gRadioInterface.sendWorkerMessage("startTone", { dtmfChar: aDtmfChar });
-  },
-
-  stopTone: function() {
-    gRadioInterface.sendWorkerMessage("stopTone");
-  },
-
-  answerCall: function(aCallIndex) {
-    gRadioInterface.sendWorkerMessage("answerCall", { callIndex: aCallIndex });
-  },
-
-  rejectCall: function(aCallIndex) {
-    gRadioInterface.sendWorkerMessage("rejectCall", { callIndex: aCallIndex });
-  },
-
-  holdCall: function(aCallIndex) {
-    gRadioInterface.sendWorkerMessage("holdCall", { callIndex: aCallIndex });
-  },
-
-  resumeCall: function(aCallIndex) {
-    gRadioInterface.sendWorkerMessage("resumeCall", { callIndex: aCallIndex });
-  },
-
-  conferenceCall: function conferenceCall() {
-    gRadioInterface.sendWorkerMessage("conferenceCall");
-  },
-
-  separateCall: function separateCall(aCallIndex) {
-    gRadioInterface.sendWorkerMessage("separateCall", { callIndex: aCallIndex });
-  },
-
-  holdConference: function holdConference() {
-    gRadioInterface.sendWorkerMessage("holdConference");
-  },
-
-  resumeConference: function resumeConference() {
-    gRadioInterface.sendWorkerMessage("resumeConference");
-  },
-
-  get microphoneMuted() {
-    return gAudioManager.microphoneMuted;
-  },
-
-  set microphoneMuted(aMuted) {
-    if (aMuted == this.microphoneMuted) {
-      return;
-    }
-    gAudioManager.microphoneMuted = aMuted;
-
-    if (!this._activeCall) {
-      gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_NORMAL;
-    }
-  },
-
-  get speakerEnabled() {
-    let force = gAudioManager.getForceForUse(nsIAudioManager.USE_COMMUNICATION);
-    return (force == nsIAudioManager.FORCE_SPEAKER);
-  },
-
-  set speakerEnabled(aEnabled) {
-    if (aEnabled == this.speakerEnabled) {
-      return;
-    }
-    let force = aEnabled ? nsIAudioManager.FORCE_SPEAKER :
-                           nsIAudioManager.FORCE_NONE;
-    gAudioManager.setForceForUse(nsIAudioManager.USE_COMMUNICATION, force);
-
-    if (!this._activeCall) {
-      gAudioManager.phoneState = nsIAudioManager.PHONE_STATE_NORMAL;
-    }
-  },
-
-  /**
-   * nsIGonkTelephonyProvider interface.
-   */
-
-  /**
-   * Handle call disconnects by updating our current state and the audio system.
-   */
-  notifyCallDisconnected: function notifyCallDisconnected(aCall) {
-    if (DEBUG) debug("handleCallDisconnected: " + JSON.stringify(aCall));
-
-    aCall.state = nsITelephonyProvider.CALL_STATE_DISCONNECTED;
-    let duration = ("started" in aCall && typeof aCall.started == "number") ?
-      new Date().getTime() - aCall.started : 0;
-    let data = {
-      number: aCall.number,
-      duration: duration,
-      direction: aCall.isOutgoing ? "outgoing" : "incoming"
-    };
-    gSystemMessenger.broadcastMessage("telephony-call-ended", data);
-
-    this._updateCallAudioState(aCall, null);
-
-    this._notifyAllListeners("callStateChanged", [aCall.callIndex,
-                                                  aCall.state,
-                                                  aCall.number,
-                                                  aCall.isActive,
-                                                  aCall.isOutgoing,
-                                                  aCall.isEmergency,
-                                                  aCall.isConference]);
-  },
-
-  /**
-   * Handle call error.
-   */
-  notifyCallError: function notifyCallError(aCallIndex, aErrorMsg) {
-    this._notifyAllListeners("notifyError", [aCallIndex, aErrorMsg]);
-  },
-
-  /**
-   * Handle an incoming call.
-   *
-   * Not much is known about this call at this point, but it's enough
-   * to start bringing up the Phone app already.
-   */
-  notifyCallRing: function notifyCallRing() {
-    if (!this._callRingWakeLock) {
-      this._callRingWakeLock = gPowerManagerService.newWakeLock("cpu");
-    }
-    if (!this._callRingWakeLockTimer) {
-      this._callRingWakeLockTimer =
-        Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
-    }
-    this._callRingWakeLockTimer
-        .initWithCallback(this._cancelCallRingWakeLockTimer.bind(this),
-                          CALL_WAKELOCK_TIMEOUT, Ci.nsITimer.TYPE_ONE_SHOT);
-
-    gSystemMessenger.broadcastMessage("telephony-new-call", {});
-  },
-
-  /**
-   * Handle call state changes by updating our current state and the audio
-   * system.
-   */
-  notifyCallStateChanged: function notifyCallStateChanged(aCall) {
-    if (DEBUG) debug("handleCallStateChange: " + JSON.stringify(aCall));
-
-    aCall.state = this._convertRILCallState(aCall.state);
-    if (aCall.state == nsITelephonyProvider.CALL_STATE_DIALING) {
-      gSystemMessenger.broadcastMessage("telephony-new-call", {});
-    }
-
-    this._updateCallAudioState(aCall, null);
-
-    this._notifyAllListeners("callStateChanged", [aCall.callIndex,
-                                                  aCall.state,
-                                                  aCall.number,
-                                                  aCall.isActive,
-                                                  aCall.isOutgoing,
-                                                  aCall.isEmergency,
-                                                  aCall.isConference]);
-  },
-
-  notifyCdmaCallWaiting: function notifyCdmaCallWaiting(aNumber) {
-    this._notifyAllListeners("notifyCdmaCallWaiting", [aNumber]);
-  },
-
-  notifySupplementaryService: function notifySupplementaryService(aCallIndex,
-                                                                  aNotification) {
-    let notification = this._convertRILSuppSvcNotification(aNotification);
-    this._notifyAllListeners("supplementaryServiceNotification",
-                             [aCallIndex, notification]);
-  },
-
-  notifyConferenceCallStateChanged: function notifyConferenceCallStateChanged(aState) {
-    if (DEBUG) debug("handleConferenceCallStateChanged: " + aState);
-    aState = aState != null ? convertRILCallState(aState) :
-                              nsITelephonyProvider.CALL_STATE_UNKNOWN;
-    this._updateCallAudioState(null, aState);
-
-    this._notifyAllListeners("conferenceCallStateChanged", [aState]);
-  },
-
-  /**
-   * nsIObserver interface.
-   */
-
-  observe: function observe(aSubject, aTopic, aData) {
-    switch (aTopic) {
-      case kPrefenceChangedObserverTopic:
-        if (aData === "ril.debugging.enabled") {
-          this._updateDebugFlag();
-        }
-        break;
-
-      case kXpcomShutdownObserverTopic:
-        // Cancel the timer for the call-ring wake lock.
-        this._cancelCallRingWakeLockTimer();
-
-        Services.obs.removeObserver(this, kPrefenceChangedObserverTopic);
-        Services.obs.removeObserver(this, kXpcomShutdownObserverTopic);
-        break;
-    }
-  }
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([TelephonyProvider]);
deleted file mode 100644
--- a/dom/telephony/gonk/TelephonyProvider.manifest
+++ /dev/null
@@ -1,2 +0,0 @@
-component {67d26434-d063-4d28-9f48-5b3189788155} TelephonyProvider.js
-contract @mozilla.org/telephony/gonktelephonyprovider;1 {67d26434-d063-4d28-9f48-5b3189788155}
deleted file mode 100644
--- a/dom/telephony/ipc/PTelephony.ipdl
+++ /dev/null
@@ -1,83 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set sw=2 ts=8 et ft=cpp : */
-/* 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 protocol PContent;
-include protocol PTelephonyRequest;
-include TelephonyTypes;
-
-namespace mozilla {
-namespace dom {
-namespace telephony {
-
-sync protocol PTelephony {
-  manager PContent;
-  manages PTelephonyRequest;
-
-child:
-  NotifyCallError(int32_t aCallIndex, nsString aError);
-
-  NotifyCallStateChanged(IPCCallStateData aData);
-
-  NotifyCdmaCallWaiting(nsString aNumber);
-
-  NotifyConferenceCallStateChanged(uint16_t aCallState);
-
-  NotifySupplementaryService(int32_t aCallIndex, uint16_t aNotification);
-
-parent:
-  /**
-   * Sent when the child no longer needs to use PTelephony.
-   */
-  __delete__();
-
-  /**
-   * Sent when the child makes an asynchronous request to the parent.  It's
-   * currently only for request call enumeration.
-   */
-  PTelephonyRequest();
-
-  RegisterListener();
-
-  UnregisterListener();
-
-  DialCall(nsString aNumber, bool aIsEmergency);
-
-  HangUpCall(uint32_t aCallIndex);
-
-  AnswerCall(uint32_t aCallIndex);
-
-  RejectCall(uint32_t aCallIndex);
-
-  HoldCall(uint32_t aCallIndex);
-
-  ResumeCall(uint32_t aCallIndex);
-
-  ConferenceCall();
-
-  SeparateCall(uint32_t aCallIndex);
-
-  HoldConference();
-
-  ResumeConference();
-
-  StartTone(nsString aTone);
-
-  StopTone();
-
-  sync GetMicrophoneMuted()
-    returns (bool aMuted);
-
-  SetMicrophoneMuted(bool aMuted);
-
-  sync GetSpeakerEnabled()
-    returns (bool aEnabled);
-
-  SetSpeakerEnabled(bool aEnabled);
-};
-
-} /* namespace telephony */
-} /* namespace dom */
-} /* namespace mozilla */
deleted file mode 100644
--- a/dom/telephony/ipc/PTelephonyRequest.ipdl
+++ /dev/null
@@ -1,30 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 protocol PTelephony;
-include TelephonyTypes;
-
-namespace mozilla {
-namespace dom {
-namespace telephony {
-
-protocol PTelephonyRequest
-{
-  manager PTelephony;
-
-child:
-  NotifyEnumerateCallState(IPCCallStateData aData);
-
-  /**
-   * Sent when the asynchronous request has completed. It's currently only for
-   * request call enumeration.
-   */
-  __delete__();
-};
-
-} /* namespace telephony */
-} /* namespace dom */
-} /* namespace mozilla */
deleted file mode 100644
--- a/dom/telephony/ipc/TelephonyChild.cpp
+++ /dev/null
@@ -1,130 +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 "mozilla/dom/telephony/TelephonyChild.h"
-
-USING_TELEPHONY_NAMESPACE
-
-/*******************************************************************************
- * TelephonyChild
- ******************************************************************************/
-
-TelephonyChild::TelephonyChild(nsITelephonyListener* aListener)
-  : mListener(aListener)
-{
-  MOZ_ASSERT(aListener);
-}
-
-void
-TelephonyChild::ActorDestroy(ActorDestroyReason aWhy)
-{
-  mListener = nullptr;
-}
-
-PTelephonyRequestChild*
-TelephonyChild::AllocPTelephonyRequestChild()
-{
-  MOZ_CRASH("Caller is supposed to manually construct a request!");
-}
-
-bool
-TelephonyChild::DeallocPTelephonyRequestChild(PTelephonyRequestChild* aActor)
-{
-  delete aActor;
-  return true;
-}
-
-bool
-TelephonyChild::RecvNotifyCallError(const int32_t& aCallIndex,
-                                    const nsString& aError)
-{
-  MOZ_ASSERT(mListener);
-
-  mListener->NotifyError(aCallIndex, aError);
-  return true;
-}
-
-bool
-TelephonyChild::RecvNotifyCallStateChanged(const IPCCallStateData& aData)
-{
-  MOZ_ASSERT(mListener);
-
-  mListener->CallStateChanged(aData.callIndex(),
-                              aData.callState(),
-                              aData.number(),
-                              aData.isActive(),
-                              aData.isOutGoing(),
-                              aData.isEmergency(),
-                              aData.isConference());
-  return true;
-}
-
-bool
-TelephonyChild::RecvNotifyCdmaCallWaiting(const nsString& aNumber)
-{
-  MOZ_ASSERT(mListener);
-
-  mListener->NotifyCdmaCallWaiting(aNumber);
-  return true;
-}
-
-bool
-TelephonyChild::RecvNotifyConferenceCallStateChanged(const uint16_t& aCallState)
-{
-  MOZ_ASSERT(mListener);
-
-  mListener->ConferenceCallStateChanged(aCallState);
-  return true;
-}
-
-bool
-TelephonyChild::RecvNotifySupplementaryService(const int32_t& aCallIndex,
-                                               const uint16_t& aNotification)
-{
-  MOZ_ASSERT(mListener);
-
-  mListener->SupplementaryServiceNotification(aCallIndex, aNotification);
-  return true;
-}
-
-/*******************************************************************************
- * TelephonyRequestChild
- ******************************************************************************/
-
-TelephonyRequestChild::TelephonyRequestChild(nsITelephonyListener* aListener)
-  : mListener(aListener)
-{
-  MOZ_ASSERT(aListener);
-}
-
-void
-TelephonyRequestChild::ActorDestroy(ActorDestroyReason aWhy)
-{
-  mListener = nullptr;
-}
-
-bool
-TelephonyRequestChild::Recv__delete__()
-{
-  MOZ_ASSERT(mListener);
-
-  mListener->EnumerateCallStateComplete();
-  return true;
-}
-
-bool
-TelephonyRequestChild::RecvNotifyEnumerateCallState(const IPCCallStateData& aData)
-{
-  MOZ_ASSERT(mListener);
-
-  mListener->EnumerateCallState(aData.callIndex(),
-                                aData.callState(),
-                                aData.number(),
-                                aData.isActive(),
-                                aData.isOutGoing(),
-                                aData.isEmergency(),
-                                aData.isConference());
-  return true;
-}
deleted file mode 100644
--- a/dom/telephony/ipc/TelephonyChild.h
+++ /dev/null
@@ -1,77 +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/. */
-
-#ifndef mozilla_dom_telephony_TelephonyChild_h
-#define mozilla_dom_telephony_TelephonyChild_h
-
-#include "mozilla/dom/telephony/TelephonyCommon.h"
-#include "mozilla/dom/telephony/PTelephonyChild.h"
-#include "mozilla/dom/telephony/PTelephonyRequestChild.h"
-#include "nsITelephonyProvider.h"
-
-BEGIN_TELEPHONY_NAMESPACE
-
-class TelephonyChild : public PTelephonyChild
-{
-public:
-  TelephonyChild(nsITelephonyListener* aListener);
-
-protected:
-  virtual ~TelephonyChild() {}
-
-  virtual void
-  ActorDestroy(ActorDestroyReason aWhy) MOZ_OVERRIDE;
-
-  virtual PTelephonyRequestChild*
-  AllocPTelephonyRequestChild() MOZ_OVERRIDE;
-
-  virtual bool
-  DeallocPTelephonyRequestChild(PTelephonyRequestChild* aActor) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvNotifyCallError(const int32_t& aCallIndex,
-                      const nsString& aError) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvNotifyCallStateChanged(const IPCCallStateData& aData) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvNotifyCdmaCallWaiting(const nsString& aNumber) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvNotifyConferenceCallStateChanged(const uint16_t& aCallState) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvNotifySupplementaryService(const int32_t& aCallIndex,
-                                 const uint16_t& aNotification) MOZ_OVERRIDE;
-
-private:
-  nsCOMPtr<nsITelephonyListener> mListener;
-};
-
-class TelephonyRequestChild : public PTelephonyRequestChild
-{
-public:
-  TelephonyRequestChild(nsITelephonyListener* aListener);
-
-protected:
-  virtual ~TelephonyRequestChild() {}
-
-  virtual void
-  ActorDestroy(ActorDestroyReason aWhy) MOZ_OVERRIDE;
-
-  virtual bool
-  Recv__delete__() MOZ_OVERRIDE;
-
-  virtual bool
-  RecvNotifyEnumerateCallState(const IPCCallStateData& aData) MOZ_OVERRIDE;
-
-private:
-  nsCOMPtr<nsITelephonyListener> mListener;
-};
-
-END_TELEPHONY_NAMESPACE
-
-#endif // mozilla_dom_telephony_TelephonyChild_h
deleted file mode 100644
--- a/dom/telephony/ipc/TelephonyIPCProvider.cpp
+++ /dev/null
@@ -1,258 +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 "mozilla/dom/ContentChild.h"
-#include "mozilla/dom/telephony/TelephonyChild.h"
-#include "ipc/TelephonyIPCProvider.h"
-
-USING_TELEPHONY_NAMESPACE
-using namespace mozilla::dom;
-
-NS_IMPL_ISUPPORTS2(TelephonyIPCProvider,
-                   nsITelephonyProvider,
-                   nsITelephonyListener)
-
-TelephonyIPCProvider::TelephonyIPCProvider()
-{
-  // Deallocated in ContentChild::DeallocPTelephonyChild().
-  mPTelephonyChild = new TelephonyChild(this);
-  ContentChild::GetSingleton()->SendPTelephonyConstructor(mPTelephonyChild);
-}
-
-TelephonyIPCProvider::~TelephonyIPCProvider()
-{
-  mPTelephonyChild->Send__delete__(mPTelephonyChild);
-  mPTelephonyChild = nullptr;
-}
-
-/*
- * Implementation of nsITelephonyProvider.
- */
-
-NS_IMETHODIMP
-TelephonyIPCProvider::RegisterListener(nsITelephonyListener *aListener)
-{
-  MOZ_ASSERT(!mListeners.Contains(aListener));
-
-  // nsTArray doesn't fail.
-  mListeners.AppendElement(aListener);
-
-  if (mListeners.Length() == 1) {
-    mPTelephonyChild->SendRegisterListener();
-  }
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::UnregisterListener(nsITelephonyListener *aListener)
-{
-  MOZ_ASSERT(mListeners.Contains(aListener));
-
-  // We always have the element here, so it can't fail.
-  mListeners.RemoveElement(aListener);
-
-  if (!mListeners.Length()) {
-    mPTelephonyChild->SendUnregisterListener();
-  }
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::EnumerateCalls(nsITelephonyListener *aListener)
-{
-  // Life time of newly allocated TelephonyRequestChild instance is managed by
-  // IPDL itself.
-  TelephonyRequestChild* actor = new TelephonyRequestChild(aListener);
-  mPTelephonyChild->SendPTelephonyRequestConstructor(actor);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::Dial(const nsAString& aNumber,
-                          bool aIsEmergency)
-{
-  mPTelephonyChild->SendDialCall(nsString(aNumber), aIsEmergency);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::HangUp(uint32_t aCallIndex)
-{
-  mPTelephonyChild->SendHangUpCall(aCallIndex);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::AnswerCall(uint32_t aCallIndex)
-{
-  mPTelephonyChild->SendAnswerCall(aCallIndex);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::RejectCall(uint32_t aCallIndex)
-{
-  mPTelephonyChild->SendRejectCall(aCallIndex);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::HoldCall(uint32_t aCallIndex)
-{
-  mPTelephonyChild->SendHoldCall(aCallIndex);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::ResumeCall(uint32_t aCallIndex)
-{
-  mPTelephonyChild->SendResumeCall(aCallIndex);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::ConferenceCall()
-{
-  mPTelephonyChild->SendConferenceCall();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::SeparateCall(uint32_t aCallIndex)
-{
-  mPTelephonyChild->SendSeparateCall(aCallIndex);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::HoldConference()
-{
-  mPTelephonyChild->SendHoldConference();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::ResumeConference()
-{
-  mPTelephonyChild->SendResumeConference();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::StartTone(const nsAString& aDtmfChar)
-{
-  mPTelephonyChild->SendStartTone(nsString(aDtmfChar));
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::StopTone()
-{
-  mPTelephonyChild->SendStopTone();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::GetMicrophoneMuted(bool* aMuted)
-{
-  mPTelephonyChild->SendGetMicrophoneMuted(aMuted);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::SetMicrophoneMuted(bool aMuted)
-{
-  mPTelephonyChild->SendSetMicrophoneMuted(aMuted);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::GetSpeakerEnabled(bool* aEnabled)
-{
-  mPTelephonyChild->SendGetSpeakerEnabled(aEnabled);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::SetSpeakerEnabled(bool aEnabled)
-{
-  mPTelephonyChild->SendSetSpeakerEnabled(aEnabled);
-  return NS_OK;
-}
-
-// nsITelephonyListener
-
-NS_IMETHODIMP
-TelephonyIPCProvider::CallStateChanged(uint32_t aCallIndex,
-                                      uint16_t aCallState,
-                                      const nsAString& aNumber,
-                                      bool aIsActive,
-                                      bool aIsOutgoing,
-                                      bool aIsEmergency,
-                                      bool aIsConference)
-{
-  for (uint32_t i = 0; i < mListeners.Length(); i++) {
-    mListeners[i]->CallStateChanged(aCallIndex, aCallState, aNumber,
-                                    aIsActive, aIsOutgoing, aIsEmergency,
-                                    aIsConference);
-  }
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::ConferenceCallStateChanged(uint16_t aCallState)
-{
-  for (uint32_t i = 0; i < mListeners.Length(); i++) {
-    mListeners[i]->ConferenceCallStateChanged(aCallState);
-  }
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::EnumerateCallStateComplete()
-{
-  MOZ_CRASH("Not a EnumerateCalls request!");
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::EnumerateCallState(uint32_t aCallIndex,
-                                        uint16_t aCallState,
-                                        const nsAString& aNumber,
-                                        bool aIsActive,
-                                        bool aIsOutgoing,
-                                        bool aIsEmergency,
-                                        bool aIsConference)
-{
-  MOZ_CRASH("Not a EnumerateCalls request!");
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::NotifyCdmaCallWaiting(const nsAString& aNumber)
-{
-  for (uint32_t i = 0; i < mListeners.Length(); i++) {
-    mListeners[i]->NotifyCdmaCallWaiting(aNumber);
-  }
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::NotifyError(int32_t aCallIndex,
-                                 const nsAString& aError)
-{
-  for (uint32_t i = 0; i < mListeners.Length(); i++) {
-    mListeners[i]->NotifyError(aCallIndex, aError);
-  }
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-TelephonyIPCProvider::SupplementaryServiceNotification(int32_t aCallIndex,
-                                                      uint16_t aNotification)
-{
-  for (uint32_t i = 0; i < mListeners.Length(); i++) {
-    mListeners[i]->SupplementaryServiceNotification(aCallIndex, aNotification);
-  }
-  return NS_OK;
-}
deleted file mode 100644
--- a/dom/telephony/ipc/TelephonyIPCProvider.h
+++ /dev/null
@@ -1,37 +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/. */
-
-#ifndef mozilla_dom_telephony_TelephonyIPCProvider_h
-#define mozilla_dom_telephony_TelephonyIPCProvider_h
-
-#include "mozilla/dom/telephony/TelephonyCommon.h"
-#include "mozilla/Attributes.h"
-#include "nsITelephonyProvider.h"
-
-BEGIN_TELEPHONY_NAMESPACE
-
-class PTelephonyChild;
-
-class TelephonyIPCProvider MOZ_FINAL : public nsITelephonyProvider
-                                     , public nsITelephonyListener
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSITELEPHONYPROVIDER
-  NS_DECL_NSITELEPHONYLISTENER
-
-  TelephonyIPCProvider();
-
-protected:
-  virtual ~TelephonyIPCProvider();
-
-private:
-  nsTArray<nsCOMPtr<nsITelephonyListener> > mListeners;
-  PTelephonyChild* mPTelephonyChild;
-};
-
-END_TELEPHONY_NAMESPACE
-
-#endif // mozilla_dom_telephony_TelephonyIPCProvider_h
deleted file mode 100644
--- a/dom/telephony/ipc/TelephonyParent.cpp
+++ /dev/null
@@ -1,448 +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 "mozilla/dom/telephony/TelephonyParent.h"
-
-USING_TELEPHONY_NAMESPACE
-
-/*******************************************************************************
- * TelephonyParent
- ******************************************************************************/
-
-NS_IMPL_ISUPPORTS1(TelephonyParent, nsITelephonyListener)
-
-TelephonyParent::TelephonyParent()
-  : mActorDestroyed(false)
-  , mRegistered(false)
-{
-}
-
-void
-TelephonyParent::ActorDestroy(ActorDestroyReason why)
-{
-  // The child process could die before this asynchronous notification, in which
-  // case ActorDestroy() was called and mActorDestroyed is set to true. Return
-  // an error here to avoid sending a message to the dead process.
-  mActorDestroyed = true;
-
-  // Try to unregister listener if we're still registered.
-  RecvUnregisterListener();
-}
-
-bool
-TelephonyParent::RecvPTelephonyRequestConstructor(PTelephonyRequestParent* aActor)
-{
-  TelephonyRequestParent* actor = static_cast<TelephonyRequestParent*>(aActor);
-
-  return actor->DoRequest();
-}
-
-PTelephonyRequestParent*
-TelephonyParent::AllocPTelephonyRequestParent()
-{
-  TelephonyRequestParent* actor = new TelephonyRequestParent();
-  // Add an extra ref for IPDL. Will be released in
-  // TelephonyParent::DeallocPTelephonyRequestParent().
-  NS_ADDREF(actor);
-
-  return actor;
-}
-
-bool
-TelephonyParent::DeallocPTelephonyRequestParent(PTelephonyRequestParent* aActor)
-{
-  // TelephonyRequestParent is refcounted, must not be freed manually.
-  static_cast<TelephonyRequestParent*>(aActor)->Release();
-  return true;
-}
-
-bool
-TelephonyParent::Recv__delete__()
-{
-  return true; // Unregister listener in TelephonyParent::ActorDestroy().
-}
-
-bool
-TelephonyParent::RecvRegisterListener()
-{
-  NS_ENSURE_TRUE(!mRegistered, true);
-
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  mRegistered = NS_SUCCEEDED(provider->RegisterListener(this));
-  return true;
-}
-
-bool
-TelephonyParent::RecvUnregisterListener()
-{
-  NS_ENSURE_TRUE(mRegistered, true);
-
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  mRegistered = !NS_SUCCEEDED(provider->UnregisterListener(this));
-  return true;
-}
-
-bool
-TelephonyParent::RecvDialCall(const nsString& aNumber,
-                              const bool& aIsEmergency)
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->Dial(aNumber, aIsEmergency);
-  return true;
-}
-
-bool
-TelephonyParent::RecvHangUpCall(const uint32_t& aCallIndex)
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->HangUp(aCallIndex);
-  return true;
-}
-
-bool
-TelephonyParent::RecvAnswerCall(const uint32_t& aCallIndex)
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->AnswerCall(aCallIndex);
-  return true;
-}
-
-bool
-TelephonyParent::RecvRejectCall(const uint32_t& aCallIndex)
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->RejectCall(aCallIndex);
-  return true;
-}
-
-bool
-TelephonyParent::RecvHoldCall(const uint32_t& aCallIndex)
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->HoldCall(aCallIndex);
-  return true;
-}
-
-bool
-TelephonyParent::RecvResumeCall(const uint32_t& aCallIndex)
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->ResumeCall(aCallIndex);
-  return true;
-}
-
-bool
-TelephonyParent::RecvConferenceCall()
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->ConferenceCall();
-  return true;
-}
-
-bool
-TelephonyParent::RecvSeparateCall(const uint32_t& aCallState)
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->SeparateCall(aCallState);
-  return true;
-}
-
-bool
-TelephonyParent::RecvHoldConference()
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->HoldConference();
-  return true;
-}
-
-bool
-TelephonyParent::RecvResumeConference()
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->ResumeConference();
-  return true;
-}
-
-bool
-TelephonyParent::RecvStartTone(const nsString& aTone)
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->StartTone(aTone);
-  return true;
-}
-
-bool
-TelephonyParent::RecvStopTone()
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->StopTone();
-  return true;
-}
-
-bool
-TelephonyParent::RecvGetMicrophoneMuted(bool* aMuted)
-{
-  *aMuted = false;
-
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->GetMicrophoneMuted(aMuted);
-  return true;
-}
-
-bool
-TelephonyParent::RecvSetMicrophoneMuted(const bool& aMuted)
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->SetMicrophoneMuted(aMuted);
-  return true;
-}
-
-bool
-TelephonyParent::RecvGetSpeakerEnabled(bool* aEnabled)
-{
-  *aEnabled = false;
-
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->GetSpeakerEnabled(aEnabled);
-  return true;
-}
-
-bool
-TelephonyParent::RecvSetSpeakerEnabled(const bool& aEnabled)
-{
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  NS_ENSURE_TRUE(provider, true);
-
-  provider->SetSpeakerEnabled(aEnabled);
-  return true;
-}
-
-// nsITelephonyListener
-
-NS_IMETHODIMP
-TelephonyParent::CallStateChanged(uint32_t aCallIndex,
-                                  uint16_t aCallState,
-                                  const nsAString& aNumber,
-                                  bool aIsActive,
-                                  bool aIsOutgoing,
-                                  bool aIsEmergency,
-                                  bool aIsConference)
-{
-  NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
-  IPCCallStateData data(aCallIndex, aCallState, nsString(aNumber), aIsActive,
-                        aIsOutgoing, aIsEmergency, aIsConference);
-  return SendNotifyCallStateChanged(data) ? NS_OK : NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-TelephonyParent::ConferenceCallStateChanged(uint16_t aCallState)
-{
-  NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
-  return SendNotifyConferenceCallStateChanged(aCallState) ? NS_OK
-                                                          : NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-TelephonyParent::EnumerateCallStateComplete()
-{
-  MOZ_CRASH("Not a EnumerateCalls request!");
-}
-
-NS_IMETHODIMP
-TelephonyParent::EnumerateCallState(uint32_t aCallIndex,
-                                    uint16_t aCallState,
-                                    const nsAString& aNumber,
-                                    bool aIsActive,
-                                    bool aIsOutgoing,
-                                    bool aIsEmergency,
-                                    bool aIsConference)
-{
-  MOZ_CRASH("Not a EnumerateCalls request!");
-}
-
-NS_IMETHODIMP
-TelephonyParent::NotifyCdmaCallWaiting(const nsAString& aNumber)
-{
-  NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
-  return SendNotifyCdmaCallWaiting(nsString(aNumber)) ? NS_OK
-                                                      : NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-TelephonyParent::NotifyError(int32_t aCallIndex,
-                             const nsAString& aError)
-{
-  NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
-  return SendNotifyCallError(aCallIndex, nsString(aError)) ? NS_OK
-                                                           : NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-TelephonyParent::SupplementaryServiceNotification(int32_t aCallIndex,
-                                                  uint16_t aNotification)
-{
-  NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
-  return SendNotifySupplementaryService(aCallIndex, aNotification)
-    ? NS_OK : NS_ERROR_FAILURE;
-}
-
-/*******************************************************************************
- * TelephonyRequestParent
- ******************************************************************************/
-
-NS_IMPL_ISUPPORTS1(TelephonyRequestParent, nsITelephonyListener)
-
-TelephonyRequestParent::TelephonyRequestParent()
-  : mActorDestroyed(false)
-{
-}
-
-void
-TelephonyRequestParent::ActorDestroy(ActorDestroyReason why)
-{
-  // The child process could die before this asynchronous notification, in which
-  // case ActorDestroy() was called and mActorDestroyed is set to true. Return
-  // an error here to avoid sending a message to the dead process.
-  mActorDestroyed = true;
-}
-
-bool
-TelephonyRequestParent::DoRequest()
-{
-  nsresult rv = NS_ERROR_FAILURE;
-
-  nsCOMPtr<nsITelephonyProvider> provider =
-    do_GetService(TELEPHONY_PROVIDER_CONTRACTID);
-  if (provider) {
-    rv = provider->EnumerateCalls(this);
-  }
-
-  if (NS_FAILED(rv)) {
-    return NS_SUCCEEDED(EnumerateCallStateComplete());
-  }
-
-  return true;
-}
-
-// nsITelephonyListener
-
-NS_IMETHODIMP
-TelephonyRequestParent::CallStateChanged(uint32_t aCallIndex,
-                                         uint16_t aCallState,
-                                         const nsAString& aNumber,
-                                         bool aIsActive,
-                                         bool aIsOutgoing,
-                                         bool aIsEmergency,
-                                         bool aIsConference)
-{
-  MOZ_CRASH("Not a TelephonyParent!");
-}
-
-NS_IMETHODIMP
-TelephonyRequestParent::ConferenceCallStateChanged(uint16_t aCallState)
-{
-  MOZ_CRASH("Not a TelephonyParent!");
-}
-
-NS_IMETHODIMP
-TelephonyRequestParent::EnumerateCallStateComplete()
-{
-  NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
-  return Send__delete__(this) ? NS_OK : NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-TelephonyRequestParent::EnumerateCallState(uint32_t aCallIndex,
-                                           uint16_t aCallState,
-                                           const nsAString& aNumber,
-                                           bool aIsActive,
-                                           bool aIsOutgoing,
-                                           bool aIsEmergency,
-                                           bool aIsConference)
-{
-  NS_ENSURE_TRUE(!mActorDestroyed, NS_ERROR_FAILURE);
-
-  IPCCallStateData data(aCallIndex, aCallState, nsString(aNumber), aIsActive,
-                        aIsOutgoing, aIsEmergency, aIsConference);
-  return SendNotifyEnumerateCallState(data) ? NS_OK : NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-TelephonyRequestParent::NotifyCdmaCallWaiting(const nsAString& aNumber)
-{
-  MOZ_CRASH("Not a TelephonyParent!");
-}
-
-NS_IMETHODIMP
-TelephonyRequestParent::NotifyError(int32_t aCallIndex,
-                                    const nsAString& aError)
-{
-  MOZ_CRASH("Not a TelephonyParent!");
-}
-
-NS_IMETHODIMP
-TelephonyRequestParent::SupplementaryServiceNotification(int32_t aCallIndex,
-                                                         uint16_t aNotification)
-{
-  MOZ_CRASH("Not a TelephonyParent!");
-}
deleted file mode 100644
--- a/dom/telephony/ipc/TelephonyParent.h
+++ /dev/null
@@ -1,128 +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/. */
-
-#ifndef mozilla_dom_telephony_TelephonyParent_h
-#define mozilla_dom_telephony_TelephonyParent_h
-
-#include "mozilla/dom/telephony/TelephonyCommon.h"
-#include "mozilla/dom/telephony/PTelephonyParent.h"
-#include "mozilla/dom/telephony/PTelephonyRequestParent.h"
-#include "nsITelephonyProvider.h"
-
-BEGIN_TELEPHONY_NAMESPACE
-
-class TelephonyParent : public PTelephonyParent
-                      , public nsITelephonyListener
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSITELEPHONYLISTENER
-
-  TelephonyParent();
-
-protected:
-  virtual ~TelephonyParent() {}
-
-  virtual void
-  ActorDestroy(ActorDestroyReason why);
-
-  virtual bool
-  RecvPTelephonyRequestConstructor(PTelephonyRequestParent* aActor) MOZ_OVERRIDE;
-
-  virtual PTelephonyRequestParent*
-  AllocPTelephonyRequestParent() MOZ_OVERRIDE;
-
-  virtual bool
-  DeallocPTelephonyRequestParent(PTelephonyRequestParent* aActor) MOZ_OVERRIDE;
-
-  virtual bool
-  Recv__delete__() MOZ_OVERRIDE;
-
-  virtual bool
-  RecvRegisterListener() MOZ_OVERRIDE;
-
-  virtual bool
-  RecvUnregisterListener() MOZ_OVERRIDE;
-
-  virtual bool
-  RecvDialCall(const nsString& aNumber,
-               const bool& aIsEmergency) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvHangUpCall(const uint32_t& aCallIndex) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvAnswerCall(const uint32_t& aCallIndex) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvRejectCall(const uint32_t& aCallIndex) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvHoldCall(const uint32_t& aCallIndex) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvResumeCall(const uint32_t& aCallIndex) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvConferenceCall() MOZ_OVERRIDE;
-
-  virtual bool
-  RecvSeparateCall(const uint32_t& callIndex) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvHoldConference() MOZ_OVERRIDE;
-
-  virtual bool
-  RecvResumeConference() MOZ_OVERRIDE;
-
-  virtual bool
-  RecvStartTone(const nsString& aTone) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvStopTone() MOZ_OVERRIDE;
-
-  virtual bool
-  RecvGetMicrophoneMuted(bool* aMuted) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvSetMicrophoneMuted(const bool& aMuted) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvGetSpeakerEnabled(bool* aEnabled) MOZ_OVERRIDE;
-
-  virtual bool
-  RecvSetSpeakerEnabled(const bool& aEnabled) MOZ_OVERRIDE;
-
-private:
-  bool mActorDestroyed;
-  bool mRegistered;
-};
-
-class TelephonyRequestParent : public PTelephonyRequestParent
-                             , public nsITelephonyListener
-{
-  friend class TelephonyParent;
-
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSITELEPHONYLISTENER
-
-protected:
-  TelephonyRequestParent();
-  virtual ~TelephonyRequestParent() {}
-
-  virtual void
-  ActorDestroy(ActorDestroyReason why);
-
-private:
-  bool mActorDestroyed;
-
-  bool
-  DoRequest();
-};
-
-END_TELEPHONY_NAMESPACE
-
-#endif /* mozilla_dom_telephony_TelephonyParent_h */
deleted file mode 100644
--- a/dom/telephony/ipc/TelephonyTypes.ipdlh
+++ /dev/null
@@ -1,24 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-namespace mozilla {
-namespace dom {
-namespace telephony {
-
-struct IPCCallStateData
-{
-  uint32_t callIndex;
-  uint16_t callState;
-  nsString number;
-  bool     isActive;
-  bool     isOutGoing;
-  bool     isEmergency;
-  bool     isConference;
-};
-
-} /* namespace telephony */
-} /* namespace dom */
-} /* namespace mozilla */
--- a/dom/telephony/moz.build
+++ b/dom/telephony/moz.build
@@ -7,52 +7,22 @@
 XPIDL_SOURCES += [
     'nsITelephonyProvider.idl',
 ]
 
 XPIDL_MODULE = 'dom_telephony'
 
 MODULE = 'dom'
 
-EXPORTS.mozilla.dom.telephony += [
-    'CallEvent.h',
-    'CallsList.h',
-    'Telephony.h',
-    'TelephonyCall.h',
-    'TelephonyCallGroup.h',
-    'TelephonyCommon.h',
-    'TelephonyFactory.h',
-    'ipc/TelephonyChild.h',
-    'ipc/TelephonyParent.h',
-]
-
 CPP_SOURCES += [
     'CallEvent.cpp',
     'CallsList.cpp',
     'Telephony.cpp',
     'TelephonyCall.cpp',
     'TelephonyCallGroup.cpp',
-    'TelephonyFactory.cpp',
-    'ipc/TelephonyChild.cpp',
-    'ipc/TelephonyIPCProvider.cpp',
-    'ipc/TelephonyParent.cpp',
 ]
 
-IPDL_SOURCES += [
-    'ipc/PTelephony.ipdl',
-    'ipc/PTelephonyRequest.ipdl',
-    'ipc/TelephonyTypes.ipdlh'
-]
-
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
-    XPIDL_SOURCES += [
-        'nsIGonkTelephonyProvider.idl',
-    ]
-    EXTRA_COMPONENTS += [
-        'gonk/TelephonyProvider.js',
-        'gonk/TelephonyProvider.manifest',
-    ]
-
 FAIL_ON_WARNINGS = True
 
 LIBXUL_LIBRARY = True
 
 LIBRARY_NAME = 'domtelephony_s'
+
deleted file mode 100644
--- a/dom/telephony/nsIGonkTelephonyProvider.idl
+++ /dev/null
@@ -1,31 +0,0 @@
-/* -*- Mode: idl; 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 "nsITelephonyProvider.idl"
-
-%{C++
-#define GONK_TELEPHONY_PROVIDER_CONTRACTID \
-        "@mozilla.org/telephony/gonktelephonyprovider;1"
-%}
-
-[scriptable, uuid(0d106c7e-ba47-48ee-ba48-c92002d401b6)]
-interface nsIGonkTelephonyProvider : nsITelephonyProvider
-{
-  void notifyCallDisconnected(in jsval call);
-
-  void notifyCallError(in long callIndex,
-                       in AString error);
-
-  void notifyCallRing();
-
-  void notifyCallStateChanged(in jsval call);
-
-  void notifyCdmaCallWaiting(in AString number);
-
-  void notifySupplementaryService(in long callIndex,
-                                  in AString notification);
-
-  void notifyConferenceCallStateChanged(in unsigned short state);
-};
--- a/dom/telephony/nsITelephonyProvider.idl
+++ b/dom/telephony/nsITelephonyProvider.idl
@@ -1,15 +1,15 @@
 /* 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 "nsISupports.idl"
 
-[scriptable, uuid(3aa42e77-7c2b-43a1-b105-7be094b0817a)]
+[scriptable, uuid(a5818719-e1b6-4fdc-8551-006055fa9996)]
 interface nsITelephonyListener : nsISupports
 {
   /**
    * Notified when a telephony call changes state.
    *
    * @param callIndex
    *        Call identifier assigned by the RIL.
    * @param callState
@@ -62,24 +62,25 @@ interface nsITelephonyListener : nsISupp
    * @param number
    *        Number of the other party.
    * @param isActive
    *        Indicates whether this call is the active one.
    * @param isOutgoing
    *        Indicates whether this call is outgoing or incoming.
    * @param isConference
    *        Indicates whether this call is a conference call.
+   * @return true to continue enumeration or false to cancel.
    */
-  void enumerateCallState(in unsigned long callIndex,
-                          in unsigned short callState,
-                          in AString number,
-                          in boolean isActive,
-                          in boolean isOutgoing,
-                          in boolean isEmergency,
-                          in boolean isConference);
+  boolean enumerateCallState(in unsigned long callIndex,
+                             in unsigned short callState,
+                             in AString number,
+                             in boolean isActive,
+                             in boolean isOutgoing,
+                             in boolean isEmergency,
+                             in boolean isConference);
 
   /**
    * Notify when RIL receives supplementary service notification.
    *
    * @param callIndex
    *        Call identifier assigned by the RIL. -1 if not specified
    * @param notification
    *        One of the nsITelephonyProvider::NOTIFICATION_* values.
@@ -102,28 +103,21 @@ interface nsITelephonyListener : nsISupp
    * Called when a waiting call comes in CDMA networks.
    *
    * @param number
    *        Number of the other party.
    */
   void notifyCdmaCallWaiting(in AString number);
 };
 
-%{C++
-#define TELEPHONY_PROVIDER_CID \
-  { 0x9cf8aa52, 0x7c1c, 0x4cde, { 0x97, 0x4e, 0xed, 0x2a, 0xa0, 0xe7, 0x35, 0xfa } }
-#define TELEPHONY_PROVIDER_CONTRACTID \
-  "@mozilla.org/telephony/telephonyprovider;1"
-%}
-
 /**
  * XPCOM component (in the content process) that provides the telephony
  * information.
  */
-[scriptable, uuid(effca006-1ca8-47f7-9bab-1323f90a14ec)]
+[scriptable, uuid(45a2f856-4e07-499a-94c6-624f90c3345b)]
 interface nsITelephonyProvider : nsISupports
 {
   const unsigned short CALL_STATE_UNKNOWN = 0;
   const unsigned short CALL_STATE_DIALING = 1;
   const unsigned short CALL_STATE_ALERTING = 2;
   const unsigned short CALL_STATE_CONNECTING = 3;
   const unsigned short CALL_STATE_CONNECTED = 4;
   const unsigned short CALL_STATE_HOLDING = 5;
@@ -136,30 +130,30 @@ interface nsITelephonyProvider : nsISupp
   const unsigned short NOTIFICATION_REMOTE_HELD = 0;
   const unsigned short NOTIFICATION_REMOTE_RESUMED = 1;
 
   /**
    * Called when a content process registers receiving unsolicited messages from
    * RadioInterfaceLayer in the chrome process. Only a content process that has
    * the 'telephony' permission is allowed to register.
    */
-  void registerListener(in nsITelephonyListener listener);
-  void unregisterListener(in nsITelephonyListener listener);
+  void registerTelephonyMsg(in nsITelephonyListener listener);
+  void unregisterTelephonyMsg(in nsITelephonyListener listener);
 
   /**
    * Will continue calling listener.enumerateCallState until the listener
    * returns false.
    */
   void enumerateCalls(in nsITelephonyListener listener);
 
   /**
    * Functionality for making and managing phone calls.
    */
-  void dial(in DOMString number,
-            in boolean isEmergency);
+  void dial(in DOMString number);
+  void dialEmergency(in DOMString number);
   void hangUp(in unsigned long callIndex);
 
   void startTone(in DOMString dtmfChar);
   void stopTone();
 
   void answerCall(in unsigned long callIndex);
   void rejectCall(in unsigned long callIndex);
   void holdCall(in unsigned long callIndex);
--- a/dom/tests/mochitest/general/test_interfaces.html
+++ b/dom/tests/mochitest/general/test_interfaces.html
@@ -97,17 +97,17 @@ var interfaceNamesInGlobalScope =
     "BlobEvent",
     {name: "BluetoothAdapter", b2g: true},
     {name: "BluetoothDevice", b2g: true},
     {name: "BluetoothDeviceEvent", b2g: true},
     {name: "BluetoothManager", b2g: true},
     {name: "BluetoothStatusChangedEvent", b2g: true},
     {name: "BoxObject", xbl: true},
     {name: "BrowserFeedWriter", desktop: true},
-    "CallEvent",
+    {name: "CallEvent", b2g: true},
     "CameraCapabilities",
     "CameraControl",
     "CameraManager",
     "CanvasGradient",
     "CanvasPattern",
     "CanvasRenderingContext2D",
     "CaretPosition",
     "CDATASection",
@@ -526,19 +526,19 @@ var interfaceNamesInGlobalScope =
     "SVGTransform",
     "SVGTransformList",
     "SVGTSpanElement",
     "SVGUnitTypes",
     "SVGUseElement",
     "SVGViewElement",
     "SVGZoomAndPan",
     "SVGZoomEvent",
-    "Telephony",
-    "TelephonyCall",
-    "TelephonyCallGroup",
+    {name: "Telephony", b2g: true},
+    {name: "TelephonyCall", b2g: true},
+    {name: "TelephonyCallGroup", b2g: true},
     "Text",
     "TextDecoder",
     "TextEncoder",
     "TextMetrics",
     "TimeEvent",
     "TimeRanges",
     "Touch",
     "TouchEvent",
--- a/dom/webidl/WebIDL.mk
+++ b/dom/webidl/WebIDL.mk
@@ -29,18 +29,16 @@ webidl_files = \
   AudioProcessingEvent.webidl \
   AudioStreamTrack.webidl \
   BarProp.webidl \
   BatteryManager.webidl \
   BeforeUnloadEvent.webidl \
   BiquadFilterNode.webidl \
   Blob.webidl \
   BrowserElementDictionaries.webidl \
-  CallEvent.webidl \
-  CallsList.webidl \
   CameraControl.webidl \
   CameraManager.webidl \
   CanvasRenderingContext2D.webidl \
   CaretPosition.webidl \
   CDATASection.webidl \
   ChannelMergerNode.webidl \
   ChannelSplitterNode.webidl \
   CharacterData.webidl \
@@ -356,19 +354,16 @@ webidl_files = \
   SVGTransformList.webidl \
   SVGTSpanElement.webidl \
   SVGUnitTypes.webidl \
   SVGURIReference.webidl \
   SVGUseElement.webidl \
   SVGViewElement.webidl \
   SVGZoomAndPan.webidl \
   SVGZoomEvent.webidl \
-  Telephony.webidl \
-  TelephonyCall.webidl \
-  TelephonyCallGroup.webidl \
   Text.webidl \
   TextDecoder.webidl \
   TextEncoder.webidl \
   TextTrack.webidl \
   TextTrackCueList.webidl \
   TextTrackList.webidl \
   TimeEvent.webidl \
   TimeRanges.webidl \
@@ -445,18 +440,22 @@ endif
 ifdef MOZ_GAMEPAD
 webidl_files += \
   Gamepad.webidl \
   $(NULL)
 endif
 
 ifdef MOZ_B2G_RIL
 webidl_files += \
+  CallsList.webidl \
   MozStkCommandEvent.webidl \
   MozVoicemail.webidl \
+  Telephony.webidl \
+  TelephonyCall.webidl \
+  TelephonyCallGroup.webidl \
   $(NULL)
 endif
 
 webidl_files += \
   BlobEvent.webidl \
   CloseEvent.webidl \
   CustomEvent.webidl \
   DeviceLightEvent.webidl \
@@ -491,16 +490,17 @@ webidl_files += \
   BluetoothDeviceEvent.webidl \
   BluetoothManager.webidl \
   BluetoothStatusChangedEvent.webidl \
   $(NULL)
 endif
 
 ifdef MOZ_B2G_RIL
 webidl_files += \
+  CallEvent.webidl \
   CFStateChangeEvent.webidl \
   DataErrorEvent.webidl \
   IccCardLockErrorEvent.webidl \
   MozCellBroadcast.webidl \
   MozCellBroadcastEvent.webidl \
   MozEmergencyCbModeEvent.webidl \
   MozOtaStatusEvent.webidl \
   MozVoicemailEvent.webidl \
--- a/layout/build/Makefile.in
+++ b/layout/build/Makefile.in
@@ -54,17 +54,16 @@ SHARED_LIBRARY_LIBS = \
 	$(DEPTH)/dom/src/jsurl/$(LIB_PREFIX)jsurl_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/src/storage/$(LIB_PREFIX)jsdomstorage_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/src/offline/$(LIB_PREFIX)jsdomoffline_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/src/geolocation/$(LIB_PREFIX)jsdomgeolocation_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/audiochannel/$(LIB_PREFIX)domaudiochannel_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/promise/$(LIB_PREFIX)dompromise_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/src/notification/$(LIB_PREFIX)jsdomnotification_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/system/$(LIB_PREFIX)domsystem_s.$(LIB_SUFFIX) \
-	$(DEPTH)/dom/telephony/$(LIB_PREFIX)domtelephony_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/workers/$(LIB_PREFIX)domworkers_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/indexedDB/$(LIB_PREFIX)dom_indexeddb_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/indexedDB/ipc/$(LIB_PREFIX)dom_indexeddb_ipc_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/browser-element/$(LIB_PREFIX)dom_browserelement_s.$(LIB_SUFFIX) \
 	$(DEPTH)/dom/time/$(LIB_PREFIX)dom_time_s.$(LIB_SUFFIX) \
 	$(DEPTH)/editor/libeditor/text/$(LIB_PREFIX)texteditor_s.$(LIB_SUFFIX) \
 	$(DEPTH)/editor/libeditor/base/$(LIB_PREFIX)editorbase_s.$(LIB_SUFFIX) \
 	$(DEPTH)/parser/html/$(LIB_PREFIX)html5p_s.$(LIB_SUFFIX) \
@@ -125,16 +124,17 @@ ifdef MOZ_B2G_BT #{
 SHARED_LIBRARY_LIBS += $(DEPTH)/dom/bluetooth/$(LIB_PREFIX)dombluetooth_s.$(LIB_SUFFIX)
 endif #}
 
 SHARED_LIBRARY_LIBS	+= $(DEPTH)/dom/camera/$(LIB_PREFIX)domcamera_s.$(LIB_SUFFIX)
 
 ifdef MOZ_B2G_RIL #{
 SHARED_LIBRARY_LIBS	+= \
   $(DEPTH)/dom/system/gonk/$(LIB_PREFIX)domsystemgonk_s.$(LIB_SUFFIX) \
+  $(DEPTH)/dom/telephony/$(LIB_PREFIX)domtelephony_s.$(LIB_SUFFIX) \
   $(DEPTH)/dom/icc/src/$(LIB_PREFIX)dom_icc_s.$(LIB_SUFFIX) \
   $(DEPTH)/dom/cellbroadcast/src/$(LIB_PREFIX)dom_cellbroadcast_s.$(LIB_SUFFIX) \
   $(DEPTH)/dom/voicemail/$(LIB_PREFIX)domvoicemail_s.$(LIB_SUFFIX) \
   $(NULL)
 endif #}
 
 ifdef MOZ_OGG
 SHARED_LIBRARY_LIBS 	+= \
--- a/layout/build/nsLayoutModule.cpp
+++ b/layout/build/nsLayoutModule.cpp
@@ -225,28 +225,24 @@ static void Shutdown();
 #include "nsMixedContentBlocker.h"
 
 #include "AudioChannelService.h"
 
 #include "mozilla/dom/power/PowerManagerService.h"
 #include "mozilla/dom/alarm/AlarmHalService.h"
 #include "mozilla/dom/time/TimeService.h"
 
-#include "mozilla/dom/telephony/TelephonyFactory.h"
-#include "nsITelephonyProvider.h"
-
 #ifdef MOZ_WIDGET_GONK
 #include "GonkGPSGeolocationProvider.h"
 #endif
 #include "MediaManager.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::dom::mobilemessage;
-using namespace mozilla::dom::telephony;
 using mozilla::dom::alarm::AlarmHalService;
 using mozilla::dom::indexedDB::IndexedDatabaseManager;
 using mozilla::dom::power::PowerManagerService;
 using mozilla::dom::quota::QuotaManager;
 using mozilla::dom::TCPSocketChild;
 using mozilla::dom::TCPSocketParent;
 using mozilla::dom::TCPServerSocketChild;
 using mozilla::dom::time::TimeService;
@@ -337,18 +333,16 @@ NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR
                                          GonkGPSGeolocationProvider::GetSingleton)
 // Since the nsVolumeService constructor calls into nsIPowerManagerService,
 // we need it to be constructed sometime after nsIPowerManagerService.
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsVolumeService,
                                          nsVolumeService::GetSingleton)
 #endif
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIMediaManagerService,
                                          MediaManager::GetInstance)
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsITelephonyProvider,
-                                         TelephonyFactory::CreateTelephonyProvider)
 
 //-----------------------------------------------------------------------------
 
 // Per bug 209804, it is necessary to observe the "xpcom-shutdown" event and
 // perform shutdown of the layout modules at that time instead of waiting for
 // our module destructor to run.  If we do not do this, then we risk holding
 // references to objects in other component libraries that have already been
 // shutdown (and possibly unloaded if 60709 is ever fixed).
@@ -812,17 +806,16 @@ NS_DEFINE_NAMED_CID(NS_GAMEPAD_TEST_CID)
 #ifdef MOZ_WEBSPEECH
 NS_DEFINE_NAMED_CID(NS_FAKE_SPEECH_RECOGNITION_SERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_SYNTHVOICEREGISTRY_CID);
 #endif
 
 #ifdef ACCESSIBILITY
 NS_DEFINE_NAMED_CID(NS_ACCESSIBILITY_SERVICE_CID);
 #endif
-NS_DEFINE_NAMED_CID(TELEPHONY_PROVIDER_CID);
 
 static nsresult
 CreateWindowCommandTableConstructor(nsISupports *aOuter,
                                     REFNSIID aIID, void **aResult)
 {
   nsresult rv;
   nsCOMPtr<nsIControllerCommandTable> commandTable =
       do_CreateInstance(NS_CONTROLLERCOMMANDTABLE_CONTRACTID, &rv);
@@ -1095,17 +1088,16 @@ static const mozilla::Module::CIDEntry k
 #endif
   { &kNS_MEDIAMANAGERSERVICE_CID, false, NULL, nsIMediaManagerServiceConstructor },
 #ifdef MOZ_GAMEPAD
   { &kNS_GAMEPAD_TEST_CID, false, NULL, GamepadServiceTestConstructor },
 #endif
 #ifdef ACCESSIBILITY
   { &kNS_ACCESSIBILITY_SERVICE_CID, false, NULL, CreateA11yService },
 #endif
-  { &kTELEPHONY_PROVIDER_CID, false, NULL, nsITelephonyProviderConstructor },
   { NULL }
 };
 
 static const mozilla::Module::ContractIDEntry kLayoutContracts[] = {
   XPCONNECT_CONTRACTS
   { "@mozilla.org/layout/xul-boxobject;1", &kNS_BOXOBJECT_CID },
 #ifdef MOZ_XUL
   { "@mozilla.org/layout/xul-boxobject-listbox;1", &kNS_LISTBOXOBJECT_CID },
@@ -1251,17 +1243,16 @@ static const mozilla::Module::ContractID
 #ifdef MOZ_GAMEPAD
   { NS_GAMEPAD_TEST_CONTRACTID, &kNS_GAMEPAD_TEST_CID },
 #endif
   { MEDIAMANAGERSERVICE_CONTRACTID, &kNS_MEDIAMANAGERSERVICE_CID },
 #ifdef ACCESSIBILITY
   { "@mozilla.org/accessibilityService;1", &kNS_ACCESSIBILITY_SERVICE_CID },
   { "@mozilla.org/accessibleRetrieval;1", &kNS_ACCESSIBILITY_SERVICE_CID },
 #endif
-  { TELEPHONY_PROVIDER_CONTRACTID, &kTELEPHONY_PROVIDER_CID },
   { NULL }
 };
 
 static const mozilla::Module::CategoryEntry kLayoutCategories[] = {
   XPCONNECT_CATEGORIES
   { "content-policy", NS_DATADOCUMENTCONTENTPOLICY_CONTRACTID, NS_DATADOCUMENTCONTENTPOLICY_CONTRACTID },
   { "content-policy", NS_NODATAPROTOCOLCONTENTPOLICY_CONTRACTID, NS_NODATAPROTOCOLCONTENTPOLICY_CONTRACTID },
   { "content-policy", "CSPService", CSPSERVICE_CONTRACTID },