Backed out changeset d405928cb934 (bug 999577) and changeset 940d041073c7 (bug 938186) for xpcshell failures.
authorRyan VanderMeulen <ryanvm@gmail.com>
Thu, 05 Jun 2014 13:32:04 -0400
changeset 199323 b0dbdb35eacef702d9ee3759ee9b724f6cea62fb
parent 199322 b1d854aec0e3f4c9968130280f3973e3eb5eb70e
child 199324 a010a557a1b59f0b576c094eac2f3cca70237c69
push idunknown
push userunknown
push dateunknown
bugs999577, 938186
milestone32.0a1
backs outd405928cb93469b7559d9599a719dae9ba670586
Backed out changeset d405928cb934 (bug 999577) and changeset 940d041073c7 (bug 938186) for xpcshell failures. CLOSED TREE
browser/base/content/test/general/browser_sanitizeDialog.js
browser/components/preferences/advanced.js
browser/components/preferences/in-content/advanced.js
browser/devtools/shared/AppCacheUtils.jsm
docshell/shistory/src/nsSHistory.cpp
dom/src/offline/nsDOMOfflineResourceList.cpp
dom/tests/mochitest/ajax/offline/offlineTests.js
gfx/thebes/gfxUserFontSet.cpp
netwerk/cache/nsCacheService.cpp
netwerk/cache/nsCacheService.h
netwerk/cache/nsICacheService.idl
netwerk/cache2/AppCacheStorage.cpp
netwerk/cache2/CacheEntry.cpp
netwerk/cache2/CacheEntry.h
netwerk/cache2/OldWrappers.cpp
netwerk/cache2/nsICacheStorage.idl
netwerk/test/TestAsyncCache.js
netwerk/test/TestCacheCollisions.js
netwerk/test/TestCachePerformance.js
netwerk/test/TestCacheService.cpp
netwerk/test/TestCacheVisitor.js
netwerk/test/TestDiskCache.js
netwerk/test/TestMCTransport.cpp
netwerk/test/TestObjectCache.js
netwerk/test/unit/test_bug767025.js
netwerk/test/unit/test_cache2-01f-basic-async.js
netwerk/test/unit/test_cache2-24-force-async.js
netwerk/test/unit/xpcshell.ini
toolkit/components/places/AsyncFaviconHelpers.cpp
uriloader/prefetch/OfflineCacheUpdateChild.h
uriloader/prefetch/nsOfflineCacheUpdate.cpp
uriloader/prefetch/nsOfflineCacheUpdate.h
uriloader/prefetch/nsOfflineCacheUpdateService.cpp
--- a/browser/base/content/test/general/browser_sanitizeDialog.js
+++ b/browser/base/content/test/general/browser_sanitizeDialog.js
@@ -13,17 +13,16 @@
  * test checks the UI of the dialog and makes sure it's correctly connected to
  * the sanitize timespan code.
  *
  * Some of this code, especially the history creation parts, was taken from
  * browser/base/content/test/general/browser_sanitize-timespans.js.
  */
 
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
-let {LoadContextInfo} = Cu.import("resource://gre/modules/LoadContextInfo.jsm", {});
 
 XPCOMUtils.defineLazyModuleGetter(this, "FormHistory",
                                   "resource://gre/modules/FormHistory.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "Downloads",
                                   "resource://gre/modules/Downloads.jsm");
 
 let tempScope = {};
 Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader)
@@ -563,64 +562,68 @@ var gAllTests = [
 
     // Give www.example.com privileges to store offline data
     var pm = Cc["@mozilla.org/permissionmanager;1"]
              .getService(Ci.nsIPermissionManager);
     pm.addFromPrincipal(principal, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION);
     pm.addFromPrincipal(principal, "offline-app", Ci.nsIOfflineCacheUpdateService.ALLOW_NO_WARN);
 
     // Store something to the offline cache
-    var appcacheserv = Cc["@mozilla.org/network/application-cache-service;1"]
-                       .getService(Ci.nsIApplicationCacheService);
-    var appcachegroupid = appcacheserv.buildGroupID(makeURI(URL + "/manifest"), LoadContextInfo.default);
-    var appcache = appcacheserv.createApplicationCache(appcachegroupid);
-
-    var cacheserv = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
-                    .getService(Ci.nsICacheStorageService);
-    var storage = cacheserv.appCacheStorage(LoadContextInfo.default, appcache);
+    const nsICache = Components.interfaces.nsICache;
+    var cs = Components.classes["@mozilla.org/network/cache-service;1"]
+             .getService(Components.interfaces.nsICacheService);
+    var session = cs.createSession(URL + "/manifest", nsICache.STORE_OFFLINE, nsICache.STREAM_BASED);
 
     // Open the dialog
     let wh = new WindowHelper();
     wh.onload = function () {
       this.selectDuration(Sanitizer.TIMESPAN_EVERYTHING);
       // Show details
       this.toggleDetails();
       // Clear only offlineApps
       this.uncheckAllCheckboxes();
       this.checkPrefCheckbox("offlineApps", true);
       this.acceptDialog();
     };
     wh.onunload = function () {
       // Check if the cache has been deleted
       var size = -1;
       var visitor = {
-        onCacheStorageInfo: function (aEntryCount, aConsumption, aCapacity, aDiskDirectory)
+        visitDevice: function (deviceID, deviceInfo)
         {
-          size = aConsumption;
+          if (deviceID == "offline")
+            size = deviceInfo.totalSize;
+
+          // Do not enumerate entries
+          return false;
+        },
+
+        visitEntry: function (deviceID, entryInfo)
+        {
+          // Do not enumerate entries.
+          return false;
         }
       };
-      storage.asyncVisitStorage(visitor, false);
-      // Offline cache visit happens synchronously, since it's forwarded to the old code
+      cs.visitEntries(visitor);
       is(size, 0, "offline application cache entries evicted");
     };
 
     var cacheListener = {
-      onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
-      onCacheEntryAvailable: function (entry, isnew, appcache, status) {
+      onCacheEntryAvailable: function (entry, access, status) {
         is(status, Cr.NS_OK);
         var stream = entry.openOutputStream(0);
         var content = "content";
         stream.write(content, content.length);
         stream.close();
         entry.close();
         wh.open();
       }
     };
 
-    storage.asyncOpenURI(makeURI(URL), "", Ci.nsICacheStorage.OPEN_TRUNCATE, cacheListener);
+    session.asyncOpenCacheEntry(URL, nsICache.ACCESS_READ_WRITE, cacheListener);
   },
   function () {
     // Test for offline apps permission deletion
 
     // Prepare stuff, we will work with www.example.com
     var URL = "http://www.example.com";
 
     var ios = Cc["@mozilla.org/network/io-service;1"]
--- a/browser/components/preferences/advanced.js
+++ b/browser/components/preferences/advanced.js
@@ -324,31 +324,40 @@ var gAdvancedPane = {
                 .getService(Components.interfaces.nsICacheStorageService);
     cacheService.asyncGetDiskConsumption(this.observer);
   },
 
   // Retrieves the amount of space currently used by offline cache
   updateActualAppCacheSize: function ()
   {
     var visitor = {
-      onCacheStorageInfo: function (aEntryCount, aConsumption, aCapacity, aDiskDirectory)
+      visitDevice: function (deviceID, deviceInfo)
       {
-        var actualSizeLabel = document.getElementById("actualAppCacheSize");
-        var sizeStrings = DownloadUtils.convertByteUnits(aConsumption);
-        var prefStrBundle = document.getElementById("bundlePreferences");
-        var sizeStr = prefStrBundle.getFormattedString("actualAppCacheSize", sizeStrings);
-        actualSizeLabel.value = sizeStr;
+        if (deviceID == "offline") {
+          var actualSizeLabel = document.getElementById("actualAppCacheSize");
+          var sizeStrings = DownloadUtils.convertByteUnits(deviceInfo.totalSize);
+          var prefStrBundle = document.getElementById("bundlePreferences");
+          var sizeStr = prefStrBundle.getFormattedString("actualAppCacheSize", sizeStrings);
+          actualSizeLabel.value = sizeStr;
+        }
+        // Do not enumerate entries
+        return false;
+      },
+
+      visitEntry: function (deviceID, entryInfo)
+      {
+        // Do not enumerate entries.
+        return false;
       }
     };
 
     var cacheService =
-      Components.classes["@mozilla.org/netwerk/cache-storage-service;1"]
-                .getService(Components.interfaces.nsICacheStorageService);
-    var storage = cacheService.appCacheStorage(LoadContextInfo.default, null);
-    storage.asyncVisitStorage(visitor, false);
+      Components.classes["@mozilla.org/network/cache-service;1"]
+                .getService(Components.interfaces.nsICacheService);
+    cacheService.visitEntries(visitor);
   },
 
   updateCacheSizeUI: function (smartSizeEnabled)
   {
     document.getElementById("useCacheBefore").disabled = smartSizeEnabled;
     document.getElementById("cacheSize").disabled = smartSizeEnabled;
     document.getElementById("useCacheAfter").disabled = smartSizeEnabled;
   },
--- a/browser/components/preferences/in-content/advanced.js
+++ b/browser/components/preferences/in-content/advanced.js
@@ -309,31 +309,40 @@ var gAdvancedPane = {
                 .getService(Components.interfaces.nsICacheStorageService);
     cacheService.asyncGetDiskConsumption(this.observer);
   },
 
   // Retrieves the amount of space currently used by offline cache
   updateActualAppCacheSize: function ()
   {
     var visitor = {
-      onCacheStorageInfo: function (aEntryCount, aConsumption, aCapacity, aDiskDirectory)
+      visitDevice: function (deviceID, deviceInfo)
       {
-        var actualSizeLabel = document.getElementById("actualAppCacheSize");
-        var sizeStrings = DownloadUtils.convertByteUnits(aConsumption);
-        var prefStrBundle = document.getElementById("bundlePreferences");
-        var sizeStr = prefStrBundle.getFormattedString("actualAppCacheSize", sizeStrings);
-        actualSizeLabel.value = sizeStr;
+        if (deviceID == "offline") {
+          var actualSizeLabel = document.getElementById("actualAppCacheSize");
+          var sizeStrings = DownloadUtils.convertByteUnits(deviceInfo.totalSize);
+          var prefStrBundle = document.getElementById("bundlePreferences");
+          var sizeStr = prefStrBundle.getFormattedString("actualAppCacheSize", sizeStrings);
+          actualSizeLabel.textContent = sizeStr;
+        }
+        // Do not enumerate entries
+        return false;
+      },
+
+      visitEntry: function (deviceID, entryInfo)
+      {
+        // Do not enumerate entries.
+        return false;
       }
     };
 
     var cacheService =
-      Components.classes["@mozilla.org/netwerk/cache-storage-service;1"]
-                .getService(Components.interfaces.nsICacheStorageService);
-    var storage = cacheService.appCacheStorage(LoadContextInfo.default, null);
-    storage.asyncVisitStorage(visitor, false);
+      Components.classes["@mozilla.org/network/cache-service;1"]
+                .getService(Components.interfaces.nsICacheService);
+    cacheService.visitEntries(visitor);
   },
 
   updateCacheSizeUI: function (smartSizeEnabled)
   {
     document.getElementById("useCacheBefore").disabled = smartSizeEnabled;
     document.getElementById("cacheSize").disabled = smartSizeEnabled;
     document.getElementById("useCacheAfter").disabled = smartSizeEnabled;
   },
--- a/browser/devtools/shared/AppCacheUtils.jsm
+++ b/browser/devtools/shared/AppCacheUtils.jsm
@@ -24,17 +24,16 @@
  */
 
 "use strict";
 
 const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
 
 let { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
 let { Services }   = Cu.import("resource://gre/modules/Services.jsm", {});
-let { LoadContextInfo } = Cu.import("resource://gre/modules/LoadContextInfo.jsm", {});
 let { Promise: promise } = Cu.import("resource://gre/modules/Promise.jsm", {});
 
 this.EXPORTED_SYMBOLS = ["AppCacheUtils"];
 
 function AppCacheUtils(documentOrUri) {
   this._parseManifest = this._parseManifest.bind(this);
 
   if (documentOrUri) {
@@ -243,58 +242,80 @@ AppCacheUtils.prototype = {
 
   listEntries: function ACU_show(searchTerm) {
     if (!Services.prefs.getBoolPref("browser.cache.disk.enable")) {
       throw new Error(l10n.GetStringFromName("cacheDisabled"));
     }
 
     let entries = [];
 
-    let appCacheStorage = Services.cache2.appCacheStorage(LoadContextInfo.default, null);
-    appCacheStorage.asyncVisitStorage({
-      onCacheStorageInfo: function() {},
+    Services.cache.visitEntries({
+      visitDevice: function(deviceID, deviceInfo) {
+        return true;
+      },
 
-      onCacheEntryInfo: function(aURI, aIdEnhance, aDataSize, aFetchCount, aLastModifiedTime, aExpirationTime) {
-        let lowerKey = aURI.asciiSpec.toLowerCase();
+      visitEntry: function(deviceID, entryInfo) {
+        if (entryInfo.deviceID == "offline") {
+          let entry = {};
+          let lowerKey = entryInfo.key.toLowerCase();
 
-        if (searchTerm && lowerKey.indexOf(searchTerm.toLowerCase()) == -1) {
-          return;
-        }
+          if (searchTerm && lowerKey.indexOf(searchTerm.toLowerCase()) == -1) {
+            return true;
+          }
 
-        if (aIdEnhance) {
-          aIdEnhance += ":";
+          for (let [key, value] of Iterator(entryInfo)) {
+            if (key == "QueryInterface") {
+              continue;
+            }
+            if (key == "clientID") {
+              entry.key = entryInfo.key;
+            }
+            if (key == "expirationTime" || key == "lastFetched" || key == "lastModified") {
+              value = new Date(value * 1000);
+            }
+            entry[key] = value;
+          }
+          entries.push(entry);
         }
-
-        let entry = {
-          "deviceID": "offline",
-          "key": aIdEnhance + aURI.asciiSpec,
-          "fetchCount": aFetchCount,
-          "lastFetched": null,
-          "lastModified": new Date(aLastModifiedTime * 1000),
-          "expirationTime": new Date(aExpirationTime * 1000),
-          "dataSize": aDataSize
-        };
-
-        entries.push(entry);
         return true;
       }
-    }, true);
+    });
 
     if (entries.length === 0) {
       throw new Error(l10n.GetStringFromName("noResults"));
     }
     return entries;
   },
 
   viewEntry: function ACU_viewEntry(key) {
-    let wm = Cc["@mozilla.org/appshell/window-mediator;1"]
-               .getService(Ci.nsIWindowMediator);
-    let win = wm.getMostRecentWindow("navigator:browser");
-    win.gBrowser.selectedTab = win.gBrowser.addTab(
-      "about:cache-entry?storage=appcache&context=&eid=&uri=" + key);
+    let uri;
+
+    Services.cache.visitEntries({
+      visitDevice: function(deviceID, deviceInfo) {
+        return true;
+      },
+
+      visitEntry: function(deviceID, entryInfo) {
+        if (entryInfo.deviceID == "offline" && entryInfo.key == key) {
+          uri = "about:cache-entry?client=" + entryInfo.clientID +
+                "&sb=1&key=" + entryInfo.key;
+          return false;
+        }
+        return true;
+      }
+    });
+
+    if (uri) {
+      let wm = Cc["@mozilla.org/appshell/window-mediator;1"]
+                 .getService(Ci.nsIWindowMediator);
+      let win = wm.getMostRecentWindow("navigator:browser");
+      win.gBrowser.selectedTab = win.gBrowser.addTab(uri);
+    } else {
+      return l10n.GetStringFromName("entryNotFound");
+    }
   },
 
   clearAll: function ACU_clearAll() {
     Services.cache.evictEntries(Ci.nsICache.STORE_OFFLINE);
   },
 
   _getManifestURI: function ACU__getManifestURI() {
     let deferred = promise.defer();
--- a/docshell/shistory/src/nsSHistory.cpp
+++ b/docshell/shistory/src/nsSHistory.cpp
@@ -14,16 +14,17 @@
 // Interfaces Needed
 #include "nsILayoutHistoryState.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellLoadInfo.h"
 #include "nsISHContainer.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIURI.h"
 #include "nsIContentViewer.h"
+#include "nsICacheService.h"
 #include "nsIObserverService.h"
 #include "prclist.h"
 #include "mozilla/Services.h"
 #include "nsTArray.h"
 #include "nsCOMArray.h"
 #include "nsDocShell.h"
 #include "mozilla/Attributes.h"
 #include "nsISHEntry.h"
@@ -184,17 +185,17 @@ NS_IMPL_ISUPPORTS(nsSHistoryObserver, ns
 
 NS_IMETHODIMP
 nsSHistoryObserver::Observe(nsISupports *aSubject, const char *aTopic,
                             const char16_t *aData)
 {
   if (!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
     nsSHistory::UpdatePrefs();
     nsSHistory::GloballyEvictContentViewers();
-  } else if (!strcmp(aTopic, "cacheservice:empty-cache") ||
+  } else if (!strcmp(aTopic, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID) ||
              !strcmp(aTopic, "memory-pressure")) {
     nsSHistory::GloballyEvictAllContentViewers();
   }
 
   return NS_OK;
 }
 
 namespace {
@@ -364,17 +365,17 @@ nsSHistory::Startup()
     Preferences::AddStrongObservers(gObserver, kObservedPrefs);
 
     nsCOMPtr<nsIObserverService> obsSvc =
       mozilla::services::GetObserverService();
     if (obsSvc) {
       // Observe empty-cache notifications so tahat clearing the disk/memory
       // cache will also evict all content viewers.
       obsSvc->AddObserver(gObserver,
-                          "cacheservice:empty-cache", false);
+                          NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID, false);
 
       // Same for memory-pressure notifications
       obsSvc->AddObserver(gObserver, "memory-pressure", false);
     }
   }
 
   // Initialize the global list of all SHistory objects
   PR_INIT_CLIST(&gSHistoryList);
@@ -385,17 +386,17 @@ nsSHistory::Startup()
 void
 nsSHistory::Shutdown()
 {
   if (gObserver) {
     Preferences::RemoveObservers(gObserver, kObservedPrefs);
     nsCOMPtr<nsIObserverService> obsSvc =
       mozilla::services::GetObserverService();
     if (obsSvc) {
-      obsSvc->RemoveObserver(gObserver, "cacheservice:empty-cache");
+      obsSvc->RemoveObserver(gObserver, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID);
       obsSvc->RemoveObserver(gObserver, "memory-pressure");
     }
     NS_RELEASE(gObserver);
   }
 }
 
 /* Add an entry to the History list at mIndex and 
  * increment the index to point to the new entry
--- a/dom/src/offline/nsDOMOfflineResourceList.cpp
+++ b/dom/src/offline/nsDOMOfflineResourceList.cpp
@@ -8,16 +8,17 @@
 #include "nsIScriptSecurityManager.h"
 #include "nsError.h"
 #include "mozilla/dom/DOMStringList.h"
 #include "nsIPrefetchService.h"
 #include "nsCPrefetchService.h"
 #include "nsNetUtil.h"
 #include "nsNetCID.h"
 #include "nsICacheSession.h"
+#include "nsICacheService.h"
 #include "nsIOfflineCacheUpdate.h"
 #include "nsAutoPtr.h"
 #include "nsContentUtils.h"
 #include "nsIObserverService.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIWebNavigation.h"
 #include "mozilla/dom/OfflineResourceListBinding.h"
 #include "mozilla/EventDispatcher.h"
--- a/dom/tests/mochitest/ajax/offline/offlineTests.js
+++ b/dom/tests/mochitest/ajax/offline/offlineTests.js
@@ -1,14 +1,13 @@
 // Utility functions for offline tests.
 var Cc = SpecialPowers.Cc;
 var Ci = SpecialPowers.Ci;
 var Cu = SpecialPowers.Cu;
 var LoadContextInfo = Cu.import("resource://gre/modules/LoadContextInfo.jsm", {}).LoadContextInfo;
-var CommonUtils = Cu.import("resource://services-common/utils.js", {}).CommonUtils;
 
 const kNetBase = 2152398848; // 0x804B0000
 var NS_ERROR_CACHE_KEY_NOT_FOUND = kNetBase + 61;
 var NS_ERROR_CACHE_KEY_WAIT_FOR_VALIDATION = kNetBase + 64;
 
 // Reading the contents of multiple cache entries asynchronously
 function OfflineCacheContents(urls) {
   this.urls = urls;
@@ -18,24 +17,23 @@ function OfflineCacheContents(urls) {
 OfflineCacheContents.prototype = {
 QueryInterface: function(iid) {
     if (!iid.equals(Ci.nsISupports) &&
         !iid.equals(Ci.nsICacheListener)) {
       throw Cr.NS_ERROR_NO_INTERFACE;
     }
     return this;
   },
-onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
-onCacheEntryAvailable: function(desc, isnew, applicationCache, status) {
+onCacheEntryAvailable: function(desc, accessGranted, status) {
     if (!desc) {
       this.fetch(this.callback);
       return;
     }
 
-    var stream = desc.openInputStream(0);
+    var stream = desc.QueryInterface(Ci.nsICacheEntryDescriptor).openInputStream(0);
     var sstream = Cc["@mozilla.org/scriptableinputstream;1"]
                  .createInstance(SpecialPowers.Ci.nsIScriptableInputStream);
     sstream.init(stream);
     this.contents[desc.key] = sstream.read(sstream.available());
     sstream.close();
     desc.close();
     this.fetch(this.callback);
   },
@@ -46,18 +44,18 @@ fetch: function(callback)
   if (this.urls.length == 0) {
     callback(this.contents);
     return;
   }
 
   var url = this.urls.shift();
   var self = this;
 
-  var cacheStorage = OfflineTest.getActiveStorage();
-  cacheStorage.asyncOpenURI(CommonUtils.makeURI(url), "", Ci.nsICacheStorage.OPEN_READONLY | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, this);
+  var cacheSession = OfflineTest.getActiveSession();
+  cacheSession.asyncOpenCacheEntry(url, Ci.nsICache.ACCESS_READ, this);
 }
 };
 
 var OfflineTest = {
 
 _allowedByDefault: false,
 
 _hasSlave: false,
@@ -252,36 +250,37 @@ failEvent: function(e)
 
 // The offline API as specified has no way to watch the load of a resource
 // added with applicationCache.mozAdd().
 waitForAdd: function(url, onFinished) {
   // Check every half second for ten seconds.
   var numChecks = 20;
 
   var waitForAddListener = {
-    onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
-    onCacheEntryAvailable: function(entry, isnew, applicationCache, status) {
+    onCacheEntryAvailable: function(entry, access, status) {
       if (entry) {
         entry.close();
         onFinished();
         return;
       }
 
       if (--numChecks == 0) {
         onFinished();
         return;
       }
 
       setTimeout(OfflineTest.priv(waitFunc), 500);
     }
   };
 
   var waitFunc = function() {
-    var cacheStorage = OfflineTest.getActiveStorage();
-    cacheStorage.asyncOpenURI(CommonUtils.makeURI(url), "", Ci.nsICacheStorage.OPEN_READONLY | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, waitForAddListener);
+    var cacheSession = OfflineTest.getActiveSession();
+    cacheSession.asyncOpenCacheEntry(url,
+                                     Ci.nsICache.ACCESS_READ,
+                                     waitForAddListener);
   }
 
   setTimeout(this.priv(waitFunc), 500);
 },
 
 manifestURL: function(overload)
 {
   var manifestURLspec;
@@ -323,26 +322,28 @@ getActiveCache: function(overload)
   // Note that this is the current active cache in the cache stack, not the
   // one associated with this window.
   var serv = Cc["@mozilla.org/network/application-cache-service;1"]
              .getService(Ci.nsIApplicationCacheService);
   var groupID = serv.buildGroupID(this.manifestURL(overload), this.loadContextInfo());
   return serv.getActiveCache(groupID);
 },
 
-getActiveStorage: function()
+getActiveSession: function()
 {
   var cache = this.getActiveCache();
   if (!cache) {
     return null;
   }
 
-  var cacheService = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
-                     .getService(Ci.nsICacheStorageService);
-  return cacheService.appCacheStorage(LoadContextInfo.default, cache);
+  var cacheService = Cc["@mozilla.org/network/cache-service;1"]
+                     .getService(Ci.nsICacheService);
+  return cacheService.createSession(cache.clientID,
+                                    Ci.nsICache.STORE_OFFLINE,
+                                    true);
 },
 
 priv: function(func)
 {
   var self = this;
   return function() {
     func(arguments);
   }
@@ -359,35 +360,34 @@ checkCacheEntries: function(entries, cal
     }
   }
 
   checkNextEntry();
 },
 
 checkCache: function(url, expectEntry, callback)
 {
-  var cacheStorage = this.getActiveStorage();
-  this._checkCache(cacheStorage, url, expectEntry, callback);
+  var cacheSession = this.getActiveSession();
+  this._checkCache(cacheSession, url, expectEntry, callback);
 },
 
-_checkCache: function(cacheStorage, url, expectEntry, callback)
+_checkCache: function(cacheSession, url, expectEntry, callback)
 {
-  if (!cacheStorage) {
+  if (!cacheSession) {
     if (expectEntry) {
       this.ok(false, url + " should exist in the offline cache (no session)");
     } else {
       this.ok(true, url + " should not exist in the offline cache (no session)");
     }
     if (callback) setTimeout(this.priv(callback), 0);
     return;
   }
 
   var _checkCacheListener = {
-    onCacheEntryCheck: function() { return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; },
-    onCacheEntryAvailable: function(entry, isnew, applicationCache, status) {
+    onCacheEntryAvailable: function(entry, access, status) {
       if (entry) {
         if (expectEntry) {
           OfflineTest.ok(true, url + " should exist in the offline cache");
         } else {
           OfflineTest.ok(false, url + " should not exist in the offline cache");
         }
         entry.close();
       } else {
@@ -407,17 +407,20 @@ checkCache: function(url, expectEntry, c
         } else {
           OfflineTest.ok(false, "got invalid error for " + url);
         }
       }
       if (callback) setTimeout(OfflineTest.priv(callback), 0);
     }
   };
 
-  cacheStorage.asyncOpenURI(CommonUtils.makeURI(url), "", Ci.nsICacheStorage.OPEN_READONLY | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, _checkCacheListener);
+  cacheSession.asyncOpenCacheEntry(url,
+                                   Ci.nsICache.ACCESS_READ,
+                                   _checkCacheListener,
+                                   false);
 },
 
 setSJSState: function(sjsPath, stateQuery)
 {
   var client = new XMLHttpRequest();
   client.open("GET", sjsPath + "?state=" + stateQuery, false);
 
   var appcachechannel = SpecialPowers.wrap(client).channel.QueryInterface(Ci.nsIApplicationCacheChannel);
--- a/gfx/thebes/gfxUserFontSet.cpp
+++ b/gfx/thebes/gfxUserFontSet.cpp
@@ -7,16 +7,17 @@
 #define FORCE_PR_LOG /* Allow logging in the release build */
 #endif /* MOZ_LOGGING */
 #include "prlog.h"
 
 #include "gfxUserFontSet.h"
 #include "gfxPlatform.h"
 #include "nsUnicharUtils.h"
 #include "nsNetUtil.h"
+#include "nsICacheService.h"
 #include "nsIProtocolHandler.h"
 #include "nsIPrincipal.h"
 #include "gfxFontConstants.h"
 #include "mozilla/Services.h"
 #include "mozilla/gfx/2D.h"
 #include "gfxPlatformFontList.h"
 
 #include "opentype-sanitiser.h"
@@ -857,17 +858,17 @@ NS_IMETHODIMP
 gfxUserFontSet::UserFontCache::Flusher::Observe(nsISupports* aSubject,
                                                 const char* aTopic,
                                                 const char16_t* aData)
 {
     if (!sUserFonts) {
         return NS_OK;
     }
 
-    if (!strcmp(aTopic, "cacheservice:empty-cache")) {
+    if (!strcmp(aTopic, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID)) {
         sUserFonts->Clear();
     } else if (!strcmp(aTopic, "last-pb-context-exited")) {
         sUserFonts->EnumerateEntries(Entry::RemoveIfPrivate, nullptr);
     } else if (!strcmp(aTopic, "xpcom-shutdown")) {
         sUserFonts->EnumerateEntries(Entry::DisconnectSVG, nullptr);
     } else {
         NS_NOTREACHED("unexpected topic");
     }
@@ -911,17 +912,17 @@ gfxUserFontSet::UserFontCache::CacheFont
                  "caching a font associated with no family yet");
     if (!sUserFonts) {
         sUserFonts = new nsTHashtable<Entry>;
 
         nsCOMPtr<nsIObserverService> obs =
             mozilla::services::GetObserverService();
         if (obs) {
             Flusher *flusher = new Flusher;
-            obs->AddObserver(flusher, "cacheservice:empty-cache",
+            obs->AddObserver(flusher, NS_CACHESERVICE_EMPTYCACHE_TOPIC_ID,
                              false);
             obs->AddObserver(flusher, "last-pb-context-exited", false);
             obs->AddObserver(flusher, "xpcom-shutdown", false);
         }
     }
 
     gfxUserFontData *data = aFontEntry->mUserFontData;
     sUserFonts->PutEntry(Key(data->mURI, data->mPrincipal, aFontEntry,
--- a/netwerk/cache/nsCacheService.cpp
+++ b/netwerk/cache/nsCacheService.cpp
@@ -1304,28 +1304,16 @@ nsCacheService::Create(nsISupports* aOut
 NS_IMETHODIMP
 nsCacheService::CreateSession(const char *          clientID,
                               nsCacheStoragePolicy  storagePolicy, 
                               bool                  streamBased,
                               nsICacheSession     **result)
 {
     *result = nullptr;
 
-    if (net::CacheObserver::UseNewCache())
-        return NS_ERROR_NOT_IMPLEMENTED;
-
-    return CreateSessionInternal(clientID, storagePolicy, streamBased, result);
-}
-
-nsresult
-nsCacheService::CreateSessionInternal(const char *          clientID,
-                                      nsCacheStoragePolicy  storagePolicy,
-                                      bool                  streamBased,
-                                      nsICacheSession     **result)
-{
     if (this == nullptr)  return NS_ERROR_NOT_AVAILABLE;
 
     nsCacheSession * session = new nsCacheSession(clientID, storagePolicy, streamBased);
     if (!session)  return NS_ERROR_OUT_OF_MEMORY;
 
     NS_ADDREF(*result = session);
 
     return NS_OK;
@@ -1468,24 +1456,16 @@ nsCacheService::IsStorageEnabledForPolic
         return true;
     }
     
     return false;
 }
 
 NS_IMETHODIMP nsCacheService::VisitEntries(nsICacheVisitor *visitor)
 {
-    if (net::CacheObserver::UseNewCache())
-        return NS_ERROR_NOT_IMPLEMENTED;
-
-    return VisitEntriesInternal(visitor);
-}
-
-nsresult nsCacheService::VisitEntriesInternal(nsICacheVisitor *visitor)
-{
     NS_ENSURE_ARG_POINTER(visitor);
 
     nsCacheServiceAutoLock lock(LOCK_TELEM(NSCACHESERVICE_VISITENTRIES));
 
     if (!(mEnableDiskDevice || mEnableMemoryDevice))
         return NS_ERROR_NOT_AVAILABLE;
 
     // XXX record the fact that a visitation is in progress, 
@@ -1530,24 +1510,16 @@ void nsCacheService::FireClearNetworkCac
         obsvc->NotifyObservers(nullptr,
                                "network-clear-cache-stored-anywhere",
                                nullptr);
     }
 }
 
 NS_IMETHODIMP nsCacheService::EvictEntries(nsCacheStoragePolicy storagePolicy)
 {
-    if (net::CacheObserver::UseNewCache())
-        return NS_ERROR_NOT_IMPLEMENTED;
-
-    return EvictEntriesInternal(storagePolicy);
-}
-
-nsresult nsCacheService::EvictEntriesInternal(nsCacheStoragePolicy storagePolicy)
-{
     if (storagePolicy == nsICache::STORE_ANYWHERE) {
         // if not called on main thread, dispatch the notification to the main thread to notify observers
         if (!NS_IsMainThread()) { 
             nsCOMPtr<nsIRunnable> event = NS_NewRunnableMethod(this,
                                                                &nsCacheService::FireClearNetworkCacheStoredAnywhereNotification);
             NS_DispatchToMainThread(event);
         } else {
             // else you're already on main thread - notify observers
--- a/netwerk/cache/nsCacheService.h
+++ b/netwerk/cache/nsCacheService.h
@@ -223,24 +223,16 @@ public:
     static void      AssertOwnsLock()
     { gService->mLock.AssertCurrentThreadOwns(); }
 
     static void      LeavePrivateBrowsing();
     bool             IsDoomListEmpty();
 
     typedef bool (*DoomCheckFn)(nsCacheEntry* entry);
 
-    // Accessors to the disabled functionality
-    nsresult CreateSessionInternal(const char *          clientID,
-                                   nsCacheStoragePolicy  storagePolicy,
-                                   bool                  streamBased,
-                                   nsICacheSession     **result);
-    nsresult VisitEntriesInternal(nsICacheVisitor *visitor);
-    nsresult EvictEntriesInternal(nsCacheStoragePolicy storagePolicy);
-
 private:
     friend class nsCacheServiceAutoLock;
     friend class nsOfflineCacheDevice;
     friend class nsProcessRequestEvent;
     friend class nsSetSmartSizeEvent;
     friend class nsBlockOnCacheThreadEvent;
     friend class nsSetDiskSmartSizeCallback;
     friend class nsDoomEvent;
--- a/netwerk/cache/nsICacheService.idl
+++ b/netwerk/cache/nsICacheService.idl
@@ -8,29 +8,20 @@
 #include "nsICache.idl"
 
 interface nsISimpleEnumerator;
 interface nsICacheListener;
 interface nsICacheSession;
 interface nsICacheVisitor;
 interface nsIEventTarget;
 
-/**
- * @deprecated
- *
- * IMPORTANT NOTE: THIS INTERFACE IS NO LONGER SUPPORTED AND PLANNED TO BE
- * REMOVED SOON. WE STRONGLY ENCORAGE TO MIGRATE THE EXISTING CODE AND FOR
- * THE NEW CODE USE ONLY THE NEW HTTP CACHE API IN netwerk/cache2/.
- */
 [scriptable, uuid(14dbe1e9-f3bc-45af-92f4-2c574fcd4e39)]
 interface nsICacheService : nsISupports
 {
     /**
-     * @throws NS_ERROR_NOT_IMPLEMENTED when the cache v2 is prefered to use.
-     *
      * Create a cache session
      *
      * A cache session represents a client's access into the cache.  The cache
      * session is not "owned" by the cache service.  Hence, it is possible to
      * create duplicate cache sessions.  Entries created by a cache session
      * are invisible to other cache sessions, unless the cache sessions are
      * equivalent.
      *
@@ -45,25 +36,21 @@ interface nsICacheService : nsISupports
      *   based cache entry can only have a storage policy of STORE_IN_MEMORY.
      * @return new cache session.
      */
     nsICacheSession createSession(in string                 clientID,
                                   in nsCacheStoragePolicy   storagePolicy,
                                   in boolean                streamBased);
 
     /**
-     * @throws NS_ERROR_NOT_IMPLEMENTED when the cache v2 is prefered to use.
-     *
      * Visit entries stored in the cache.  Used to implement about:cache.
      */
     void visitEntries(in nsICacheVisitor visitor);
 
     /**
-     * @throws NS_ERROR_NOT_IMPLEMENTED when the cache v2 is prefered to use.
-     *
      * Evicts all entries in all devices implied by the storage policy.
      *
      * @note This function may evict some items but will throw if it fails to evict
      *       everything.
      */
     void evictEntries(in nsCacheStoragePolicy  storagePolicy);
 
     /**
--- a/netwerk/cache2/AppCacheStorage.cpp
+++ b/netwerk/cache2/AppCacheStorage.cpp
@@ -5,17 +5,17 @@
 #include "CacheLog.h"
 #include "AppCacheStorage.h"
 #include "CacheStorageService.h"
 
 #include "OldWrappers.h"
 
 #include "nsICacheEntryDoomCallback.h"
 
-#include "nsCacheService.h"
+#include "nsICacheService.h"
 #include "nsIApplicationCache.h"
 #include "nsIApplicationCacheService.h"
 #include "nsIURI.h"
 #include "nsNetCID.h"
 #include "nsServiceManagerUtils.h"
 #include "nsThreadUtils.h"
 
 namespace mozilla {
@@ -114,17 +114,17 @@ NS_IMETHODIMP AppCacheStorage::AsyncEvic
     if (LoadInfo()->AppId() == nsILoadContextInfo::NO_APP_ID &&
         !LoadInfo()->IsInBrowserElement()) {
 
       // Clear everything.
       nsCOMPtr<nsICacheService> serv =
           do_GetService(NS_CACHESERVICE_CONTRACTID, &rv);
       NS_ENSURE_SUCCESS(rv, rv);
 
-      rv = nsCacheService::GlobalInstance()->EvictEntriesInternal(nsICache::STORE_OFFLINE);
+      rv = serv->EvictEntries(nsICache::STORE_OFFLINE);
       NS_ENSURE_SUCCESS(rv, rv);
     }
     else {
       // Clear app or inbrowser staff.
       rv = appCacheService->DiscardByAppId(LoadInfo()->AppId(),
                                            LoadInfo()->IsInBrowserElement());
       NS_ENSURE_SUCCESS(rv, rv);
     }
@@ -156,16 +156,16 @@ NS_IMETHODIMP AppCacheStorage::AsyncVisi
   nsresult rv;
 
   nsCOMPtr<nsICacheService> serv =
     do_GetService(NS_CACHESERVICE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsRefPtr<_OldVisitCallbackWrapper> cb = new _OldVisitCallbackWrapper(
     "offline", aVisitor, aVisitEntries, LoadInfo());
-  rv = nsCacheService::GlobalInstance()->VisitEntriesInternal(cb);
+  rv = serv->VisitEntries(cb);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
 } // net
 } // mozilla
--- a/netwerk/cache2/CacheEntry.cpp
+++ b/netwerk/cache2/CacheEntry.cpp
@@ -71,25 +71,24 @@ CacheEntryHandle::~CacheEntryHandle()
 
   MOZ_COUNT_DTOR(CacheEntryHandle);
 }
 
 // CacheEntry::Callback
 
 CacheEntry::Callback::Callback(CacheEntry* aEntry,
                                nsICacheEntryOpenCallback *aCallback,
-                               bool aReadOnly, bool aCheckOnAnyThread, bool aForceAsync)
+                               bool aReadOnly, bool aCheckOnAnyThread)
 : mEntry(aEntry)
 , mCallback(aCallback)
 , mTargetThread(do_GetCurrentThread())
 , mReadOnly(aReadOnly)
 , mCheckOnAnyThread(aCheckOnAnyThread)
 , mRecheckAfterWrite(false)
 , mNotWanted(false)
-, mForceAsync(aForceAsync)
 {
   MOZ_COUNT_CTOR(CacheEntry::Callback);
 
   // The counter may go from zero to non-null only under the service lock
   // but here we expect it to be already positive.
   MOZ_ASSERT(mEntry->HandlesCount());
   mEntry->AddHandleRef();
 }
@@ -97,17 +96,16 @@ CacheEntry::Callback::Callback(CacheEntr
 CacheEntry::Callback::Callback(CacheEntry::Callback const &aThat)
 : mEntry(aThat.mEntry)
 , mCallback(aThat.mCallback)
 , mTargetThread(aThat.mTargetThread)
 , mReadOnly(aThat.mReadOnly)
 , mCheckOnAnyThread(aThat.mCheckOnAnyThread)
 , mRecheckAfterWrite(aThat.mRecheckAfterWrite)
 , mNotWanted(aThat.mNotWanted)
-, mForceAsync(aThat.mForceAsync)
 {
   MOZ_COUNT_CTOR(CacheEntry::Callback);
 
   // The counter may go from zero to non-null only under the service lock
   // but here we expect it to be already positive.
   MOZ_ASSERT(mEntry->HandlesCount());
   mEntry->AddHandleRef();
 }
@@ -128,58 +126,30 @@ void CacheEntry::Callback::ExchangeEntry
   // The counter may go from zero to non-null only under the service lock
   // but here we expect it to be already positive.
   MOZ_ASSERT(aEntry->HandlesCount());
   aEntry->AddHandleRef();
   mEntry->ReleaseHandleRef();
   mEntry = aEntry;
 }
 
-bool CacheEntry::Callback::ForceAsync()
+nsresult CacheEntry::Callback::OnCheckThread(bool *aOnCheckThread) const
 {
-  if (!mForceAsync) {
-    return false;
-  }
-
-  // Drop the flag now.  First time we must claim we are not on the proper thread
-  // what will simply force a post.  But, the post does the check again and that
-  // time we must already tell the true we are on the proper thread otherwise we
-  // just loop indefinitely.  Also, we need to post only once the first callback
-  // of OnCheck or OnAvail.  OnAvail after OnCheck can already go directly.
-  // Note on thread safety: when called from OnCheckThread we are definitely under
-  // the lock, when called from OnAvailThread we don't anymore need to be under
-  // the lock since all concurrency risks are over by that time.
-  mForceAsync = false;
-  return true;
-}
-
-nsresult CacheEntry::Callback::OnCheckThread(bool *aOnCheckThread)
-{
-  if (ForceAsync()) {
-    *aOnCheckThread = false;
-    return NS_OK;
-  }
-
   if (!mCheckOnAnyThread) {
     // Check we are on the target
     return mTargetThread->IsOnCurrentThread(aOnCheckThread);
   }
 
   // We can invoke check anywhere
   *aOnCheckThread = true;
   return NS_OK;
 }
 
-nsresult CacheEntry::Callback::OnAvailThread(bool *aOnAvailThread)
+nsresult CacheEntry::Callback::OnAvailThread(bool *aOnAvailThread) const
 {
-  if (ForceAsync()) {
-    *aOnAvailThread = false;
-    return NS_OK;
-  }
-
   return mTargetThread->IsOnCurrentThread(aOnAvailThread);
 }
 
 // CacheEntry
 
 NS_IMPL_ISUPPORTS(CacheEntry,
                   nsICacheEntry,
                   nsIRunnable,
@@ -293,22 +263,21 @@ void CacheEntry::AsyncOpen(nsICacheEntry
   LOG(("CacheEntry::AsyncOpen [this=%p, state=%s, flags=%d, callback=%p]",
     this, StateString(mState), aFlags, aCallback));
 
   bool readonly = aFlags & nsICacheStorage::OPEN_READONLY;
   bool bypassIfBusy = aFlags & nsICacheStorage::OPEN_BYPASS_IF_BUSY;
   bool truncate = aFlags & nsICacheStorage::OPEN_TRUNCATE;
   bool priority = aFlags & nsICacheStorage::OPEN_PRIORITY;
   bool multithread = aFlags & nsICacheStorage::CHECK_MULTITHREADED;
-  bool async = aFlags & nsICacheStorage::FORCE_ASYNC_CALLBACK;
 
   MOZ_ASSERT(!readonly || !truncate, "Bad flags combination");
   MOZ_ASSERT(!(truncate && mState > LOADING), "Must not call truncate on already loaded entry");
 
-  Callback callback(this, aCallback, readonly, multithread, async);
+  Callback callback(this, aCallback, readonly, multithread);
 
   mozilla::MutexAutoLock lock(mLock);
 
   RememberCallback(callback, bypassIfBusy);
 
   // Load() opens the lock
   if (Load(truncate, priority)) {
     // Loading is in progress...
@@ -724,17 +693,17 @@ bool CacheEntry::InvokeCallback(Callback
 
     mozilla::MutexAutoUnlock unlock(mLock);
     InvokeAvailableCallback(aCallback);
   }
 
   return true;
 }
 
-void CacheEntry::InvokeAvailableCallback(Callback & aCallback)
+void CacheEntry::InvokeAvailableCallback(Callback const & aCallback)
 {
   LOG(("CacheEntry::InvokeAvailableCallback [this=%p, state=%s, cb=%p, r/o=%d, n/w=%d]",
     this, StateString(mState), aCallback.mCallback.get(), aCallback.mReadOnly, aCallback.mNotWanted));
 
   nsresult rv;
 
   uint32_t const state = mState;
 
--- a/netwerk/cache2/CacheEntry.h
+++ b/netwerk/cache2/CacheEntry.h
@@ -130,17 +130,17 @@ private:
   // We must monitor when a cache entry whose consumer is responsible
   // for writing it the first time gets released.  We must then invoke
   // waiting callbacks to not break the chain.
   class Callback
   {
   public:
     Callback(CacheEntry* aEntry,
              nsICacheEntryOpenCallback *aCallback,
-             bool aReadOnly, bool aCheckOnAnyThread, bool aForceAsync);
+             bool aReadOnly, bool aCheckOnAnyThread);
     Callback(Callback const &aThat);
     ~Callback();
 
     // Called when this callback record changes it's owning entry,
     // mainly during recreation.
     void ExchangeEntry(CacheEntry* aEntry);
 
     // We are raising reference count here to take into account the pending
@@ -148,21 +148,19 @@ private:
     // it's pointer).
     nsRefPtr<CacheEntry> mEntry;
     nsCOMPtr<nsICacheEntryOpenCallback> mCallback;
     nsCOMPtr<nsIThread> mTargetThread;
     bool mReadOnly : 1;
     bool mCheckOnAnyThread : 1;
     bool mRecheckAfterWrite : 1;
     bool mNotWanted : 1;
-    bool mForceAsync : 1;
 
-    bool ForceAsync();
-    nsresult OnCheckThread(bool *aOnCheckThread);
-    nsresult OnAvailThread(bool *aOnAvailThread);
+    nsresult OnCheckThread(bool *aOnCheckThread) const;
+    nsresult OnAvailThread(bool *aOnAvailThread) const;
   };
 
   // Since OnCacheEntryAvailable must be invoked on the main thread
   // we need a runnable for it...
   class AvailableCallbackRunnable : public nsRunnable
   {
   public:
     AvailableCallbackRunnable(CacheEntry* aEntry,
@@ -212,17 +210,17 @@ private:
   bool Load(bool aTruncate, bool aPriority);
   void OnLoaded();
 
   void RememberCallback(Callback & aCallback, bool aBypassIfBusy);
   void InvokeCallbacksLock();
   void InvokeCallbacks();
   bool InvokeCallbacks(bool aReadOnly);
   bool InvokeCallback(Callback & aCallback);
-  void InvokeAvailableCallback(Callback & aCallback);
+  void InvokeAvailableCallback(Callback const & aCallback);
 
   nsresult OpenOutputStreamInternal(int64_t offset, nsIOutputStream * *_retval);
 
   // When this entry is new and recreated w/o a callback, we need to wrap it
   // with a handle to detect writing consumer is gone.
   CacheEntryHandle* NewWriteHandle();
   void OnHandleClosed(CacheEntryHandle const* aHandle);
 
--- a/netwerk/cache2/OldWrappers.cpp
+++ b/netwerk/cache2/OldWrappers.cpp
@@ -613,20 +613,20 @@ GetCacheSession(nsCSubstring const &aSch
 
   LOG(("  GetCacheSession for client=%s, policy=%d", clientId.get(), storagePolicy));
 
   nsCOMPtr<nsICacheService> serv =
       do_GetService(NS_CACHESERVICE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsICacheSession> session;
-  rv = nsCacheService::GlobalInstance()->CreateSessionInternal(clientId.get(),
-                                                               storagePolicy,
-                                                               nsICache::STREAM_BASED,
-                                                               getter_AddRefs(session));
+  rv = serv->CreateSession(clientId.get(),
+                           storagePolicy,
+                           nsICache::STREAM_BASED,
+                           getter_AddRefs(session));
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = session->SetIsPrivate(aLoadInfo->IsPrivate());
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = session->SetDoomEntriesIfExpired(false);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -979,17 +979,17 @@ NS_IMETHODIMP _OldStorage::AsyncEvictSto
     if (mLoadInfo->AppId() == nsILoadContextInfo::NO_APP_ID &&
         !mLoadInfo->IsInBrowserElement()) {
 
       // Clear everything.
       nsCOMPtr<nsICacheService> serv =
           do_GetService(NS_CACHESERVICE_CONTRACTID, &rv);
       NS_ENSURE_SUCCESS(rv, rv);
 
-      rv = nsCacheService::GlobalInstance()->EvictEntriesInternal(nsICache::STORE_OFFLINE);
+      rv = serv->EvictEntries(nsICache::STORE_OFFLINE);
       NS_ENSURE_SUCCESS(rv, rv);
     }
     else {
       // Clear app or inbrowser staff.
       nsCOMPtr<nsIApplicationCacheService> appCacheService =
         do_GetService(NS_APPLICATIONCACHESERVICE_CONTRACTID, &rv);
       NS_ENSURE_SUCCESS(rv, rv);
 
@@ -1068,17 +1068,17 @@ NS_IMETHODIMP _OldStorage::AsyncVisitSto
   } else if (!mWriteToDisk || mLoadInfo->IsPrivate()) {
     deviceID = const_cast<char*>("memory");
   } else {
     deviceID = const_cast<char*>("disk");
   }
 
   nsRefPtr<_OldVisitCallbackWrapper> cb = new _OldVisitCallbackWrapper(
     deviceID, aVisitor, aVisitEntries, mLoadInfo);
-  rv = nsCacheService::GlobalInstance()->VisitEntriesInternal(cb);
+  rv = serv->VisitEntries(cb);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
 // Internal
 
 nsresult _OldStorage::AssembleCacheKey(nsIURI *aURI,
--- a/netwerk/cache2/nsICacheStorage.idl
+++ b/netwerk/cache2/nsICacheStorage.idl
@@ -46,23 +46,16 @@ interface nsICacheStorage : nsISupports
    * Perform the cache entry check (onCacheEntryCheck invocation) on any thread 
    * for optimal perfomance optimization.  If this flag is not specified it is
    * ensured that onCacheEntryCheck is called on the same thread as respective 
    * asyncOpen has been called.
    */
   const uint32_t CHECK_MULTITHREADED = 1 << 4;
 
   /**
-   * Forces the callback to be invoked always only asynchronously regardless
-   * we have all the information to invoke it directly from inside asyncOpenURI
-   * method.
-   */
-  const uint32_t FORCE_ASYNC_CALLBACK = 1 << 5;
-
-  /**
    * Asynchronously opens a cache entry for the specified URI.
    * Result is fetched asynchronously via the callback.
    *
    * @param aURI
    *    The URI to search in cache or to open for writting.
    * @param aIdExtension
    *    Any string that will extend (distinguish) the entry.  Two entries
    *    with the same aURI but different aIdExtension will be comletely
@@ -71,17 +64,16 @@ interface nsICacheStorage : nsISupports
    * @param aFlags
    *    OPEN_NORMALLY - open cache entry normally for read and write
    *    OPEN_TRUNCATE - delete any existing entry before opening it
    *    OPEN_READONLY - don't create an entry if there is none
    *    OPEN_PRIORITY - give this request a priority over others
    *    OPEN_BYPASS_IF_BUSY - backward compatibility only, LOAD_BYPASS_LOCAL_CACHE_IF_BUSY
    *    CHECK_MULTITHREADED - onCacheEntryCheck may be called on any thread, consumer 
    *                          implementation is thread-safe
-   *    FORCE_ASYNC_CALLBACK - always call the callback asynchronously
    * @param aCallback
    *    The consumer that receives the result.
    *    IMPORTANT: The callback may be called sooner the method returns.
    */
   void asyncOpenURI(in nsIURI aURI, in ACString aIdExtension,
                     in uint32_t aFlags,
                     in nsICacheEntryOpenCallback aCallback);
 
new file mode 100644
--- /dev/null
+++ b/netwerk/test/TestAsyncCache.js
@@ -0,0 +1,285 @@
+var DEBUG = true;
+
+var clientID = "javascript";
+var nsICache = Components.interfaces.nsICache;
+
+function getEventQueue()
+{
+    var nsIEventQueueService = Components.interfaces.nsIEventQueueService;
+    var CID = Components.classes["@mozilla.org/event-queue-service;1"];
+    var service = CID.getService(nsIEventQueueService);
+    return service.getSpecialEventQueue(nsIEventQueueService.CURRENT_THREAD_EVENT_QUEUE);
+}
+
+var eventQueue = getEventQueue();
+
+function getCacheService()
+{
+    var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
+    var service = nsCacheService.getService(Components.interfaces.nsICacheService);
+    return service;
+}
+
+function createCacheSession(clientID, storagePolicy, streamable)
+{
+    var service = getCacheService();
+    var session = service.createSession(clientID, storagePolicy, streamable);
+    return session;
+}
+
+function openCacheEntry(url, mode)
+{
+    var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
+    var entry = session.openCacheEntry(url, mode);
+    return entry;
+}
+
+function wrapInputStream(input)
+{
+    var nsIScriptableInputStream = Components.interfaces.nsIScriptableInputStream;
+    var factory = Components.classes["@mozilla.org/scriptableinputstream;1"];
+    var wrapper = factory.createInstance(nsIScriptableInputStream);
+    wrapper.init(input);
+    return wrapper;
+}
+
+function download(url)
+{
+    var data = "";
+    var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 65536);
+    var stream = url.getContent();
+    while (true) {
+        var count = stream.read(buffer);
+        if (count <= 0)
+            break;
+        var str = new java.lang.String(buffer, 0, count);
+        data += str;
+    }
+    stream.close();
+    return data;
+}
+
+function write(url, data)
+{
+    var key = url.toString();
+    var outputEntry = openCacheEntry(key, nsICache.ACCESS_WRITE);
+    var output = outputEntry.transport.openOutputStream(0, -1, 0);
+    var count = output.write(data, data.length);
+
+    // store some metadata.
+    outputEntry.setMetaDataElement("size", data.length);
+
+    output.close();
+    outputEntry.markValid();
+    outputEntry.close();
+
+    return count;
+}
+
+function CacheListener()
+{
+    this.done = false;
+}
+
+CacheListener.prototype = {
+    QueryInterface : function(iid)
+    {
+        if (iid.equals(Components.interfaces.nsICacheListener))
+            return this;
+        throw Components.results.NS_NOINTERFACE;
+    },
+
+    onCacheEntryAvailable : function(/* in nsICacheEntryDescriptor */   descriptor,
+                                     /* in nsCacheAccessMode */         accessGranted,
+                                     /* in nsresult */                  status)
+    {
+        this.descriptor = descriptor;
+        this.status = status;
+        this.done = true;
+    }
+};
+
+function asyncOpenCacheEntry(url, mode)
+{
+    var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
+    var listener = new CacheListener();
+    session.asyncOpenCacheEntry(url, mode, listener);
+    while (!listener.done)
+        eventQueue.processPendingEvents();
+    return listener.descriptor;
+}
+
+function asyncWrite(key, data)
+{
+    var outputEntry = asyncOpenCacheEntry(key, nsICache.ACCESS_WRITE);
+    
+    var output = outputEntry.transport.openOutputStream(0, -1, 0);
+    var count = output.write(data, data.length);
+
+    // store some metadata.
+    outputEntry.setMetaDataElement("size", data.length);
+
+    output.close();
+    outputEntry.markValid();
+    outputEntry.close();
+
+    return count;
+}
+
+function StreamListener()
+{
+    this.done = false;
+    this.data = "";
+    this.wrapper = null;
+}
+
+StreamListener.prototype = {
+    QueryInterface : function(iid)
+    {
+        if (iid.equals(Components.interfaces.nsIStreamListener) ||
+            iid.equals(Components.interfaces.nsIStreamObserver))
+            return this;
+        throw Components.results.NS_NOINTERFACE;
+    },
+    
+    onStartRequest : function(request, context)
+    {
+    },
+    
+    onStopRequest : function(request, context, statusCode, statusText)
+    {
+        this.statusCode = statusCode;
+        this.done = true;
+    },
+    
+    onDataAvailable : function(request, context, input, offset, count)
+    {
+        if (this.wrapper == null)
+            this.wrapper = wrapInputStream(input);
+        input = this.wrapper;
+        this.data += input.read(count);
+    }
+};
+
+function asyncRead(key)
+{
+    var inputEntry = asyncOpenCacheEntry(key, nsICache.ACCESS_READ);
+    var listener = new StreamListener();
+    inputEntry.transport.asyncRead(listener, null, 0, inputEntry.dataSize, 0);
+    while (!listener.done)
+        eventQueue.processPendingEvents();
+    inputEntry.close();
+    return listener.data;
+}
+
+function read(key)
+{
+    var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
+    var input = wrapInputStream(inputEntry.transport.openInputStream(0, -1, 0));
+    var data = input.read(input.available());
+    input.close();
+    inputEntry.close();
+    return data;
+}
+
+function readMetaData(key, element)
+{
+    var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
+    var metadata = inputEntry.getMetaDataElement(element);
+    inputEntry.close();
+    return metadata;
+}
+
+function doom(url)
+{
+    var key = url.toString();
+    var doomedEntry = openCacheEntry(key, nsICache.ACCESS_READ_WRITE);
+    doomedEntry.doom();
+    doomedEntry.close();
+}
+
+function test()
+{
+    // download some real content from the network.
+    var url = new java.net.URL("http://www.mozilla.org");
+    var key = url.toString();
+    var data = download(url);
+    
+    if (asyncWrite(key, data) == data.length)
+        print("disk cache write works!");
+    else
+        print("disk cache write broken!");
+
+    if (asyncRead(key) == data)
+        print("disk cache read works!");
+    else
+        print("disk cache read broken!");
+
+    if (readMetaData(key, "size") == data.length)
+        print("disk cache metadata works!");
+    else
+        print("disk cache metadata broken!");
+}
+
+function median(array)
+{
+    var cmp = function(x, y) { return x - y; }
+    array.sort(cmp);
+    var middle = Math.floor(array.length / 2);
+    return array[middle];
+}
+
+function sum(array)
+{
+    var s = 0;
+    var len = array.length;
+    for (var i = 0; i < len; ++i)
+        s += array[i];
+    return s;
+}
+
+function time()
+{
+    var N = 50;
+    var System = java.lang.System;
+    var url = new java.net.URL("http://www.mozilla.org");
+    var key = url.toString();
+    var downloadTimes = new Array();
+    for (var i = 0; i < N; ++i) {
+        var begin = System.currentTimeMillis();
+        download(url);
+        var end = System.currentTimeMillis();
+        downloadTimes.push(end - begin);
+    }
+    var downloadTotal = sum(downloadTimes);
+    var downloadMean = downloadTotal / N;
+    var downloadMedian = median(downloadTimes);
+    print("" + N + " downloads took " + downloadTotal + " milliseconds.");
+    print("mean = " + downloadMean + " milliseconds.");
+    print("median = " + downloadMedian + " milliseconds.");
+
+    var readTimes = new Array();
+    for (var i = 0; i < N; ++i) {
+        var begin = System.currentTimeMillis();
+        asyncRead(key);
+        var end = System.currentTimeMillis();
+        readTimes.push(end - begin);
+    }
+    var readTotal = sum(readTimes);
+    var readMean = readTotal / N;
+    var readMedian = median(readTimes);
+    print("" + N + " reads took " + readTotal + " milliseconds.");
+    print("mean = " + readMean + " milliseconds.");
+    print("median = " + readMedian + " milliseconds.");
+}
+
+// load the cache service before doing anything with Java...
+getCacheService();
+
+if (DEBUG) {
+    print("cache service loaded.");
+} else {
+    print("running disk cache test.");
+    test();
+    print("disk cache test complete.");
+}
new file mode 100644
--- /dev/null
+++ b/netwerk/test/TestCacheCollisions.js
@@ -0,0 +1,291 @@
+var DEBUG = true;
+
+var clientID = "HTTP";
+var nsICache = Components.interfaces.nsICache;
+
+function getEventQueue()
+{
+    var nsIEventQueueService = Components.interfaces.nsIEventQueueService;
+    var CID = Components.classes["@mozilla.org/event-queue-service;1"];
+    var service = CID.getService(nsIEventQueueService);
+    return service.getSpecialEventQueue(nsIEventQueueService.CURRENT_THREAD_EVENT_QUEUE);
+}
+
+var eventQueue = getEventQueue();
+
+function getCacheService()
+{
+    var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
+    var service = nsCacheService.getService(Components.interfaces.nsICacheService);
+    return service;
+}
+
+function createCacheSession(clientID, storagePolicy, streamable)
+{
+    var service = getCacheService();
+    var session = service.createSession(clientID, storagePolicy, streamable);
+    return session;
+}
+
+function openCacheEntry(url, mode)
+{
+    var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
+    var entry = session.openCacheEntry(url, mode);
+    return entry;
+}
+
+function wrapInputStream(input)
+{
+    var nsIScriptableInputStream = Components.interfaces.nsIScriptableInputStream;
+    var factory = Components.classes["@mozilla.org/scriptableinputstream;1"];
+    var wrapper = factory.createInstance(nsIScriptableInputStream);
+    wrapper.init(input);
+    return wrapper;
+}
+
+function download(key)
+{
+    var url = new java.net.URL(key);
+    var data = "";
+    var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 65536);
+    var stream = url.openStream();
+    while (true) {
+        var count = stream.read(buffer);
+        if (count <= 0)
+            break;
+        var str = new java.lang.String(buffer, 0, count);
+        data += str;
+    }
+    stream.close();
+    return data;
+}
+
+function write(url, data)
+{
+    var key = url.toString();
+    var outputEntry = openCacheEntry(key, nsICache.ACCESS_WRITE);
+    var output = outputEntry.transport.openOutputStream(0, -1, 0);
+    var count = output.write(data, data.length);
+
+    // store some metadata.
+    outputEntry.setMetaDataElement("size", data.length);
+
+    output.close();
+    outputEntry.markValid();
+    outputEntry.close();
+
+    return count;
+}
+
+function CacheListener()
+{
+    this.done = false;
+}
+
+CacheListener.prototype = {
+    QueryInterface : function(iid)
+    {
+        if (iid.equals(Components.interfaces.nsICacheListener))
+            return this;
+        throw Components.results.NS_NOINTERFACE;
+    },
+
+    onCacheEntryAvailable : function(/* in nsICacheEntryDescriptor */   descriptor,
+                                     /* in nsCacheAccessMode */         accessGranted,
+                                     /* in nsresult */                  status)
+    {
+        this.descriptor = descriptor;
+        this.status = status;
+        this.done = true;
+    }
+};
+
+function asyncOpenCacheEntry(url, mode)
+{
+    var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
+    var listener = new CacheListener();
+    session.asyncOpenCacheEntry(url, mode, listener);
+    while (!listener.done)
+        eventQueue.processPendingEvents();
+    return listener.descriptor;
+}
+
+function asyncWrite(key, data)
+{
+    var outputEntry = asyncOpenCacheEntry(key, nsICache.ACCESS_WRITE);
+    
+    var output = outputEntry.transport.openOutputStream(0, -1, 0);
+    var count = output.write(data, data.length);
+
+    // store some metadata.
+    outputEntry.setMetaDataElement("size", data.length);
+
+    output.close();
+    outputEntry.markValid();
+    outputEntry.close();
+
+    return count;
+}
+
+function StreamListener()
+{
+    this.done = false;
+    this.data = "";
+    this.wrapper = null;
+}
+
+StreamListener.prototype = {
+    QueryInterface : function(iid)
+    {
+        if (iid.equals(Components.interfaces.nsIStreamListener) ||
+            iid.equals(Components.interfaces.nsIStreamObserver))
+            return this;
+        throw Components.results.NS_NOINTERFACE;
+    },
+    
+    onStartRequest : function(request, context)
+    {
+    },
+    
+    onStopRequest : function(request, context, statusCode, statusText)
+    {
+        this.statusCode = statusCode;
+        this.done = true;
+    },
+    
+    onDataAvailable : function(request, context, input, offset, count)
+    {
+        if (this.wrapper == null)
+            this.wrapper = wrapInputStream(input);
+        input = this.wrapper;
+        this.data += input.read(count);
+    }
+};
+
+function asyncRead(key)
+{
+    var inputEntry = asyncOpenCacheEntry(key, nsICache.ACCESS_READ);
+    var listener = new StreamListener();
+    inputEntry.transport.asyncRead(listener, null, 0, inputEntry.dataSize, 0);
+    while (!listener.done)
+        eventQueue.processPendingEvents();
+    inputEntry.close();
+    return listener.data;
+}
+
+function read(key)
+{
+    var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
+    var input = wrapInputStream(inputEntry.transport.openInputStream(0, -1, 0));
+    var data = input.read(input.available());
+    input.close();
+    inputEntry.close();
+    return data;
+}
+
+function readMetaData(key, element)
+{
+    var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
+    var metadata = inputEntry.getMetaDataElement(element);
+    inputEntry.close();
+    return metadata;
+}
+
+function doom(url)
+{
+    var key = url.toString();
+    var doomedEntry = openCacheEntry(key, nsICache.ACCESS_READ_WRITE);
+    doomedEntry.doom();
+    doomedEntry.close();
+}
+
+// two keys which are known to collide right now.
+var key1 = "http://a772.g.akamai.net/7/772/51/7648437e551b56/www.apple.com/t/2001/us/en/i/2.gif";
+var key2 = "http://a772.g.akamai.net/7/772/51/70601300d0bde6/www.apple.com/t/2001/us/en/i/1right.gif";
+
+function test()
+{
+    // 1. generate a collision, and close the colliding entry first.
+    var entry1 = asyncOpenCacheEntry(key1, nsICache.ACCESS_READ_WRITE);
+    var data1 = key1;
+    entry1.setMetaDataElement("size", data1.length);
+    entry1.markValid();
+    var output1 = entry1.transport.openOutputStream(0, -1, 0);
+    output1.write(data1, data1.length);
+    
+    var entry2 = asyncOpenCacheEntry(key2, nsICache.ACCESS_READ_WRITE);
+    var data2 = key2;
+    entry2.setMetaDataElement("size", data2.length);
+    entry2.markValid();
+    var output2 = entry2.transport.openOutputStream(0, -1, 0);
+    output2.write(data2, data2.length);
+
+    output1.close();
+    output2.close();
+    
+    entry1.close();
+    entry2.close();
+}
+
+function median(array)
+{
+    var cmp = function(x, y) { return x - y; }
+    array.sort(cmp);
+    var middle = Math.floor(array.length / 2);
+    return array[middle];
+}
+
+function sum(array)
+{
+    var s = 0;
+    var len = array.length;
+    for (var i = 0; i < len; ++i)
+        s += array[i];
+    return s;
+}
+
+function time()
+{
+    var N = 50;
+    var System = java.lang.System;
+    var url = new java.net.URL("http://www.mozilla.org");
+    var key = url.toString();
+    var downloadTimes = new Array();
+    for (var i = 0; i < N; ++i) {
+        var begin = System.currentTimeMillis();
+        download(url);
+        var end = System.currentTimeMillis();
+        downloadTimes.push(end - begin);
+    }
+    var downloadTotal = sum(downloadTimes);
+    var downloadMean = downloadTotal / N;
+    var downloadMedian = median(downloadTimes);
+    print("" + N + " downloads took " + downloadTotal + " milliseconds.");
+    print("mean = " + downloadMean + " milliseconds.");
+    print("median = " + downloadMedian + " milliseconds.");
+
+    var readTimes = new Array();
+    for (var i = 0; i < N; ++i) {
+        var begin = System.currentTimeMillis();
+        asyncRead(key);
+        var end = System.currentTimeMillis();
+        readTimes.push(end - begin);
+    }
+    var readTotal = sum(readTimes);
+    var readMean = readTotal / N;
+    var readMedian = median(readTimes);
+    print("" + N + " reads took " + readTotal + " milliseconds.");
+    print("mean = " + readMean + " milliseconds.");
+    print("median = " + readMedian + " milliseconds.");
+}
+
+// load the cache service before doing anything with Java...
+getCacheService();
+
+if (DEBUG) {
+    print("cache service loaded.");
+} else {
+    print("running disk cache test.");
+    test();
+    print("disk cache test complete.");
+}
new file mode 100644
--- /dev/null
+++ b/netwerk/test/TestCachePerformance.js
@@ -0,0 +1,198 @@
+var DEBUG = true;
+
+var clientID = "javascript";
+var nsICache = Components.interfaces.nsICache;
+
+function getCacheService()
+{
+    var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
+    var service = nsCacheService.getService(Components.interfaces.nsICacheService);
+    return service;
+}
+
+function createCacheSession(clientID, storagePolicy, streamable)
+{
+    var service = getCacheService();
+    var session = service.createSession(clientID, storagePolicy, streamable);
+    return session;
+}
+
+function openCacheEntry(url, mode)
+{
+    var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
+    var entry = session.openCacheEntry(url, mode);
+    return entry;
+}
+
+function wrapInputStream(input)
+{
+    var nsIScriptableInputStream = Components.interfaces.nsIScriptableInputStream;
+    var factory = Components.classes["@mozilla.org/scriptableinputstream;1"];
+    var wrapper = factory.createInstance(nsIScriptableInputStream);
+    wrapper.init(input);
+    return wrapper;
+}
+
+function getIOService()
+{
+    var CID = Components.classes["@mozilla.org/network/io-service;1"];
+    var service = CID.getService(Components.interfaces.nsIIOService);
+    return service;
+}
+
+function downloadHTTP(spec)
+{
+    var ioService = getIOService();
+    var uri = ioService.newURI(spec, null, null);
+    var channel = ioService.newChannelFromURI(uri);
+    var input = wrapInputStream(channel.open());
+    var data = input.read(input.available());
+    input.close();
+    return data;
+}
+
+function download(url)
+{
+    var data = "";
+    var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 65536);
+    var stream = url.getContent();
+    while (true) {
+        var count = stream.read(buffer);
+        if (count <= 0)
+            break;
+        var str = new java.lang.String(buffer, 0, count);
+        data += str;
+    }
+    stream.close();
+    return data;
+}
+
+function write(url, data)
+{
+    var key = url.toString();
+    var outputEntry = openCacheEntry(key, nsICache.ACCESS_WRITE);
+    var output = outputEntry.transport.openOutputStream(0, -1, 0);
+    var count = output.write(data, data.length);
+
+    // store some metadata.
+    outputEntry.setMetaDataElement("size", data.length);
+
+    output.close();
+    outputEntry.markValid();
+    outputEntry.close();
+
+    return count;
+}
+
+function read(url)
+{
+    var key = url.toString();
+    var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
+    var input = wrapInputStream(inputEntry.transport.openInputStream(0, -1, 0));
+    var data = input.read(input.available());
+    input.close();
+    inputEntry.close();
+    return data;
+}
+
+function readMetaData(url, element)
+{
+    var key = url.toString();
+    var inputEntry = openCacheEntry(key, nsICache.ACCESS_READ);
+    var metadata = inputEntry.getMetaDataElement(element);
+    inputEntry.close();
+    return metadata;
+}
+
+function doom(url)
+{
+    var key = url.toString();
+    var doomedEntry = openCacheEntry(key, nsICache.ACCESS_READ_WRITE);
+    doomedEntry.doom();
+    doomedEntry.close();
+}
+
+function test()
+{
+    // download some real content from the network.
+    var url = new java.net.URL("http://www.mozilla.org");
+    var key = url.toString();
+    var data = download(url);
+    
+    if (write(url, data) == data.length)
+        print("disk cache write works!");
+    else
+        print("disk cache write broken!");
+
+    if (read(url) == data)
+        print("disk cache read works!");
+    else
+        print("disk cache read broken!");
+        
+    if (readMetaData(url, "size") == data.length)
+        print("disk cache metadata works!");
+    else
+        print("disk cache metadata broken!");
+}
+
+function median(array)
+{
+    var cmp = function(x, y) { return x - y; }
+    array.sort(cmp);
+    var middle = Math.floor(array.length / 2);
+    return array[middle];
+}
+
+function sum(array)
+{
+    var s = 0;
+    var len = array.length;
+    for (var i = 0; i < len; ++i)
+        s += array[i];
+    return s;
+}
+
+function time()
+{
+    var N = 50;
+    var System = java.lang.System;
+    var url = new java.net.URL("http://www.mozilla.org");
+    var downloadTimes = new Array();
+    for (var i = 0; i < N; ++i) {
+        var begin = System.currentTimeMillis();
+        download(url);
+        var end = System.currentTimeMillis();
+        downloadTimes.push(end - begin);
+    }
+    var downloadTotal = sum(downloadTimes);
+    var downloadMean = downloadTotal / N;
+    var downloadMedian = median(downloadTimes);
+    print("" + N + " downloads took " + downloadTotal + " milliseconds.");
+    print("mean = " + downloadMean + " milliseconds.");
+    print("median = " + downloadMedian + " milliseconds.");
+
+    var readTimes = new Array();
+    for (var i = 0; i < N; ++i) {
+        var begin = System.currentTimeMillis();
+        read(url);
+        var end = System.currentTimeMillis();
+        readTimes.push(end - begin);
+    }
+    var readTotal = sum(readTimes);
+    var readMean = readTotal / N;
+    var readMedian = median(readTimes);
+    print("" + N + " reads took " + readTotal + " milliseconds.");
+    print("mean = " + readMean + " milliseconds.");
+    print("median = " + readMedian + " milliseconds.");
+}
+
+// load the cache service before doing anything with Java...
+getCacheService();
+
+if (DEBUG) {
+    print("cache service loaded.");
+} else {
+    print("running disk cache test.");
+    test();
+    print("disk cache test complete.");
+}
new file mode 100644
--- /dev/null
+++ b/netwerk/test/TestCacheService.cpp
@@ -0,0 +1,199 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ *
+ * 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 "nspr.h"
+#include "nscore.h"
+#include "nsError.h"
+#include "nsIServiceManager.h"
+#include "nsNetCID.h"
+#include "nsICache.h"
+#include "nsICacheService.h"
+#include "nsICacheSession.h"
+#include "nsICacheEntryDescriptor.h"
+#include "nsICacheListener.h"
+#include "nsIDNSService.h"
+#include "nsXPCOM.h"
+#include "nsISupportsPrimitives.h"
+#include "nsSupportsPrimitives.h"
+#include "nsIEventQueueService.h"
+
+
+static NS_DEFINE_CID(kEventQueueServiceCID,      NS_EVENTQUEUESERVICE_CID);
+static NS_DEFINE_CID(kCacheServiceCID,           NS_CACHESERVICE_CID);
+
+nsCOMPtr<nsIEventQueue>   gEventQ;
+nsCOMPtr<nsICacheService> gCacheService;
+
+class AsyncCacheRequest
+{
+public:
+    AsyncCacheRequest(const char * key);
+    ~AsyncCacheRequest();
+
+    const char * mKey;
+};
+
+
+nsresult
+MakeCacheSession(const char * clientID, nsICacheSession **session)
+{
+    nsresult rv;
+
+    if (!gCacheService) {
+        //    nsCOMPtr<nsICacheService> cacheService = 
+        //             do_GetService(kCacheServiceCID, &rv);
+        gCacheService = do_GetService(kCacheServiceCID, &rv);
+        if (NS_FAILED(rv) || !gCacheService) {
+            printf("do_GetService(kCacheServiceCID) failed : %x\n", rv);
+            goto error_exit;
+        }
+    }
+
+    rv = gCacheService->CreateSession(clientID,
+                                     nsICache::STORE_IN_MEMORY,
+                                     nsICache::NOT_STREAM_BASED,
+                                     session);
+    if (NS_FAILED(rv))
+        printf("nsCacheService::CreateSession() failed : %x\n", rv);
+
+ error_exit:
+    return rv;
+}
+
+
+void
+TestMemoryObjectCache()
+{
+    printf("\nTesting Memory Object Cache:\n");
+    nsCOMPtr<nsICacheSession> session;
+    nsresult rv = MakeCacheSession("testClientID", getter_AddRefs(session));
+    if (NS_FAILED(rv))  return;
+
+    nsCOMPtr<nsICacheEntryDescriptor> descriptor;
+
+    // Test ACCESS_READ for nonexistent entry
+    printf("\nTest ACCESS_READ:\n");
+    rv = session->OpenCacheEntry(NS_LITERAL_CSTRING("nonexistent entry"),
+                                 nsICache::ACCESS_READ,
+                                 nsICache::BLOCKING,
+                                 getter_AddRefs(descriptor));
+    if (rv != NS_ERROR_CACHE_KEY_NOT_FOUND)
+        printf("OpenCacheEntry(ACCESS_READ) returned: %x for nonexistent entry\n", rv);
+
+    NS_NAMED_LITERAL_CSTRING(cacheKey, "http://www.mozilla.org/somekey");
+
+    // Test creating new entry
+    printf("\nTest ACCESS_READ_WRITE:\n");
+    rv = session->OpenCacheEntry(cacheKey,
+                                 nsICache::ACCESS_READ_WRITE,
+                                 nsICache::BLOCKING,
+                                 getter_AddRefs(descriptor));
+    if (NS_FAILED(rv)) {
+        printf("OpenCacheEntry(ACCESS_READ_WRITE) failed: %x\n", rv);
+        goto error_exit;
+    }
+
+    nsCOMPtr<nsISupportsCString> foo =
+        do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID, &rv);
+
+    foo->SetData(NS_LITERAL_CSTRING("hello world"));
+
+    rv = descriptor->SetCacheElement(foo);
+    rv = descriptor->SetDataSize(11);
+    rv = descriptor->SetMetaDataElement("itemOne", "metaData works");
+    descriptor = nullptr;
+
+    // Test refetching entry
+
+    rv = session->OpenCacheEntry(cacheKey,
+                                 nsICache::ACCESS_READ_WRITE,
+                                 nsICache::BLOCKING,
+                                 getter_AddRefs(descriptor));
+    if (NS_FAILED(rv)) {
+        printf("OpenCacheEntry(ACCESS_READ_WRITE #2) failed: %x", rv);
+        goto error_exit;
+    }
+
+    nsCOMPtr<nsISupportsCString> bar;
+    descriptor->GetCacheElement(getter_AddRefs(bar));
+    if (foo.get() != bar.get()) {
+        printf("cache elements not the same\n");
+    } else {
+        printf("data matches...\n");
+    }
+
+    char * metaData;
+    rv = descriptor->GetMetaDataElement("itemOne", &metaData);
+    if (NS_SUCCEEDED(rv))   printf("metaData = %s\n", metaData);
+    else printf("GetMetaDataElement failed : rv = %x\n", rv);
+    descriptor = nullptr;
+
+    // Test ACCESS_WRITE entry
+    printf("\nTest ACCESS_WRITE:\n");
+    rv = session->OpenCacheEntry(cacheKey,
+                                 nsICache::ACCESS_WRITE,
+                                 nsICache::BLOCKING,
+                                 getter_AddRefs(descriptor));
+    if (NS_FAILED(rv)) {
+        printf("OpenCacheEntry(ACCESS_WRITE) failed: %x", rv);
+        goto error_exit;
+    }
+    rv = descriptor->GetCacheElement(getter_AddRefs(bar));
+    if (bar)
+        printf("FAILED: we didn't get new entry.\n");
+    if (NS_FAILED(rv))
+        printf("GetCacheElement failed : %x\n", rv);
+
+    rv = descriptor->GetMetaDataElement("itemOne", &metaData);
+    if (NS_SUCCEEDED(rv))
+        if (metaData)  printf("metaData = %s\n", metaData);
+        else           printf("metaData = nullptr\n");
+    else printf("GetMetaDataElement failed : rv = %x\n", rv);
+
+    printf("\n");
+ error_exit:
+
+    return;
+}
+
+
+int
+main(int argc, char* argv[])
+{
+    nsresult rv = NS_OK;
+
+    // Start up XPCOM
+    rv = NS_InitXPCOM2(nullptr, nullptr, nullptr);
+    if (NS_FAILED(rv)) return rv;
+
+    /**
+     * Create event queue for this thread
+     */
+    nsCOMPtr<nsIEventQueueService> eventQService = 
+             do_GetService(kEventQueueServiceCID, &rv);
+    if (NS_FAILED(rv)) goto error_exit;
+
+    eventQService->GetThreadEventQueue(NS_CURRENT_THREAD, getter_AddRefs(gEventQ));
+
+    /**
+     * Test Cache
+     */
+    TestMemoryObjectCache();
+
+
+ error_exit:
+    gEventQ = nullptr;
+    eventQService = nullptr;
+
+    NS_ShutdownXPCOM(nullptr);
+
+    printf("XPCOM shut down.\n\n");
+    return rv;
+}
+
+
+
new file mode 100644
--- /dev/null
+++ b/netwerk/test/TestCacheVisitor.js
@@ -0,0 +1,54 @@
+var DEBUG = true;
+
+var clientID = "javascript";
+var nsICache = Components.interfaces.nsICache;
+
+function getCacheService()
+{
+    var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
+    var service = nsCacheService.getService(Components.interfaces.nsICacheService);
+    return service;
+}
+
+function CacheVisitor()
+{
+}
+
+CacheVisitor.prototype = {
+    QueryInterface : function(iid)
+    {
+        if (iid.equals(Components.interfaces.nsICacheVisitor))
+            return this;
+        throw Components.results.NS_NOINTERFACE;
+    },
+
+    visitDevice : function(deviceID, deviceInfo)
+    {
+        print("[visiting device (deviceID = " + deviceID + ", description = " + deviceInfo.description + ")]");
+        return true;
+    },
+    
+    visitEntry : function(deviceID, entryInfo)
+    {
+        print("[visiting entry (clientID = " + entryInfo.clientID + ", key = " + entryInfo.key + ")]");
+        return true;
+    }
+};
+
+function test()
+{
+    var cacheService = getCacheService();
+    var visitor = new CacheVisitor();
+    cacheService.visitEntries(visitor);
+}
+
+// load the cache service before doing anything with Java...
+getCacheService();
+
+if (DEBUG) {
+    print("cache service loaded.");
+} else {
+    print("running cache visitor test.");
+    test();
+    print("cache visitor test complete.");
+}
new file mode 100644
--- /dev/null
+++ b/netwerk/test/TestDiskCache.js
@@ -0,0 +1,84 @@
+var DEBUG = false;
+
+var clientID = "javascript";
+var key = "theme:button";
+var nsICache = Components.interfaces.nsICache;
+
+function getCacheService()
+{
+    var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
+    var service = nsCacheService.getService(Components.interfaces.nsICacheService);
+    return service;
+}
+
+function createCacheSession(clientID, storagePolicy, streamable)
+{
+    var service = getCacheService();
+    var session = service.createSession(clientID, storagePolicy, streamable);
+    return session;
+}
+
+function openCacheEntry(mode)
+{
+    var session = createCacheSession(clientID, nsICache.STORE_ON_DISK, true);
+    var entry = session.openCacheEntry(key, mode);
+    return entry;
+}
+
+function wrapInputStream(input)
+{
+    var nsIScriptableInputStream = Components.interfaces.nsIScriptableInputStream;
+    var factory = Components.classes["@mozilla.org/scriptableinputstream;1"];
+    var wrapper = factory.createInstance(nsIScriptableInputStream);
+    wrapper.init(input);
+    return wrapper;
+}
+
+function test()
+{
+    var outputEntry = openCacheEntry(nsICache.ACCESS_WRITE);
+    var output = outputEntry.transport.openOutputStream(0, -1, 0);
+    if (output.write("foo", 3) == 3)
+        print("disk cache write works!");
+    else
+        print("disk cache write broken!");
+
+    // store some metadata.
+    outputEntry.setMetaDataElement("size", "3");
+
+    output.close();
+    outputEntry.markValid();
+    outputEntry.close();
+
+    var inputEntry = openCacheEntry(nsICache.ACCESS_READ);
+    var input = wrapInputStream(inputEntry.transport.openInputStream(0, -1, 0));
+
+    if (input.read(input.available()) == "foo")
+        print("disk cache read works!");
+    else
+        print("disk cache read broken!");
+
+    if (inputEntry.getMetaDataElement("size") == "3")
+        print("disk cache metadata works!");
+    else
+        print("disk cache metadata broken!");
+
+    input.close();
+    inputEntry.close();
+}
+
+function doom()
+{
+    var doomedEntry = openCacheEntry(nsICache.ACCESS_READ_WRITE);
+    doomedEntry.doom();
+    doomedEntry.close();
+}
+
+if (DEBUG) {
+    getCacheService();
+    print("cache service loaded.");
+} else {
+    print("running disk cache test.");
+    test();
+    print("disk cache test complete.");
+}
new file mode 100644
--- /dev/null
+++ b/netwerk/test/TestMCTransport.cpp
@@ -0,0 +1,226 @@
+/* -*- 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 <stdio.h>
+
+#include "nsIServiceManager.h"
+#include "nsIEventQueueService.h"
+#include "nsIOutputStream.h"
+#include "nsIStreamListener.h"
+#include "nsITransport.h"
+#include "nsIInputStream.h"
+#include "nsIOutputStream.h"
+#include "nsCOMPtr.h"
+#include "plstr.h"
+#include "prprf.h"
+#include <algorithm>
+
+#ifndef USE_CREATE_INSTANCE
+#include "nsICacheService.h"
+#include "nsICacheSession.h"
+#include "nsICacheEntryDescriptor.h"
+#include "nsNetCID.h"
+static NS_DEFINE_CID(kCacheServiceCID, NS_CACHESERVICE_CID);
+static nsICacheSession *session = nullptr;
+static nsICacheEntryDescriptor *desc = nullptr;
+#endif
+
+/**
+ * This test program exercises the memory cache's nsITransport implementation.
+ *
+ * This test program loads a file into the memory cache (using OpenOutputStream),
+ * and then reads the file back out (using AsyncRead).  The data read from the
+ * memory cache is written to a new file (with .out added as a suffix to the file
+ * name).
+ */
+
+static NS_DEFINE_CID(kEventQueueServiceCID, NS_EVENTQUEUESERVICE_CID);
+static nsIEventQueue *gEventQ = nullptr;
+
+class TestListener : public nsIStreamListener
+{
+public:
+    NS_DECL_ISUPPORTS
+    NS_DECL_NSISTREAMLISTENER
+    NS_DECL_NSIREQUESTOBSERVER
+
+    TestListener(char *);
+    virtual ~TestListener();
+
+private:
+    char *mFilename;
+    FILE *mFile;
+};
+
+NS_IMPL_ISUPPORTS(TestListener,
+                  nsIStreamListener,
+                  nsIRequestObserver)
+
+TestListener::TestListener(char *filename)
+    : mFilename(filename)
+    , mFile(nullptr)
+{
+}
+
+TestListener::~TestListener()
+{
+}
+
+NS_IMETHODIMP
+TestListener::OnStartRequest(nsIRequest *req, nsISupports *ctx)
+{
+    printf("OnStartRequest\n");
+
+    mFile = fopen(mFilename, "w");
+    if (!mFile)
+        return NS_ERROR_FAILURE;
+
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+TestListener::OnStopRequest(nsIRequest *req, nsISupports *ctx, nsresult status)
+{
+    printf("OnStopRequest: status=%x\n", status);
+
+    if (mFile)
+        fclose(mFile);
+
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+TestListener::OnDataAvailable(nsIRequest *req, nsISupports *ctx,
+                              nsIInputStream *is,
+                              uint64_t offset, uint32_t count)
+{
+    printf("OnDataAvailable: offset=%llu count=%u\n", offset, count);
+
+    if (!mFile) return NS_ERROR_FAILURE;
+
+    char buf[128];
+    nsresult rv;
+    uint32_t nread = 0;
+
+    while (count) {
+        uint32_t amount = std::min<uint32_t>(count, sizeof(buf));
+
+        rv = is->Read(buf, amount, &nread);
+        if (NS_FAILED(rv)) return rv;
+
+        fwrite(buf, nread, 1, mFile);
+        count -= nread;
+    }
+    return NS_OK;
+}
+
+nsresult TestMCTransport(const char *filename)
+{
+    nsresult rv = NS_OK;
+    nsCOMPtr<nsITransport> transport;
+
+#ifdef USE_CREATE_INSTANCE
+    transport = do_CreateInstance(
+            "@mozilla.org/network/memory-cache-transport;1", &rv);
+    if (NS_FAILED(rv))
+        return rv;
+#else
+    nsCOMPtr<nsICacheService> serv(do_GetService(kCacheServiceCID, &rv));
+    if (NS_FAILED(rv)) return rv;
+
+    rv = serv->CreateSession("TestMCTransport",
+                             nsICache::STORE_IN_MEMORY, true,
+                             &session);
+    if (NS_FAILED(rv)) return rv;
+
+    rv = session->OpenCacheEntry(nsDependentCString(filename),
+                                 nsICache::ACCESS_READ_WRITE,
+                                 nsICache::BLOCKING,
+                                 &desc);
+    if (NS_FAILED(rv)) return rv;
+
+    rv = desc->MarkValid();
+    if (NS_FAILED(rv)) return rv;
+
+    rv = desc->GetTransport(getter_AddRefs(transport));
+    if (NS_FAILED(rv)) return rv;
+#endif
+
+    nsCOMPtr<nsIOutputStream> os;
+    rv = transport->OpenOutputStream(0, (uint32_t) -1, 0, getter_AddRefs(os));
+    if (NS_FAILED(rv)) return rv;
+
+    char *out = PR_smprintf("%s.out", filename);
+    nsCOMPtr<nsIStreamListener> listener = new TestListener(out);
+    if (!listener)
+        return NS_ERROR_OUT_OF_MEMORY;
+
+    nsCOMPtr<nsIRequest> req;
+    rv = transport->AsyncRead(listener, nullptr, 0, (uint32_t) -1, 0, getter_AddRefs(req));
+    if (NS_FAILED(rv)) return rv;
+
+    FILE *file = fopen(filename, "r");
+    if (!file)
+        return NS_ERROR_FILE_NOT_FOUND;
+
+    char buf[256];
+    uint32_t count, total=0;
+
+    while ((count = fread(buf, 1, sizeof(buf), file)) > 0) {
+        printf("writing %u bytes\n", count);
+        total += count;
+        rv = os->Write(buf, count, &count);
+        if (NS_FAILED(rv)) return rv;
+
+        // process an event
+        PLEvent *event = nullptr;
+        gEventQ->GetEvent(&event);
+        if (event) gEventQ->HandleEvent(event);
+    }
+
+    printf("wrote %u bytes\n", total);
+
+    return rv;
+}
+
+int main(int argc, char **argv)
+{
+    nsresult rv;
+
+    if (argc < 2) {
+        printf("usage: %s filename\n", argv[0]);
+        return -1;
+    }
+
+    nsCOMPtr<nsIEventQueueService> eqs = 
+             do_GetService(kEventQueueServiceCID, &rv);
+    if (NS_FAILED(rv)) {
+        printf("failed to create event queue service: rv=%x\n", rv);
+        return -1;
+    }
+
+    rv = eqs->CreateMonitoredThreadEventQueue();
+    if (NS_FAILED(rv)) {
+        printf("failed to create monitored event queue: rv=%x\n", rv);
+        return -1;
+    }
+
+    rv = eqs->GetThreadEventQueue(NS_CURRENT_THREAD, &gEventQ);
+    if (NS_FAILED(rv)) {
+        printf("failed to get thread event queue: %x\n", rv);
+        return -1;
+    }
+
+    rv = TestMCTransport(argv[1]);
+    printf("TestMCTransport returned %x\n", rv);
+
+    gEventQ->ProcessPendingEvents();
+
+#ifndef USE_CREATE_INSTANCE
+    NS_IF_RELEASE(desc);
+    NS_IF_RELEASE(session);
+#endif
+    return 0;
+}
new file mode 100644
--- /dev/null
+++ b/netwerk/test/TestObjectCache.js
@@ -0,0 +1,48 @@
+function getCacheService()
+{
+    var nsCacheService = Components.classes["@mozilla.org/network/cache-service;1"];
+    var service = nsCacheService.getService(Components.interfaces.nsICacheService);
+    return service;
+}
+
+function createCacheSession(clientID, storagePolicy, streamable)
+{
+    var service = getCacheService();
+    var nsICache = Components.interfaces.nsICache;
+    var session = service.createSession(clientID, storagePolicy, streamable);
+    return session;
+}
+
+function openCacheEntry(clientID, url)
+{
+    var nsICache = Components.interfaces.nsICache;
+    var session = createCacheSession(clientID, nsICache.STORE_ANYWHERE, false);
+    var entry = session.openCacheEntry(url, nsICache.ACCESS_READ_WRITE);
+    return entry;
+}
+
+function wrapString(str)
+{
+    var nsISupportsCString = Components.interfaces.nsISupportsCString;
+    var factory = Components.classes["@mozilla.org/supports-cstring;1"];
+    var wrapper = factory.createInstance(nsISupportsCString);
+    wrapper.data = str;
+    return wrapper;
+}
+
+function test()
+{
+    var data = wrapString("javascript");
+    var entry = openCacheEntry("javascript", "theme:button");
+    entry.cacheElement = data;
+    entry.markValid();
+    entry.close();
+
+    var newEntry = openCacheEntry("javascript", "theme:button");
+    if (newEntry.cacheElement === data)
+        print("object cache works.");
+    else
+        print("object cache failed.");
+}
+
+test();
--- a/netwerk/test/unit/test_bug767025.js
+++ b/netwerk/test/unit/test_bug767025.js
@@ -17,18 +17,18 @@ Cu.import("resource://testing-common/htt
  *    - all documents except pages/foo1 are gone since pages/foo1 & pages/foo3
  *      are activated.
  */
 
 Cu.import("resource://gre/modules/Services.jsm");
 
 const kNS_OFFLINECACHEUPDATESERVICE_CONTRACTID =
   "@mozilla.org/offlinecacheupdate-service;1";
-const kNS_CACHESTORAGESERVICE_CONTRACTID =
-  "@mozilla.org/netwerk/cache-storage-service;1";
+const kNS_CACHESERVICE_CONTRACTID =
+  "@mozilla.org/network/cache-service;1";
 const kNS_APPLICATIONCACHESERVICE_CONTRACTID =
   "@mozilla.org/network/application-cache-service;1";
 
 const kManifest = "CACHE MANIFEST\n" +
   "/pages/foo1\n" +
   "/pages/foo2\n" +
   "/pages/foo3\n" +
   "/pages/foo4\n";
@@ -80,20 +80,19 @@ function init_http_server() {
   httpServer.registerPathHandler("/app", app_handler);
   for (i = 1; i <= 4; i++) {
     httpServer.registerPathHandler("/pages/foo" + i, datafile_handler);
   }
   httpServer.start(4444);
 }
 
 function clean_app_cache() {
-  let cache_service = Cc[kNS_CACHESTORAGESERVICE_CONTRACTID].
-    getService(Ci.nsICacheStorageService);
-  let storage = cache_service.appCacheStorage(LoadContextInfo.default, null);
-  storage.asyncEvictStorage(null);
+  let cache_service = Cc[kNS_CACHESERVICE_CONTRACTID].
+    getService(Ci.nsICacheService);
+  cache_service.evictEntries(Ci.nsICache.STORE_OFFLINE);
 }
 
 function do_app_cache(manifestURL, pageURL) {
   let update_service = Cc[kNS_OFFLINECACHEUPDATESERVICE_CONTRACTID].
     getService(Ci.nsIOfflineCacheUpdateService);
 
   Services.perms.add(manifestURL,
 		     "offline-app",
deleted file mode 100644
--- a/netwerk/test/unit/test_cache2-01f-basic-async.js
+++ /dev/null
@@ -1,28 +0,0 @@
-function run_test()
-{
-  do_get_profile();
-
-  // Open for write, write
-  asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, null,
-    new OpenCallback(NEW, "a1m", "a1d", function(entry) {
-      // Open for read and check
-      asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, null,
-        new OpenCallback(NORMAL, "a1m", "a1d", function(entry) {
-          // Open for rewrite (truncate), write different meta and data
-          asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_TRUNCATE | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, null,
-            new OpenCallback(NEW, "a2m", "a2d", function(entry) {
-              // Open for read and check
-              asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, null,
-                new OpenCallback(NORMAL, "a2m", "a2d", function(entry) {
-                  finish_cache2_test();
-                })
-              );
-            })
-          );
-        })
-      );
-    })
-  );
-
-  do_test_pending();
-}
deleted file mode 100644
--- a/netwerk/test/unit/test_cache2-24-force-async.js
+++ /dev/null
@@ -1,42 +0,0 @@
-function run_test()
-{
-  do_get_profile();
-
-  // Open for write, write, and wait for finishing it before notification to avoid concurrent write
-  // since we want to get as much as possible the scenario when an entry is left in the pool
-  // and a new consumer comes to open it later.
-  var outOfAsyncOpen0 = false;
-  asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, null,
-    new OpenCallback(NEW|WAITFORWRITE, "a1m", "a1d", function(entry) {
-      do_check_true(outOfAsyncOpen0);
-      // Open for read, expect callback happen from inside asyncOpenURI
-      var outOfAsyncOpen1 = false;
-      asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null,
-        function(entry) {
-          do_check_false(outOfAsyncOpen1);
-          var outOfAsyncOpen2 = false;
-          // Open for read, again should be sync
-          asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY, null,
-            function(entry) {
-              do_check_false(outOfAsyncOpen2);
-              var outOfAsyncOpen3 = false;
-              // Open for read, expect callback happen from outside of asyncOpenURI
-              asyncOpenCacheEntry("http://a/", "disk", Ci.nsICacheStorage.OPEN_NORMALLY | Ci.nsICacheStorage.FORCE_ASYNC_CALLBACK, null,
-                function(entry) {
-                  do_check_true(outOfAsyncOpen3);
-                  finish_cache2_test();
-                }
-              );
-              outOfAsyncOpen3 = true;
-            }
-          );
-          outOfAsyncOpen2 = true;
-        }
-      );
-      outOfAsyncOpen1 = true;
-    })
-  );
-  outOfAsyncOpen0 = true;
-
-  do_test_pending();
-}
--- a/netwerk/test/unit/xpcshell.ini
+++ b/netwerk/test/unit/xpcshell.ini
@@ -20,17 +20,16 @@ support-files =
 
 [test_nsIBufferedOutputStream_writeFrom_block.js]
 [test_cache2-01-basic.js]
 [test_cache2-01a-basic-readonly.js]
 [test_cache2-01b-basic-datasize.js]
 [test_cache2-01c-basic-hasmeta-only.js]
 [test_cache2-01d-basic-not-wanted.js]
 [test_cache2-01e-basic-bypass-if-busy.js]
-[test_cache2-01f-basic-async.js]
 [test_cache2-02-open-non-existing.js]
 [test_cache2-03-oncacheentryavail-throws.js]
 [test_cache2-04-oncacheentryavail-throws2x.js]
 [test_cache2-05-visit.js]
 [test_cache2-06-pb-mode.js]
 # Bug 675039, comment 6: "The difference is that the memory cache is disabled in Armv6 builds."
 skip-if = os == "android"
 [test_cache2-07-visit-memory.js]
@@ -53,17 +52,16 @@ skip-if = os == "android"
 [test_cache2-16-conditional-200.js]
 [test_cache2-17-evict-all.js]
 [test_cache2-18-not-valid.js]
 [test_cache2-19-range-206.js]
 [test_cache2-20-range-200.js]
 [test_cache2-21-anon-storage.js]
 [test_cache2-22-anon-visit.js]
 [test_cache2-23-read-over-chunk.js]
-[test_cache2-24-force-async.js]
 [test_304_responses.js]
 # Bug 675039: test hangs on Android-armv6 
 skip-if = os == "android"
 [test_cacheForOfflineUse_no-store.js]
 [test_307_redirect.js]
 [test_NetUtil.js]
 [test_URIs.js]
 [test_aboutblank.js]
--- a/toolkit/components/places/AsyncFaviconHelpers.cpp
+++ b/toolkit/components/places/AsyncFaviconHelpers.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
  * 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 "AsyncFaviconHelpers.h"
 
+#include "nsICacheService.h"
 #include "nsICacheEntry.h"
 #include "nsICachingChannel.h"
 #include "nsIAsyncVerifyRedirectCallback.h"
 
 #include "nsNavHistory.h"
 #include "nsFaviconService.h"
 #include "mozilla/storage.h"
 #include "nsNetUtil.h"
--- a/uriloader/prefetch/OfflineCacheUpdateChild.h
+++ b/uriloader/prefetch/OfflineCacheUpdateChild.h
@@ -6,16 +6,17 @@
 #ifndef nsOfflineCacheUpdateChild_h
 #define nsOfflineCacheUpdateChild_h
 
 #include "mozilla/docshell/POfflineCacheUpdateChild.h"
 #include "nsIOfflineCacheUpdate.h"
 
 #include "nsCOMArray.h"
 #include "nsCOMPtr.h"
+#include "nsICacheService.h"
 #include "nsIDOMDocument.h"
 #include "nsIObserver.h"
 #include "nsIObserverService.h"
 #include "nsIURI.h"
 #include "nsString.h"
 #include "nsWeakReference.h"
 
 namespace mozilla {
--- a/uriloader/prefetch/nsOfflineCacheUpdate.cpp
+++ b/uriloader/prefetch/nsOfflineCacheUpdate.cpp
@@ -10,16 +10,18 @@
 #include "nsOfflineCacheUpdate.h"
 
 #include "nsCPrefetchService.h"
 #include "nsCURILoader.h"
 #include "nsIApplicationCacheContainer.h"
 #include "nsIApplicationCacheChannel.h"
 #include "nsIApplicationCacheService.h"
 #include "nsICache.h"
+#include "nsICacheService.h"
+#include "nsICacheSession.h"
 #include "nsICachingChannel.h"
 #include "nsIContent.h"
 #include "mozilla/dom/Element.h"
 #include "nsIDocumentLoader.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMOfflineResourceList.h"
 #include "nsIDocument.h"
--- a/uriloader/prefetch/nsOfflineCacheUpdate.h
+++ b/uriloader/prefetch/nsOfflineCacheUpdate.h
@@ -6,16 +6,17 @@
 #ifndef nsOfflineCacheUpdate_h__
 #define nsOfflineCacheUpdate_h__
 
 #include "nsIOfflineCacheUpdate.h"
 
 #include "nsAutoPtr.h"
 #include "nsCOMArray.h"
 #include "nsCOMPtr.h"
+#include "nsICacheService.h"
 #include "nsIChannelEventSink.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMNode.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIMutableArray.h"
 #include "nsIObserver.h"
 #include "nsIObserverService.h"
 #include "nsIApplicationCache.h"
--- a/uriloader/prefetch/nsOfflineCacheUpdateService.cpp
+++ b/uriloader/prefetch/nsOfflineCacheUpdateService.cpp
@@ -13,16 +13,19 @@
 #include "OfflineCacheUpdateGlue.h"
 #include "nsOfflineCacheUpdate.h"
 
 #include "nsCPrefetchService.h"
 #include "nsCURILoader.h"
 #include "nsIApplicationCacheContainer.h"
 #include "nsIApplicationCacheChannel.h"
 #include "nsIApplicationCacheService.h"
+#include "nsICache.h"
+#include "nsICacheService.h"
+#include "nsICacheSession.h"
 #include "nsICachingChannel.h"
 #include "nsIContent.h"
 #include "nsIDocShell.h"
 #include "nsIDocumentLoader.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMOfflineResourceList.h"
 #include "nsIDocument.h"