Backout the latest cedar merge wholesale until I test the correctness of the merge locally. This commit takes the tree state back to changeset 8d3f6093c425 (the last known good changeset before the merge)
authorEhsan Akhgari <ehsan@mozilla.com>
Fri, 01 Apr 2011 12:23:48 -0400
changeset 64605 da9ddc764f848048b458f9470c1d4c96037780f3
parent 64604 e4cc301d26d4140012dbb34be1368042ff3ec8ad
child 64606 e61659c0f0d4505edcb6c018a38f21c830da2e26
child 64610 6c50efc31ee4a01ad28b68a57dcab5ded95356e1
push id1
push userroot
push dateTue, 26 Apr 2011 22:38:44 +0000
treeherdermozilla-beta@bfdb6e623a36 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone2.2a1pre
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Backout the latest cedar merge wholesale until I test the correctness of the merge locally. This commit takes the tree state back to changeset 8d3f6093c425 (the last known good changeset before the merge)
browser/components/nsBrowserContentHandler.js
browser/components/nsBrowserGlue.js
browser/components/search/content/search.xml
browser/locales/en-US/chrome/browser/browser.properties
content/base/src/nsGkAtomList.h
content/canvas/src/nsCanvasRenderingContext2D.cpp
content/canvas/test/test_canvas.html
content/html/document/src/nsHTMLContentSink.cpp
dom/ipc/AudioParent.cpp
dom/src/threads/test/WorkerTest.jsm
dom/src/threads/test/test_chromeWorkerJSM.xul
embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
embedding/components/webbrowserpersist/src/nsWebBrowserPersist.h
gfx/thebes/GLContext.h
modules/libjar/nsJARChannel.cpp
modules/libpr0n/decoders/icon/mac/nsIconChannelCocoa.mm
modules/libpr0n/decoders/icon/os2/nsIconChannel.cpp
modules/libpr0n/decoders/icon/win/nsIconChannel.cpp
modules/libpref/src/init/all.js
modules/plugin/base/src/nsPluginHost.cpp
modules/plugin/base/src/nsPluginStreamListenerPeer.cpp
netwerk/base/public/nsNetUtil.h
netwerk/base/src/nsBufferedStreams.cpp
netwerk/base/src/nsBufferedStreams.h
netwerk/base/src/nsFileStreams.cpp
netwerk/base/src/nsIncrementalDownload.cpp
netwerk/base/src/nsInputStreamPump.cpp
netwerk/base/src/nsSocketTransport2.cpp
netwerk/base/src/nsSocketTransport2.h
netwerk/base/src/nsStreamTransportService.cpp
netwerk/protocol/ftp/nsFtpConnectionThread.h
netwerk/protocol/http/nsAHttpTransaction.h
netwerk/protocol/http/nsHttpChannel.cpp
netwerk/protocol/http/nsHttpConnection.cpp
netwerk/protocol/http/nsHttpConnection.h
netwerk/protocol/http/nsHttpConnectionMgr.cpp
netwerk/protocol/http/nsHttpConnectionMgr.h
netwerk/protocol/http/nsHttpHandler.cpp
netwerk/protocol/http/nsHttpHandler.h
netwerk/protocol/http/nsHttpPipeline.cpp
netwerk/protocol/http/nsHttpTransaction.cpp
netwerk/protocol/http/nsHttpTransaction.h
netwerk/streamconv/converters/nsMultiMixedConv.cpp
netwerk/streamconv/converters/nsMultiMixedConv.h
netwerk/test/TestProtocols.cpp
netwerk/test/TestStreamTransport.cpp
parser/htmlparser/tests/mochitest/file_bug543062.sjs
security/manager/boot/src/nsStrictTransportSecurityService.cpp
security/manager/ssl/src/nsNSSComponent.cpp
startupcache/StartupCache.cpp
toolkit/content/widgets/tabbox.xml
uriloader/base/nsDocLoader.cpp
uriloader/base/nsDocLoader.h
uriloader/exthandler/nsExternalHelperAppService.cpp
uriloader/exthandler/nsExternalHelperAppService.h
view/src/nsViewManager.cpp
widget/public/nsIWidget.h
widget/src/cocoa/nsChildView.mm
widget/src/os2/nsClipboard.cpp
widget/src/os2/nsClipboard.h
widget/src/windows/nsWindow.cpp
xpcom/components/nsComponentManager.cpp
xpcom/ds/Makefile.in
xpcom/ds/nsInt64.h
xpcom/ds/nsTime.h
xpcom/io/nsFastLoadFile.cpp
xpcom/io/nsMultiplexInputStream.cpp
xpcom/io/nsPipe3.cpp
xpcom/io/nsStorageStream.cpp
xpcom/io/nsStringStream.cpp
xpcom/reflect/xptinfo/src/xptiprivate.h
xpinstall/src/nsXPInstallManager.cpp
--- a/browser/components/nsBrowserContentHandler.js
+++ b/browser/components/nsBrowserContentHandler.js
@@ -562,25 +562,17 @@ nsBrowserContentHandler.prototype = {
 
         searchParam = param.substr(2);
         doSearch(searchParam, cmdLine);
       }
     }
 #endif
   },
 
-  helpInfo : "  -browser           Open a browser window.\n" +
-             "  -new-window  <url> Open <url> in a new window.\n" +
-             "  -new-tab     <url> Open <url> in a new tab.\n" +
-#ifdef XP_WIN
-             "  -preferences       Open Options dialog.\n" +
-#else
-             "  -preferences       Open Preferences dialog.\n" +
-#endif
-             "  -search     <term> Search <term> with your default search engine.\n",
+  helpInfo : "  -browser           Open a browser window.\n",
 
   /* nsIBrowserHandler */
 
   get defaultArgs() {
     var prefb = Components.classes["@mozilla.org/preferences-service;1"]
                           .getService(nsIPrefBranch);
 
     var overridePage = "";
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -1461,16 +1461,21 @@ ContentPermissionPrompt.prototype = {
     var mainAction = {
       label: browserBundle.GetStringFromName("geolocation.shareLocation"),
       accessKey: browserBundle.GetStringFromName("geolocation.shareLocation.accesskey"),
       callback: function(notification) {
         request.allow();
       },
     };
 
+    // XXX Bug 573536
+    // browserBundle.GetStringFromName("geolocation.learnMore")
+    //var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].getService(Ci.nsIURLFormatter);
+    //link.href = formatter.formatURLPref("browser.geolocation.warning.infoURL");
+
     var message;
     var secondaryActions = [];
 
     // Different message/options if it is a local file
     if (requestingURI.schemeIs("file")) {
       message = browserBundle.formatStringFromName("geolocation.fileWantsToKnow",
                                                    [requestingURI.path], 1);
     } else {
--- a/browser/components/search/content/search.xml
+++ b/browser/components/search/content/search.xml
@@ -469,22 +469,18 @@
           else {
             var newTabPref = textBox._prefBranch.getBoolPref("browser.search.openintab");
             if ((aEvent && aEvent.altKey) ^ newTabPref)
               where = "tab";
           }
 
           // Save the current value in the form history
           if (textValue) {
-            try {
-              textBox._formHistSvc.addEntry(textBox.getAttribute("autocompletesearchparam"),
-                                            textValue);
-            } catch (ex) {
-              Components.utils.reportError("Saving search to form history failed: " + ex);
-            }
+            textBox._formHistSvc.addEntry(textBox.getAttribute("autocompletesearchparam"),
+                                          textValue);
           }
 
           this.doSearch(textValue, where);
         ]]></body>
       </method>
 
       <method name="doSearch">
         <parameter name="aData"/>
--- a/browser/locales/en-US/chrome/browser/browser.properties
+++ b/browser/locales/en-US/chrome/browser/browser.properties
@@ -1,9 +1,11 @@
+nv_done=Done
 nv_timeout=Timed Out
+nv_stopped=Stopped
 openFile=Open File
 
 droponhometitle=Set Home Page
 droponhomemsg=Do you want this document to be your new home page?
 
 # context menu strings
 
 # LOCALIZATION NOTE (contextMenuSearchText): %1$S is the search engine,
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -1377,285 +1377,185 @@ GK_ATOM(_moz_math_fontstyle_, "_moz-math
 GK_ATOM(_moz_math_rowalign_, "_moz-math-rowalign")
 GK_ATOM(_moz_math_rowline_, "_moz-math-rowline")
 
 GK_ATOM(abs_, "abs")
 GK_ATOM(accent_, "accent")
 GK_ATOM(accentunder_, "accentunder")
 GK_ATOM(actiontype_, "actiontype")
 GK_ATOM(alignmentscope_, "alignmentscope")
-GK_ATOM(altimg_, "altimg")
-GK_ATOM(altimg_height_, "altimg-height")
-GK_ATOM(altimg_valign_, "altimg-valign")
-GK_ATOM(altimg_width_, "altimg-width")
 GK_ATOM(annotation_, "annotation")
-GK_ATOM(annotation_xml_, "annotation-xml")
 GK_ATOM(apply_, "apply")
-GK_ATOM(approx_, "approx")
 GK_ATOM(arccos_, "arccos")
-GK_ATOM(arccosh_, "arccosh")
-GK_ATOM(arccot_, "arccot")
-GK_ATOM(arccoth_, "arccoth")
-GK_ATOM(arccsc_, "arccsc")
-GK_ATOM(arccsch_, "arccsch")
-GK_ATOM(arcsec_, "arcsec")
-GK_ATOM(arcsech_, "arcsech")
 GK_ATOM(arcsin_, "arcsin")
-GK_ATOM(arcsinh_, "arcsinh")
 GK_ATOM(arctan_, "arctan")
-GK_ATOM(arctanh_, "arctanh")
-GK_ATOM(arg_, "arg")
 GK_ATOM(bevelled_, "bevelled")
-GK_ATOM(bind_, "bind")
 GK_ATOM(bvar_, "bvar")
-GK_ATOM(card_, "card")
-GK_ATOM(cartesianproduct_, "cartesianproduct")
-GK_ATOM(cbytes_, "cbytes")
-GK_ATOM(cd_, "cd")
-GK_ATOM(cdgroup_, "cdgroup")
-GK_ATOM(cerror_, "cerror")
-GK_ATOM(charalign_, "charalign")
 GK_ATOM(ci_, "ci")
-GK_ATOM(closure_, "closure")
 GK_ATOM(cn_, "cn")
-GK_ATOM(codomain_, "codomain")
 GK_ATOM(columnalign_, "columnalign")
-GK_ATOM(columnalignment_, "columnalignment")
 GK_ATOM(columnlines_, "columnlines")
 GK_ATOM(columnspacing_, "columnspacing")
 GK_ATOM(columnspan_, "columnspan")
 GK_ATOM(columnwidth_, "columnwidth")
-GK_ATOM(complexes_, "complexes")
 GK_ATOM(compose_, "compose")
 GK_ATOM(condition_, "condition")
 GK_ATOM(conjugate_, "conjugate")
 GK_ATOM(cos_, "cos")
 GK_ATOM(cosh_, "cosh")
 GK_ATOM(cot_, "cot")
 GK_ATOM(coth_, "coth")
-GK_ATOM(crossout_, "crossout")
 GK_ATOM(csc_, "csc")
 GK_ATOM(csch_, "csch")
-GK_ATOM(cs_, "cs")
-GK_ATOM(csymbol_, "csymbol")
-GK_ATOM(curl_, "curl")
-GK_ATOM(decimalpoint_, "decimalpoint")
-GK_ATOM(definitionURL_, "definitionURL")
 GK_ATOM(degree_, "degree")
 GK_ATOM(denomalign_, "denomalign")
 GK_ATOM(depth_, "depth")
 GK_ATOM(determinant_, "determinant")
 GK_ATOM(diff_, "diff")
 GK_ATOM(displaystyle_, "displaystyle")
-GK_ATOM(divergence_, "divergence")
 GK_ATOM(divide_, "divide")
-GK_ATOM(domain_, "domain")
-GK_ATOM(domainofapplication_, "domainofapplication")
 GK_ATOM(edge_, "edge")
-GK_ATOM(el_, "el")
-GK_ATOM(emptyset_, "emptyset")
 GK_ATOM(eq_, "eq")
 GK_ATOM(equalcolumns_, "equalcolumns")
 GK_ATOM(equalrows_, "equalrows")
-GK_ATOM(equivalent_, "equivalent")
-GK_ATOM(eulergamma_, "eulergamma")
 GK_ATOM(exists_, "exists")
 GK_ATOM(exp_, "exp")
-GK_ATOM(exponentiale_, "exponentiale")
 GK_ATOM(factorial_, "factorial")
-GK_ATOM(factorof_, "factorof")
 GK_ATOM(fence_, "fence")
 GK_ATOM(fn_, "fn")
 GK_ATOM(fontfamily_, "fontfamily")
 GK_ATOM(fontsize_, "fontsize")
 GK_ATOM(fontstyle_, "fontstyle")
 GK_ATOM(fontweight_, "fontweight")
 GK_ATOM(forall_, "forall")
 GK_ATOM(framespacing_, "framespacing")
-GK_ATOM(gcd_, "gcd")
 GK_ATOM(geq_, "geq")
 GK_ATOM(groupalign_, "groupalign")
 GK_ATOM(gt_, "gt")
 GK_ATOM(ident_, "ident")
-GK_ATOM(imaginaryi_, "imaginaryi")
-GK_ATOM(imaginary_, "imaginary")
 GK_ATOM(implies_, "implies")
-GK_ATOM(indentalignfirst_, "indentalignfirst")
-GK_ATOM(indentalign_, "indentalign")
-GK_ATOM(indentalignlast_, "indentalignlast")
-GK_ATOM(indentshiftfirst_, "indentshiftfirst")
-GK_ATOM(indentshift_, "indentshift")
-GK_ATOM(indenttarget_, "indenttarget")
-GK_ATOM(integers_, "integers")
+GK_ATOM(int_, "int")
 GK_ATOM(intersect_, "intersect")
 GK_ATOM(interval_, "interval")
-GK_ATOM(int_, "int")
 GK_ATOM(inverse_, "inverse")
 GK_ATOM(lambda_, "lambda")
-GK_ATOM(laplacian_, "laplacian")
 GK_ATOM(largeop_, "largeop")
-GK_ATOM(lcm_, "lcm")
 GK_ATOM(leq_, "leq")
 GK_ATOM(limit_, "limit")
 GK_ATOM(linebreak_, "linebreak")
-GK_ATOM(linebreakmultchar_, "linebreakmultchar")
-GK_ATOM(linebreakstyle_, "linebreakstyle")
 GK_ATOM(linethickness_, "linethickness")
 GK_ATOM(list_, "list")
 GK_ATOM(ln_, "ln")
-GK_ATOM(location_, "location")
+GK_ATOM(log_, "log")
 GK_ATOM(logbase_, "logbase")
-GK_ATOM(log_, "log")
-GK_ATOM(longdivstyle_, "longdivstyle")
 GK_ATOM(lowlimit_, "lowlimit")
 GK_ATOM(lquote_, "lquote")
 GK_ATOM(lspace_, "lspace")
 GK_ATOM(lt_, "lt")
 GK_ATOM(maction_, "maction")
 GK_ATOM(maligngroup_, "maligngroup")
-GK_ATOM(malign_, "malign")
 GK_ATOM(malignmark_, "malignmark")
-GK_ATOM(malignscope_, "malignscope")
 GK_ATOM(mathbackground_, "mathbackground")
 GK_ATOM(mathcolor_, "mathcolor")
 GK_ATOM(mathsize_, "mathsize")
 GK_ATOM(mathvariant_, "mathvariant")
 GK_ATOM(matrixrow_, "matrixrow")
 GK_ATOM(maxsize_, "maxsize")
 GK_ATOM(mean_, "mean")
 GK_ATOM(median_, "median")
 GK_ATOM(mediummathspace_, "mediummathspace")
 GK_ATOM(menclose_, "menclose")
 GK_ATOM(merror_, "merror")
 GK_ATOM(mfenced_, "mfenced")
 GK_ATOM(mfrac_, "mfrac")
-GK_ATOM(mfraction_, "mfraction")
-GK_ATOM(mglyph_, "mglyph")
 GK_ATOM(mi_, "mi")
 GK_ATOM(minlabelspacing_, "minlabelspacing")
 GK_ATOM(minsize_, "minsize")
 GK_ATOM(minus_, "minus")
 GK_ATOM(mlabeledtr_, "mlabeledtr")
-GK_ATOM(mlongdiv_, "mlongdiv")
 GK_ATOM(mmultiscripts_, "mmultiscripts")
 GK_ATOM(mn_, "mn")
-GK_ATOM(momentabout_, "momentabout")
+GK_ATOM(mo_, "mo")
 GK_ATOM(moment_, "moment")
-GK_ATOM(mo_, "mo")
-GK_ATOM(monospaced_, "monospaced")
 GK_ATOM(movablelimits_, "movablelimits")
 GK_ATOM(mover_, "mover")
 GK_ATOM(mpadded_, "mpadded")
 GK_ATOM(mphantom_, "mphantom")
 GK_ATOM(mprescripts_, "mprescripts")
 GK_ATOM(mroot_, "mroot")
 GK_ATOM(mrow_, "mrow")
-GK_ATOM(mscarries_, "mscarries")
-GK_ATOM(mscarry_, "mscarry")
-GK_ATOM(msgroup_, "msgroup")
-GK_ATOM(msline_, "msline")
 GK_ATOM(ms_, "ms")
 GK_ATOM(mspace_, "mspace")
 GK_ATOM(msqrt_, "msqrt")
-GK_ATOM(msrow_, "msrow")
-GK_ATOM(mstack_, "mstack")
 GK_ATOM(mstyle_, "mstyle")
 GK_ATOM(msub_, "msub")
 GK_ATOM(msubsup_, "msubsup")
 GK_ATOM(msup_, "msup")
 GK_ATOM(mtable_, "mtable")
 GK_ATOM(mtd_, "mtd")
 GK_ATOM(mtext_, "mtext")
 GK_ATOM(mtr_, "mtr")
 GK_ATOM(munder_, "munder")
 GK_ATOM(munderover_, "munderover")
-GK_ATOM(naturalnumbers_, "naturalnumbers")
-GK_ATOM(negativemediummathspace_, "negativemediummathspace")
-GK_ATOM(negativethickmathspace_, "negativethickmathspace")
-GK_ATOM(negativethinmathspace_, "negativethinmathspace")
-GK_ATOM(negativeverythickmathspace_, "negativeverythickmathspace")
-GK_ATOM(negativeverythinmathspace_, "negativeverythinmathspace")
-GK_ATOM(negativeveryverythickmathspace_, "negativeveryverythickmathspace")
-GK_ATOM(negativeveryverythinmathspace_, "negativeveryverythinmathspace")
 GK_ATOM(neq_, "neq")
-GK_ATOM(notanumber_, "notanumber")
 GK_ATOM(notation_, "notation")
-GK_ATOM(note_, "note")
 GK_ATOM(notin_, "notin")
 GK_ATOM(notprsubset_, "notprsubset")
 GK_ATOM(notsubset_, "notsubset")
 GK_ATOM(numalign_, "numalign")
 GK_ATOM(other_, "other")
-GK_ATOM(outerproduct_, "outerproduct")
 GK_ATOM(partialdiff_, "partialdiff")
-GK_ATOM(piece_, "piece")
-GK_ATOM(piecewise_, "piecewise")
-GK_ATOM(pi_, "pi")
 GK_ATOM(plus_, "plus")
 GK_ATOM(power_, "power")
-GK_ATOM(primes_, "primes")
 GK_ATOM(product_, "product")
 GK_ATOM(prsubset_, "prsubset")
 GK_ATOM(quotient_, "quotient")
-GK_ATOM(rationals_, "rationals")
-GK_ATOM(real_, "real")
-GK_ATOM(reals_, "reals")
 GK_ATOM(reln_, "reln")
 GK_ATOM(root_, "root")
 GK_ATOM(rowalign_, "rowalign")
 GK_ATOM(rowlines_, "rowlines")
 GK_ATOM(rowspacing_, "rowspacing")
 GK_ATOM(rquote_, "rquote")
 GK_ATOM(rspace_, "rspace")
-GK_ATOM(scalarproduct_, "scalarproduct")
-GK_ATOM(schemaLocation_, "schemaLocation")
 GK_ATOM(scriptlevel_, "scriptlevel")
 GK_ATOM(scriptminsize_, "scriptminsize")
 GK_ATOM(scriptsizemultiplier_, "scriptsizemultiplier")
-GK_ATOM(scriptsize_, "scriptsize")
 GK_ATOM(sdev_, "sdev")
-GK_ATOM(sech_, "sech")
 GK_ATOM(sec_, "sec")
+GK_ATOM(sech_, "sech")
 GK_ATOM(selection_, "selection")
-GK_ATOM(selector_, "selector")
 GK_ATOM(semantics_, "semantics")
+GK_ATOM(sep_, "sep")
 GK_ATOM(separator_, "separator")
 GK_ATOM(separators_, "separators")
-GK_ATOM(sep_, "sep")
+GK_ATOM(set_, "set")
 GK_ATOM(setdiff_, "setdiff")
-GK_ATOM(set_, "set")
-GK_ATOM(share_, "share")
-GK_ATOM(shift_, "shift")
 GK_ATOM(side_, "side")
+GK_ATOM(sin_, "sin")
 GK_ATOM(sinh_, "sinh")
-GK_ATOM(sin_, "sin")
-GK_ATOM(stackalign_, "stackalign")
 GK_ATOM(stretchy_, "stretchy")
 GK_ATOM(subscriptshift_, "subscriptshift")
 GK_ATOM(subset_, "subset")
 GK_ATOM(superscriptshift_, "superscriptshift")
 GK_ATOM(symmetric_, "symmetric")
+GK_ATOM(tan_, "tan")
 GK_ATOM(tanh_, "tanh")
-GK_ATOM(tan_, "tan")
 GK_ATOM(tendsto_, "tendsto")
 GK_ATOM(thickmathspace_, "thickmathspace")
 GK_ATOM(thinmathspace_, "thinmathspace")
 GK_ATOM(times_, "times")
 GK_ATOM(transpose_, "transpose")
 GK_ATOM(union_, "union")
 GK_ATOM(uplimit_, "uplimit")
-GK_ATOM(variance_, "variance")
-GK_ATOM(vectorproduct_, "vectorproduct")
+GK_ATOM(var_, "var")
 GK_ATOM(vector_, "vector")
 GK_ATOM(verythickmathspace_, "verythickmathspace")
 GK_ATOM(verythinmathspace_, "verythinmathspace")
 GK_ATOM(veryverythickmathspace_, "veryverythickmathspace")
 GK_ATOM(veryverythinmathspace_, "veryverythinmathspace")
-GK_ATOM(voffset_, "voffset")
-GK_ATOM(xref_, "xref")
 GK_ATOM(math, "math") // the only one without an underscore
 #endif
 
 #if defined(MOZ_SVG) || defined(MOZ_MATHML)
 GK_ATOM(xor_, "xor")
 #endif
 
 #ifndef DISABLE_XFORMS_HOOKS
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -3360,19 +3360,17 @@ bitblt(gfxImageSurface *s, int src_x, in
 //   -- render the region defined by (sx,sy,sw,wh) in image-local space into the region (dx,dy,dw,dh) on the canvas
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::DrawImage(nsIDOMElement *imgElt, float a1,
                                       float a2, float a3, float a4, float a5,
                                       float a6, float a7, float a8,
                                       PRUint8 optional_argc)
 {
-    if (!imgElt) {
-        return NS_ERROR_DOM_TYPE_MISMATCH_ERR;
-    }
+    NS_ENSURE_ARG(imgElt);
 
     double sx,sy,sw,sh;
     double dx,dy,dw,dh;
 
     gfxMatrix matrix;
     nsRefPtr<gfxPattern> pattern;
     gfxIntSize imgSize;
     nsRefPtr<gfxASurface> imgsurf =
--- a/content/canvas/test/test_canvas.html
+++ b/content/canvas/test/test_canvas.html
@@ -3492,17 +3492,17 @@ isPixel(ctx, 55,25, 0,255,0,255, 2);
 
 function test_2d_drawImage_null() {
 
 var canvas = document.getElementById('c121');
 var ctx = canvas.getContext('2d');
 
 var _thrown = undefined; try {
   ctx.drawImage(null, 0, 0);
-} catch (e) { _thrown = e }; ok(_thrown && _thrown.code == DOMException.TYPE_MISMATCH_ERR, "should throw TYPE_MISMATCH_ERR");
+} catch (e) { _thrown = e }; todo(_thrown && _thrown.code == DOMException.TYPE_MISMATCH_ERR, "should throw TYPE_MISMATCH_ERR");
 
 
 }
 </script>
 
 <!-- [[[ test_2d.drawImage.outsidesource.html ]]] -->
 
 <p>Canvas test: 2d.drawImage.outsidesource</p>
@@ -3664,17 +3664,17 @@ function test_2d_drawImage_wrongtype() {
 
 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
 var canvas = document.getElementById('c127');
 var ctx = canvas.getContext('2d');
 
 var _thrown = undefined; try {
   ctx.drawImage(undefined, 0, 0);
-} catch (e) { _thrown = e }; ok(_thrown && _thrown.code == DOMException.TYPE_MISMATCH_ERR, "should throw TYPE_MISMATCH_ERR");
+} catch (e) { _thrown = e }; ok(_thrown && _thrown.result == Components.results.NS_ERROR_INVALID_ARG, "should throw NS_ERROR_INVALID_ARG");
 var _thrown = undefined; try {
   ctx.drawImage(0, 0, 0);
 } catch (e) { _thrown = e }; ok(_thrown && _thrown.result == Components.results.NS_ERROR_XPC_BAD_CONVERT_JS_ZERO_ISNOT_NULL, "should throw NS_ERROR_XPC_BAD_CONVERT_JS_ZERO_ISNOT_NULL");
 var _thrown = undefined; try {
   ctx.drawImage("", 0, 0);
 } catch (e) { _thrown = e }; ok(_thrown && _thrown.result == Components.results.NS_ERROR_XPC_BAD_CONVERT_JS, "should throw NS_ERROR_XPC_BAD_CONVERT_JS");
 var _thrown = undefined; try {
   ctx.drawImage(document.createElement('p'), 0, 0);
--- a/content/html/document/src/nsHTMLContentSink.cpp
+++ b/content/html/document/src/nsHTMLContentSink.cpp
@@ -55,16 +55,17 @@
 #include "nsIContentViewer.h"
 #include "nsIMarkupDocumentViewer.h"
 #include "nsINodeInfo.h"
 #include "nsHTMLTokens.h"
 #include "nsIAppShell.h"
 #include "nsCRT.h"
 #include "prtime.h"
 #include "prlog.h"
+#include "nsInt64.h"
 #include "nsNodeUtils.h"
 #include "nsIContent.h"
 #include "mozilla/dom/Element.h"
 
 #include "nsGenericHTMLElement.h"
 
 #include "nsIDOMText.h"
 #include "nsIDOMComment.h"
--- a/dom/ipc/AudioParent.cpp
+++ b/dom/ipc/AudioParent.cpp
@@ -33,17 +33,16 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "mozilla/dom/AudioParent.h"
-#include "mozilla/unused.h"
 #include "nsThreadUtils.h"
 
 // C++ file contents
 namespace mozilla {
 namespace dom {
 
 class AudioWriteEvent : public nsRunnable
 {
@@ -155,17 +154,17 @@ AudioParent::Notify(nsITimer* timer)
 {
   if (!mIPCOpen) {
     timer->Cancel();
     return NS_ERROR_FAILURE;
   }
 
   NS_ASSERTION(mStream, "AudioStream not initialized.");
   PRInt64 offset = mStream->GetSampleOffset();
-  unused << SendSampleOffsetUpdate(offset, PR_IntervalNow());
+  SendSampleOffsetUpdate(offset, PR_IntervalNow());
   return NS_OK;
 }
 
 bool
 AudioParent::RecvWrite(
         const nsCString& data,
         const PRUint32& count)
 {
@@ -218,17 +217,17 @@ AudioParent::RecvResume()
   thread->Dispatch(event, nsIEventTarget::DISPATCH_NORMAL);
   return true;
 }
 
 bool
 AudioParent::RecvShutdown()
 {
   Shutdown();
-  unused << PAudioParent::Send__delete__(this);
+  PAudioParent::Send__delete__(this);
   return true;
 }
 
 bool
 AudioParent::SendDrainDone()
 {
   if (mIPCOpen)
     return PAudioParent::SendDrainDone();
--- a/dom/src/threads/test/WorkerTest.jsm
+++ b/dom/src/threads/test/WorkerTest.jsm
@@ -47,11 +47,10 @@ XPCOMUtils.defineLazyServiceGetter(this,
                                    "nsIWorkerFactory");
 
 const WorkerTest = {
   go: function(message, messageCallback, errorCallback) {
     let worker = workerFactory.newChromeWorker("WorkerTest_worker.js");
     worker.onmessage = messageCallback;
     worker.onerror = errorCallback;
     worker.postMessage(message);
-    return worker;
   }
 };
--- a/dom/src/threads/test/test_chromeWorkerJSM.xul
+++ b/dom/src/threads/test/test_chromeWorkerJSM.xul
@@ -49,38 +49,29 @@
 
   <script type="application/javascript">
   <![CDATA[
 
     function test()
     {
       SimpleTest.waitForExplicitFinish();
 
-      var worker;
-
-      function done()
-      {
-        worker = null;
-        SimpleTest.finish();
-      }
-
       function messageCallback(event) {
         is(event.data, "Done", "Correct message");
-        done();
+        SimpleTest.finish();
       }
 
       function errorCallback(event) {
         ok(false, "Worker had an error: " + event.message);
-        done();
+        SimpleTest.finish();
       }
 
       Components.utils.import("resource://gre/modules/WorkerTest.jsm");
 
-      worker = WorkerTest.go(window.location.href, messageCallback,
-                             errorCallback);
+      WorkerTest.go(window.location.href, messageCallback, errorCallback);
     }
 
   ]]>
   </script>
 
   <body xmlns="http://www.w3.org/1999/xhtml">
     <p id="display"></p>
     <div id="content" style="display:none;"></div>
--- a/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
+++ b/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.cpp
@@ -57,16 +57,17 @@
 #include "nsIUploadChannel.h"
 #include "nsICachingChannel.h"
 #include "nsIFileChannel.h"
 #include "nsEscape.h"
 #include "nsUnicharUtils.h"
 #include "nsIStringEnumerator.h"
 #include "nsCRT.h"
 #include "nsSupportsArray.h"
+#include "nsInt64.h"
 #include "nsContentCID.h"
 #include "nsStreamUtils.h"
 
 #include "nsCExternalHandlerService.h"
 
 #include "nsIURL.h"
 #include "nsIFileURL.h"
 #include "nsIDocument.h"
@@ -162,18 +163,18 @@ struct URIData
 };
 
 // Information about the output stream
 struct OutputData
 {
     nsCOMPtr<nsIURI> mFile;
     nsCOMPtr<nsIURI> mOriginalLocation;
     nsCOMPtr<nsIOutputStream> mStream;
-    PRInt64 mSelfProgress;
-    PRInt64 mSelfProgressMax;
+    nsInt64 mSelfProgress;
+    nsInt64 mSelfProgressMax;
     PRPackedBool mCalcFileExt;
 
     OutputData(nsIURI *aFile, nsIURI *aOriginalLocation, PRBool aCalcFileExt) :
         mFile(aFile),
         mOriginalLocation(aOriginalLocation),
         mSelfProgress(0),
         mSelfProgressMax(10000),
         mCalcFileExt(aCalcFileExt)
@@ -186,18 +187,18 @@ struct OutputData
             mStream->Close();
         }
     }
 };
 
 struct UploadData
 {
     nsCOMPtr<nsIURI> mFile;
-    PRInt64 mSelfProgress;
-    PRInt64 mSelfProgressMax;
+    nsInt64 mSelfProgress;
+    nsInt64 mSelfProgressMax;
 
     UploadData(nsIURI *aFile) :
         mFile(aFile),
         mSelfProgress(0),
         mSelfProgressMax(10000)
     {
     }
 };
@@ -238,18 +239,16 @@ nsWebBrowserPersist::nsWebBrowserPersist
     mJustStartedLoading(PR_TRUE),
     mCompleted(PR_FALSE),
     mStartSaving(PR_FALSE),
     mReplaceExisting(PR_TRUE),
     mSerializingOutput(PR_FALSE),
     mPersistFlags(kDefaultPersistFlags),
     mPersistResult(NS_OK),
     mWrapColumn(72),
-    mTotalCurrentProgress(0),
-    mTotalMaxProgress(0),
     mEncodingFlags(0)
 {
 }
 
 nsWebBrowserPersist::~nsWebBrowserPersist()
 {
     Cleanup();
 }
--- a/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.h
+++ b/embedding/components/webbrowserpersist/src/nsWebBrowserPersist.h
@@ -53,16 +53,17 @@
 #include "nsIDocumentEncoder.h"
 #include "nsITransport.h"
 #include "nsIProgressEventSink.h"
 #include "nsILocalFile.h"
 #include "nsIWebProgressListener2.h"
 
 #include "nsHashtable.h"
 #include "nsTArray.h"
+#include "nsInt64.h"
 
 #include "nsCWebBrowserPersist.h"
 
 class nsEncoderNodeFixup;
 class nsIStorageStream;
 
 struct URIData;
 struct CleanupData;
@@ -234,18 +235,18 @@ private:
     PRPackedBool              mCancel;
     PRPackedBool              mJustStartedLoading;
     PRPackedBool              mCompleted;
     PRPackedBool              mStartSaving;
     PRPackedBool              mReplaceExisting;
     PRPackedBool              mSerializingOutput;
     PRUint32                  mPersistFlags;
     PRUint32                  mPersistResult;
-    PRInt64                   mTotalCurrentProgress;
-    PRInt64                   mTotalMaxProgress;
+    nsInt64                   mTotalCurrentProgress;
+    nsInt64                   mTotalMaxProgress;
     PRInt16                   mWrapColumn;
     PRUint32                  mEncodingFlags;
     nsString                  mContentType;
 };
 
 // Helper class does node fixup during persistence
 class nsEncoderNodeFixup : public nsIDocumentEncoderNodeFixup
 {
--- a/gfx/thebes/GLContext.h
+++ b/gfx/thebes/GLContext.h
@@ -2062,19 +2062,16 @@ public:
     nsTArray<NamedResource> mTrackedBuffers;
 #endif
 
 };
 
 inline PRBool
 DoesVendorStringMatch(const char* aVendorString, const char *aWantedVendor)
 {
-    if (!aVendorString || !aWantedVendor)
-        return PR_FALSE;
-
     const char *occurrence = strstr(aVendorString, aWantedVendor);
 
     // aWantedVendor not found
     if (!occurrence)
         return PR_FALSE;
 
     // aWantedVendor preceded by alpha character
     if (occurrence != aVendorString && isalpha(*(occurrence-1)))
--- a/modules/libjar/nsJARChannel.cpp
+++ b/modules/libjar/nsJARChannel.cpp
@@ -37,16 +37,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsJAR.h"
 #include "nsJARChannel.h"
 #include "nsJARProtocolHandler.h"
 #include "nsMimeTypes.h"
 #include "nsNetUtil.h"
+#include "nsInt64.h"
 #include "nsEscape.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsIViewSourceChannel.h"
 #include "nsChannelProperties.h"
 
 #include "nsIScriptSecurityManager.h"
 #include "nsIPrincipal.h"
--- a/modules/libpr0n/decoders/icon/mac/nsIconChannelCocoa.mm
+++ b/modules/libpr0n/decoders/icon/mac/nsIconChannelCocoa.mm
@@ -51,16 +51,17 @@
 #include "nsIStringStream.h"
 #include "nsIURL.h"
 #include "nsNetUtil.h"
 #include "nsIMIMEService.h"
 #include "nsCExternalHandlerService.h"
 #include "plstr.h"
 #include "nsILocalFileMac.h"
 #include "nsIFileURL.h"
+#include "nsInt64.h"
 #include "nsTArray.h"
 #include "nsObjCExceptions.h"
 
 #include <Cocoa/Cocoa.h>
 
 // nsIconChannel methods
 nsIconChannel::nsIconChannel()
 {
@@ -214,17 +215,17 @@ nsresult nsIconChannel::ExtractIconInfoF
 
 NS_IMETHODIMP nsIconChannel::AsyncOpen(nsIStreamListener *aListener, nsISupports *ctxt)
 {
   nsCOMPtr<nsIInputStream> inStream;
   nsresult rv = MakeInputStream(getter_AddRefs(inStream), PR_TRUE);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Init our stream pump
-  rv = mPump->Init(inStream, PRInt64(-1), PRInt64(-1), 0, 0, PR_FALSE);
+  rv = mPump->Init(inStream, nsInt64(-1), nsInt64(-1), 0, 0, PR_FALSE);
   NS_ENSURE_SUCCESS(rv, rv);
   
   rv = mPump->AsyncRead(this, ctxt);
   if (NS_SUCCEEDED(rv)) {
     // Store our real listener
     mListener = aListener;
     // Add ourself to the load group, if available
     if (mLoadGroup)
--- a/modules/libpr0n/decoders/icon/os2/nsIconChannel.cpp
+++ b/modules/libpr0n/decoders/icon/os2/nsIconChannel.cpp
@@ -42,16 +42,17 @@
 
 //------------------------------------------------------------------------
 
 #include "nsIconChannel.h"
 #include "nsIIconURI.h"
 #include "nsReadableUtils.h"
 #include "nsMemory.h"
 #include "nsNetUtil.h"
+#include "nsInt64.h"
 #include "nsILocalFile.h"
 #include "nsIFileURL.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsIRwsService.h"
 
 #define INCL_PM
 #include <os2.h>
 
@@ -197,17 +198,17 @@ nsIconChannel::Open(nsIInputStream **_re
 NS_IMETHODIMP nsIconChannel::AsyncOpen(nsIStreamListener *aListener, nsISupports *ctxt)
 {
   nsCOMPtr<nsIInputStream> inStream;
   nsresult rv = MakeInputStream(getter_AddRefs(inStream), PR_TRUE);
   if (NS_FAILED(rv))
     return rv;
 
   // Init our streampump
-  rv = mPump->Init(inStream, PRInt64(-1), PRInt64(-1), 0, 0, PR_FALSE);
+  rv = mPump->Init(inStream, nsInt64(-1), nsInt64(-1), 0, 0, PR_FALSE);
   if (NS_FAILED(rv))
     return rv;
 
   rv = mPump->AsyncRead(this, ctxt);
   if (NS_SUCCEEDED(rv)) {
     // Store our real listener
     mListener = aListener;
     // Add ourself to the load group, if available
--- a/modules/libpr0n/decoders/icon/win/nsIconChannel.cpp
+++ b/modules/libpr0n/decoders/icon/win/nsIconChannel.cpp
@@ -48,16 +48,17 @@
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
 #include "nsMimeTypes.h"
 #include "nsMemory.h"
 #include "nsIStringStream.h"
 #include "nsIURL.h"
 #include "nsNetUtil.h"
+#include "nsInt64.h"
 #include "nsIFile.h"
 #include "nsIFileURL.h"
 #include "nsIMIMEService.h"
 #include "nsCExternalHandlerService.h"
 #include "nsDirectoryServiceDefs.h"
 
 #if MOZ_WINSDK_TARGETVER >= MOZ_NTDDI_LONGHORN
 #ifdef _WIN32_WINNT
@@ -243,17 +244,17 @@ nsresult nsIconChannel::ExtractIconInfoF
 NS_IMETHODIMP nsIconChannel::AsyncOpen(nsIStreamListener *aListener, nsISupports *ctxt)
 {
   nsCOMPtr<nsIInputStream> inStream;
   nsresult rv = MakeInputStream(getter_AddRefs(inStream), PR_TRUE);
   if (NS_FAILED(rv))
     return rv;
 
   // Init our streampump
-  rv = mPump->Init(inStream, PRInt64(-1), PRInt64(-1), 0, 0, PR_FALSE);
+  rv = mPump->Init(inStream, nsInt64(-1), nsInt64(-1), 0, 0, PR_FALSE);
   if (NS_FAILED(rv))
     return rv;
 
   rv = mPump->AsyncRead(this, ctxt);
   if (NS_SUCCEEDED(rv)) {
     // Store our real listener
     mListener = aListener;
     // Add ourself to the load group, if available
--- a/modules/libpref/src/init/all.js
+++ b/modules/libpref/src/init/all.js
@@ -748,21 +748,16 @@ pref("network.http.prompt-temp-redirect"
 // for certain services (i.e. EF for VoIP, AF4x for interactive video,
 // AF3x for broadcast/streaming video, etc)
 
 // default value for HTTP
 // in a DSCP environment this should be 40 (0x28, or AF11), per RFC-4594,
 // Section 4.8 "High-Throughput Data Service Class"
 pref("network.http.qos", 0);
 
-// The number of milliseconds after sending a SYN for an HTTP connection,
-// to wait before trying a different connection. 0 means do not use a second
-// connection.
-pref("network.http.connection-retry-timeout", 250);
-
 // default values for FTP
 // in a DSCP environment this should be 40 (0x28, or AF11), per RFC-4594,
 // Section 4.8 "High-Throughput Data Service Class", and 80 (0x50, or AF22)
 // per Section 4.7 "Low-Latency Data Service Class".
 pref("network.ftp.data.qos", 0);
 pref("network.ftp.control.qos", 0);
 
 // </http>
--- a/modules/plugin/base/src/nsPluginHost.cpp
+++ b/modules/plugin/base/src/nsPluginHost.cpp
@@ -128,16 +128,17 @@
 #include "nsIPlatformCharset.h"
 
 #include "nsIDirectoryService.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsXULAppAPI.h"
 #include "nsAppDirectoryServiceDefs.h"
 #include "nsIFile.h"
 #include "nsPluginDirServiceProvider.h"
+#include "nsInt64.h"
 #include "nsPluginError.h"
 
 #include "nsUnicharUtils.h"
 #include "nsPluginManifestLineReader.h"
 
 #include "nsIWeakReferenceUtils.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMHTMLObjectElement.h"
@@ -2884,17 +2885,17 @@ nsPluginHost::ReadPluginInfo()
   if (NS_FAILED(rv))
     return rv;
 
   PRInt64 fileSize;
   rv = localFile->GetFileSize(&fileSize);
   if (NS_FAILED(rv))
     return rv;
 
-  PRInt32 flen = PRInt64(fileSize);
+  PRInt32 flen = nsInt64(fileSize);
   if (flen == 0) {
     NS_WARNING("Plugins Registry Empty!");
     return NS_OK; // ERROR CONDITION
   }
 
   nsPluginManifestLineReader reader;
   char* registry = reader.Init(flen);
   if (!registry)
--- a/modules/plugin/base/src/nsPluginStreamListenerPeer.cpp
+++ b/modules/plugin/base/src/nsPluginStreamListenerPeer.cpp
@@ -964,17 +964,17 @@ NS_IMETHODIMP nsPluginStreamListenerPeer
     if (brr) {
       if (!mDataForwardToRequest)
         return NS_ERROR_FAILURE;
       
       PRInt64 absoluteOffset64 = LL_ZERO;
       brr->GetStartRange(&absoluteOffset64);
       
       // XXX handle 64-bit for real
-      PRInt32 absoluteOffset = (PRInt32)PRInt64(absoluteOffset64);
+      PRInt32 absoluteOffset = (PRInt32)nsInt64(absoluteOffset64);
       
       // we need to track how much data we have forwarded to the
       // plugin.
       
       // FIXME: http://bugzilla.mozilla.org/show_bug.cgi?id=240130
       //
       // Why couldn't this be tracked on the plugin info, and not in a
       // *hash table*?
@@ -1044,17 +1044,17 @@ NS_IMETHODIMP nsPluginStreamListenerPeer
               this, aStatus, request));
   
   // for ByteRangeRequest we're just updating the mDataForwardToRequest hash and return.
   nsCOMPtr<nsIByteRangeRequest> brr = do_QueryInterface(request);
   if (brr) {
     PRInt64 absoluteOffset64 = LL_ZERO;
     brr->GetStartRange(&absoluteOffset64);
     // XXX support 64-bit offsets
-    PRInt32 absoluteOffset = (PRInt32)PRInt64(absoluteOffset64);
+    PRInt32 absoluteOffset = (PRInt32)nsInt64(absoluteOffset64);
     
     nsPRUintKey key(absoluteOffset);
     
     // remove the request from our data forwarding count hash.
     mDataForwardToRequest->Remove(&key);
     
     
     PLUGIN_LOG(PLUGIN_LOG_NOISY,
--- a/netwerk/base/public/nsNetUtil.h
+++ b/netwerk/base/public/nsNetUtil.h
@@ -85,16 +85,17 @@
 #include "nsIProxyInfo.h"
 #include "nsIFileStreams.h"
 #include "nsIBufferedStreams.h"
 #include "nsIInputStreamPump.h"
 #include "nsIAsyncStreamCopier.h"
 #include "nsIPersistentProperties2.h"
 #include "nsISyncStreamListener.h"
 #include "nsInterfaceRequestorAgg.h"
+#include "nsInt64.h"
 #include "nsINetUtil.h"
 #include "nsIURIWithPrincipal.h"
 #include "nsIAuthPrompt.h"
 #include "nsIAuthPrompt2.h"
 #include "nsIAuthPromptAdapterFactory.h"
 #include "nsComponentManagerUtils.h"
 #include "nsServiceManagerUtils.h"
 #include "nsINestedURI.h"
@@ -484,18 +485,18 @@ NS_NewInputStreamChannel(nsIChannel     
 {
     return NS_NewInputStreamChannel(result, uri, stream, contentType,
                                     &contentCharset);
 }
 
 inline nsresult
 NS_NewInputStreamPump(nsIInputStreamPump **result,
                       nsIInputStream      *stream,
-                      PRInt64              streamPos = PRInt64(-1),
-                      PRInt64              streamLen = PRInt64(-1),
+                      PRInt64              streamPos = nsInt64(-1),
+                      PRInt64              streamLen = nsInt64(-1),
                       PRUint32             segsize = 0,
                       PRUint32             segcount = 0,
                       PRBool               closeWhenDone = PR_FALSE)
 {
     nsresult rv;
     nsCOMPtr<nsIInputStreamPump> pump =
         do_CreateInstance(NS_INPUTSTREAMPUMP_CONTRACTID, &rv);
     if (NS_SUCCEEDED(rv)) {
@@ -1034,17 +1035,17 @@ NS_BackgroundInputStream(nsIInputStream 
                          PRUint32         segmentSize  = 0,
                          PRUint32         segmentCount = 0)
 {
     nsresult rv;
     nsCOMPtr<nsIStreamTransportService> sts =
         do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID, &rv);
     if (NS_SUCCEEDED(rv)) {
         nsCOMPtr<nsITransport> inTransport;
-        rv = sts->CreateInputTransport(stream, PRInt64(-1), PRInt64(-1),
+        rv = sts->CreateInputTransport(stream, nsInt64(-1), nsInt64(-1),
                                        PR_TRUE, getter_AddRefs(inTransport));
         if (NS_SUCCEEDED(rv))
             rv = inTransport->OpenInputStream(nsITransport::OPEN_BLOCKING,
                                               segmentSize, segmentCount,
                                               result);
     }
     return rv;
 }
@@ -1058,17 +1059,17 @@ NS_BackgroundOutputStream(nsIOutputStrea
                           PRUint32          segmentSize  = 0,
                           PRUint32          segmentCount = 0)
 {
     nsresult rv;
     nsCOMPtr<nsIStreamTransportService> sts =
         do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID, &rv);
     if (NS_SUCCEEDED(rv)) {
         nsCOMPtr<nsITransport> inTransport;
-        rv = sts->CreateOutputTransport(stream, PRInt64(-1), PRInt64(-1),
+        rv = sts->CreateOutputTransport(stream, nsInt64(-1), nsInt64(-1),
                                         PR_TRUE, getter_AddRefs(inTransport));
         if (NS_SUCCEEDED(rv))
             rv = inTransport->OpenOutputStream(nsITransport::OPEN_BLOCKING,
                                                segmentSize, segmentCount,
                                                result);
     }
     return rv;
 }
--- a/netwerk/base/src/nsBufferedStreams.cpp
+++ b/netwerk/base/src/nsBufferedStreams.cpp
@@ -160,17 +160,17 @@ nsBufferedStream::Seek(PRInt32 whence, P
     // If the underlying stream isn't a random access store, then fail early.
     // We could possibly succeed for the case where the seek position denotes
     // something that happens to be read into the buffer, but that would make
     // the failure data-dependent.
     nsresult rv;
     nsCOMPtr<nsISeekableStream> ras = do_QueryInterface(mStream, &rv);
     if (NS_FAILED(rv)) return rv;
 
-    PRInt64 absPos = 0;
+    nsInt64 absPos;
     switch (whence) {
       case nsISeekableStream::NS_SEEK_SET:
         absPos = offset;
         break;
       case nsISeekableStream::NS_SEEK_CUR:
         absPos = mBufferStartOffset;
         absPos += mCursor;
         absPos += offset;
@@ -200,18 +200,18 @@ nsBufferedStream::Seek(PRInt32 whence, P
     rv = Flush();
     if (NS_FAILED(rv)) return rv;
 
     rv = ras->Seek(whence, offset);
     if (NS_FAILED(rv)) return rv;
 
     METER(if (bufstats.mBigSeekIndex < MAX_BIG_SEEKS)
               bufstats.mBigSeek[bufstats.mBigSeekIndex].mOldOffset =
-                  mBufferStartOffset + PRInt64(mCursor));
-    const PRInt64 minus1 = -1;
+                  mBufferStartOffset + nsInt64(mCursor));
+    const nsInt64 minus1 = -1;
     if (absPos == minus1) {
         // then we had the SEEK_END case, above
         PRInt64 tellPos;
         rv = ras->Tell(&tellPos);
         mBufferStartOffset = tellPos;
         if (NS_FAILED(rv)) return rv;
     }
     else {
@@ -226,17 +226,17 @@ nsBufferedStream::Seek(PRInt32 whence, P
 }
 
 NS_IMETHODIMP
 nsBufferedStream::Tell(PRInt64 *result)
 {
     if (mStream == nsnull)
         return NS_BASE_STREAM_CLOSED;
     
-    PRInt64 result64 = mBufferStartOffset;
+    nsInt64 result64 = mBufferStartOffset;
     result64 += mCursor;
     *result = result64;
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsBufferedStream::SetEOF()
 {
--- a/netwerk/base/src/nsBufferedStreams.h
+++ b/netwerk/base/src/nsBufferedStreams.h
@@ -40,16 +40,17 @@
 
 #include "nsIBufferedStreams.h"
 #include "nsIInputStream.h"
 #include "nsIOutputStream.h"
 #include "nsISafeOutputStream.h"
 #include "nsISeekableStream.h"
 #include "nsIStreamBufferAccess.h"
 #include "nsCOMPtr.h"
+#include "nsInt64.h"
 #include "nsIIPCSerializable.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 
 class nsBufferedStream : public nsISeekableStream
 {
 public:
     NS_DECL_ISUPPORTS
@@ -64,17 +65,17 @@ protected:
     nsresult Init(nsISupports* stream, PRUint32 bufferSize);
     NS_IMETHOD Fill() = 0;
     NS_IMETHOD Flush() = 0;
 
     PRUint32                    mBufferSize;
     char*                       mBuffer;
 
     // mBufferStartOffset is the offset relative to the start of mStream.
-    PRInt64                     mBufferStartOffset;
+    nsInt64                     mBufferStartOffset;
 
     // mCursor is the read cursor for input streams, or write cursor for
     // output streams, and is relative to mBufferStartOffset.
     PRUint32                    mCursor;
 
     // mFillPoint is the amount available in the buffer for input streams,
     // or the high watermark of bytes written into the buffer, and therefore
     // is relative to mBufferStartOffset.
--- a/netwerk/base/src/nsFileStreams.cpp
+++ b/netwerk/base/src/nsFileStreams.cpp
@@ -52,16 +52,17 @@
 
 #include "private/pprio.h"
 
 #include "nsFileStreams.h"
 #include "nsILocalFile.h"
 #include "nsXPIDLString.h"
 #include "prerror.h"
 #include "nsCRT.h"
+#include "nsInt64.h"
 #include "nsIFile.h"
 #include "nsDirectoryIndexStream.h"
 #include "nsMimeTypes.h"
 #include "nsReadLine.h"
 #include "nsNetUtil.h"
 #include "nsIClassInfoImpl.h"
 
 #define NS_NO_INPUT_BUFFERING 1 // see http://bugzilla.mozilla.org/show_bug.cgi?id=41067
@@ -101,34 +102,34 @@ NS_IMETHODIMP
 nsFileStream::Seek(PRInt32 whence, PRInt64 offset)
 {
     nsresult rv = DoPendingOpen();
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (mFD == nsnull)
         return NS_BASE_STREAM_CLOSED;
 
-    PRInt64 cnt = PR_Seek64(mFD, offset, (PRSeekWhence)whence);
-    if (cnt == PRInt64(-1)) {
+    nsInt64 cnt = PR_Seek64(mFD, offset, (PRSeekWhence)whence);
+    if (cnt == nsInt64(-1)) {
         return NS_ErrorAccordingToNSPR();
     }
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsFileStream::Tell(PRInt64 *result)
 {
     nsresult rv = DoPendingOpen();
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (mFD == nsnull)
         return NS_BASE_STREAM_CLOSED;
 
-    PRInt64 cnt = PR_Seek64(mFD, 0, PR_SEEK_CUR);
-    if (cnt == PRInt64(-1)) {
+    nsInt64 cnt = PR_Seek64(mFD, 0, PR_SEEK_CUR);
+    if (cnt == nsInt64(-1)) {
         return NS_ErrorAccordingToNSPR();
     }
     *result = cnt;
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsFileStream::SetEOF()
--- a/netwerk/base/src/nsIncrementalDownload.cpp
+++ b/netwerk/base/src/nsIncrementalDownload.cpp
@@ -43,16 +43,17 @@
 #include "nsIAsyncVerifyRedirectCallback.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIObserverService.h"
 #include "nsIObserver.h"
 #include "nsIPropertyBag2.h"
 #include "nsIServiceManager.h"
 #include "nsILocalFile.h"
 #include "nsITimer.h"
+#include "nsInt64.h"
 #include "nsNetUtil.h"
 #include "nsAutoPtr.h"
 #include "nsWeakReference.h"
 #include "nsChannelProperties.h"
 #include "prio.h"
 #include "prprf.h"
 
 // Error code used internally by the incremental downloader to cancel the
@@ -95,28 +96,28 @@ static nsresult
 AppendToFile(nsILocalFile *lf, const char *data, PRUint32 len)
 {
   PRInt32 flags = PR_WRONLY | PR_CREATE_FILE | PR_APPEND;
   return WriteToFile(lf, data, len, flags);
 }
 
 // maxSize may be -1 if unknown
 static void
-MakeRangeSpec(const PRInt64 &size, const PRInt64 &maxSize, PRInt32 chunkSize,
+MakeRangeSpec(const nsInt64 &size, const nsInt64 &maxSize, PRInt32 chunkSize,
               PRBool fetchRemaining, nsCString &rangeSpec)
 {
   rangeSpec.AssignLiteral("bytes=");
   rangeSpec.AppendInt(PRInt64(size));
   rangeSpec.Append('-');
 
   if (fetchRemaining)
     return;
 
-  PRInt64 end = size + PRInt64(chunkSize);
-  if (maxSize != PRInt64(-1) && end > maxSize)
+  nsInt64 end = size + nsInt64(chunkSize);
+  if (maxSize != nsInt64(-1) && end > maxSize)
     end = maxSize;
   end -= 1;
 
   rangeSpec.AppendInt(PRInt64(end));
 }
 
 //-----------------------------------------------------------------------------
 
@@ -159,18 +160,18 @@ private:
   nsCOMPtr<nsIURI>                         mFinalURI;
   nsCOMPtr<nsILocalFile>                   mDest;
   nsCOMPtr<nsIChannel>                     mChannel;
   nsCOMPtr<nsITimer>                       mTimer;
   nsAutoArrayPtr<char>                     mChunk;
   PRInt32                                  mChunkLen;
   PRInt32                                  mChunkSize;
   PRInt32                                  mInterval;
-  PRInt64                                  mTotalSize;
-  PRInt64                                  mCurrentSize;
+  nsInt64                                  mTotalSize;
+  nsInt64                                  mCurrentSize;
   PRUint32                                 mLoadFlags;
   PRInt32                                  mNonPartialCount;
   nsresult                                 mStatus;
   PRPackedBool                             mIsPending;
   PRPackedBool                             mDidOnStartRequest;
   PRTime                                   mLastProgressUpdate;
   nsCOMPtr<nsIAsyncVerifyRedirectCallback> mRedirectCallback;
   nsCOMPtr<nsIChannel>                     mNewRedirectChannel;
@@ -191,26 +192,26 @@ nsIncrementalDownload::nsIncrementalDown
   , mRedirectCallback(nsnull)
   , mNewRedirectChannel(nsnull)
 {
 }
 
 nsresult
 nsIncrementalDownload::FlushChunk()
 {
-  NS_ASSERTION(mTotalSize != PRInt64(-1), "total size should be known");
+  NS_ASSERTION(mTotalSize != nsInt64(-1), "total size should be known");
 
   if (mChunkLen == 0)
     return NS_OK;
 
   nsresult rv = AppendToFile(mDest, mChunk, mChunkLen);
   if (NS_FAILED(rv))
     return rv;
 
-  mCurrentSize += PRInt64(mChunkLen);
+  mCurrentSize += nsInt64(mChunkLen);
   mChunkLen = 0;
 
   return NS_OK;
 }
 
 void
 nsIncrementalDownload::UpdateProgress()
 {
@@ -279,26 +280,26 @@ nsIncrementalDownload::ProcessTimeout()
                               nsnull, this, mLoadFlags);
   if (NS_FAILED(rv))
     return rv;
 
   nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(channel, &rv);
   if (NS_FAILED(rv))
     return rv;
 
-  NS_ASSERTION(mCurrentSize != PRInt64(-1),
+  NS_ASSERTION(mCurrentSize != nsInt64(-1),
       "we should know the current file size by now");
 
   rv = ClearRequestHeader(http);
   if (NS_FAILED(rv))
     return rv;
 
   // Don't bother making a range request if we are just going to fetch the
   // entire document.
-  if (mInterval || mCurrentSize != PRInt64(0)) {
+  if (mInterval || mCurrentSize != nsInt64(0)) {
     nsCAutoString range;
     MakeRangeSpec(mCurrentSize, mTotalSize, mChunkSize, mInterval == 0, range);
 
     rv = http->SetRequestHeader(NS_LITERAL_CSTRING("Range"), range, PR_FALSE);
     if (NS_FAILED(rv))
       return rv;
   }
 
@@ -313,17 +314,17 @@ nsIncrementalDownload::ProcessTimeout()
   mChannel = channel;
   return NS_OK;
 }
 
 // Reads the current file size and validates it.
 nsresult
 nsIncrementalDownload::ReadCurrentSize()
 {
-  PRInt64 size;
+  nsInt64 size;
   nsresult rv = mDest->GetFileSize((PRInt64 *) &size);
   if (rv == NS_ERROR_FILE_NOT_FOUND ||
       rv == NS_ERROR_FILE_TARGET_DOES_NOT_EXIST) {
     mCurrentSize = 0;
     return NS_OK;
   }
   if (NS_FAILED(rv))
     return rv;
@@ -547,17 +548,17 @@ nsIncrementalDownload::OnStartRequest(ns
   PRUint32 code;
   rv = http->GetResponseStatus(&code);
   if (NS_FAILED(rv))
     return rv;
   if (code != 206) {
     // We may already have the entire file downloaded, in which case
     // our request for a range beyond the end of the file would have
     // been met with an error response code.
-    if (code == 416 && mTotalSize == PRInt64(-1)) {
+    if (code == 416 && mTotalSize == nsInt64(-1)) {
       mTotalSize = mCurrentSize;
       // Return an error code here to suppress OnDataAvailable.
       return NS_ERROR_DOWNLOAD_COMPLETE;
     }
     // The server may have decided to give us all of the data in one chunk.  If
     // we requested a partial range, then we don't want to download all of the
     // data at once.  So, we'll just try again, but if this keeps happening then
     // we'll eventually give up.
@@ -581,17 +582,17 @@ nsIncrementalDownload::OnStartRequest(ns
     }
   } else {
     // We got a partial response, so clear this counter in case the next chunk
     // results in a 200 response.
     mNonPartialCount = 0;
   }
 
   // Do special processing after the first response.
-  if (mTotalSize == PRInt64(-1)) {
+  if (mTotalSize == nsInt64(-1)) {
     // Update knowledge of mFinalURI
     rv = http->GetURI(getter_AddRefs(mFinalURI));
     if (NS_FAILED(rv))
       return rv;
 
     if (code == 206) {
       // OK, read the Content-Range header to determine the total size of this
       // download file.
@@ -608,42 +609,42 @@ nsIncrementalDownload::OnStartRequest(ns
         return NS_ERROR_UNEXPECTED;
     } else {
       // Use nsIPropertyBag2 to fetch the content length as it exposes the
       // value as a 64-bit number.
       nsCOMPtr<nsIPropertyBag2> props = do_QueryInterface(request, &rv);
       if (NS_FAILED(rv))
         return rv;
       rv = props->GetPropertyAsInt64(NS_CHANNEL_PROP_CONTENT_LENGTH,
-                                     &mTotalSize);
+                                     &mTotalSize.mValue);
       // We need to know the total size of the thing we're trying to download.
-      if (mTotalSize == PRInt64(-1)) {
+      if (mTotalSize == nsInt64(-1)) {
         NS_WARNING("server returned no content-length header!");
         return NS_ERROR_UNEXPECTED;
       }
       // Need to truncate (or create, if it doesn't exist) the file since we
       // are downloading the whole thing.
       WriteToFile(mDest, nsnull, 0, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE);
       mCurrentSize = 0;
     }
 
     // Notify observer that we are starting...
     rv = CallOnStartRequest();
     if (NS_FAILED(rv))
       return rv;
   }
 
   // Adjust mChunkSize accordingly if mCurrentSize is close to mTotalSize.
-  PRInt64 diff = mTotalSize - mCurrentSize;
-  if (diff <= PRInt64(0)) {
+  nsInt64 diff = mTotalSize - mCurrentSize;
+  if (diff <= nsInt64(0)) {
     NS_WARNING("about to set a bogus chunk size; giving up");
     return NS_ERROR_UNEXPECTED;
   }
 
-  if (diff < PRInt64(mChunkSize))
+  if (diff < nsInt64(mChunkSize))
     mChunkSize = PRUint32(diff);
 
   mChunk = new char[mChunkSize];
   if (!mChunk)
     rv = NS_ERROR_OUT_OF_MEMORY;
 
   return rv;
 }
--- a/netwerk/base/src/nsInputStreamPump.cpp
+++ b/netwerk/base/src/nsInputStreamPump.cpp
@@ -282,17 +282,17 @@ NS_IMETHODIMP
 nsInputStreamPump::Init(nsIInputStream *stream,
                         PRInt64 streamPos, PRInt64 streamLen,
                         PRUint32 segsize, PRUint32 segcount,
                         PRBool closeWhenDone)
 {
     NS_ENSURE_TRUE(mState == STATE_IDLE, NS_ERROR_IN_PROGRESS);
 
     mStreamOffset = PRUint64(streamPos);
-    if (PRInt64(streamLen) >= PRInt64(0))
+    if (nsInt64(streamLen) >= nsInt64(0))
         mStreamLength = PRUint64(streamLen);
     mStream = stream;
     mSegSize = segsize;
     mSegCount = segcount;
     mCloseWhenDone = closeWhenDone;
 
     return NS_OK;
 }
--- a/netwerk/base/src/nsSocketTransport2.cpp
+++ b/netwerk/base/src/nsSocketTransport2.cpp
@@ -48,16 +48,17 @@
 #include "nsStreamUtils.h"
 #include "nsNetSegmentUtils.h"
 #include "nsTransportUtils.h"
 #include "nsProxyInfo.h"
 #include "nsNetCID.h"
 #include "nsAutoPtr.h"
 #include "nsCOMPtr.h"
 #include "netCore.h"
+#include "nsInt64.h"
 #include "prmem.h"
 #include "plstr.h"
 #include "prnetdb.h"
 #include "prerror.h"
 #include "prerr.h"
 
 #include "nsIServiceManager.h"
 #include "nsIProxyObjectManager.h"
@@ -1783,31 +1784,19 @@ nsSocketTransport::GetSecurityCallbacks(
     MutexAutoLock lock(mLock);
     NS_IF_ADDREF(*callbacks = mCallbacks);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSocketTransport::SetSecurityCallbacks(nsIInterfaceRequestor *callbacks)
 {
-    nsCOMPtr<nsISupports> secinfo;
-    {
-        MutexAutoLock lock(mLock);
-        mCallbacks = callbacks;
-        SOCKET_LOG(("Reset callbacks for secinfo=%p callbacks=%p\n",
-                    mSecInfo.get(), mCallbacks.get()));
-
-        secinfo = mSecInfo;
-    }
-
-    // don't call into PSM while holding mLock!!
-    nsCOMPtr<nsISSLSocketControl> secCtrl(do_QueryInterface(secinfo));
-    if (secCtrl)
-        secCtrl->SetNotificationCallbacks(callbacks);
-
+    MutexAutoLock lock(mLock);
+    mCallbacks = callbacks;
+    // XXX should we tell PSM about this?
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSocketTransport::SetEventSink(nsITransportEventSink *sink,
                                 nsIEventTarget *target)
 {
     nsCOMPtr<nsITransportEventSink> temp;
--- a/netwerk/base/src/nsSocketTransport2.h
+++ b/netwerk/base/src/nsSocketTransport2.h
@@ -41,16 +41,17 @@
 #ifdef DEBUG_darinf
 #define ENABLE_SOCKET_TRACING
 #endif
 
 #include "mozilla/Mutex.h"
 #include "nsSocketTransportService2.h"
 #include "nsString.h"
 #include "nsCOMPtr.h"
+#include "nsInt64.h"
 
 #include "nsISocketTransport.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIAsyncInputStream.h"
 #include "nsIAsyncOutputStream.h"
 #include "nsIDNSListener.h"
 #include "nsIDNSRecord.h"
 #include "nsICancelable.h"
--- a/netwerk/base/src/nsStreamTransportService.cpp
+++ b/netwerk/base/src/nsStreamTransportService.cpp
@@ -33,16 +33,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsStreamTransportService.h"
 #include "nsXPCOMCIDInternal.h"
 #include "nsNetSegmentUtils.h"
+#include "nsInt64.h"
 #include "nsTransportUtils.h"
 #include "nsStreamUtils.h"
 #include "nsNetError.h"
 #include "nsNetCID.h"
 
 #include "nsIServiceManager.h"
 #include "nsIAsyncInputStream.h"
 #include "nsIAsyncOutputStream.h"
--- a/netwerk/protocol/ftp/nsFtpConnectionThread.h
+++ b/netwerk/protocol/ftp/nsFtpConnectionThread.h
@@ -38,16 +38,17 @@
 
 #ifndef __nsFtpState__h_
 #define __nsFtpState__h_
 
 #include "ftpCore.h"
 #include "nsFTPChannel.h"
 #include "nsBaseContentStream.h"
 
+#include "nsInt64.h"
 #include "nsIThread.h"
 #include "nsIRunnable.h"
 #include "nsISocketTransportService.h"
 #include "nsISocketTransport.h"
 #include "nsIServiceManager.h"
 #include "nsIStreamListener.h"
 #include "nsICacheListener.h"
 #include "nsIURI.h"
--- a/netwerk/protocol/http/nsAHttpTransaction.h
+++ b/netwerk/protocol/http/nsAHttpTransaction.h
@@ -39,17 +39,16 @@
 #define nsAHttpTransaction_h__
 
 #include "nsISupports.h"
 
 class nsAHttpConnection;
 class nsAHttpSegmentReader;
 class nsAHttpSegmentWriter;
 class nsIInterfaceRequestor;
-class nsIEventTarget;
 
 //----------------------------------------------------------------------------
 // Abstract base class for a HTTP transaction:
 //
 // A transaction is a "sink" for the response data.  The connection pushes
 // data to the transaction by writing to it.  The transaction supports
 // WriteSegments and may refuse to accept data if its buffers are full (its
 // write function returns NS_BASE_STREAM_WOULD_BLOCK in this case).
@@ -58,18 +57,17 @@ class nsIEventTarget;
 class nsAHttpTransaction : public nsISupports
 {
 public:
     // called by the connection when it takes ownership of the transaction.
     virtual void SetConnection(nsAHttpConnection *) = 0;
 
     // called by the connection to get security callbacks to set on the 
     // socket transport.
-    virtual void GetSecurityCallbacks(nsIInterfaceRequestor **,
-                                      nsIEventTarget **) = 0;
+    virtual void GetSecurityCallbacks(nsIInterfaceRequestor **) = 0;
 
     // called to report socket status (see nsITransportEventSink)
     virtual void OnTransportStatus(nsresult status, PRUint64 progress) = 0;
 
     // called to check the transaction status.
     virtual PRBool   IsDone() = 0;
     virtual nsresult Status() = 0;
 
@@ -85,18 +83,17 @@ public:
                                    PRUint32 count, PRUint32 *countWritten) = 0;
 
     // called to close the transaction
     virtual void Close(nsresult reason) = 0;
 };
 
 #define NS_DECL_NSAHTTPTRANSACTION \
     void SetConnection(nsAHttpConnection *); \
-    void GetSecurityCallbacks(nsIInterfaceRequestor **, \
-                              nsIEventTarget **);       \
+    void GetSecurityCallbacks(nsIInterfaceRequestor **); \
     void OnTransportStatus(nsresult status, PRUint64 progress); \
     PRBool   IsDone(); \
     nsresult Status(); \
     PRUint32 Available(); \
     nsresult ReadSegments(nsAHttpSegmentReader *, PRUint32, PRUint32 *); \
     nsresult WriteSegments(nsAHttpSegmentWriter *, PRUint32, PRUint32 *); \
     void     Close(nsresult reason);
 
--- a/netwerk/protocol/http/nsHttpChannel.cpp
+++ b/netwerk/protocol/http/nsHttpChannel.cpp
@@ -59,16 +59,17 @@
 #include "nsIStreamListenerTee.h"
 #include "nsISeekableStream.h"
 #include "nsMimeTypes.h"
 #include "nsPrintfCString.h"
 #include "nsNetUtil.h"
 #include "prprf.h"
 #include "prnetdb.h"
 #include "nsEscape.h"
+#include "nsInt64.h"
 #include "nsStreamUtils.h"
 #include "nsIOService.h"
 #include "nsICacheService.h"
 #include "nsDNSPrefetch.h"
 #include "nsChannelClassifier.h"
 #include "nsIRedirectResultListener.h"
 
 // True if the local cache should be bypassed when processing a request.
@@ -2495,30 +2496,30 @@ nsHttpChannel::CheckCache()
         mRequestHead.PeekHeader(nsHttp::If_Match) ||
         mRequestHead.PeekHeader(nsHttp::If_Range);
 
     if (method != nsHttp::Head && !isCachedRedirect) {
         // If the cached content-length is set and it does not match the data
         // size of the cached content, then the cached response is partial...
         // either we need to issue a byte range request or we need to refetch
         // the entire document.
-        PRInt64 contentLength = mCachedResponseHead->ContentLength();
-        if (contentLength != PRInt64(-1)) {
+        nsInt64 contentLength = mCachedResponseHead->ContentLength();
+        if (contentLength != nsInt64(-1)) {
             PRUint32 size;
             rv = mCacheEntry->GetDataSize(&size);
             NS_ENSURE_SUCCESS(rv, rv);
 
-            if (PRInt64(size) != contentLength) {
+            if (nsInt64(size) != contentLength) {
                 LOG(("Cached data size does not match the Content-Length header "
                      "[content-length=%lld size=%u]\n", PRInt64(contentLength), size));
 
                 PRBool hasContentEncoding =
                     mCachedResponseHead->PeekHeader(nsHttp::Content_Encoding)
                     != nsnull;
-                if ((PRInt64(size) < contentLength) &&
+                if ((nsInt64(size) < contentLength) &&
                      size > 0 &&
                      !hasContentEncoding &&
                      mCachedResponseHead->IsResumable() &&
                      !mCustomConditionalRequest &&
                      !mCachedResponseHead->NoStore()) {
                     // looks like a partial entry we can reuse
                     rv = SetupByteRangeRequest(size);
                     NS_ENSURE_SUCCESS(rv, rv);
@@ -2828,17 +2829,17 @@ nsHttpChannel::ReadFromCache()
     }
 
     // open input stream for reading...
     nsCOMPtr<nsIInputStream> stream;
     rv = mCacheEntry->OpenInputStream(0, getter_AddRefs(stream));
     if (NS_FAILED(rv)) return rv;
 
     rv = nsInputStreamPump::Create(getter_AddRefs(mCachePump),
-                                   stream, PRInt64(-1), PRInt64(-1), 0, 0,
+                                   stream, nsInt64(-1), nsInt64(-1), 0, 0,
                                    PR_TRUE);
     if (NS_FAILED(rv)) return rv;
 
     rv = mCachePump->AsyncRead(this, mListenerContext);
     if (NS_FAILED(rv)) return rv;
 
     PRUint32 suspendCount = mSuspendCount;
     while (suspendCount--)
--- a/netwerk/protocol/http/nsHttpConnection.cpp
+++ b/netwerk/protocol/http/nsHttpConnection.cpp
@@ -45,37 +45,34 @@
 #include "nsIOService.h"
 #include "nsISocketTransportService.h"
 #include "nsISocketTransport.h"
 #include "nsIServiceManager.h"
 #include "nsISSLSocketControl.h"
 #include "nsStringStream.h"
 #include "netCore.h"
 #include "nsNetCID.h"
-#include "nsAutoLock.h"
-#include "nsProxyRelease.h"
 #include "prmem.h"
 
 #ifdef DEBUG
 // defined by the socket transport service while active
 extern PRThread *gSocketThread;
 #endif
 
 static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID);
 
 //-----------------------------------------------------------------------------
 // nsHttpConnection <public>
 //-----------------------------------------------------------------------------
 
 nsHttpConnection::nsHttpConnection()
     : mTransaction(nsnull)
+    , mConnInfo(nsnull)
     , mLastReadTime(0)
     , mIdleTimeout(0)
-    , mConsiderReusedAfterInterval(0)
-    , mConsiderReusedAfterEpoch(0)
     , mKeepAlive(PR_TRUE) // assume to keep-alive by default
     , mKeepAliveMask(PR_TRUE)
     , mSupportsPipelining(PR_FALSE) // assume low-grade server
     , mIsReused(PR_FALSE)
     , mCompletedSSLConnect(PR_FALSE)
     , mLastTransactionExpectedNoContent(PR_FALSE)
 {
     LOG(("Creating nsHttpConnection @%x\n", this));
@@ -83,106 +80,90 @@ nsHttpConnection::nsHttpConnection()
     // grab a reference to the handler to ensure that it doesn't go away.
     nsHttpHandler *handler = gHttpHandler;
     NS_ADDREF(handler);
 }
 
 nsHttpConnection::~nsHttpConnection()
 {
     LOG(("Destroying nsHttpConnection @%x\n", this));
-
-    if (mCallbacks) {
-        nsIInterfaceRequestor *cbs = nsnull;
-        mCallbacks.swap(cbs);
-        NS_ProxyRelease(mCallbackTarget, cbs);
-    }
+ 
+    NS_IF_RELEASE(mConnInfo);
+    NS_IF_RELEASE(mTransaction);
 
     // release our reference to the handler
     nsHttpHandler *handler = gHttpHandler;
     NS_RELEASE(handler);
 }
 
 nsresult
-nsHttpConnection::Init(nsHttpConnectionInfo *info,
-                       PRUint16 maxHangTime,
-                       nsISocketTransport *transport,
-                       nsIAsyncInputStream *instream,
-                       nsIAsyncOutputStream *outstream,
-                       nsIInterfaceRequestor *callbacks,
-                       nsIEventTarget *callbackTarget)
+nsHttpConnection::Init(nsHttpConnectionInfo *info, PRUint16 maxHangTime)
 {
-    NS_ABORT_IF_FALSE(transport && instream && outstream,
-                      "invalid socket information");
-    LOG(("nsHttpConnection::Init [this=%p "
-         "transport=%p instream=%p outstream=%p]\n",
-         this, transport, instream, outstream));
+    LOG(("nsHttpConnection::Init [this=%x]\n", this));
 
     NS_ENSURE_ARG_POINTER(info);
     NS_ENSURE_TRUE(!mConnInfo, NS_ERROR_ALREADY_INITIALIZED);
 
     mConnInfo = info;
+    NS_ADDREF(mConnInfo);
+
     mMaxHangTime = maxHangTime;
     mLastReadTime = NowInSeconds();
-
-    mSocketTransport = transport;
-    mSocketIn = instream;
-    mSocketOut = outstream;
-    nsresult rv = mSocketTransport->SetEventSink(this, nsnull);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    mCallbacks = callbacks;
-    mCallbackTarget = callbackTarget;
-    rv = mSocketTransport->SetSecurityCallbacks(this);
-    NS_ENSURE_SUCCESS(rv, rv);
-
     return NS_OK;
 }
 
 // called on the socket thread
 nsresult
 nsHttpConnection::Activate(nsAHttpTransaction *trans, PRUint8 caps)
 {
     nsresult rv;
 
-    NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread");
     LOG(("nsHttpConnection::Activate [this=%x trans=%x caps=%x]\n",
          this, trans, caps));
 
     NS_ENSURE_ARG_POINTER(trans);
     NS_ENSURE_TRUE(!mTransaction, NS_ERROR_IN_PROGRESS);
 
     // take ownership of the transaction
     mTransaction = trans;
+    NS_ADDREF(mTransaction);
 
     // set mKeepAlive according to what will be requested
     mKeepAliveMask = mKeepAlive = (caps & NS_HTTP_ALLOW_KEEPALIVE);
 
+    // if we don't have a socket transport then create a new one
+    if (!mSocketTransport) {
+        rv = CreateTransport(caps);
+        if (NS_FAILED(rv))
+            goto loser;
+    }
+
     // need to handle SSL proxy CONNECT if this is the first time.
     if (mConnInfo->UsingSSL() && mConnInfo->UsingHttpProxy() && !mCompletedSSLConnect) {
         rv = SetupSSLProxyConnect();
         if (NS_FAILED(rv))
-            goto failed_activation;
+            goto loser;
     }
 
-    rv = OnOutputStreamReady(mSocketOut);
-    
-failed_activation:
-    if (NS_FAILED(rv)) {
-        mTransaction = nsnull;
-    }
+    // wait for the output stream to be readable
+    rv = mSocketOut->AsyncWait(this, 0, 0, nsnull);
+    if (NS_SUCCEEDED(rv))
+        return rv;
 
+loser:
+    NS_RELEASE(mTransaction);
     return rv;
 }
 
 void
 nsHttpConnection::Close(nsresult reason)
 {
     LOG(("nsHttpConnection::Close [this=%x reason=%x]\n", this, reason));
 
-    NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
 
     if (NS_FAILED(reason)) {
         if (mSocketTransport) {
             mSocketTransport->SetSecurityCallbacks(nsnull);
             mSocketTransport->SetEventSink(nsnull, nsnull);
             mSocketTransport->Close(reason);
         }
         mKeepAlive = PR_FALSE;
@@ -206,35 +187,18 @@ nsHttpConnection::ProxyStartSSL()
     if (NS_FAILED(rv)) return rv;
 
     return ssl->ProxyStartSSL();
 }
 
 PRBool
 nsHttpConnection::CanReuse()
 {
-    PRBool canReuse = IsKeepAlive() &&
-        (NowInSeconds() - mLastReadTime < mIdleTimeout) &&
-        IsAlive();
-    
-    // An idle persistent connection should not have data waiting to be read
-    // before a request is sent. Data here is likely a 408 timeout response
-    // which we would deal with later on through the restart logic, but that
-    // path is more expensive than just closing the socket now. SSL check can
-    // be removed with fixing of 631801
-
-    PRUint32 dataSize;
-    if (canReuse && mSocketIn && !mConnInfo->UsingSSL() &&
-        NS_SUCCEEDED(mSocketIn->Available(&dataSize)) && dataSize) {
-        LOG(("nsHttpConnection::CanReuse %p %s"
-             "Socket not reusable because read data pending (%d) on it.\n",
-             this, mConnInfo->Host(), dataSize));
-        canReuse = PR_FALSE;
-    }
-    return canReuse;
+    return IsKeepAlive() && (NowInSeconds() - mLastReadTime < mIdleTimeout)
+                         && IsAlive();
 }
 
 PRUint32 nsHttpConnection::TimeToLive()
 {
     PRInt32 tmp = mIdleTimeout - (NowInSeconds() - mLastReadTime);
     if (0 > tmp)
         tmp = 0;
 
@@ -417,45 +381,24 @@ nsHttpConnection::OnHeadersAvailable(nsA
             NS_ASSERTION(NS_SUCCEEDED(rv), "mSocketOut->AsyncWait failed");
         }
         else {
             LOG(("SSL proxy CONNECT failed!\n"));
             // NOTE: this cast is valid since this connection cannot be
             // processing a transaction pipeline until after the first HTTP/1.1
             // response.
             nsHttpTransaction *trans =
-                    static_cast<nsHttpTransaction *>(mTransaction.get());
+                    static_cast<nsHttpTransaction *>(mTransaction);
             trans->SetSSLConnectFailed();
         }
     }
 
     return NS_OK;
 }
 
-PRBool
-nsHttpConnection::IsReused()
-{
-    if (mIsReused)
-        return PR_TRUE;
-    if (!mConsiderReusedAfterInterval)
-        return PR_FALSE;
-    
-    // ReusedAfter allows a socket to be consider reused only after a certain
-    // interval of time has passed
-    return (PR_IntervalNow() - mConsiderReusedAfterEpoch) >=
-        mConsiderReusedAfterInterval;
-}
-
-void
-nsHttpConnection::SetIsReusedAfter(PRUint32 afterMilliseconds)
-{
-    mConsiderReusedAfterEpoch = PR_IntervalNow();
-    mConsiderReusedAfterInterval = PR_MillisecondsToInterval(afterMilliseconds);
-}
-
 void
 nsHttpConnection::GetSecurityInfo(nsISupports **secinfo)
 {
     NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
 
     if (mSocketTransport) {
         if (NS_FAILED(mSocketTransport->GetSecurityInfo(secinfo)))
             *secinfo = nsnull;
@@ -489,31 +432,96 @@ nsHttpConnection::ResumeRecv()
     NS_NOTREACHED("no socket input stream");
     return NS_ERROR_UNEXPECTED;
 }
 
 //-----------------------------------------------------------------------------
 // nsHttpConnection <private>
 //-----------------------------------------------------------------------------
 
+nsresult
+nsHttpConnection::CreateTransport(PRUint8 caps)
+{
+    nsresult rv;
+
+    NS_PRECONDITION(!mSocketTransport, "unexpected");
+
+    nsCOMPtr<nsISocketTransportService> sts =
+            do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
+    if (NS_FAILED(rv)) return rv;
+
+    // configure the socket type based on the connection type requested.
+    const char* types[1];
+
+    if (mConnInfo->UsingSSL())
+        types[0] = "ssl";
+    else
+        types[0] = gHttpHandler->DefaultSocketType();
+
+    nsCOMPtr<nsISocketTransport> strans;
+    PRUint32 typeCount = (types[0] != nsnull);
+
+    rv = sts->CreateTransport(types, typeCount,
+                              nsDependentCString(mConnInfo->Host()),
+                              mConnInfo->Port(),
+                              mConnInfo->ProxyInfo(),
+                              getter_AddRefs(strans));
+    if (NS_FAILED(rv)) return rv;
+
+    PRUint32 tmpFlags = 0;
+    if (caps & NS_HTTP_REFRESH_DNS)
+        tmpFlags = nsISocketTransport::BYPASS_CACHE;
+    
+    if (caps & NS_HTTP_LOAD_ANONYMOUS)
+        tmpFlags |= nsISocketTransport::ANONYMOUS_CONNECT;
+    
+    strans->SetConnectionFlags(tmpFlags); 
+
+    strans->SetQoSBits(gHttpHandler->GetQoSBits());
+
+    // NOTE: these create cyclical references, which we break inside
+    //       nsHttpConnection::Close
+    rv = strans->SetEventSink(this, nsnull);
+    if (NS_FAILED(rv)) return rv;
+    rv = strans->SetSecurityCallbacks(this);
+    if (NS_FAILED(rv)) return rv;
+
+    // next open the socket streams
+    nsCOMPtr<nsIOutputStream> sout;
+    rv = strans->OpenOutputStream(nsITransport::OPEN_UNBUFFERED, 0, 0,
+                                  getter_AddRefs(sout));
+    if (NS_FAILED(rv)) return rv;
+    nsCOMPtr<nsIInputStream> sin;
+    rv = strans->OpenInputStream(nsITransport::OPEN_UNBUFFERED, 0, 0,
+                                 getter_AddRefs(sin));
+    if (NS_FAILED(rv)) return rv;
+
+    mSocketTransport = strans;
+    mSocketIn = do_QueryInterface(sin);
+    mSocketOut = do_QueryInterface(sout);
+    return NS_OK;
+}
+
 void
 nsHttpConnection::CloseTransaction(nsAHttpTransaction *trans, nsresult reason)
 {
     LOG(("nsHttpConnection::CloseTransaction[this=%x trans=%x reason=%x]\n",
         this, trans, reason));
 
     NS_ASSERTION(trans == mTransaction, "wrong transaction");
     NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
 
     // mask this error code because its not a real error.
     if (reason == NS_BASE_STREAM_CLOSED)
         reason = NS_OK;
 
     mTransaction->Close(reason);
-    mTransaction = nsnull;
+
+    NS_RELEASE(mTransaction);
+    mTransaction = 0;
 
     if (NS_FAILED(reason))
         Close(reason);
 
     // flag the connection as reused here for convenience sake.  certainly
     // it might be going away instead ;-)
     mIsReused = PR_TRUE;
 }
@@ -714,18 +722,17 @@ nsHttpConnection::SetupSSLProxyConnect()
     request.SetRequestURI(buf);
     request.SetHeader(nsHttp::User_Agent, gHttpHandler->UserAgent());
 
     // send this header for backwards compatibility.
     request.SetHeader(nsHttp::Proxy_Connection, NS_LITERAL_CSTRING("keep-alive"));
 
     // NOTE: this cast is valid since this connection cannot be processing a
     // transaction pipeline until after the first HTTP/1.1 response.
-    nsHttpTransaction *trans =
-        static_cast<nsHttpTransaction *>(mTransaction.get());
+    nsHttpTransaction *trans = static_cast<nsHttpTransaction *>(mTransaction);
     
     val = trans->RequestHead()->PeekHeader(nsHttp::Host);
     if (val) {
         // all HTTP/1.1 requests must include a Host header (even though it
         // may seem redundant in this case; see bug 82388).
         request.SetHeader(nsHttp::Host, nsDependentCString(val));
     }
 
@@ -779,18 +786,18 @@ nsHttpConnection::OnInputStreamReady(nsI
 
 //-----------------------------------------------------------------------------
 // nsHttpConnection::nsIOutputStreamCallback
 //-----------------------------------------------------------------------------
 
 NS_IMETHODIMP
 nsHttpConnection::OnOutputStreamReady(nsIAsyncOutputStream *out)
 {
-    NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread");
-    NS_ABORT_IF_FALSE(out == mSocketOut, "unexpected socket");
+    NS_ASSERTION(out == mSocketOut, "unexpected stream");
+    NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
 
     // if the transaction was dropped...
     if (!mTransaction) {
         LOG(("  no transaction; ignoring event\n"));
         return NS_OK;
     }
 
     nsresult rv = OnSocketWritable();
@@ -822,19 +829,19 @@ nsHttpConnection::OnTransportStatus(nsIT
 // not called on the socket transport thread
 NS_IMETHODIMP
 nsHttpConnection::GetInterface(const nsIID &iid, void **result)
 {
     // NOTE: This function is only called on the UI thread via sync proxy from
     //       the socket transport thread.  If that weren't the case, then we'd
     //       have to worry about the possibility of mTransaction going away
     //       part-way through this function call.  See CloseTransaction.
-
-    // NOTE - there is a bug here, the call to getinterface is proxied off the
-    // nss thread, not the ui thread as the above comment says. So there is
-    // indeed a chance of mTransaction going away. bug 615342
+    NS_ASSERTION(PR_GetCurrentThread() != gSocketThread, "wrong thread");
+ 
+    if (mTransaction) {
+        nsCOMPtr<nsIInterfaceRequestor> callbacks;
+        mTransaction->GetSecurityCallbacks(getter_AddRefs(callbacks));
+        if (callbacks)
+            return callbacks->GetInterface(iid, result);
+    }
 
-    NS_ASSERTION(PR_GetCurrentThread() != gSocketThread, "wrong thread");
-
-    if (mCallbacks)
-        return mCallbacks->GetInterface(iid, result);
     return NS_ERROR_NO_INTERFACE;
 }
--- a/netwerk/protocol/http/nsHttpConnection.h
+++ b/netwerk/protocol/http/nsHttpConnection.h
@@ -41,24 +41,22 @@
 
 #include "nsHttp.h"
 #include "nsHttpConnectionInfo.h"
 #include "nsAHttpConnection.h"
 #include "nsAHttpTransaction.h"
 #include "nsXPIDLString.h"
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
-#include "prinrval.h"
 
 #include "nsIStreamListener.h"
 #include "nsISocketTransport.h"
 #include "nsIAsyncInputStream.h"
 #include "nsIAsyncOutputStream.h"
 #include "nsIInterfaceRequestor.h"
-#include "nsIEventTarget.h"
 
 //-----------------------------------------------------------------------------
 // nsHttpConnection - represents a connection to a HTTP server (or proxy)
 //
 // NOTE: this objects lives on the socket thread only.  it should not be
 // accessed from any other thread.
 //-----------------------------------------------------------------------------
 
@@ -81,20 +79,17 @@ public:
     nsHttpConnection();
     virtual ~nsHttpConnection();
 
     // Initialize the connection:
     //  info        - specifies the connection parameters.
     //  maxHangTime - limits the amount of time this connection can spend on a
     //                single transaction before it should no longer be kept 
     //                alive.  a value of 0xffff indicates no limit.
-    nsresult Init(nsHttpConnectionInfo *info, PRUint16 maxHangTime,
-                  nsISocketTransport *, nsIAsyncInputStream *,
-                  nsIAsyncOutputStream *, nsIInterfaceRequestor *,
-                  nsIEventTarget *);
+    nsresult Init(nsHttpConnectionInfo *info, PRUint16 maxHangTime);
 
     // Activate causes the given transaction to be processed on this
     // connection.  It fails if there is already an existing transaction.
     nsresult Activate(nsAHttpTransaction *, PRUint8 caps);
 
     // Close the underlying socket transport.
     void Close(nsresult reason);
 
@@ -127,30 +122,29 @@ public:
     nsHttpConnectionInfo *ConnectionInfo() { return mConnInfo; }
 
     // nsAHttpConnection compatible methods (non-virtual):
     nsresult OnHeadersAvailable(nsAHttpTransaction *, nsHttpRequestHead *, nsHttpResponseHead *, PRBool *reset);
     void     CloseTransaction(nsAHttpTransaction *, nsresult reason);
     void     GetConnectionInfo(nsHttpConnectionInfo **ci) { NS_IF_ADDREF(*ci = mConnInfo); }
     void     GetSecurityInfo(nsISupports **);
     PRBool   IsPersistent() { return IsKeepAlive(); }
-    PRBool   IsReused();
-    void     SetIsReusedAfter(PRUint32 afterMilliseconds);
-    void     SetIdleTimeout(PRUint16 val) {mIdleTimeout = val;}
+    PRBool   IsReused() { return mIsReused; }
     nsresult PushBack(const char *data, PRUint32 length) { NS_NOTREACHED("PushBack"); return NS_ERROR_UNEXPECTED; }
     nsresult ResumeSend();
     nsresult ResumeRecv();
 
     static NS_METHOD ReadFromStream(nsIInputStream *, void *, const char *,
                                     PRUint32, PRUint32, PRUint32 *);
 
 private:
     // called to cause the underlying socket to start speaking SSL
     nsresult ProxyStartSSL();
 
+    nsresult CreateTransport(PRUint8 caps);
     nsresult OnTransactionDone(nsresult reason);
     nsresult OnSocketWritable();
     nsresult OnSocketReadable();
 
     nsresult SetupSSLProxyConnect();
 
     PRBool   IsAlive();
     PRBool   SupportsPipelining(nsHttpResponseHead *);
@@ -161,30 +155,22 @@ private:
     nsCOMPtr<nsIAsyncOutputStream>  mSocketOut;
 
     nsresult                        mSocketInCondition;
     nsresult                        mSocketOutCondition;
 
     nsCOMPtr<nsIInputStream>        mSSLProxyConnectStream;
     nsCOMPtr<nsIInputStream>        mRequestStream;
 
-    // mTransaction only points to the HTTP Transaction callbacks if the
-    // transaction is open, otherwise it is null.
-    nsRefPtr<nsAHttpTransaction>    mTransaction;
-
-    nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
-    nsCOMPtr<nsIEventTarget>        mCallbackTarget;
-
-    nsRefPtr<nsHttpConnectionInfo> mConnInfo;
+    nsAHttpTransaction             *mTransaction; // hard ref
+    nsHttpConnectionInfo           *mConnInfo;    // hard ref
 
     PRUint32                        mLastReadTime;
     PRUint16                        mMaxHangTime;    // max download time before dropping keep-alive status
     PRUint16                        mIdleTimeout;    // value of keep-alive: timeout=
-    PRIntervalTime                  mConsiderReusedAfterInterval;
-    PRIntervalTime                  mConsiderReusedAfterEpoch;
 
     PRPackedBool                    mKeepAlive;
     PRPackedBool                    mKeepAliveMask;
     PRPackedBool                    mSupportsPipelining;
     PRPackedBool                    mIsReused;
     PRPackedBool                    mCompletedSSLConnect;
     PRPackedBool                    mLastTransactionExpectedNoContent;
 };
--- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp
+++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp
@@ -393,40 +393,34 @@ nsHttpConnectionMgr::ProcessOneTransacti
     nsConnectionEntry *ent = (nsConnectionEntry *) data;
 
     if (self->ProcessPendingQForEntry(ent))
         return kHashEnumerateStop;
 
     return kHashEnumerateNext;
 }
 
-// If the global number of idle connections is preventing the opening of
-// new connections to a host without idle connections, then
-// close them regardless of their TTL
 PRIntn
-nsHttpConnectionMgr::PurgeExcessIdleConnectionsCB(nsHashKey *key,
-                                                  void *data, void *closure)
+nsHttpConnectionMgr::PurgeOneIdleConnectionCB(nsHashKey *key, void *data, void *closure)
 {
     nsHttpConnectionMgr *self = (nsHttpConnectionMgr *) closure;
     nsConnectionEntry *ent = (nsConnectionEntry *) data;
 
-    while (self->mNumIdleConns + self->mNumActiveConns + 1 >= self->mMaxConns) {
-        if (!ent->mIdleConns.Length()) {
-            // There are no idle conns left in this connection entry
-            return kHashEnumerateNext;
-        }
+    if (ent->mIdleConns.Length() > 0) {
         nsHttpConnection *conn = ent->mIdleConns[0];
         ent->mIdleConns.RemoveElementAt(0);
         conn->Close(NS_ERROR_ABORT);
         NS_RELEASE(conn);
         self->mNumIdleConns--;
         if (0 == self->mNumIdleConns)
             self->StopPruneDeadConnectionsTimer();
+        return kHashEnumerateStop;
     }
-    return kHashEnumerateStop;
+
+    return kHashEnumerateNext;
 }
 
 PRIntn
 nsHttpConnectionMgr::PruneDeadConnectionsCB(nsHashKey *key, void *data, void *closure)
 {
     nsHttpConnectionMgr *self = (nsHttpConnectionMgr *) closure;
     nsConnectionEntry *ent = (nsConnectionEntry *) data;
 
@@ -473,17 +467,16 @@ nsHttpConnectionMgr::PruneDeadConnection
             LOG(("    active conn [%x] with trans [%x]\n", conn, conn->Transaction()));
         }
     }
 #endif
 
     // if this entry is empty, then we can remove it.
     if (ent->mIdleConns.Length()   == 0 &&
         ent->mActiveConns.Length() == 0 &&
-        ent->mHalfOpens.Length()   == 0 &&
         ent->mPendingQ.Length()    == 0) {
         LOG(("    removing empty connection entry\n"));
         delete ent;
         return kHashEnumerateRemove;
     }
 
     // else, use this opportunity to compact our arrays...
     ent->mIdleConns.Compact();
@@ -533,20 +526,16 @@ nsHttpConnectionMgr::ShutdownPassCB(nsHa
         trans = ent->mPendingQ[0];
 
         ent->mPendingQ.RemoveElementAt(0);
 
         trans->Close(NS_ERROR_ABORT);
         NS_RELEASE(trans);
     }
 
-    // close all half open tcp connections
-    for (PRInt32 i = ((PRInt32) ent->mHalfOpens.Length()) - 1; i >= 0; i--)
-        ent->mHalfOpens[i]->Abandon();
-
     delete ent;
     return kHashEnumerateRemove;
 }
 
 //-----------------------------------------------------------------------------
 
 PRBool
 nsHttpConnectionMgr::ProcessPendingQForEntry(nsConnectionEntry *ent)
@@ -556,17 +545,17 @@ nsHttpConnectionMgr::ProcessPendingQForE
 
     PRInt32 i, count = ent->mPendingQ.Length();
     if (count > 0) {
         LOG(("  pending-count=%u\n", count));
         nsHttpTransaction *trans = nsnull;
         nsHttpConnection *conn = nsnull;
         for (i=0; i<count; ++i) {
             trans = ent->mPendingQ[i];
-            GetConnection(ent, trans, &conn);
+            GetConnection(ent, trans->Caps(), &conn);
             if (conn)
                 break;
         }
         if (conn) {
             LOG(("  dispatching pending transaction...\n"));
 
             // remove pending transaction
             ent->mPendingQ.RemoveElementAt(i);
@@ -596,18 +585,18 @@ nsHttpConnectionMgr::ProcessPendingQForE
 PRBool
 nsHttpConnectionMgr::AtActiveConnectionLimit(nsConnectionEntry *ent, PRUint8 caps)
 {
     nsHttpConnectionInfo *ci = ent->mConnInfo;
 
     LOG(("nsHttpConnectionMgr::AtActiveConnectionLimit [ci=%s caps=%x]\n",
         ci->HashKey().get(), caps));
 
-    // If there are more active connections than the global limit, then we're
-    // done. Purging idle connections won't get us below it.
+    // If we have more active connections than the limit, then we're done --
+    // purging idle connections won't get us below it.
     if (mNumActiveConns >= mMaxConns) {
         LOG(("  num active conns == max conns\n"));
         return PR_TRUE;
     }
 
     nsHttpConnection *conn;
     PRInt32 i, totalCount, persistCount = 0;
     
@@ -615,21 +604,16 @@ nsHttpConnectionMgr::AtActiveConnectionL
 
     // count the number of persistent connections
     for (i=0; i<totalCount; ++i) {
         conn = ent->mActiveConns[i];
         if (conn->IsKeepAlive()) // XXX make sure this is thread-safe
             persistCount++;
     }
 
-    // Add in the in-progress tcp connections, we will assume they are
-    // keepalive enabled.
-    totalCount += ent->mHalfOpens.Length();
-    persistCount += ent->mHalfOpens.Length();
-    
     LOG(("   total=%d, persist=%d\n", totalCount, persistCount));
 
     PRUint16 maxConns;
     PRUint16 maxPersistConns;
 
     if (ci->UsingHttpProxy() && !ci->UsingSSL()) {
         maxConns = mMaxConnsPerProxy;
         maxPersistConns = mMaxPersistConnsPerProxy;
@@ -640,36 +624,28 @@ nsHttpConnectionMgr::AtActiveConnectionL
     }
 
     // use >= just to be safe
     return (totalCount >= maxConns) || ( (caps & NS_HTTP_ALLOW_KEEPALIVE) &&
                                          (persistCount >= maxPersistConns) );
 }
 
 void
-nsHttpConnectionMgr::GetConnection(nsConnectionEntry *ent,
-                                   nsHttpTransaction *trans,
+nsHttpConnectionMgr::GetConnection(nsConnectionEntry *ent, PRUint8 caps,
                                    nsHttpConnection **result)
 {
     LOG(("nsHttpConnectionMgr::GetConnection [ci=%s caps=%x]\n",
-        ent->mConnInfo->HashKey().get(), PRUint32(trans->Caps())));
-
-    // First, see if an idle persistent connection may be reused instead of
-    // establishing a new socket. We do not need to check the connection limits
-    // yet as they govern the maximum number of open connections and reusing
-    // an old connection never increases that.
+        ent->mConnInfo->HashKey().get(), PRUint32(caps)));
 
     *result = nsnull;
 
     nsHttpConnection *conn = nsnull;
 
-    if (trans->Caps() & NS_HTTP_ALLOW_KEEPALIVE) {
-        // search the idle connection list. Each element in the list
-        // has a reference, so if we remove it from the list into a local
-        // ptr, that ptr now owns the reference
+    if (caps & NS_HTTP_ALLOW_KEEPALIVE) {
+        // search the idle connection list
         while (!conn && (ent->mIdleConns.Length() > 0)) {
             conn = ent->mIdleConns[0];
             // we check if the connection can be reused before even checking if
             // it is a "matching" connection.
             if (!conn->CanReuse()) {
                 LOG(("   dropping stale connection: [conn=%x]\n", conn));
                 conn->Close(NS_ERROR_ABORT);
                 NS_RELEASE(conn);
@@ -689,78 +665,41 @@ nsHttpConnectionMgr::GetConnection(nsCon
     if (!conn) {
         // Check if we need to purge an idle connection. Note that we may have
         // removed one above; if so, this will be a no-op. We do this before
         // checking the active connection limit to catch the case where we do
         // have an idle connection, but the purge timer hasn't fired yet.
         // XXX this just purges a random idle connection.  we should instead
         // enumerate the entire hash table to find the eldest idle connection.
         if (mNumIdleConns && mNumIdleConns + mNumActiveConns + 1 >= mMaxConns)
-            mCT.Enumerate(PurgeExcessIdleConnectionsCB, this);
+            mCT.Enumerate(PurgeOneIdleConnectionCB, this);
 
         // Need to make a new TCP connection. First, we check if we've hit
         // either the maximum connection limit globally or for this particular
         // host or proxy. If we have, we're done.
-        if (AtActiveConnectionLimit(ent, trans->Caps())) {
-            LOG(("nsHttpConnectionMgr::GetConnection [ci = %s]"
-                 "at active connection limit - will queue\n",
-                 ent->mConnInfo->HashKey().get()));
+        if (AtActiveConnectionLimit(ent, caps)) {
+            LOG(("  at active connection limit!\n"));
             return;
         }
 
-        nsresult rv = CreateTransport(ent, trans);
-        if (NS_FAILED(rv))
-            trans->Close(rv);
-        return;
+        conn = new nsHttpConnection();
+        if (!conn)
+            return;
+        NS_ADDREF(conn);
+
+        nsresult rv = conn->Init(ent->mConnInfo, mMaxRequestDelay);
+        if (NS_FAILED(rv)) {
+            NS_RELEASE(conn);
+            return;
+        }
     }
 
-    // hold an owning ref to this connection
-    ent->mActiveConns.AppendElement(conn);
-    mNumActiveConns++;
-    NS_ADDREF(conn);
-
     *result = conn;
 }
 
-void
-nsHttpConnectionMgr::AddActiveConn(nsHttpConnection *conn,
-                                   nsConnectionEntry *ent)
-{
-    NS_ADDREF(conn);
-    ent->mActiveConns.AppendElement(conn);
-    mNumActiveConns++;
-}
-
-void
-nsHttpConnectionMgr::StartedConnect()
-{
-    mNumActiveConns++;
-}
-
-void
-nsHttpConnectionMgr::RecvdConnect()
-{
-    mNumActiveConns--;
-}
-
-nsresult
-nsHttpConnectionMgr::CreateTransport(nsConnectionEntry *ent,
-                                     nsHttpTransaction *trans)
-{
-    NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread");
-
-    nsRefPtr<nsHalfOpenSocket> sock = new nsHalfOpenSocket(ent, trans);
-    nsresult rv = sock->SetupPrimaryStreams();
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    sock->SetupBackupTimer();
-    ent->mHalfOpens.AppendElement(sock);
-    return NS_OK;
-}
-
 nsresult
 nsHttpConnectionMgr::DispatchTransaction(nsConnectionEntry *ent,
                                          nsAHttpTransaction *trans,
                                          PRUint8 caps,
                                          nsHttpConnection *conn)
 {
     LOG(("nsHttpConnectionMgr::DispatchTransaction [ci=%s trans=%x caps=%x conn=%x]\n",
         ent->mConnInfo->HashKey().get(), trans, caps, conn));
@@ -772,16 +711,21 @@ nsHttpConnectionMgr::DispatchTransaction
 
     nsHttpPipeline *pipeline = nsnull;
     if (conn->SupportsPipelining() && (caps & NS_HTTP_ALLOW_PIPELINING)) {
         LOG(("  looking to build pipeline...\n"));
         if (BuildPipeline(ent, trans, &pipeline))
             trans = pipeline;
     }
 
+    // hold an owning ref to this connection
+    ent->mActiveConns.AppendElement(conn);
+    mNumActiveConns++;
+    NS_ADDREF(conn);
+
     // give the transaction the indirect reference to the connection.
     trans->SetConnection(handle);
 
     nsresult rv = conn->Activate(trans, caps);
 
     if (NS_FAILED(rv)) {
         LOG(("  conn->Activate failed [rv=%x]\n", rv));
         ent->mActiveConns.RemoveElement(conn);
@@ -844,18 +788,16 @@ nsHttpConnectionMgr::BuildPipeline(nsCon
     LOG(("  pipelined %u transactions\n", numAdded));
     NS_ADDREF(*result = pipeline);
     return PR_TRUE;
 }
 
 nsresult
 nsHttpConnectionMgr::ProcessNewTransaction(nsHttpTransaction *trans)
 {
-    NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread");
-
     // since "adds" and "cancels" are processed asynchronously and because
     // various events might trigger an "add" directly on the socket thread,
     // we must take care to avoid dispatching a transaction that has already
     // been canceled (see bug 190001).
     if (NS_FAILED(trans->Status())) {
         LOG(("  transaction was canceled... dropping event!\n"));
         return NS_OK;
     }
@@ -888,19 +830,28 @@ nsHttpConnectionMgr::ProcessNewTransacti
 
         // steal reference from connection handle.
         // XXX prevent SetConnection(nsnull) from calling ReclaimConnection
         conn = handle->mConn;
         handle->mConn = nsnull;
 
         // destroy connection handle.
         trans->SetConnection(nsnull);
+
+        // remove sticky connection from active connection list; we'll add it
+        // right back in DispatchTransaction.
+        if (ent->mActiveConns.RemoveElement(conn))
+            mNumActiveConns--;
+        else {
+            NS_ERROR("sticky connection not found in active list");
+            return NS_ERROR_UNEXPECTED;
+        }
     }
     else
-        GetConnection(ent, trans, &conn);
+        GetConnection(ent, caps, &conn);
 
     nsresult rv;
     if (!conn) {
         LOG(("  adding transaction to pending queue [trans=%x pending-count=%u]\n",
             trans, ent->mPendingQ.Length()+1));
         // put this transaction on the pending queue...
         InsertTransactionSorted(ent->mPendingQ, trans);
         NS_ADDREF(trans);
@@ -1040,45 +991,38 @@ nsHttpConnectionMgr::OnMsgReclaimConnect
     nsHttpConnectionInfo *ci = conn->ConnectionInfo();
     NS_ADDREF(ci);
 
     nsCStringKey key(ci->HashKey());
     nsConnectionEntry *ent = (nsConnectionEntry *) mCT.Get(&key);
 
     NS_ASSERTION(ent, "no connection entry");
     if (ent) {
-        // If the connection is in the active list, remove that entry
-        // and the reference held by the mActiveConns list.
-        // This is never the final reference on conn as the event context
-        // is also holding one that is released at the end of this function.
-        if (ent->mActiveConns.RemoveElement(conn)) {
-            nsHttpConnection *temp = conn;
-            NS_RELEASE(temp);
-            mNumActiveConns--;
-        }
-
+        ent->mActiveConns.RemoveElement(conn);
+        mNumActiveConns--;
         if (conn->CanReuse()) {
             LOG(("  adding connection to idle list\n"));
             // hold onto this connection in the idle list.  we push it to
             // the end of the list so as to ensure that we'll visit older
             // connections first before getting to this one.
-            NS_ADDREF(conn);
             ent->mIdleConns.AppendElement(conn);
             mNumIdleConns++;
             // If the added connection was first idle connection or has shortest
             // time to live among the idle connections, pruning dead
             // connections needs to be done when it can't be reused anymore.
             PRUint32 timeToLive = conn->TimeToLive();
             if(!mTimer || NowInSeconds() + timeToLive < mTimeOfNextWakeUp)
                 PruneDeadConnectionsAfter(timeToLive);
         }
         else {
             LOG(("  connection cannot be reused; closing connection\n"));
             // make sure the connection is closed and release our reference.
             conn->Close(NS_ERROR_ABORT);
+            nsHttpConnection *temp = conn;
+            NS_RELEASE(temp);
         }
     }
  
     OnMsgProcessPendingQ(NS_OK, ci); // releases |ci|
     NS_RELEASE(conn);
 }
 
 void
@@ -1179,333 +1123,16 @@ nsHttpConnectionMgr::nsConnectionHandle:
 }
 
 nsresult
 nsHttpConnectionMgr::nsConnectionHandle::PushBack(const char *buf, PRUint32 bufLen)
 {
     return mConn->PushBack(buf, bufLen);
 }
 
-
-//////////////////////// nsHalfOpenSocket
-
-
-NS_IMPL_THREADSAFE_ISUPPORTS4(nsHttpConnectionMgr::nsHalfOpenSocket,
-                              nsIOutputStreamCallback,
-                              nsITransportEventSink,
-                              nsIInterfaceRequestor,
-                              nsITimerCallback)
-
-nsHttpConnectionMgr::
-nsHalfOpenSocket::nsHalfOpenSocket(nsConnectionEntry *ent,
-                                   nsHttpTransaction *trans)
-    : mEnt(ent),
-      mTransaction(trans)
-{
-    NS_ABORT_IF_FALSE(ent && trans, "constructor with null arguments");
-    LOG(("Creating nsHalfOpenSocket [this=%p trans=%p ent=%s]\n",
-         this, trans, ent->mConnInfo->Host()));
-}
-
-nsHttpConnectionMgr::nsHalfOpenSocket::~nsHalfOpenSocket()
-{
-    NS_ABORT_IF_FALSE(!mStreamOut, "streamout not null");
-    NS_ABORT_IF_FALSE(!mBackupStreamOut, "backupstreamout not null");
-    NS_ABORT_IF_FALSE(!mSynTimer, "syntimer not null");
-    LOG(("Destroying nsHalfOpenSocket [this=%p]\n", this));
-    
-    if (mEnt) {
-        PRInt32 index = mEnt->mHalfOpens.IndexOf(this);
-        NS_ABORT_IF_FALSE(index != -1, "half open complete but no item");
-        mEnt->mHalfOpens.RemoveElementAt(index);
-    }
-}
-
-nsresult
-nsHttpConnectionMgr::
-nsHalfOpenSocket::SetupStreams(nsISocketTransport **transport,
-                               nsIAsyncInputStream **instream,
-                               nsIAsyncOutputStream **outstream)
-{
-    nsresult rv;
-
-    const char* types[1];
-    types[0] = (mEnt->mConnInfo->UsingSSL()) ?
-        "ssl" : gHttpHandler->DefaultSocketType();
-    PRUint32 typeCount = (types[0] != nsnull);
-
-    nsCOMPtr<nsISocketTransport> socketTransport;
-    nsCOMPtr<nsISocketTransportService> sts;
-
-    sts = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    rv = sts->CreateTransport(types, typeCount,
-                              nsDependentCString(mEnt->mConnInfo->Host()),
-                              mEnt->mConnInfo->Port(),
-                              mEnt->mConnInfo->ProxyInfo(),
-                              getter_AddRefs(socketTransport));
-    NS_ENSURE_SUCCESS(rv, rv);
-    
-    PRUint32 tmpFlags = 0;
-    if (mTransaction->Caps() & NS_HTTP_REFRESH_DNS)
-        tmpFlags = nsISocketTransport::BYPASS_CACHE;
-
-    if (mTransaction->Caps() & NS_HTTP_LOAD_ANONYMOUS)
-        tmpFlags |= nsISocketTransport::ANONYMOUS_CONNECT;
-
-    socketTransport->SetConnectionFlags(tmpFlags);
-
-    socketTransport->SetQoSBits(gHttpHandler->GetQoSBits());
-
-    rv = socketTransport->SetEventSink(this, nsnull);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    rv = socketTransport->SetSecurityCallbacks(this);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsCOMPtr<nsIOutputStream> sout;
-    rv = socketTransport->OpenOutputStream(nsITransport::OPEN_UNBUFFERED,
-                                            0, 0,
-                                            getter_AddRefs(sout));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsCOMPtr<nsIInputStream> sin;
-    rv = socketTransport->OpenInputStream(nsITransport::OPEN_UNBUFFERED,
-                                           0, 0,
-                                           getter_AddRefs(sin));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    socketTransport.forget(transport);
-    CallQueryInterface(sin, instream);
-    CallQueryInterface(sout, outstream);
-
-    rv = (*outstream)->AsyncWait(this, 0, 0, nsnull);
-    if (NS_SUCCEEDED(rv))
-        gHttpHandler->ConnMgr()->StartedConnect();
-
-    return rv;
-}
-
-nsresult
-nsHttpConnectionMgr::nsHalfOpenSocket::SetupPrimaryStreams()
-{
-    nsresult rv = SetupStreams(getter_AddRefs(mSocketTransport),
-                               getter_AddRefs(mStreamIn),
-                               getter_AddRefs(mStreamOut));
-    LOG(("nsHalfOpenSocket::SetupPrimaryStream [this=%p ent=%s rv=%x]",
-         this, mEnt->mConnInfo->Host(), rv));
-    if (NS_FAILED(rv)) {
-        if (mStreamOut)
-            mStreamOut->AsyncWait(nsnull, 0, 0, nsnull);
-        mStreamOut = nsnull;
-        mStreamIn = nsnull;
-        mSocketTransport = nsnull;
-    }
-    return rv;
-}
-
-nsresult
-nsHttpConnectionMgr::nsHalfOpenSocket::SetupBackupStreams()
-{
-    nsresult rv = SetupStreams(getter_AddRefs(mBackupTransport),
-                               getter_AddRefs(mBackupStreamIn),
-                               getter_AddRefs(mBackupStreamOut));
-    LOG(("nsHalfOpenSocket::SetupBackupStream [this=%p ent=%s rv=%x]",
-         this, mEnt->mConnInfo->Host(), rv));
-    if (NS_FAILED(rv)) {
-        if (mBackupStreamOut)
-            mBackupStreamOut->AsyncWait(nsnull, 0, 0, nsnull);
-        mBackupStreamOut = nsnull;
-        mBackupStreamIn = nsnull;
-        mBackupTransport = nsnull;
-    }
-    return rv;
-}
-
-void
-nsHttpConnectionMgr::nsHalfOpenSocket::SetupBackupTimer()
-{
-    PRUint16 timeout = gHttpHandler->GetIdleSynTimeout();
-    NS_ABORT_IF_FALSE(!mSynTimer, "timer already initd");
-    if (timeout) {
-        // Setup the timer that will establish a backup socket
-        // if we do not get a writable event on the main one.
-        // We do this because a lost SYN takes a very long time
-        // to repair at the TCP level.
-        //
-        // Failure to setup the timer is something we can live with,
-        // so don't return an error in that case.
-        nsresult rv;
-        mSynTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
-        if (NS_SUCCEEDED(rv))
-            mSynTimer->InitWithCallback(this, timeout, nsITimer::TYPE_ONE_SHOT);
-    }
-}
-
-void
-nsHttpConnectionMgr::nsHalfOpenSocket::Abandon()
-{
-    LOG(("nsHalfOpenSocket::Abandon [this=%p ent=%s]",
-         this, mEnt->mConnInfo->Host()));
-    nsRefPtr<nsHalfOpenSocket> deleteProtector(this);
-
-    if (mStreamOut) {
-        gHttpHandler->ConnMgr()->RecvdConnect();
-        mStreamOut->AsyncWait(nsnull, 0, 0, nsnull);
-        mStreamOut = nsnull;
-    }
-    if (mBackupStreamOut) {
-        gHttpHandler->ConnMgr()->RecvdConnect();
-        mBackupStreamOut->AsyncWait(nsnull, 0, 0, nsnull);
-        mBackupStreamOut = nsnull;
-    }
-    if (mSynTimer) {
-        mSynTimer->Cancel();
-        mSynTimer = nsnull;
-    }
-
-    mEnt = nsnull;
-}
-
-NS_IMETHODIMP // method for nsITimerCallback
-nsHttpConnectionMgr::nsHalfOpenSocket::Notify(nsITimer *timer)
-{
-    NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread");
-    NS_ABORT_IF_FALSE(timer == mSynTimer, "wrong timer");
-
-    mSynTimer = nsnull;
-    if (!gHttpHandler->ConnMgr()->
-        AtActiveConnectionLimit(mEnt, mTransaction->Caps())) {
-        SetupBackupStreams();
-    }
-    return NS_OK;
-}
-
-// method for nsIAsyncOutputStreamCallback
-NS_IMETHODIMP
-nsHttpConnectionMgr::
-nsHalfOpenSocket::OnOutputStreamReady(nsIAsyncOutputStream *out)
-{
-    NS_ABORT_IF_FALSE(PR_GetCurrentThread() == gSocketThread, "wrong thread");
-    NS_ABORT_IF_FALSE(out == mStreamOut ||
-                      out == mBackupStreamOut, "stream mismatch");
-    LOG(("nsHalfOpenSocket::OnOutputStreamReady [this=%p ent=%s %s]\n", 
-         this, mEnt->mConnInfo->Host(),
-         out == mStreamOut ? "primary" : "backup"));
-    PRInt32 index;
-    nsresult rv;
-    
-    gHttpHandler->ConnMgr()->RecvdConnect();
-
-    // If the syntimer is still armed, we can cancel it because no backup
-    // socket should be formed at this point
-    if (mSynTimer) {
-        NS_ABORT_IF_FALSE (out == mStreamOut, "timer for non existant stream");
-        LOG(("nsHalfOpenSocket::OnOutputStreamReady "
-             "Backup connection timer canceled\n"));
-        mSynTimer->Cancel();
-        mSynTimer = nsnull;
-    }
-
-    // assign the new socket to the http connection
-    nsRefPtr<nsHttpConnection> conn = new nsHttpConnection();
-    LOG(("nsHalfOpenSocket::OnOutputStreamReady "
-         "Created new nshttpconnection %p\n", conn));
-
-    nsCOMPtr<nsIInterfaceRequestor> callbacks;
-    nsCOMPtr<nsIEventTarget>        callbackTarget;
-    mTransaction->GetSecurityCallbacks(getter_AddRefs(callbacks),
-                                       getter_AddRefs(callbackTarget));
-    if (out == mStreamOut) {
-        rv = conn->Init(mEnt->mConnInfo,
-                        gHttpHandler->ConnMgr()->mMaxRequestDelay,
-                        mSocketTransport, mStreamIn, mStreamOut,
-                        callbacks, callbackTarget);
-
-        // The nsHttpConnection object now owns these streams and sockets
-        mStreamOut = nsnull;
-        mStreamIn = nsnull;
-        mSocketTransport = nsnull;
-    }
-    else {
-        rv = conn->Init(mEnt->mConnInfo,
-                        gHttpHandler->ConnMgr()->mMaxRequestDelay,
-                        mBackupTransport, mBackupStreamIn, mBackupStreamOut,
-                        callbacks, callbackTarget);
-
-        // The nsHttpConnection object now owns these streams and sockets
-        mBackupStreamOut = nsnull;
-        mBackupStreamIn = nsnull;
-        mBackupTransport = nsnull;
-    }
-
-    if (NS_FAILED(rv)) {
-        LOG(("nsHalfOpenSocket::OnOutputStreamReady "
-             "conn->init (%p) failed %x\n", conn, rv));
-        return rv;
-    }
-
-    // if this is still in the pending list, remove it and dispatch it
-    index = mEnt->mPendingQ.IndexOf(mTransaction);
-    if (index != -1) {
-        mEnt->mPendingQ.RemoveElementAt(index);
-        nsHttpTransaction *temp = mTransaction;
-        NS_RELEASE(temp);
-        gHttpHandler->ConnMgr()->AddActiveConn(conn, mEnt);
-        rv = gHttpHandler->ConnMgr()->DispatchTransaction(mEnt, mTransaction,
-                                                          mTransaction->Caps(),
-                                                          conn);
-    }
-    else {
-        // this transaction was dispatched off the pending q before all the
-        // sockets established themselves.
-
-        // We need to establish a small non-zero idle timeout so the connection
-        // mgr perceives this socket as suitable for persistent connection reuse
-        conn->SetIdleTimeout(NS_MIN((PRUint16) 5, gHttpHandler->IdleTimeout()));
-
-        // After about 1 second allow for the possibility of restarting a
-        // transaction due to server close. Keep at sub 1 second as that is the
-        // minimum granularity we can expect a server to be timing out with.
-        conn->SetIsReusedAfter(950);
-
-        NS_ADDREF(conn);  // because onmsg*() expects to drop a reference
-        gHttpHandler->ConnMgr()->OnMsgReclaimConnection(NS_OK, conn);
-    }
-
-    return rv;
-}
-
-// method for nsITransportEventSink
-NS_IMETHODIMP
-nsHttpConnectionMgr::nsHalfOpenSocket::OnTransportStatus(nsITransport *trans,
-                                                         nsresult status,
-                                                         PRUint64 progress,
-                                                         PRUint64 progressMax)
-{
-    if (mTransaction)
-        mTransaction->OnTransportStatus(status, progress);
-    return NS_OK;
-}
-
-// method for nsIInterfaceRequestor
-NS_IMETHODIMP
-nsHttpConnectionMgr::nsHalfOpenSocket::GetInterface(const nsIID &iid,
-                                                    void **result)
-{
-    if (mTransaction) {
-        nsCOMPtr<nsIInterfaceRequestor> callbacks;
-        mTransaction->GetSecurityCallbacks(getter_AddRefs(callbacks), nsnull);
-        if (callbacks)
-            return callbacks->GetInterface(iid, result);
-    }
-    return NS_ERROR_NO_INTERFACE;
-}
-
 PRBool
 nsHttpConnectionMgr::nsConnectionHandle::LastTransactionExpectedNoContent()
 {
     return mConn->LastTransactionExpectedNoContent();
 }
 
 void
 nsHttpConnectionMgr::
--- a/netwerk/protocol/http/nsHttpConnectionMgr.h
+++ b/netwerk/protocol/http/nsHttpConnectionMgr.h
@@ -41,18 +41,16 @@
 
 #include "nsHttpConnectionInfo.h"
 #include "nsHttpConnection.h"
 #include "nsHttpTransaction.h"
 #include "nsTArray.h"
 #include "nsThreadUtils.h"
 #include "nsHashtable.h"
 #include "nsAutoPtr.h"
-#include "prmon.h"
-#include "nsISocketTransportService.h"
 #include "mozilla/Monitor.h"
 
 #include "nsIObserver.h"
 #include "nsITimer.h"
 
 class nsHttpPipeline;
 
 //-----------------------------------------------------------------------------
@@ -136,18 +134,17 @@ public:
     void AddTransactionToPipeline(nsHttpPipeline *);
 
     // called to force the transaction queue to be processed once more, giving
     // preference to the specified connection.
     nsresult ProcessPendingQ(nsHttpConnectionInfo *);
 
 private:
     virtual ~nsHttpConnectionMgr();
-    class nsHalfOpenSocket;
-    
+
     // nsConnectionEntry
     //
     // mCT maps connection info hash key to nsConnectionEntry object, which
     // contains list of active and idle connections as well as the list of
     // pending transactions.
     //
     struct nsConnectionEntry
     {
@@ -157,17 +154,16 @@ private:
             NS_ADDREF(mConnInfo);
         }
        ~nsConnectionEntry() { NS_RELEASE(mConnInfo); }
 
         nsHttpConnectionInfo        *mConnInfo;
         nsTArray<nsHttpTransaction*> mPendingQ;    // pending transaction queue
         nsTArray<nsHttpConnection*>  mActiveConns; // active connections
         nsTArray<nsHttpConnection*>  mIdleConns;   // idle persistent connections
-        nsTArray<nsHalfOpenSocket*>  mHalfOpens;
     };
 
     // nsConnectionHandle
     //
     // thin wrapper around a real connection, used to keep track of references
     // to the connection to determine when the connection may be reused.  the
     // transaction (or pipeline) owns a reference to this handle.  this extra
     // layer of indirection greatly simplifies consumer code, avoiding the
@@ -181,58 +177,16 @@ private:
         NS_DECL_NSAHTTPCONNECTION
 
         nsConnectionHandle(nsHttpConnection *conn) { NS_ADDREF(mConn = conn); }
         virtual ~nsConnectionHandle();
 
         nsHttpConnection *mConn;
     };
 
-    // nsHalfOpenSocket is used to hold the state of an opening TCP socket
-    // while we wait for it to establish and bind it to a connection
-
-    class nsHalfOpenSocket : public nsIOutputStreamCallback,
-                             public nsITransportEventSink,
-                             public nsIInterfaceRequestor,
-                             public nsITimerCallback
-    {
-    public:
-        NS_DECL_ISUPPORTS
-        NS_DECL_NSIOUTPUTSTREAMCALLBACK
-        NS_DECL_NSITRANSPORTEVENTSINK
-        NS_DECL_NSIINTERFACEREQUESTOR
-        NS_DECL_NSITIMERCALLBACK
-
-        nsHalfOpenSocket(nsConnectionEntry *ent,
-                         nsHttpTransaction *trans);
-        ~nsHalfOpenSocket();
-        
-        nsresult SetupStreams(nsISocketTransport **,
-                              nsIAsyncInputStream **,
-                              nsIAsyncOutputStream **);
-        nsresult SetupPrimaryStreams();
-        nsresult SetupBackupStreams();
-        void     SetupBackupTimer();
-        void     Abandon();
-        
-    private:
-        nsConnectionEntry              *mEnt;
-        nsRefPtr<nsHttpTransaction>    mTransaction;
-        nsCOMPtr<nsISocketTransport>   mSocketTransport;
-        nsCOMPtr<nsIAsyncOutputStream> mStreamOut;
-        nsCOMPtr<nsIAsyncInputStream>  mStreamIn;
-
-        // for syn retry
-        nsCOMPtr<nsITimer>             mSynTimer;
-        nsCOMPtr<nsISocketTransport>   mBackupTransport;
-        nsCOMPtr<nsIAsyncOutputStream> mBackupStreamOut;
-        nsCOMPtr<nsIAsyncInputStream>  mBackupStreamIn;
-    };
-    friend class nsHalfOpenSocket;
-
     //-------------------------------------------------------------------------
     // NOTE: these members may be accessed from any thread (use mMonitor)
     //-------------------------------------------------------------------------
 
     PRInt32                      mRef;
     mozilla::Monitor             mMonitor;
     nsCOMPtr<nsIEventTarget>     mSocketThreadTarget;
 
@@ -247,34 +201,29 @@ private:
 
     PRPackedBool mIsShuttingDown;
 
     //-------------------------------------------------------------------------
     // NOTE: these members are only accessed on the socket transport thread
     //-------------------------------------------------------------------------
 
     static PRIntn ProcessOneTransactionCB(nsHashKey *, void *, void *);
-
+    static PRIntn PurgeOneIdleConnectionCB(nsHashKey *, void *, void *);
     static PRIntn PruneDeadConnectionsCB(nsHashKey *, void *, void *);
     static PRIntn ShutdownPassCB(nsHashKey *, void *, void *);
-    static PRIntn PurgeExcessIdleConnectionsCB(nsHashKey *, void *, void *);
+
     PRBool   ProcessPendingQForEntry(nsConnectionEntry *);
     PRBool   AtActiveConnectionLimit(nsConnectionEntry *, PRUint8 caps);
-    void     GetConnection(nsConnectionEntry *, nsHttpTransaction *,
-                           nsHttpConnection **);
+    void     GetConnection(nsConnectionEntry *, PRUint8 caps, nsHttpConnection **);
     nsresult DispatchTransaction(nsConnectionEntry *, nsAHttpTransaction *,
                                  PRUint8 caps, nsHttpConnection *);
     PRBool   BuildPipeline(nsConnectionEntry *, nsAHttpTransaction *, nsHttpPipeline **);
     nsresult ProcessNewTransaction(nsHttpTransaction *);
     nsresult EnsureSocketThreadTargetIfOnline();
-    nsresult CreateTransport(nsConnectionEntry *, nsHttpTransaction *);
-    void     AddActiveConn(nsHttpConnection *, nsConnectionEntry *);
-    void     StartedConnect();
-    void     RecvdConnect();
-    
+
     // message handlers have this signature
     typedef void (nsHttpConnectionMgr:: *nsConnEventHandler)(PRInt32, void *);
 
     // nsConnEvent
     //
     // subclass of nsRunnable used to marshall events to the socket transport
     // thread.  this class is used to implement PostEvent.
     //
--- a/netwerk/protocol/http/nsHttpHandler.cpp
+++ b/netwerk/protocol/http/nsHttpHandler.cpp
@@ -173,17 +173,16 @@ nsHttpHandler::nsHttpHandler()
     , mHttpVersion(NS_HTTP_VERSION_1_1)
     , mProxyHttpVersion(NS_HTTP_VERSION_1_1)
     , mCapabilities(NS_HTTP_ALLOW_KEEPALIVE)
     , mProxyCapabilities(NS_HTTP_ALLOW_KEEPALIVE)
     , mReferrerLevel(0xff) // by default we always send a referrer
     , mIdleTimeout(10)
     , mMaxRequestAttempts(10)
     , mMaxRequestDelay(10)
-    , mIdleSynTimeout(250)
     , mMaxConnections(24)
     , mMaxConnectionsPerServer(8)
     , mMaxPersistentConnectionsPerServer(2)
     , mMaxPersistentConnectionsPerProxy(4)
     , mMaxPipelinedRequests(2)
     , mRedirectionLimit(10)
     , mPhishyUserPassLength(1)
     , mQoSBits(0x00)
@@ -921,22 +920,16 @@ nsHttpHandler::PrefsChanged(nsIPrefBranc
     }
 
     if (PREF_CHANGED(HTTP_PREF("redirection-limit"))) {
         rv = prefs->GetIntPref(HTTP_PREF("redirection-limit"), &val);
         if (NS_SUCCEEDED(rv))
             mRedirectionLimit = (PRUint8) NS_CLAMP(val, 0, 0xff);
     }
 
-    if (PREF_CHANGED(HTTP_PREF("connection-retry-timeout"))) {
-        rv = prefs->GetIntPref(HTTP_PREF("connection-retry-timeout"), &val);
-        if (NS_SUCCEEDED(rv))
-            mIdleSynTimeout = (PRUint16) NS_CLAMP(val, 0, 3000);
-    }
-
     if (PREF_CHANGED(HTTP_PREF("version"))) {
         nsXPIDLCString httpVersion;
         prefs->GetCharPref(HTTP_PREF("version"), getter_Copies(httpVersion));
         if (httpVersion) {
             if (!PL_strcmp(httpVersion, "1.1"))
                 mHttpVersion = NS_HTTP_VERSION_1_1;
             else if (!PL_strcmp(httpVersion, "0.9"))
                 mHttpVersion = NS_HTTP_VERSION_0_9;
--- a/netwerk/protocol/http/nsHttpHandler.h
+++ b/netwerk/protocol/http/nsHttpHandler.h
@@ -102,17 +102,16 @@ public:
     PRBool         SendSecureXSiteReferrer() { return mSendSecureXSiteReferrer; }
     PRUint8        RedirectionLimit()        { return mRedirectionLimit; }
     PRUint16       IdleTimeout()             { return mIdleTimeout; }
     PRUint16       MaxRequestAttempts()      { return mMaxRequestAttempts; }
     const char    *DefaultSocketType()       { return mDefaultSocketType.get(); /* ok to return null */ }
     nsIIDNService *IDNConverter()            { return mIDNConverter; }
     PRUint32       PhishyUserPassLength()    { return mPhishyUserPassLength; }
     PRUint8        GetQoSBits()              { return mQoSBits; }
-    PRUint16       GetIdleSynTimeout()       { return mIdleSynTimeout; }
     
     PRBool         IsPersistentHttpsCachingEnabled() { return mEnablePersistentHttpsCaching; }
 
     PRBool         PromptTempRedirect()      { return mPromptTempRedirect; }
 
     nsHttpAuthCache     *AuthCache() { return &mAuthCache; }
     nsHttpConnectionMgr *ConnMgr()   { return mConnMgr; }
 
@@ -259,17 +258,16 @@ private:
     PRUint8  mProxyHttpVersion;
     PRUint8  mCapabilities;
     PRUint8  mProxyCapabilities;
     PRUint8  mReferrerLevel;
 
     PRUint16 mIdleTimeout;
     PRUint16 mMaxRequestAttempts;
     PRUint16 mMaxRequestDelay;
-    PRUint16 mIdleSynTimeout;
 
     PRUint16 mMaxConnections;
     PRUint8  mMaxConnectionsPerServer;
     PRUint8  mMaxPersistentConnectionsPerServer;
     PRUint8  mMaxPersistentConnectionsPerProxy;
     PRUint8  mMaxPipelinedRequests;
 
     PRUint8  mRedirectionLimit;
--- a/netwerk/protocol/http/nsHttpPipeline.cpp
+++ b/netwerk/protocol/http/nsHttpPipeline.cpp
@@ -318,30 +318,26 @@ nsHttpPipeline::SetConnection(nsAHttpCon
     NS_IF_ADDREF(mConnection = conn);
 
     PRInt32 i, count = mRequestQ.Length();
     for (i=0; i<count; ++i)
         Request(i)->SetConnection(this);
 }
 
 void
-nsHttpPipeline::GetSecurityCallbacks(nsIInterfaceRequestor **result,
-                                     nsIEventTarget        **target)
+nsHttpPipeline::GetSecurityCallbacks(nsIInterfaceRequestor **result)
 {
     NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
 
     // return security callbacks from first request
     nsAHttpTransaction *trans = Request(0);
     if (trans)
-        trans->GetSecurityCallbacks(result, target);
-    else {
+        trans->GetSecurityCallbacks(result);
+    else
         *result = nsnull;
-        if (target)
-            *target = nsnull;
-    }
 }
 
 void
 nsHttpPipeline::OnTransportStatus(nsresult status, PRUint64 progress)
 {
     LOG(("nsHttpPipeline::OnStatus [this=%x status=%x progress=%llu]\n",
         this, status, progress));
 
--- a/netwerk/protocol/http/nsHttpTransaction.cpp
+++ b/netwerk/protocol/http/nsHttpTransaction.cpp
@@ -327,22 +327,19 @@ nsHttpTransaction::TakeResponseHead()
 void
 nsHttpTransaction::SetConnection(nsAHttpConnection *conn)
 {
     NS_IF_RELEASE(mConnection);
     NS_IF_ADDREF(mConnection = conn);
 }
 
 void
-nsHttpTransaction::GetSecurityCallbacks(nsIInterfaceRequestor **cb,
-                                        nsIEventTarget        **target)
+nsHttpTransaction::GetSecurityCallbacks(nsIInterfaceRequestor **cb)
 {
     NS_IF_ADDREF(*cb = mCallbacks);
-    if (target)
-        NS_IF_ADDREF(*target = mConsumerTarget);
 }
 
 void
 nsHttpTransaction::OnTransportStatus(nsresult status, PRUint64 progress)
 {
     LOG(("nsHttpTransaction::OnSocketStatus [this=%x status=%x progress=%llu]\n",
         this, status, progress));
 
@@ -560,17 +557,17 @@ nsHttpTransaction::Close(nsresult reason
     if (mActivityDistributor) {
         // report the reponse is complete if not already reported
         if (!mResponseIsComplete)
             mActivityDistributor->ObserveActivity(
                 mChannel,
                 NS_HTTP_ACTIVITY_TYPE_HTTP_TRANSACTION,
                 NS_HTTP_ACTIVITY_SUBTYPE_RESPONSE_COMPLETE,
                 PR_Now(),
-                static_cast<PRUint64>(mContentRead),
+                static_cast<PRUint64>(mContentRead.mValue),
                 EmptyCString());
 
         // report that this transaction is closing
         mActivityDistributor->ObserveActivity(
             mChannel,
             NS_HTTP_ACTIVITY_TYPE_HTTP_TRANSACTION,
             NS_HTTP_ACTIVITY_SUBTYPE_TRANSACTION_CLOSE,
             PR_Now(), LL_ZERO, EmptyCString());
@@ -982,17 +979,17 @@ nsHttpTransaction::HandleContentStart()
                 mChunkedDecoder = new nsHttpChunkedDecoder();
                 if (!mChunkedDecoder)
                     return NS_ERROR_OUT_OF_MEMORY;
                 LOG(("chunked decoder created\n"));
                 // Ignore server specified Content-Length.
                 mContentLength = -1;
             }
 #if defined(PR_LOGGING)
-            else if (mContentLength == PRInt64(-1))
+            else if (mContentLength == nsInt64(-1))
                 LOG(("waiting for the server to close the connection.\n"));
 #endif
         }
     }
 
     mDidContentStart = PR_TRUE;
     return NS_OK;
 }
@@ -1022,31 +1019,31 @@ nsHttpTransaction::HandleContent(char *b
     }
 
     if (mChunkedDecoder) {
         // give the buf over to the chunked decoder so it can reformat the
         // data and tell us how much is really there.
         rv = mChunkedDecoder->HandleChunkedContent(buf, count, contentRead, contentRemaining);
         if (NS_FAILED(rv)) return rv;
     }
-    else if (mContentLength >= PRInt64(0)) {
+    else if (mContentLength >= nsInt64(0)) {
         // HTTP/1.0 servers have been known to send erroneous Content-Length
         // headers. So, unless the connection is persistent, we must make
         // allowances for a possibly invalid Content-Length header. Thus, if
         // NOT persistent, we simply accept everything in |buf|.
         if (mConnection->IsPersistent()) {
-            PRInt64 remaining = mContentLength - mContentRead;
-            PRInt64 count64 = count;
+            nsInt64 remaining = mContentLength - mContentRead;
+            nsInt64 count64 = count;
             *contentRead = PR_MIN(count64, remaining);
             *contentRemaining = count - *contentRead;
         }
         else {
             *contentRead = count;
             // mContentLength might need to be increased...
-            PRInt64 position = mContentRead + PRInt64(count);
+            nsInt64 position = mContentRead + nsInt64(count);
             if (position > mContentLength) {
                 mContentLength = position;
                 //mResponseHead->SetContentLength(mContentLength);
             }
         }
     }
     else {
         // when we are just waiting for the server to close the connection...
@@ -1059,33 +1056,33 @@ nsHttpTransaction::HandleContent(char *b
         mContentRead += *contentRead;
         /* when uncommenting, take care of 64-bit integers w/ PR_MAX...
         if (mProgressSink)
             mProgressSink->OnProgress(nsnull, nsnull, mContentRead, PR_MAX(0, mContentLength));
         */
     }
 
     LOG(("nsHttpTransaction::HandleContent [this=%x count=%u read=%u mContentRead=%lld mContentLength=%lld]\n",
-        this, count, *contentRead, mContentRead, mContentLength));
+        this, count, *contentRead, mContentRead.mValue, mContentLength.mValue));
 
     // check for end-of-file
     if ((mContentRead == mContentLength) ||
         (mChunkedDecoder && mChunkedDecoder->ReachedEOF())) {
         // the transaction is done with a complete response.
         mTransactionDone = PR_TRUE;
         mResponseIsComplete = PR_TRUE;
 
         // report the entire response has arrived
         if (mActivityDistributor)
             mActivityDistributor->ObserveActivity(
                 mChannel,
                 NS_HTTP_ACTIVITY_TYPE_HTTP_TRANSACTION,
                 NS_HTTP_ACTIVITY_SUBTYPE_RESPONSE_COMPLETE,
                 PR_Now(),
-                static_cast<PRUint64>(mContentRead),
+                static_cast<PRUint64>(mContentRead.mValue),
                 EmptyCString());
     }
 
     return NS_OK;
 }
 
 nsresult
 nsHttpTransaction::ProcessData(char *buf, PRUint32 count, PRUint32 *countRead)
--- a/netwerk/protocol/http/nsHttpTransaction.h
+++ b/netwerk/protocol/http/nsHttpTransaction.h
@@ -39,16 +39,17 @@
 #ifndef nsHttpTransaction_h__
 #define nsHttpTransaction_h__
 
 #include "nsHttp.h"
 #include "nsHttpHeaderArray.h"
 #include "nsAHttpTransaction.h"
 #include "nsAHttpConnection.h"
 #include "nsCOMPtr.h"
+#include "nsInt64.h"
 
 #include "nsIPipe.h"
 #include "nsIInputStream.h"
 #include "nsIOutputStream.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsISocketTransportService.h"
 #include "nsITransport.h"
 #include "nsIEventTarget.h"
@@ -173,18 +174,18 @@ private:
     nsHttpRequestHead              *mRequestHead;     // weak ref
     nsHttpResponseHead             *mResponseHead;    // hard ref
 
     nsAHttpSegmentReader           *mReader;
     nsAHttpSegmentWriter           *mWriter;
 
     nsCString                       mLineBuf;         // may contain a partial line
 
-    PRInt64                         mContentLength;   // equals -1 if unknown
-    PRInt64                         mContentRead;     // count of consumed content bytes
+    nsInt64                         mContentLength;   // equals -1 if unknown
+    nsInt64                         mContentRead;     // count of consumed content bytes
 
     // After a 304/204 or other "no-content" style response we will skip over
     // up to MAX_INVALID_RESPONSE_BODY_SZ bytes when looking for the next
     // response header to deal with servers that actually sent a response
     // body where they should not have. This member tracks how many bytes have
     // so far been skipped.
     PRUint32                        mInvalidResponseBytesRead;
 
@@ -192,31 +193,30 @@ private:
 
     nsresult                        mStatus;
 
     PRInt16                         mPriority;
 
     PRUint16                        mRestartCount;        // the number of times this transaction has been restarted
     PRUint8                         mCaps;
 
-    // state flags, all logically boolean, but not packed together into a
-    // bitfield so as to avoid bitfield-induced races.  See bug 560579.
-    PRPackedBool                    mClosed;
-    PRPackedBool                    mConnected;
-    PRPackedBool                    mHaveStatusLine;
-    PRPackedBool                    mHaveAllHeaders;
-    PRPackedBool                    mTransactionDone;
-    PRPackedBool                    mResponseIsComplete;
-    PRPackedBool                    mDidContentStart;
-    PRPackedBool                    mNoContent; // expecting an empty entity body
-    PRPackedBool                    mSentData;
-    PRPackedBool                    mReceivedData;
-    PRPackedBool                    mStatusEventPending;
-    PRPackedBool                    mHasRequestBody;
-    PRPackedBool                    mSSLConnectFailed;
-    PRPackedBool                    mHttpResponseMatched;
+    // state flags
+    PRUint32                        mClosed             : 1;
+    PRUint32                        mConnected          : 1;
+    PRUint32                        mHaveStatusLine     : 1;
+    PRUint32                        mHaveAllHeaders     : 1;
+    PRUint32                        mTransactionDone    : 1;
+    PRUint32                        mResponseIsComplete : 1;
+    PRUint32                        mDidContentStart    : 1;
+    PRUint32                        mNoContent          : 1; // expecting an empty entity body
+    PRUint32                        mSentData           : 1;
+    PRUint32                        mReceivedData       : 1;
+    PRUint32                        mStatusEventPending : 1;
+    PRUint32                        mHasRequestBody     : 1;
+    PRUint32                        mSSLConnectFailed   : 1;
+    PRUint32                        mHttpResponseMatched: 1;
 
     // mClosed           := transaction has been explicitly closed
     // mTransactionDone  := transaction ran to completion or was interrupted
     // mResponseComplete := transaction ran to completion
 };
 
 #endif // nsHttpTransaction_h__
--- a/netwerk/streamconv/converters/nsMultiMixedConv.cpp
+++ b/netwerk/streamconv/converters/nsMultiMixedConv.cpp
@@ -32,16 +32,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsMultiMixedConv.h"
 #include "nsMemory.h"
+#include "nsInt64.h"
 #include "plstr.h"
 #include "nsIHttpChannel.h"
 #include "nsIServiceManager.h"
 #include "nsNetUtil.h"
 #include "nsMimeTypes.h"
 #include "nsIStringStream.h"
 #include "nsReadableUtils.h"
 #include "nsCRT.h"
@@ -974,17 +975,17 @@ nsMultiMixedConv::ParseHeaders(nsIChanne
                     
                     mByteRangeStart = atoi(range); // XXX want 64-bit conv
                     tmpPtr++;
                     mByteRangeEnd = atoi(tmpPtr);
                 }
 
                 mIsByteRangeRequest = PR_TRUE;
                 if (mContentLength == LL_MAXUINT)
-                    mContentLength = PRUint64(PRInt64(mByteRangeEnd - mByteRangeStart + PRInt64(1)));
+                    mContentLength = PRUint64(PRInt64(mByteRangeEnd - mByteRangeStart + nsInt64(1)));
             }
         }
         *newLine = tmpChar;
         newLine += lineFeedIncrement;
         cursorLen -= (newLine - cursor);
         cursor = newLine;
     }
 
--- a/netwerk/streamconv/converters/nsMultiMixedConv.h
+++ b/netwerk/streamconv/converters/nsMultiMixedConv.h
@@ -38,16 +38,17 @@
 #define __nsmultimixedconv__h__
 
 #include "nsIStreamConverter.h"
 #include "nsIChannel.h"
 #include "nsIURI.h"
 #include "nsString.h"
 #include "nsXPIDLString.h"
 #include "nsCOMPtr.h"
+#include "nsInt64.h"
 #include "nsIByteRangeRequest.h"
 #include "nsIMultiPartChannel.h"
 #include "nsAutoPtr.h"
 
 #define NS_MULTIMIXEDCONVERTER_CID                         \
 { /* 7584CE90-5B25-11d3-A175-0050041CAF44 */         \
     0x7584ce90,                                      \
     0x5b25,                                          \
@@ -96,18 +97,18 @@ protected:
   nsCOMPtr<nsILoadGroup>  mLoadGroup;
 
   nsCString               mContentType;
   nsCString               mContentCharset;
   nsCString               mContentDisposition;
   PRUint64                mContentLength;
 
   PRBool                  mIsByteRangeRequest;
-  PRInt64                 mByteRangeStart;
-  PRInt64                 mByteRangeEnd;
+  nsInt64                 mByteRangeStart;
+  nsInt64                 mByteRangeEnd;
 
   PRUint32                mPartID; // unique ID that can be used to identify
                                    // this part of the multipart document
   PRBool                  mIsLastPart;
 };
 
 // The nsMultiMixedConv stream converter converts a stream of type "multipart/x-mixed-replace"
 // to it's subparts. There was some debate as to whether or not the functionality desired
@@ -184,16 +185,16 @@ protected:
     char                *mBuffer;
     PRUint32            mBufLen;
     PRUint64            mTotalSent;
     PRBool              mFirstOnData;   // used to determine if we're in our first OnData callback.
 
     // The following members are for tracking the byte ranges in
     // multipart/mixed content which specified the 'Content-Range:'
     // header...
-    PRInt64             mByteRangeStart;
-    PRInt64             mByteRangeEnd;
+    nsInt64             mByteRangeStart;
+    nsInt64             mByteRangeEnd;
     PRBool              mIsByteRangeRequest;
 
     PRUint32            mCurrentPartID;
 };
 
 #endif /* __nsmultimixedconv__h__ */
--- a/netwerk/test/TestProtocols.cpp
+++ b/netwerk/test/TestProtocols.cpp
@@ -82,16 +82,18 @@
 #include "nsChannelProperties.h"
 
 #include "nsISimpleEnumerator.h"
 #include "nsStringAPI.h"
 #include "nsNetUtil.h"
 #include "prlog.h"
 #include "prtime.h"
 
+#include "nsInt64.h"
+
 namespace TestProtocols {
 
 #if defined(PR_LOGGING)
 //
 // set NSPR_LOG_MODULES=Test:5
 //
 static PRLogModuleInfo *gTestLog = nsnull;
 #endif
@@ -188,17 +190,17 @@ public:
 
   URLLoadInfo(const char* aUrl);
   virtual ~URLLoadInfo();
 
   // ISupports interface...
   NS_DECL_ISUPPORTS
 
   const char* Name() { return mURLString.get(); }
-  PRInt64   mBytesRead;
+  nsInt64   mBytesRead;
   PRTime    mTotalTime;
   PRTime    mConnectTime;
   nsCString mURLString;
 };
 
 URLLoadInfo::URLLoadInfo(const char *aUrl) : mURLString(aUrl)
 {
   mBytesRead = 0;
@@ -534,19 +536,19 @@ InputTestConsumer::OnStopRequest(nsIRequ
         LOG(("\tHTTP Status: %u\n", httpStatus));
      if (NS_ERROR_UNKNOWN_HOST == aStatus ||
          NS_ERROR_UNKNOWN_PROXY_HOST == aStatus) {
          LOG(("\tDNS lookup failed.\n"));
      }
     LOG(("\tTime to connect: %.3f seconds\n", connectTime));
     LOG(("\tTime to read: %.3f seconds.\n", readTime));
     LOG(("\tRead: %lld bytes.\n", info->mBytesRead.mValue));
-    if (info->mBytesRead == PRInt64(0)) {
+    if (info->mBytesRead == nsInt64(0)) {
     } else if (readTime > 0.0) {
-      LOG(("\tThroughput: %.0f bps.\n", (PRFloat64)(info->mBytesRead*PRInt64(8))/readTime));
+      LOG(("\tThroughput: %.0f bps.\n", (PRFloat64)(info->mBytesRead*nsInt64(8))/readTime));
     } else {
       LOG(("\tThroughput: REAL FAST!!\n"));
     }
   } else {
     LOG(("\nFinished loading: UNKNOWN URL. Status Code: %x\n", aStatus));
   }
 
   if (--gKeepRunning == 0)
--- a/netwerk/test/TestStreamTransport.cpp
+++ b/netwerk/test/TestStreamTransport.cpp
@@ -220,22 +220,22 @@ RunTest(nsIFile *srcFile, nsIFile *destF
     rv = NS_NewLocalFileInputStream(getter_AddRefs(srcStr), srcFile);
     if (NS_FAILED(rv)) return rv;
 
     nsCOMPtr<nsIOutputStream> destStr;
     rv = NS_NewLocalFileOutputStream(getter_AddRefs(destStr), destFile);
     if (NS_FAILED(rv)) return rv;
 
     nsCOMPtr<nsITransport> srcTransport;
-    rv = sts->CreateInputTransport(srcStr, PRInt64(-1), PRInt64(-1), PR_TRUE,
+    rv = sts->CreateInputTransport(srcStr, nsInt64(-1), nsInt64(-1), PR_TRUE,
                                    getter_AddRefs(srcTransport));
     if (NS_FAILED(rv)) return rv;
 
     nsCOMPtr<nsITransport> destTransport;
-    rv = sts->CreateOutputTransport(destStr, PRInt64(-1), PRInt64(-1), PR_TRUE,
+    rv = sts->CreateOutputTransport(destStr, nsInt64(-1), nsInt64(-1), PR_TRUE,
                                     getter_AddRefs(destTransport));
     if (NS_FAILED(rv)) return rv;
 
     MyCopier *copier = new MyCopier();
     if (copier == nsnull)
         return NS_ERROR_OUT_OF_MEMORY;
     NS_ADDREF(copier);
 
@@ -265,17 +265,17 @@ RunBlockingTest(nsIFile *srcFile, nsIFil
     rv = NS_NewLocalFileInputStream(getter_AddRefs(srcIn), srcFile);
     if (NS_FAILED(rv)) return rv;
 
     nsCOMPtr<nsIOutputStream> fileOut;
     rv = NS_NewLocalFileOutputStream(getter_AddRefs(fileOut), destFile);
     if (NS_FAILED(rv)) return rv;
     
     nsCOMPtr<nsITransport> destTransport;
-    rv = sts->CreateOutputTransport(fileOut, PRInt64(-1), PRInt64(-1),
+    rv = sts->CreateOutputTransport(fileOut, nsInt64(-1), nsInt64(-1),
                                     PR_TRUE, getter_AddRefs(destTransport));
     if (NS_FAILED(rv)) return rv;
 
     nsCOMPtr<nsIOutputStream> destOut;
     rv = destTransport->OpenOutputStream(nsITransport::OPEN_BLOCKING, 100, 10, getter_AddRefs(destOut));
     if (NS_FAILED(rv)) return rv;
 
     char buf[120];
--- a/parser/htmlparser/tests/mochitest/file_bug543062.sjs
+++ b/parser/htmlparser/tests/mochitest/file_bug543062.sjs
@@ -1,12 +1,10 @@
-var timer;
-
 function armTimer(response) {
-  timer = Components.classes["@mozilla.org/timer;1"]
+  var timer = Components.classes["@mozilla.org/timer;1"]
     .createInstance(Components.interfaces.nsITimer);
   timer.initWithCallback(function() {
       if (getState("docwritepreloadssecond") == "second" && getState("docwritepreloadsthird") == "third") {
         response.write("ok(true, 'Second and third scripts should have started loading while the first one is loading');");
         response.finish();
       } else {
         armTimer(response);
       }
--- a/security/manager/boot/src/nsStrictTransportSecurityService.cpp
+++ b/security/manager/boot/src/nsStrictTransportSecurityService.cpp
@@ -40,16 +40,17 @@
 #include "prprf.h"
 #include "nsCRTGlue.h"
 #include "nsIPermissionManager.h"
 #include "nsIPrivateBrowsingService.h"
 #include "nsISSLStatus.h"
 #include "nsISSLStatusProvider.h"
 #include "nsStrictTransportSecurityService.h"
 #include "nsIURI.h"
+#include "nsInt64.h"
 #include "nsNetUtil.h"
 #include "nsThreadUtils.h"
 #include "nsStringGlue.h"
 
 #if defined(PR_LOGGING)
 PRLogModuleInfo *gSTSLog = PR_NewLogModule("nsSTSService");
 #endif
 
--- a/security/manager/ssl/src/nsNSSComponent.cpp
+++ b/security/manager/ssl/src/nsNSSComponent.cpp
@@ -88,16 +88,17 @@
 
 #include "nsIWindowWatcher.h"
 #include "nsIPrompt.h"
 #include "nsProxiedService.h"
 #include "nsIPrincipal.h"
 #include "nsReadableUtils.h"
 #include "nsIDateTimeFormat.h"
 #include "prtypes.h"
+#include "nsInt64.h"
 #include "nsTime.h"
 #include "nsIEntropyCollector.h"
 #include "nsIBufEntropyCollector.h"
 #include "nsIServiceManager.h"
 #include "nsILocalFile.h"
 #include "nsITokenPasswordDialogs.h"
 #include "nsICRLManager.h"
 #include "nsNSSShutDown.h"
--- a/startupcache/StartupCache.cpp
+++ b/startupcache/StartupCache.cpp
@@ -60,19 +60,17 @@
 #include "nsITimer.h"
 #include "nsIZipWriter.h"
 #include "nsIZipReader.h"
 #include "nsWeakReference.h"
 #include "nsZipArchive.h"
 #include "mozilla/Omnijar.h"
 #include "prenv.h"
 #include "mozilla/FunctionTimer.h"
-#include "nsThreadUtils.h"
-#include "nsXULAppAPI.h"
-
+ 
 #ifdef IS_BIG_ENDIAN
 #define SC_ENDIAN "big"
 #else
 #define SC_ENDIAN "little"
 #endif
 
 #if PR_BYTES_PER_WORD == 4
 #define SC_WORDSIZE "4"
@@ -123,31 +121,28 @@ StartupCache::StartupCache()
 
 StartupCache::~StartupCache() 
 {
   if (mTimer) {
     mTimer->Cancel();
   }
 
   // Generally, the in-memory table should be empty here,
-  // but an early shutdown means either mTimer didn't run 
-  // or the write thread is still running.
-  WaitOnWriteThread();
+  // but in special cases (like Talos Ts tests) we
+  // could shut down before we write.
+  // This mechanism will change when IO is moved off-thread
+  // (bug 586859) or when Talos first-run is changed to allow
+  // our timer to work (bug 591471).
   WriteToDisk();
   gStartupCache = nsnull;
 }
 
 nsresult
 StartupCache::Init() 
 {
-  if (XRE_GetProcessType() != GeckoProcessType_Default) {
-    NS_WARNING("Startup cache is only available in the chrome process");
-    return NS_ERROR_NOT_AVAILABLE;
-  }
-
   nsresult rv;
   mTable.Init();
 #ifdef DEBUG
   mWriteObjectMap.Init();
 #endif
 
   // This allows to override the startup cache filename
   // which is useful from xpcshell, when there is no ProfLDS directory to keep cache in.
@@ -201,38 +196,35 @@ StartupCache::Init()
   // If it's corrupted, just remove it and start over.
   if (NS_FAILED(rv) && rv != NS_ERROR_FILE_NOT_FOUND) {
     NS_WARNING("Failed to load startupcache file correctly, removing!");
     InvalidateCache();
   }
   return NS_OK;
 }
 
-/** 
- * LoadArchive can be called from the main thread or while reloading cache on write thread.
- */
 nsresult
 StartupCache::LoadArchive() 
 {
+  WaitOnWriteThread();
   PRBool exists;
   mArchive = NULL;
   nsresult rv = mFile->Exists(&exists);
   if (NS_FAILED(rv) || !exists)
     return NS_ERROR_FILE_NOT_FOUND;
   
   mArchive = new nsZipArchive();
   return mArchive->OpenArchive(mFile);
 }
 
 // NOTE: this will not find a new entry until it has been written to disk!
 // Consumer should take ownership of the resulting buffer.
 nsresult
 StartupCache::GetBuffer(const char* id, char** outbuf, PRUint32* length) 
 {
-  NS_ASSERTION(NS_IsMainThread(), "Startup cache only available on main thread");
   WaitOnWriteThread();
   if (!mStartupWriteInitiated) {
     CacheEntry* entry; 
     nsDependentCString idStr(id);
     mTable.Get(idStr, &entry);
     if (entry) {
       *outbuf = new char[entry->size];
       memcpy(*outbuf, entry->data, entry->size);
@@ -263,17 +255,16 @@ StartupCache::GetBuffer(const char* id, 
 #endif
   return NS_ERROR_NOT_AVAILABLE;
 }
 
 // Makes a copy of the buffer, client retains ownership of inbuf.
 nsresult
 StartupCache::PutBuffer(const char* id, const char* inbuf, PRUint32 len) 
 {
-  NS_ASSERTION(NS_IsMainThread(), "Startup cache only available on main thread");
   WaitOnWriteThread();
   if (StartupCache::gShutdownInitiated) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   nsAutoArrayPtr<char> data(new char[len]);
   memcpy(data, inbuf, len);
 
@@ -324,24 +315,20 @@ CacheCloseHelper(const nsACString& key, 
   rv = writer->AddEntryStream(key, holder->time, PR_TRUE, stream, PR_FALSE);
   
   if (NS_FAILED(rv)) {
     NS_WARNING("cache entry deleted but not written to disk.");
   }
   return PL_DHASH_REMOVE;
 }
 
-
-/** 
- * WriteToDisk writes the cache out to disk. Callers of WriteToDisk need to call WaitOnWriteThread
- * to make sure there isn't a write happening on another thread
- */
 void
 StartupCache::WriteToDisk() 
 {
+  WaitOnWriteThread();
   nsresult rv;
   mStartupWriteInitiated = PR_TRUE;
 
   if (mTable.Count() == 0)
     return;
 
   nsCOMPtr<nsIZipWriter> zipW = do_CreateInstance("@mozilla.org/zipwriter;1");
   if (!zipW)
@@ -390,22 +377,23 @@ StartupCache::InvalidateCache()
 /*
  * WaitOnWriteThread() is called from a main thread to wait for the worker
  * thread to finish. However since the same code is used in the worker thread and
  * main thread, the worker thread can also call WaitOnWriteThread() which is a no-op.
  */
 void
 StartupCache::WaitOnWriteThread()
 {
-  NS_ASSERTION(NS_IsMainThread(), "Startup cache should only wait for io thread on main thread");
-  if (!mWriteThread || mWriteThread == PR_GetCurrentThread())
+  PRThread* writeThread = mWriteThread;
+  if (!writeThread || writeThread == PR_GetCurrentThread())
     return;
 
   NS_TIME_FUNCTION_MIN(30);
-  PR_JoinThread(mWriteThread);
+  //NS_WARNING("Waiting on startupcache write");
+  PR_JoinThread(writeThread);
   mWriteThread = NULL;
 }
 
 void 
 StartupCache::ThreadedWrite(void *aClosure)
 {
   gStartupCache->WriteToDisk();
 }
--- a/toolkit/content/widgets/tabbox.xml
+++ b/toolkit/content/widgets/tabbox.xml
@@ -472,17 +472,17 @@
             isTabFocused =
               (document.commandDispatcher.focusedElement == this.selectedItem);
           } catch (e) {}
           this.selectedItem = aNewTab;
           if (isTabFocused) {
             aNewTab.focus();
           }
           else if (this.getAttribute("setfocus") != "false") {
-            document.commandDispatcher.advanceFocusIntoSubtree(this.tabbox.selectedPanel);
+            document.commandDispatcher.advanceFocusIntoSubtree(aNewTab);
             
             // Make sure that the focus doesn't move outside the tabbox
             if (this.tabbox) {
               try {
                 let el = document.commandDispatcher.focusedElement;
                 while (el && el != this.tabbox)
                   el = el.parentNode;
                 if (el != this.tabbox)
--- a/uriloader/base/nsDocLoader.cpp
+++ b/uriloader/base/nsDocLoader.cpp
@@ -102,18 +102,18 @@ struct nsRequestInfo : public PLDHashEnt
   {
   }
 
   nsIRequest* Request() {
     return static_cast<nsIRequest*>(const_cast<void*>(mKey));
   }
 
   const void* mKey; // Must be first for the pldhash stubs to work
-  PRInt64 mCurrentProgress;
-  PRInt64 mMaxProgress;
+  nsInt64 mCurrentProgress;
+  nsInt64 mMaxProgress;
   PRBool mUploading;
 
   PRBool mIsDone;
   nsString mLastStatus;
   nsresult mLastStatusCode;
 };
 
 
@@ -146,21 +146,16 @@ struct nsListenerInfo {
   // Mask indicating which notifications the listener wants to receive.
   unsigned long mNotifyMask;
 };
 
 
 nsDocLoader::nsDocLoader()
   : mParent(nsnull),
     mListenerInfoList(8),
-    mCurrentSelfProgress(0),
-    mMaxSelfProgress(0),
-    mCurrentTotalProgress(0),
-    mMaxTotalProgress(0),
-    mCompletedTotalProgress(0),
     mIsLoadingDocument(PR_FALSE),
     mIsRestoringDocument(PR_FALSE),
     mDontFlushLayout(PR_FALSE),
     mIsFlushingLayout(PR_FALSE)
 {
 #if defined(PR_LOGGING)
   if (nsnull == gDocLoaderLog) {
       gDocLoaderLog = PR_NewLogModule("DocLoader");
@@ -598,26 +593,26 @@ nsDocLoader::OnStopRequest(nsIRequest *a
   // Since the URI has finished loading, all the data is there.  Also,
   // this will allow a more accurate estimation of the max progress (in case
   // the old value was unknown ie. -1)
   //
   nsRequestInfo *info = GetRequestInfo(aRequest);
   if (info) {
     info->mIsDone = PR_TRUE;
 
-    PRInt64 oldMax = info->mMaxProgress;
+    nsInt64 oldMax = info->mMaxProgress;
 
     info->mMaxProgress = info->mCurrentProgress;
     
     //
     // If a request whose content-length was previously unknown has just
     // finished loading, then use this new data to try to calculate a
     // mMaxSelfProgress...
     //
-    if ((oldMax < PRInt64(0)) && (mMaxSelfProgress < PRInt64(0))) {
+    if ((oldMax < nsInt64(0)) && (mMaxSelfProgress < nsInt64(0))) {
       mMaxSelfProgress = CalculateMaxProgress();
     }
 
     // As we know the total progress of this request now, save it to be part
     // of CalculateMaxProgress() result. We need to remove the info from the
     // hash, see bug 480713.
     mCompletedTotalProgress += info->mMaxProgress;
     
@@ -1015,65 +1010,65 @@ nsDocLoader::GetIsLoadingDocument(PRBool
 {
   *aIsLoadingDocument = mIsLoadingDocument;
 
   return NS_OK;
 }
 
 PRInt64 nsDocLoader::GetMaxTotalProgress()
 {
-  PRInt64 newMaxTotal = 0;
+  nsInt64 newMaxTotal = 0;
 
   PRInt32 count = mChildList.Count();
   nsCOMPtr<nsIWebProgress> webProgress;
   for (PRInt32 i=0; i < count; i++) 
   {
-    PRInt64 individualProgress = 0;
+    nsInt64 individualProgress = 0;
     nsIDocumentLoader* docloader = ChildAt(i);
     if (docloader)
     {
       // Cast is safe since all children are nsDocLoader too
       individualProgress = ((nsDocLoader *) docloader)->GetMaxTotalProgress();
     }
-    if (individualProgress < PRInt64(0)) // if one of the elements doesn't know it's size
+    if (individualProgress < nsInt64(0)) // if one of the elements doesn't know it's size
                                          // then none of them do
     {
-       newMaxTotal = PRInt64(-1);
+       newMaxTotal = nsInt64(-1);
        break;
     }
     else
      newMaxTotal += individualProgress;
   }
 
-  PRInt64 progress = -1;
-  if (mMaxSelfProgress >= PRInt64(0) && newMaxTotal >= PRInt64(0))
+  nsInt64 progress = -1;
+  if (mMaxSelfProgress >= nsInt64(0) && newMaxTotal >= nsInt64(0))
     progress = newMaxTotal + mMaxSelfProgress;
   
   return progress;
 }
 
 ////////////////////////////////////////////////////////////////////////////////////
 // The following section contains support for nsIProgressEventSink which is used to 
 // pass progress and status between the actual request and the doc loader. The doc loader
 // then turns around and makes the right web progress calls based on this information.
 ////////////////////////////////////////////////////////////////////////////////////
 
 NS_IMETHODIMP nsDocLoader::OnProgress(nsIRequest *aRequest, nsISupports* ctxt, 
                                       PRUint64 aProgress, PRUint64 aProgressMax)
 {
   nsRequestInfo *info;
-  PRInt64 progressDelta = 0;
+  nsInt64 progressDelta = 0;
 
   //
   // Update the RequestInfo entry with the new progress data
   //
   info = GetRequestInfo(aRequest);
   if (info) {
     // suppress sending STATE_TRANSFERRING if this is upload progress (see bug 240053)
-    if (!info->mUploading && (PRInt64(0) == info->mCurrentProgress) && (PRInt64(0) == info->mMaxProgress)) {
+    if (!info->mUploading && (nsInt64(0) == info->mCurrentProgress) && (nsInt64(0) == info->mMaxProgress)) {
       //
       // If we receive an OnProgress event from a toplevel channel that the URI Loader
       // has not yet targeted, then we must suppress the event.  This is necessary to
       // ensure that webprogresslisteners do not get confused when the channel is
       // finally targeted.  See bug 257308.
       //
       nsLoadFlags lf = 0;
       aRequest->GetLoadFlags(&lf);
@@ -1088,18 +1083,18 @@ NS_IMETHODIMP nsDocLoader::OnProgress(ns
       // (aMaxProgress > 0) then the content-length of the data is known,
       // so update mMaxSelfProgress...  Otherwise, set it to -1 to indicate
       // that the content-length is no longer known.
       //
       if (PRUint64(aProgressMax) != LL_MAXUINT) {
         mMaxSelfProgress  += PRInt64(aProgressMax);
         info->mMaxProgress = PRInt64(aProgressMax);
       } else {
-        mMaxSelfProgress   =  PRInt64(-1);
-        info->mMaxProgress =  PRInt64(-1);
+        mMaxSelfProgress   =  nsInt64(-1);
+        info->mMaxProgress =  nsInt64(-1);
       }
 
       // Send a STATE_TRANSFERRING notification for the request.
       PRInt32 flags;
     
       flags = nsIWebProgressListener::STATE_TRANSFERRING | 
               nsIWebProgressListener::STATE_IS_REQUEST;
       //
@@ -1111,17 +1106,17 @@ NS_IMETHODIMP nsDocLoader::OnProgress(ns
         // Send STATE_TRANSFERRING for the document too...
         flags |= nsIWebProgressListener::STATE_IS_DOCUMENT;
       }
 
       FireOnStateChange(this, aRequest, flags, NS_OK);
     }
 
     // Update the current progress count...
-    progressDelta = PRInt64(aProgress) - info->mCurrentProgress;
+    progressDelta = nsInt64(PRInt64(aProgress)) - info->mCurrentProgress;
     mCurrentSelfProgress += progressDelta;
 
     info->mCurrentProgress = PRInt64(aProgress);
   }
   //
   // The request is not part of the load group, so ignore its progress
   // information...
   //
@@ -1565,32 +1560,32 @@ void nsDocLoader::ClearRequestInfoHash(v
 }
 
 // PLDHashTable enumeration callback that calculates the max progress.
 static PLDHashOperator
 CalcMaxProgressCallback(PLDHashTable *table, PLDHashEntryHdr *hdr,
                         PRUint32 number, void *arg)
 {
   const nsRequestInfo *info = static_cast<const nsRequestInfo *>(hdr);
-  PRInt64 *max = static_cast<PRInt64 *>(arg);
+  nsInt64 *max = static_cast<nsInt64 *>(arg);
 
   if (info->mMaxProgress < info->mCurrentProgress) {
-    *max = PRInt64(-1);
+    *max = nsInt64(-1);
 
     return PL_DHASH_STOP;
   }
 
   *max += info->mMaxProgress;
 
   return PL_DHASH_NEXT;
 }
 
 PRInt64 nsDocLoader::CalculateMaxProgress()
 {
-  PRInt64 max = mCompletedTotalProgress;
+  nsInt64 max = mCompletedTotalProgress;
   PL_DHashTableEnumerate(&mRequestInfoHash, CalcMaxProgressCallback, &max);
   return max;
 }
 
 NS_IMETHODIMP nsDocLoader::AsyncOnChannelRedirect(nsIChannel *aOldChannel,
                                                   nsIChannel *aNewChannel,
                                                   PRUint32 aFlags,
                                                   nsIAsyncVerifyRedirectCallback *cb)
--- a/uriloader/base/nsDocLoader.h
+++ b/uriloader/base/nsDocLoader.h
@@ -52,16 +52,17 @@
 #include "nsString.h"
 #include "nsIChannel.h"
 #include "nsIProgressEventSink.h"
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIChannelEventSink.h"
 #include "nsISecurityEventSink.h"
 #include "nsISupportsPriority.h"
+#include "nsInt64.h"
 #include "nsCOMPtr.h"
 #include "pldhash.h"
 
 struct nsRequestInfo;
 struct nsListenerInfo;
 
 /****************************************************************************
  * nsDocLoader implementation...
@@ -220,24 +221,24 @@ protected:
     nsCOMPtr<nsILoadGroup>        mLoadGroup;
     // We hold weak refs to all our kids
     nsVoidArray                   mChildList;
 
     // The following member variables are related to the new nsIWebProgress 
     // feedback interfaces that travis cooked up.
     PRInt32 mProgressStateFlags;
 
-    PRInt64 mCurrentSelfProgress;
-    PRInt64 mMaxSelfProgress;
+    nsInt64 mCurrentSelfProgress;
+    nsInt64 mMaxSelfProgress;
 
-    PRInt64 mCurrentTotalProgress;
-    PRInt64 mMaxTotalProgress;
+    nsInt64 mCurrentTotalProgress;
+    nsInt64 mMaxTotalProgress;
 
     PLDHashTable mRequestInfoHash;
-    PRInt64 mCompletedTotalProgress;
+    nsInt64 mCompletedTotalProgress;
 
     /*
      * This flag indicates that the loader is loading a document.  It is set
      * from the call to LoadDocument(...) until the OnConnectionsComplete(...)
      * notification is fired...
      */
     PRPackedBool mIsLoadingDocument;
 
--- a/uriloader/exthandler/nsExternalHelperAppService.cpp
+++ b/uriloader/exthandler/nsExternalHelperAppService.cpp
@@ -1574,17 +1574,17 @@ NS_IMETHODIMP nsExternalAppHandler::OnSt
   nsCOMPtr<nsIChannel> aChannel = do_QueryInterface(request);
   
   nsresult rv;
   
   nsCOMPtr<nsIFileChannel> fileChan(do_QueryInterface(request));
   mIsFileChannel = fileChan != nsnull;
 
   // Get content length
-  mContentLength = GetContentLengthAsInt64(request);
+  mContentLength.mValue = GetContentLengthAsInt64(request);
 
   nsCOMPtr<nsIPropertyBag2> props(do_QueryInterface(request, &rv));
   // Determine whether a new window was opened specifically for this request
   if (props) {
     PRBool tmp = PR_FALSE;
     props->GetPropertyAsBool(NS_LITERAL_STRING("docshell.newWindowTarget"),
                              &tmp);
     mShouldCloseWindow = tmp;
--- a/uriloader/exthandler/nsExternalHelperAppService.h
+++ b/uriloader/exthandler/nsExternalHelperAppService.h
@@ -44,16 +44,18 @@
 #define nsExternalHelperAppService_h__
 
 #ifdef MOZ_LOGGING
 #define FORCE_PR_LOG
 #endif
 #include "prlog.h"
 #include "prtime.h"
 
+#include "nsInt64.h"
+
 #include "nsIExternalHelperAppService.h"
 #include "nsIExternalProtocolService.h"
 #include "nsIWebProgressListener2.h"
 #include "nsIHelperAppLauncherDialog.h"
 
 #include "nsIMIMEInfo.h"
 #include "nsIMIMEService.h"
 #include "nsIStreamListener.h"
@@ -334,18 +336,18 @@ protected:
   PRUint32 mReason;
 
   /**
    * Track the executable-ness of the temporary file.
    */
   PRBool mTempFileIsExecutable;
 
   PRTime mTimeDownloadStarted;
-  PRInt64 mContentLength;
-  PRInt64 mProgress; /**< Number of bytes received (for sending progress notifications). */
+  nsInt64 mContentLength;
+  nsInt64 mProgress; /**< Number of bytes received (for sending progress notifications). */
 
   /**
    * When we are told to save the temp file to disk (in a more permament
    * location) before we are done writing the content to a temp file, then
    * we need to remember the final destination until we are ready to use it.
    */
   nsCOMPtr<nsIFile> mFinalFileDestination;
 
--- a/view/src/nsViewManager.cpp
+++ b/view/src/nsViewManager.cpp
@@ -48,16 +48,17 @@
 #include "nsView.h"
 #include "nsISupportsArray.h"
 #include "nsCOMPtr.h"
 #include "nsIServiceManager.h"
 #include "nsGUIEvent.h"
 #include "nsIPrefBranch.h"
 #include "nsIPrefService.h"
 #include "nsRegion.h"
+#include "nsInt64.h"
 #include "nsHashtable.h"
 #include "nsCOMArray.h"
 #include "nsThreadUtils.h"
 #include "nsContentUtils.h"
 #include "nsIPluginWidget.h"
 #include "nsXULPopupManager.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
--- a/widget/public/nsIWidget.h
+++ b/widget/public/nsIWidget.h
@@ -630,19 +630,17 @@ class nsIWidget : public nsISupports {
      *               the case of popups may not be this widget's toplevel
      *               window) is already active, and this function indicates
      *               that keyboard events should be reported through the
      *               aHandleEventFunction provided to this->Create().
      */
     NS_IMETHOD SetFocus(PRBool aRaise = PR_FALSE) = 0;
 
     /**
-     * Get this widget's outside dimensions relative to its parent widget. For
-     * popup widgets the returned rect is in screen coordinates and not
-     * relative to its parent widget.
+     * Get this widget's outside dimensions relative to its parent widget
      *
      * @param aRect   On return it holds the  x, y, width and height of
      *                this widget.
      */
     NS_IMETHOD GetBounds(nsIntRect &aRect) = 0;
 
     /**
      * Get this widget's outside dimensions in global coordinates. This
--- a/widget/src/cocoa/nsChildView.mm
+++ b/widget/src/cocoa/nsChildView.mm
@@ -3443,42 +3443,39 @@ NSEvent* gLastDragMouseDownEvent = nil;
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
 
   if (!mGeckoChild || mBlockedLastMouseDown)
     return;
 
   nsAutoRetainCocoaObject kungFuDeathGrip(self);
 
-#ifndef NP_NO_CARBON
-  EventRecord carbonEvent;
-#endif // ifndef NP_NO_CARBON
-  NPCocoaEvent cocoaEvent;
-	
   nsMouseEvent geckoEvent(PR_TRUE, NS_MOUSE_BUTTON_UP, nsnull, nsMouseEvent::eReal);
   [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent];
   if ([theEvent modifierFlags] & NSControlKeyMask)
     geckoEvent.button = nsMouseEvent::eRightButton;
   else
     geckoEvent.button = nsMouseEvent::eLeftButton;
 
   // Create event for use by plugins.
   // This is going to our child view so we don't need to look up the destination
   // event type.
   if (mIsPluginView) {
 #ifndef NP_NO_CARBON
+    EventRecord carbonEvent;
     if (mPluginEventModel == NPEventModelCarbon) {
       carbonEvent.what = mouseUp;
       carbonEvent.message = 0;
       carbonEvent.when = ::TickCount();
       ::GetGlobalMouse(&carbonEvent.where);
       carbonEvent.modifiers = ::GetCurrentKeyModifiers();
       geckoEvent.pluginEvent = &carbonEvent;
     }
 #endif
+    NPCocoaEvent cocoaEvent;
     if (mPluginEventModel == NPEventModelCocoa) {
       InitNPCocoaEvent(&cocoaEvent);
       NSPoint point = [self convertPoint:[theEvent locationInWindow] fromView:nil];
       cocoaEvent.type = NPCocoaEventMouseUp;
       cocoaEvent.data.mouse.modifierFlags = [theEvent modifierFlags];
       cocoaEvent.data.mouse.pluginX = point.x;
       cocoaEvent.data.mouse.pluginY = point.y;
       cocoaEvent.data.mouse.buttonNumber = [theEvent buttonNumber];
@@ -3636,36 +3633,33 @@ NSEvent* gLastDragMouseDownEvent = nil;
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
 
   if (!mGeckoChild)
     return;
 
   gLastDragView = self;
 
-#ifndef NP_NO_CARBON
-  EventRecord carbonEvent;
-#endif // ifndef NP_NO_CARBON
-  NPCocoaEvent cocoaEvent;
-
   nsMouseEvent geckoEvent(PR_TRUE, NS_MOUSE_MOVE, nsnull, nsMouseEvent::eReal);
   [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent];
 
   // create event for use by plugins
   if (mIsPluginView) {
 #ifndef NP_NO_CARBON
+    EventRecord carbonEvent;
     if (mPluginEventModel == NPEventModelCarbon) {
       carbonEvent.what = NPEventType_AdjustCursorEvent;
       carbonEvent.message = 0;
       carbonEvent.when = ::TickCount();
       ::GetGlobalMouse(&carbonEvent.where);
       carbonEvent.modifiers = btnState | ::GetCurrentKeyModifiers();
       geckoEvent.pluginEvent = &carbonEvent;
     }
 #endif
+    NPCocoaEvent cocoaEvent;
     if (mPluginEventModel == NPEventModelCocoa) {
       InitNPCocoaEvent(&cocoaEvent);
       NSPoint point = [self convertPoint:[theEvent locationInWindow] fromView:nil];
       cocoaEvent.type = NPCocoaEventMouseDragged;
       cocoaEvent.data.mouse.modifierFlags = [theEvent modifierFlags];
       cocoaEvent.data.mouse.pluginX = point.x;
       cocoaEvent.data.mouse.pluginY = point.y;
       cocoaEvent.data.mouse.buttonNumber = [theEvent buttonNumber];
@@ -3744,38 +3738,35 @@ NSEvent* gLastDragMouseDownEvent = nil;
 
 - (void)rightMouseUp:(NSEvent *)theEvent
 {
   NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
 
   if (!mGeckoChild)
     return;
 
-#ifndef NP_NO_CARBON
-  EventRecord carbonEvent;
-#endif // ifndef NP_NO_CARBON
-  NPCocoaEvent cocoaEvent;
-
   nsMouseEvent geckoEvent(PR_TRUE, NS_MOUSE_BUTTON_UP, nsnull, nsMouseEvent::eReal);
   [self convertCocoaMouseEvent:theEvent toGeckoEvent:&geckoEvent];
   geckoEvent.button = nsMouseEvent::eRightButton;
   geckoEvent.clickCount = [theEvent clickCount];
 
   // create event for use by plugins
   if (mIsPluginView) {
 #ifndef NP_NO_CARBON
+    EventRecord carbonEvent;
     if (mPluginEventModel == NPEventModelCarbon) {
       carbonEvent.what = mouseUp;
       carbonEvent.message = 0;
       carbonEvent.when = ::TickCount();
       ::GetGlobalMouse(&carbonEvent.where);
       carbonEvent.modifiers = controlKey;  // fake a context menu click
       geckoEvent.pluginEvent = &carbonEvent;
     }
 #endif
+    NPCocoaEvent cocoaEvent;
     if (mPluginEventModel == NPEventModelCocoa) {
       InitNPCocoaEvent(&cocoaEvent);
       NSPoint point = [self convertPoint:[theEvent locationInWindow] fromView:nil];
       cocoaEvent.type = NPCocoaEventMouseUp;
       cocoaEvent.data.mouse.modifierFlags = [theEvent modifierFlags];
       cocoaEvent.data.mouse.pluginX = point.x;
       cocoaEvent.data.mouse.pluginY = point.y;
       cocoaEvent.data.mouse.buttonNumber = [theEvent buttonNumber];
@@ -5847,33 +5838,30 @@ static const char* ToEscapedString(NSStr
       mGeckoChild->TextInputHandler()->IsIMEComposing()) {
     return;
   }
 
   nsAutoRetainCocoaObject kungFuDeathGrip(self);
 
   PRUint32 message = isKeyDown ? NS_KEY_DOWN : NS_KEY_UP;
 
-#ifndef NP_NO_CARBON
-  EventRecord carbonEvent;
-#endif // ifndef NP_NO_CARBON
-  NPCocoaEvent cocoaEvent;
-	
   // Fire a key event.
   nsKeyEvent geckoEvent(PR_TRUE, message, nsnull);
   [self convertCocoaKeyEvent:theEvent toGeckoEvent:&geckoEvent];
 
   // create event for use by plugins
   if (mIsPluginView) {
 #ifndef NP_NO_CARBON
+    EventRecord carbonEvent;
     if (mPluginEventModel == NPEventModelCarbon) {
       ConvertCocoaKeyEventToCarbonEvent(theEvent, carbonEvent, message);
       geckoEvent.pluginEvent = &carbonEvent;
     }
 #endif
+    NPCocoaEvent cocoaEvent;
     if (mPluginEventModel == NPEventModelCocoa) {
       ConvertCocoaKeyEventToNPCocoaEvent(theEvent, cocoaEvent, message);
       geckoEvent.pluginEvent = &cocoaEvent;
     }
   }
 
   mGeckoChild->DispatchWindowEvent(geckoEvent);
 
--- a/widget/src/os2/nsClipboard.cpp
+++ b/widget/src/os2/nsClipboard.cpp
@@ -39,24 +39,23 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsXPCOM.h"
 #include "nsISupportsPrimitives.h"
 #include "nsCOMPtr.h"
 #include "nsPrimitiveHelpers.h"
 #include "nsXPIDLString.h"
 #include "prmem.h"
+#include "nsIObserverService.h"
+#include "nsIServiceManager.h"
 #include "nsOS2Uni.h"
 #include "nsClipboard.h"
+#include "mozilla/Services.h"
 
-#define INCL_DOSERRORS
-#define INCL_WIN
-#include <os2.h>
-
-inline PRUint32 RegisterClipboardFormat(PCSZ pcszFormat)
+inline ULONG RegisterClipboardFormat(PCSZ pcszFormat)
 {
   ATOM atom = WinFindAtom(WinQuerySystemAtomTable(), pcszFormat);
   if (!atom) {
     atom = WinAddAtom(WinQuerySystemAtomTable(), pcszFormat); 
   }
   return atom;
 }
 
@@ -68,21 +67,30 @@ nsClipboard::nsClipboard() : nsBaseClipb
   RegisterClipboardFormat(kAOLMailMime);
   RegisterClipboardFormat(kPNGImageMime);
   RegisterClipboardFormat(kJPEGImageMime);
   RegisterClipboardFormat(kGIFImageMime);
   RegisterClipboardFormat(kFileMime);
   RegisterClipboardFormat(kURLMime);
   RegisterClipboardFormat(kNativeImageMime);
   RegisterClipboardFormat(kNativeHTMLMime);
+
+  // Register for a shutdown notification so that we can flush data
+  // to the OS clipboard.
+  nsCOMPtr<nsIObserverService> observerService =
+    mozilla::services::GetObserverService();
+  if (observerService)
+    observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, PR_FALSE);
 }
 
 nsClipboard::~nsClipboard()
 {}
 
+NS_IMPL_ISUPPORTS_INHERITED1(nsClipboard, nsBaseClipboard, nsIObserver)
+
 nsresult nsClipboard::SetNativeClipboardData(PRInt32 aWhichClipboard)
 {
   if (aWhichClipboard != kGlobalClipboard)
     return NS_ERROR_FAILURE;
 
   return DoClipboardAction(Write);
 }
 
@@ -97,17 +105,17 @@ nsresult nsClipboard::GetNativeClipboard
   nsresult rc = DoClipboardAction(Read);
   mTransferable = tmp;
   return rc;
 }
 
 // Get some data from the clipboard
 PRBool nsClipboard::GetClipboardData(const char *aFlavor)
 {
-  PRUint32 ulFormatID = GetFormatID(aFlavor);
+  ULONG ulFormatID = GetFormatID( aFlavor );
   
   PRBool found = GetClipboardDataByID( ulFormatID, aFlavor );
 
   if (!found) 
   {
     if (!strcmp( aFlavor, kUnicodeMime ))
     {
       found = GetClipboardDataByID( CF_TEXT, aFlavor );
@@ -116,32 +124,32 @@ PRBool nsClipboard::GetClipboardData(con
     {
       found = GetClipboardDataByID( CF_BITMAP, aFlavor );
     }
   }
 
   return found;
 }
 
-PRBool nsClipboard::GetClipboardDataByID(PRUint32 aFormatID, const char *aFlavor)
+PRBool nsClipboard::GetClipboardDataByID(ULONG ulFormatID, const char *aFlavor)
 {
   PVOID pDataMem;
   PRUint32 NumOfBytes;
   PRBool TempBufAllocated = PR_FALSE;
 
-  PVOID pClipboardData = reinterpret_cast<PVOID>(WinQueryClipbrdData(0, aFormatID));
+  PVOID pClipboardData = reinterpret_cast<PVOID>(WinQueryClipbrdData( 0, ulFormatID ));
 
   if (!pClipboardData) 
     return PR_FALSE;
 
   if (strstr( aFlavor, "text/" ))  // All text/.. flavors are null-terminated
   {
     pDataMem = pClipboardData;
 
-    if (aFormatID == CF_TEXT)     // CF_TEXT is one byte character set
+    if (ulFormatID == CF_TEXT)     // CF_TEXT is one byte character set
     {
       PRUint32 NumOfChars = strlen( static_cast<char*>(pDataMem) );
       NumOfBytes = NumOfChars;
 
       if (!strcmp( aFlavor, kUnicodeMime ))  // Asked for unicode, but only plain text available.  Convert it!
       {
         nsAutoChar16Buffer buffer;
         PRInt32 bufLength;
@@ -165,17 +173,17 @@ PRBool nsClipboard::GetClipboardDataByID
 
     // DOM wants LF only, so convert from CRLF
     nsLinebreakHelpers::ConvertPlatformToDOMLinebreaks( aFlavor, &pDataMem,   // pDataMem could be reallocated !!
                                                         reinterpret_cast<PRInt32*>(&NumOfBytes) );  // yuck
 
   }
   else                             // Assume rest of flavors are binary data
   {
-    if (aFormatID == CF_BITMAP)
+    if (ulFormatID == CF_BITMAP)
     {
       if (!strcmp( aFlavor, kJPEGImageMime ))
       {
         // OS2TODO  Convert bitmap to jpg
 #ifdef DEBUG
         printf( "nsClipboard:: No JPG found on clipboard; need to convert BMP\n");
 #endif
       }
@@ -237,17 +245,17 @@ void nsClipboard::SetClipboardData(const
   if (NumOfBytes == 0) return;
   nsPrimitiveHelpers::CreateDataFromPrimitive( aFlavor, genericDataWrapper, &pMozData, NumOfBytes );
 
   /* If creating the data failed, just return */
   if (!pMozData) {
     return;
   }
 
-  PRUint32 ulFormatID = GetFormatID(aFlavor);
+  ULONG ulFormatID = GetFormatID( aFlavor );
 
   if (strstr( aFlavor, "text/" ))  // All text/.. flavors are null-terminated
   {
     if (ulFormatID == CF_TEXT)     // CF_TEXT is one byte character set
     {
       char* pByteMem = nsnull;
 
       if (DosAllocSharedMem( reinterpret_cast<PPVOID>(&pByteMem), nsnull, NumOfBytes + sizeof(char), 
@@ -393,36 +401,76 @@ nsresult nsClipboard::DoClipboardAction(
     }
     WinCloseClipbrd(0/*hab*/);
     rc = NS_OK;
   }
   return rc;
 }
 
 // get the format ID for a given mimetype
-PRUint32 nsClipboard::GetFormatID(const char *aMimeStr)
+ULONG nsClipboard::GetFormatID(const char *aMimeStr)
 {
   if (strcmp(aMimeStr, kTextMime) == 0)
     return CF_TEXT;
 
   return RegisterClipboardFormat(aMimeStr);
 }
 
+// nsIObserver
+NS_IMETHODIMP
+nsClipboard::Observe(nsISupports *aSubject, const char *aTopic,
+                     const PRUnichar *aData)
+{
+  // This will be called on shutdown.
+
+  // make sure we have a good transferable
+  if (!mTransferable)
+    return NS_ERROR_FAILURE;
+
+  if (WinOpenClipbrd(0/*hab*/)) {
+    WinEmptyClipbrd(0/*hab*/);
+
+    // get flavor list that includes all flavors that can be written (including ones
+    // obtained through conversion)
+    nsCOMPtr<nsISupportsArray> flavorList;
+    nsresult errCode = mTransferable->FlavorsTransferableCanExport(getter_AddRefs(flavorList));
+    if (NS_FAILED(errCode))
+      return NS_ERROR_FAILURE;
+
+    // Walk through flavors and put data on to clipboard
+    PRUint32 i;
+    PRUint32 cnt;
+    flavorList->Count(&cnt);
+    for (i = 0; i < cnt; i++) {
+      nsCOMPtr<nsISupports> genericFlavor;
+      flavorList->GetElementAt(i, getter_AddRefs(genericFlavor));
+      nsCOMPtr<nsISupportsCString> currentFlavor(do_QueryInterface(genericFlavor));
+      if (currentFlavor) {
+        nsXPIDLCString flavorStr;
+        currentFlavor->ToString(getter_Copies(flavorStr));
+        SetClipboardData(flavorStr);
+      }
+    }
+    WinCloseClipbrd(0/*hab*/);
+  }
+  return NS_OK;
+}
+
 NS_IMETHODIMP nsClipboard::HasDataMatchingFlavors(const char** aFlavorList,
                                                   PRUint32 aLength,
                                                   PRInt32 aWhichClipboard,
                                                   PRBool *_retval)
 {
   *_retval = PR_FALSE;
   if (aWhichClipboard != kGlobalClipboard || !aFlavorList)
     return NS_OK;
 
   for (PRUint32 i = 0; i < aLength; ++i) {
     ULONG fmtInfo = 0;
-    PRUint32 format = GetFormatID(aFlavorList[i]);
+    ULONG format = GetFormatID(aFlavorList[i]);
 
     if (WinQueryClipbrdFmtInfo(0/*hab*/, format, &fmtInfo)) {
       *_retval = PR_TRUE;
       break;
     }
 
     // if the client asked for unicode and it wasn't present, check if we have CF_TEXT.
     if (!strcmp(aFlavorList[i], kUnicodeMime)) {
--- a/widget/src/os2/nsClipboard.h
+++ b/widget/src/os2/nsClipboard.h
@@ -34,45 +34,58 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsClipboard_h
 #define _nsClipboard_h
 
 #include "nsBaseClipboard.h"
+#include "nsIObserver.h"
+
+#define INCL_DOSERRORS
+#define INCL_WIN
+#include <os2.h>
+
 class nsITransferable;
 
 /**
  * Native OS/2 Clipboard wrapper
  */
 
 struct FormatRecord;
 
-class nsClipboard : public nsBaseClipboard
+class nsClipboard : public nsBaseClipboard,
+		    public nsIObserver
 {
 
 public:
   nsClipboard();
   virtual ~nsClipboard();
 
+  // nsISupports
+  NS_DECL_ISUPPORTS_INHERITED
+
+  // nsIObserver
+  NS_DECL_NSIOBSERVER
+
   // nsIClipboard
   NS_IMETHOD HasDataMatchingFlavors(const char** aFlavorList, PRUint32 aLength,
                                     PRInt32 aWhichClipboard, PRBool *_retval);
 
 protected:
   NS_IMETHOD SetNativeClipboardData(PRInt32 aWhichClipboard);
   NS_IMETHOD GetNativeClipboardData(nsITransferable *aTransferable, PRInt32 aWhichClipboard);
 
   enum ClipboardAction
   {
     Read,
     Write
   };
 
-  PRUint32 GetFormatID(const char *aMimeStr);
+  ULONG    GetFormatID(const char *aMimeStr);
   PRBool   GetClipboardData(const char *aFlavour);
-  PRBool   GetClipboardDataByID(PRUint32 aFormatID, const char *aFlavor);
+  PRBool   GetClipboardDataByID(ULONG ulFormatID, const char *aFlavor);
   void     SetClipboardData(const char *aFlavour);
   nsresult DoClipboardAction(ClipboardAction aAction);
 };
 
 #endif
--- a/widget/src/windows/nsWindow.cpp
+++ b/widget/src/windows/nsWindow.cpp
@@ -1967,24 +1967,16 @@ NS_METHOD nsWindow::GetBounds(nsIntRect 
   if (mWnd) {
     RECT r;
     VERIFY(::GetWindowRect(mWnd, &r));
 
     // assign size
     aRect.width  = r.right - r.left;
     aRect.height = r.bottom - r.top;
 
-    // popup window bounds' are in screen coordinates, not relative to parent
-    // window
-    if (mWindowType == eWindowType_popup) {
-      aRect.x = r.left;
-      aRect.y = r.top;
-      return NS_OK;
-    }
-
     // chrome on parent:
     //  ___      5,5   (chrome start)
     // |  ____   10,10 (client start)
     // | |  ____ 20,20 (child start)
     // | | |
     // 20,20 - 5,5 = 15,15 (??)
     // minus GetClientOffset:
     // 15,15 - 5,5 = 10,10
--- a/xpcom/components/nsComponentManager.cpp
+++ b/xpcom/components/nsComponentManager.cpp
@@ -85,16 +85,17 @@
 #include "nsThreadUtils.h"
 #include "prthread.h"
 #include "private/pprthred.h"
 #include "nsTArray.h"
 #include "prio.h"
 #include "mozilla/FunctionTimer.h"
 #include "ManifestParser.h"
 
+#include "nsInt64.h"
 #include "nsManifestLineReader.h"
 #include "mozilla/GenericFactory.h"
 #include "nsSupportsPrimitives.h"
 #include "nsArrayEnumerator.h"
 #include "nsStringEnumerator.h"
 
 #include NEW_H     // for placement new
 
--- a/xpcom/ds/Makefile.in
+++ b/xpcom/ds/Makefile.in
@@ -95,16 +95,17 @@ EXPORTS		= \
 		nsCRT.h \
 		nsDoubleHashtable.h \
 		nsExpirationTracker.h \
 		nsFixedSizeAllocator.h \
 		nsHashSets.h \
 		nsHashtable.h \
 		nsIByteBuffer.h \
 		nsIUnicharBuffer.h \
+		nsInt64.h \
 		nsMathUtils.h \
 		nsObserverService.h \
 		nsRecyclingAllocator.h \
 		nsStaticNameTable.h \
 		nsStaticAtom.h \
 		nsSupportsArray.h \
 		nsSupportsPrimitives.h \
 		nsTime.h \
new file mode 100644
--- /dev/null
+++ b/xpcom/ds/nsInt64.h
@@ -0,0 +1,417 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 1998
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef nsInt64_h__
+#define nsInt64_h__
+
+#include "prlong.h"
+#include "nscore.h"
+
+/**
+ * This class encapsulates full 64-bit integer functionality and
+ * provides simple arithmetic and conversion operations.
+ */
+
+// If you ever decide that you need to add a non-inline method to this
+// class, be sure to change the class declaration to "class NS_BASE
+// nsInt64".
+
+template<class T>
+class nsTInt64
+{
+public: //XXX should be private
+    T mValue;
+
+public:
+    /**
+     * Construct a new 64-bit integer.
+     */
+    nsTInt64(void) : mValue(LL_ZERO) {
+    }
+
+    /**
+     * Construct a new 64-bit integer from a 32-bit signed integer
+     */
+    nsTInt64(const PRInt32 aInt32) {
+        LL_I2L(mValue, aInt32);
+    }
+
+    /**
+     * Construct a new 64-bit integer from a 32-bit unsigned integer
+     */
+    nsTInt64(const PRUint32 aUint32) {
+        LL_UI2L(mValue, aUint32);
+    }
+
+    /**
+     * Construct a new 64-bit integer from a floating point value.
+     */
+    nsTInt64(const PRFloat64 aFloat64) {
+        LL_D2L(mValue, aFloat64);
+    }
+
+    /**
+     * Construct a new 64-bit integer from a native 64-bit integer
+     */
+    nsTInt64(const T aInt64) : mValue(aInt64) {
+    }
+
+    /**
+     * Construct a new 64-bit integer from another 64-bit integer
+     */
+    nsTInt64(const nsTInt64& aObject) : mValue(aObject.mValue) {
+    }
+
+    // ~nsTInt64(void) -- XXX destructor unnecessary
+
+    /**
+     * Assign a 64-bit integer to another 64-bit integer
+     */
+    const nsTInt64& operator =(const nsTInt64& aObject) {
+        mValue = aObject.mValue;
+        return *this;
+    }
+
+    /**
+     * Convert a 64-bit integer to a signed 32-bit value
+     */
+    operator PRInt32(void) const {
+        PRInt32 result;
+        LL_L2I(result, mValue);
+        return result;
+    }
+
+    /**
+     * Convert a 64-bit integer to an unsigned 32-bit value
+     */
+    operator PRUint32(void) const {
+        PRUint32 result;
+        LL_L2UI(result, mValue);
+        return result;
+    }
+
+    /**
+     * Convert a 64-bit integer to a floating point value
+     */
+    operator PRFloat64(void) const {
+        PRFloat64 result;
+        LL_L2D(result, mValue);
+        return result;
+    }
+
+    /**
+     * Convert a 64-bit integer to a native 64-bit integer.
+     */
+    operator T() const {
+        return mValue;
+    }
+
+    /**
+     * Perform unary negation on a 64-bit integer.
+     */
+    const nsTInt64 operator -(void) {
+        nsTInt64 result;
+        LL_NEG(result.mValue, mValue);
+        return result;
+    }
+
+    // Arithmetic operators
+
+    /**
+     * Increment a 64-bit integer by a 64-bit integer amount.
+     */
+    nsTInt64& operator +=(const nsTInt64& aObject) {
+        LL_ADD(mValue, mValue, aObject.mValue);
+        return *this;
+    }
+
+    /**
+     * Decrement a 64-bit integer by a 64-bit integer amount.
+     */
+    nsTInt64& operator -=(const nsTInt64& aObject) {
+        LL_SUB(mValue, mValue, aObject.mValue);
+        return *this;
+    }
+
+    /**
+     * Multiply a 64-bit integer by a 64-bit integer amount.
+     */
+    nsTInt64& operator *=(const nsTInt64& aObject) {
+        LL_MUL(mValue, mValue, aObject.mValue);
+        return *this;
+    }
+
+    /**
+     * Divide a 64-bit integer by a 64-bit integer amount.
+     */
+    nsTInt64& operator /=(const nsTInt64& aObject) {
+        LL_DIV(mValue, mValue, aObject.mValue);
+        return *this;
+    }
+
+    /**
+     * Compute the modulus of a 64-bit integer to a 64-bit value.
+     */
+    nsTInt64& operator %=(const nsTInt64& aObject) {
+        LL_MOD(mValue, mValue, aObject.mValue);
+        return *this;
+    }
+
+    /**
+     * Shift a 64-bit integer left.
+     */
+    nsTInt64& operator <<=(int aCount) {
+        LL_SHL(mValue, mValue, aCount);
+        return *this;
+    }
+
+    /**
+     * Shift a 64-bit signed integer right.
+     */
+    nsTInt64& operator >>=(int aCount) {
+        LL_SHR(mValue, mValue, aCount);
+        return *this;
+    }
+
+    // Comparison operators
+    /**
+     * Add two 64-bit integers.
+     */
+    inline const nsTInt64
+    operator +(const nsTInt64& aObject2) const {
+        return nsTInt64(*this) += aObject2;
+    }
+
+    /**
+     * Subtract one 64-bit integer from another.
+     */
+    inline const nsTInt64
+    operator -(const nsTInt64& aObject2) const {
+        return nsTInt64(*this) -= aObject2;
+    }
+
+    /**
+     * Multiply two 64-bit integers
+     */
+    inline const nsTInt64
+    operator *(const nsTInt64& aObject2) const {
+        return nsTInt64(*this) *= aObject2;
+    }
+
+    /**
+     * Divide one 64-bit integer by another
+     */
+    inline const nsTInt64
+    operator /(const nsTInt64& aObject2) const {
+        return nsTInt64(*this) /= aObject2;
+    }
+
+    /**
+     * Compute the modulus of two 64-bit integers
+     */
+    inline const nsTInt64
+    operator %(const nsTInt64& aObject2) const {
+        return nsTInt64(*this) %= aObject2;
+    }
+
+    /**
+     * Shift left a 64-bit integer
+     */
+    inline const nsTInt64
+    operator <<(int aCount) const {
+        return nsTInt64(*this) <<= aCount;
+    }
+
+    /**
+     * Shift right a signed 64-bit integer
+     */
+    inline const nsTInt64
+    operator >>(int aCount) const {
+        return nsTInt64(*this) >>= aCount;
+    }
+
+    /**
+     * Determine if two 64-bit integers are equal
+     */
+    inline PRBool
+    operator ==(const nsTInt64& aObject2) const {
+        return LL_EQ(mValue, aObject2.mValue);
+    }
+
+    inline PRBool
+    operator ==(T aValue) const {
+        return LL_EQ(mValue, aValue);
+    }
+
+    /**
+     * Determine if two 64-bit integers are not equal
+     */
+    inline PRBool
+    operator !=(const nsTInt64& aObject2) const {
+        return LL_NE(mValue, aObject2.mValue);
+    }
+
+    inline PRBool
+    operator !=(T aValue) const {
+        return LL_NE(mValue, aValue);
+    }
+
+    /**
+     * Perform a bitwise AND of two 64-bit integers
+     */
+    inline const nsTInt64
+    operator &(const nsTInt64& aObject2) const {
+        return nsTInt64(*this) &= aObject2;
+    }
+
+    /**
+     * Perform a bitwise OR of two 64-bit integers
+     */
+    inline const nsTInt64
+    operator |(const nsTInt64& aObject2) const {
+        return nsTInt64(*this) |= aObject2;
+    }
+
+    /**
+     * Perform a bitwise XOR of two 64-bit integers
+     */
+    inline const nsTInt64
+    operator ^(const nsTInt64& aObject2) const {
+        return nsTInt64(*this) ^= aObject2;
+    }
+
+    // Bitwise operators
+
+    /**
+     * Compute the bitwise NOT of a 64-bit integer
+     */
+    const nsTInt64 operator ~(void) const {
+        nsTInt64 result;
+        LL_NOT(result.mValue, mValue);
+        return result;
+    }
+
+    /**
+     * Compute the bitwise AND with another 64-bit integer
+     */
+    nsTInt64& operator &=(const nsTInt64& aObject) {
+        LL_AND(mValue, mValue, aObject.mValue);
+        return *this;
+    }
+
+    /**
+     * Compute the bitwise OR with another 64-bit integer
+     */
+    nsTInt64& operator |=(const nsTInt64& aObject) {
+        LL_OR(mValue, mValue, aObject.mValue);
+        return *this;
+    }
+
+    /**
+     * Compute the bitwise XOR with another 64-bit integer
+     */
+    nsTInt64& operator ^=(const nsTInt64& aObject) {
+        LL_XOR(mValue, mValue, aObject.mValue);
+        return *this;
+    }
+
+
+    /**
+     * Allow doing if (!some_nsInt64)
+     */
+    PRBool operator!() const {
+        return LL_IS_ZERO(mValue);
+    }
+    
+};
+
+typedef nsTInt64<PRInt64> nsInt64;
+typedef nsTInt64<PRUint64> nsUint64;
+
+/**
+ * Determine if one 64-bit integer is strictly greater than another, using signed values
+ */
+inline PRBool
+operator >(const nsInt64& aObject1, const nsInt64& aObject2) {
+    return LL_CMP(aObject1.mValue, >, aObject2.mValue);
+}
+
+inline PRBool
+operator >(const nsUint64& aObject1, const nsUint64& aObject2) {
+    return LL_UCMP(aObject1.mValue, >, aObject2.mValue);
+}
+
+/**
+ * Determine if one 64-bit integer is greater than or equal to another, using signed values
+ */
+inline PRBool
+operator >=(const nsInt64& aObject1, const nsInt64& aObject2) {
+    return ! LL_CMP(aObject1.mValue, <, aObject2.mValue);
+}
+
+inline PRBool
+operator >=(const nsUint64& aObject1, const nsUint64& aObject2) {
+    return ! LL_UCMP(aObject1.mValue, <, aObject2.mValue);
+}
+
+/**
+ * Determine if one 64-bit integer is strictly less than another, using signed values
+ */
+inline PRBool 
+operator <(const nsInt64& aObject1, const nsInt64& aObject2) {
+    return LL_CMP(aObject1.mValue, <, aObject2.mValue);
+}
+
+inline PRBool 
+operator <(const nsUint64& aObject1, const nsUint64& aObject2) {
+    return LL_UCMP(aObject1.mValue, <, aObject2.mValue);
+}
+
+/**
+ * Determine if one 64-bit integers is less than or equal to another, using signed values
+ */
+inline PRBool
+operator <=(const nsInt64& aObject1, const nsInt64& aObject2) {
+    return ! LL_CMP(aObject1.mValue, >, aObject2.mValue);
+}
+
+inline PRBool
+operator <=(const nsUint64& aObject1, const nsUint64& aObject2) {
+    return ! LL_UCMP(aObject1.mValue, >, aObject2.mValue);
+}
+
+#endif // nsInt64_h__
--- a/xpcom/ds/nsTime.h
+++ b/xpcom/ds/nsTime.h
@@ -34,34 +34,35 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsTime_h__
 #define nsTime_h__
 
 #include "prtime.h"
+#include "nsInt64.h"
 #include "nscore.h"
 
 /**
  * This class encapsulates full 64-bit time functionality and
  * provides simple arithmetic and conversion operations.
  */
 
 // If you ever decide that you need to add a non-inline method to this
 // class, be sure to change the class declaration to "class NS_BASE
 // nsTime".
 
-class nsTime
+class nsTime : public nsInt64
 {
 public:
     /**
      * Construct the current time.
      */
-    nsTime(void) : mValue(PR_Now()) {
+    nsTime(void) : nsInt64(PR_Now()) {
     }
 
     /**
      * Construct the time from a string.
      */
     nsTime(const char* dateStr, PRBool defaultToGMT) {
         PRInt64 theTime;
         PRStatus status = PR_ParseTimeString(dateStr, defaultToGMT, &theTime);
@@ -69,29 +70,47 @@ public:
             mValue = theTime;
         else
             mValue = LL_ZERO;
     }
 
     /**
      * Construct a time from a PRTime.
      */
-    nsTime(const PRTime aTime) : mValue(aTime) {
+    nsTime(const PRTime aTime) : nsInt64(aTime) {
+    }
+
+    /**
+     * Construct a time from a 64-bit value.
+     */
+    nsTime(const nsInt64& aTime) : nsInt64(aTime) {
+    }
+
+    /**
+     * Construct a time from another time.
+     */
+    nsTime(const nsTime& aTime) : nsInt64(aTime.mValue) {
     }
 
     // ~nsTime(void) -- XXX destructor unnecessary
 
     /**
+     * Assign one time to another.
+     */
+    const nsTime& operator =(const nsTime& aTime) {
+        mValue = aTime.mValue;
+        return *this;
+    }
+
+    /**
      * Convert a nsTime object to a PRTime
      */
     operator PRTime(void) const {
         return mValue;
     }
-
-    PRInt64 mValue;
 };
 
 /**
  * Determine if one time is strictly less than another
  */
 inline const PRBool
 operator <(const nsTime& aTime1, const nsTime& aTime2) {
     return aTime1.mValue < aTime2.mValue;
--- a/xpcom/io/nsFastLoadFile.cpp
+++ b/xpcom/io/nsFastLoadFile.cpp
@@ -51,16 +51,17 @@
 #include "nsILocalFile.h"
 #include "nsISeekableStream.h"
 #include "nsISerializable.h"
 #include "nsIStreamBufferAccess.h"
 #include "nsIClassInfo.h"
 
 #include "nsBinaryStream.h"
 #include "nsFastLoadFile.h"
+#include "nsInt64.h"
 #ifdef XP_UNIX
 #include <sys/mman.h>
 #endif
 
 #ifdef DEBUG_brendan
 # define METERING
 # define DEBUG_MUX
 #endif
--- a/xpcom/io/nsMultiplexInputStream.cpp
+++ b/xpcom/io/nsMultiplexInputStream.cpp
@@ -46,16 +46,17 @@
 #include "mozilla/net/NeckoMessageUtils.h"
 #endif
 
 #include "nsMultiplexInputStream.h"
 #include "nsIMultiplexInputStream.h"
 #include "nsISeekableStream.h"
 #include "nsCOMPtr.h"
 #include "nsCOMArray.h"
+#include "nsInt64.h"
 #include "nsIIPCSerializable.h"
 #include "nsIClassInfoImpl.h"
 
 class nsMultiplexInputStream : public nsIMultiplexInputStream,
                                public nsISeekableStream,
                                public nsIIPCSerializable
 {
 public:
@@ -378,17 +379,17 @@ nsMultiplexInputStream::Seek(PRInt32 aWh
 /* PRUint32 tell (); */
 NS_IMETHODIMP
 nsMultiplexInputStream::Tell(PRInt64 *_retval)
 {
     if (NS_FAILED(mStatus))
         return mStatus;
 
     nsresult rv;
-    PRInt64 ret64 = 0;
+    nsInt64 ret64 = 0;
     PRUint32 i, last;
     last = mStartedReadingCurrent ? mCurrentStream+1 : mCurrentStream;
     for (i = 0; i < last; ++i) {
         nsCOMPtr<nsISeekableStream> stream = do_QueryInterface(mStreams[i]);
         NS_ENSURE_TRUE(stream, NS_ERROR_NO_INTERFACE);
 
         PRInt64 pos;
         rv = stream->Tell(&pos);
--- a/xpcom/io/nsPipe3.cpp
+++ b/xpcom/io/nsPipe3.cpp
@@ -40,16 +40,17 @@
 #include "nsIEventTarget.h"
 #include "nsISeekableStream.h"
 #include "nsIProgrammingLanguage.h"
 #include "nsSegmentedBuffer.h"
 #include "nsStreamUtils.h"
 #include "nsCOMPtr.h"
 #include "nsCRT.h"
 #include "prlog.h"
+#include "nsInt64.h"
 #include "nsIClassInfoImpl.h"
 #include "nsAtomicRefcnt.h"
 
 using namespace mozilla;
 
 #if defined(PR_LOGGING)
 //
 // set NSPR_LOG_MODULES=nsPipe:5
@@ -148,17 +149,17 @@ public:
     PRBool   OnInputReadable(PRUint32 bytesWritten, nsPipeEvents &);
     PRBool   OnInputException(nsresult, nsPipeEvents &);
 
 private:
     nsPipe                        *mPipe;
 
     // separate refcnt so that we know when to close the consumer
     nsrefcnt                       mReaderRefCnt;
-    PRInt64                        mLogicalOffset;
+    nsInt64                        mLogicalOffset;
     PRPackedBool                   mBlocking;
 
     // these variables can only be accessed while inside the pipe's monitor
     PRPackedBool                   mBlocked;
     PRUint32                       mAvailable;
     nsCOMPtr<nsIInputStreamCallback> mCallback;
     PRUint32                       mCallbackFlags;
 };
@@ -202,17 +203,17 @@ public:
     PRBool   OnOutputWritable(nsPipeEvents &);
     PRBool   OnOutputException(nsresult, nsPipeEvents &);
 
 private:
     nsPipe                         *mPipe;
 
     // separate refcnt so that we know when to close the producer
     nsrefcnt                        mWriterRefCnt;
-    PRInt64                         mLogicalOffset;
+    nsInt64                         mLogicalOffset;
     PRPackedBool                    mBlocking;
 
     // these variables can only be accessed while inside the pipe's monitor
     PRPackedBool                    mBlocked;
     PRPackedBool                    mWritable;
     nsCOMPtr<nsIOutputStreamCallback> mCallback;
     PRUint32                        mCallbackFlags;
 };
--- a/xpcom/io/nsStorageStream.cpp
+++ b/xpcom/io/nsStorageStream.cpp
@@ -49,16 +49,17 @@
 #include "nsStorageStream.h"
 #include "nsSegmentedBuffer.h"
 #include "nsStreamUtils.h"
 #include "nsCOMPtr.h"
 #include "prbit.h"
 #include "nsIInputStream.h"
 #include "nsISeekableStream.h"
 #include "prlog.h"
+#include "nsInt64.h"
 
 #if defined(PR_LOGGING)
 //
 // Log module for StorageStream logging...
 //
 // To enable logging (see prlog.h for full details):
 //
 //    set NSPR_LOG_MODULES=StorageStreamLog:5
--- a/xpcom/io/nsStringStream.cpp
+++ b/xpcom/io/nsStringStream.cpp
@@ -56,16 +56,17 @@
 #include "IPC/IPCMessageUtils.h"
 #endif
 
 #include "nsStringStream.h"
 #include "nsStreamUtils.h"
 #include "nsReadableUtils.h"
 #include "nsISeekableStream.h"
 #include "nsISupportsPrimitives.h"
+#include "nsInt64.h"
 #include "nsCRT.h"
 #include "prerror.h"
 #include "plstr.h"
 #include "nsIClassInfoImpl.h"
 #include "nsIIPCSerializable.h"
 
 //-----------------------------------------------------------------------------
 // nsIStringInputStream implementation
--- a/xpcom/reflect/xptinfo/src/xptiprivate.h
+++ b/xpcom/reflect/xptinfo/src/xptiprivate.h
@@ -64,16 +64,17 @@
 
 #include "mozilla/Monitor.h"
 #include "mozilla/Mutex.h"
 
 #include "nsCRT.h"
 #include "nsMemory.h"
 
 #include "nsCOMArray.h"
+#include "nsInt64.h"
 #include "nsQuickSort.h"
 
 #include "nsXPIDLString.h"
 
 #include "nsIInputStream.h"
 
 #include "nsHashKeys.h"
 #include "nsDataHashtable.h"
--- a/xpinstall/src/nsXPInstallManager.cpp
+++ b/xpinstall/src/nsXPInstallManager.cpp
@@ -35,16 +35,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nscore.h"
 #include "prprf.h"
 #include "plstr.h"
+#include "nsInt64.h"
 
 #include "nsISupports.h"
 #include "nsIServiceManager.h"
 
 #include "nsIURL.h"
 #include "nsIFileURL.h"
 
 #include "nsITransport.h"