Showing posts with label ppc970. Show all posts
Showing posts with label ppc970. Show all posts

Friday, July 30, 2021

And now for something completely different: "Upgrading" your Quad G5 LCS

One of the most consistently popular old posts on this blog is our discussion on long-life computing and how to extend the working, arguably even useful, life of your Power Mac. However, what I think gives it particular continued traction is it has a section on how to swap out the liquid cooling system of the Quad G5, obviously the most powerful Power Macintosh ever made and one of the only two G5 systems I believe worth using (the other being the dual-processor 2.3GHz, as it is aircooled). LCSes are finicky beasts under the best of conditions and certain liquid-cooled models of the G5 line have notoriously bad reputations for leakage. My parents' dual 2.5GHz, for example, succumbed to a leak and it ended up being a rather ugly postmortem.

The Quad G5 is one of the better ones in this regard and most of the ones that would have suffered early deaths already have, but it still requires service due to evaporative losses and sediment, and any Quad on its original processors is by now almost certainly a windtunnel under load. An ailing LCS, even an intact one, runs the real risk of an unexpected shutdown if the CPU it can no longer cool effectively ends up exceeding its internal thermal limits; you'll see a red OVERTEMP light illuminate on the logic board when this is imminent, followed by a CHECKSTOP. Like an automotive radiator it is possible to open the LCS up and flush the coolant (and potentially service the pumps), but this is not a trivial process. Additionally, those instructions are for the single-pump Delphi version 1 assembly, which is the more reliable of the two; the less reliable double-pump Cooligy version 2 assemblies are even harder to work on.

Unfortunately our current employment situation requires I downsize, so I've been starting on consolidating or finding homes for excess spare systems. I had several spare Quad G5 systems in storage in various states, all version 2 Cooligy LCSes, but the only LCS assemblies I have in stock (and the LCS in my original Quad G5) are version 1. These LCSes were bought Apple Certified Refurbished, so they were known to be in good condition and ready to go; as the spare Quads were all on their original marginal LCSes and processors, I figured I would simply "upgrade" the best-condition v2 G5 with a v1 assembly. The G5 service manual doesn't say anything about this, though it has nothing in it indicating that they aren't interchangeable, or that they need different logic boards or ROMs, and now having done it I can attest that it "just works." So here's a few things to watch out for.

Both the v1 and the v2 assemblies have multiple sets of screws: four "captive" (not really) float plate screws, six processor mount screws, four terminal assembly screws (all of which require a 3mm flathead hex driver), and four captive ballheads (4mm ballhead hex). Here's the v1, again:

And here's the v2. Compare and contrast.
The float plate screws differ between the two versions, and despite the manual calling them "captive" can be inadvertently removed. If your replacement v1 doesn't have float plate screws in it, as mine didn't, the system will not boot unless they are installed (along with the terminal assembly screws, which are integral portions of the CPU power connections). I had to steal them from a dead G5 core module that I fortunately happen to have kept.

Once installed, the grey inlet frame used in the v2 doesn't grip the v1:

The frame is not a necessary part. You can leave it out as the front fan module and clear deflector are sufficient to direct airflow. However, if you have a spare v1 inlet frame, you can install that; the mounting is the same.

The fan and pump connector cable is also the same between v1 and v2, though you may need to move the cable around a bit to get the halves to connect if it was in a wacky location.

Now run thermal calibration, and enjoy your renewed Apple PowerPC tank.

Saturday, March 25, 2017

45.9.0b1 available

TenFourFox 45.9.0 beta 1 is now available (downloads, hashes). This version continues deploying more of the multiple microoptimizations started with 45.8, including rescheduling xptcall which is the glue used for calling XPCOM functions (use CTR instead of LR for branching, reorder instructions to eliminate register and FXU dependencies), more reduced branches, hoisting call loads earlier in code sequences, optimized arithmetic inline caches for both Baseline and Ion code generation (especially integer operations for division, min/max and absolute value), fixing a stupid bug which used a branchy way of doing logical comparisons on floating point values (this passed tests but was unnecessarily inefficient), and eliminating some irrelevant branches in font runs and graphics. While I was at it I cherrypicked a few other minor perf boosts from 46 and stuck those in as well.

Also, the font blacklist is updated (fixing Apple and Medium) along with new support for blocking ATSUI-incompatible data:font/* URLs, and there is a speculative fix for the long-running issue of making changing the default search engine stick (this is difficult for me to test because none of my systems seem to be affected). The guts for repairing geolocation are in this version too but I'm still dithering over the service; most likely we will use the Mozilla Location Service though I'm open to other suggestions. Remember that the only sensor data Power Macs can provide for geolocation out of the box is the WiFi SSIDs they see (but this is perfectly sufficient for MLS). This should be finalized by the time 45.9 goes to release.

For FPR1, the first feature I'm planning to implement is one that was cancelled for 45 during beta: Brotli compression, which on supported sites can reduce data transfer by 14 to 39 percent with little impact on decompression time. This will involve backporting the current Brotli decompressor from 52ESR and then making necessary changes to Necko to support it, but happily much of the work was already done before it was disabled (for a critical bug that could not be easily worked around at the time) and released in 46. If there is sufficient time, I'd also like to implement the "New Hot NSS" (get it?) and backport the NSS security and encryption library from 52ESR as well, both of which will also reduce the burden of backporting security fixes. That's a bit of a bigger job, though, and might be FPR2 territory. Other major want-to-dos will be some JavaScript ES6 features I predict will be commonly used in the near future like Unicode regexes and changes to function scoping, both of which landed in 46 and should be easy to add to 45.

Only one site has been reported as incompatible with our plan to shut down SHA-1 certificate support with FPR1. As mentioned, it would take a major site failure for me to call this plan off, but I'd still like as much testing as possible beforehand. If you haven't done it already, please go into about:config and switch security.pki.sha1_enforcement_level to 1, and report any sites that fail. This approach of complete decommissioning is essentially the same policy Google Chrome will be taking, and soon no major browser will accept SHA-1 certificates as trusted for TLS, so it's not like we're going out on a limb here. Please note that reversing this change will not be a supported configuration because (the security implications notwithstanding) it may be un-possible to allow doing so after the new NSS library is eventually transplanted in.

Once 45.9 comes out, we will switch to our own Github repository and the source code will be uploaded and maintained from there (no more changeset overlays!). However, pull requests won't be accepted unless they're tied to an issue already accepted on the worklist, and we will still enforce the policy that non-contributor bug reports need to be triaged through Tenderapp first. Watch for the repo's magical population shortly after 45.9's final release on April 18.

Unfortunately, I don't think there will be a Tenfourbird FPR1: it appears that our anonymous colleague in the Land of the Rising Sun has not made any builds since 38.9, and that is a real shame. :(

Saturday, February 4, 2017

An experiment: introducing the PopOutPlayer (plus: microbenchmarking PowerPC SPRs)

TenFourFox 45.8 is coming along -- Operation Short Change (my initiative to rework IonMonkey to properly emit single branch instructions instead of entire branch stanzas when the target is guaranteed to be in range) is smoothing out the browser quite a bit but there are hundreds of places that need to be changed. I've finished the macroassembler and the regular expression engine (and improved both of them in a couple other minor ways), and now I'm working on the Ion code generator. This mostly benefits systems that cannot fit generated code into cache, so while the Quad G5 with its (comparatively large) 1MB per core has only improved somewhere on the order of about 5%, I expect more on low-end systems because hot code is now more likely to stay in the i-cache. I am also planning to put user agent support in 45.8, and there are a few other custodial improvements. The idea is to release that to beta testing around Valentine's Day so I don't have to buy you lot any flowers.

A long while back I mentioned a couple secret projects; one of them was SandboxSafari, and the other was intended as a followup to the now obsolete MacTubes Enabler. That second project got backburnered for awhile, but since I'm noticing changes that may obsolete the work I've done on it as well, I'm going to push it out the door in its current state. Without further ado, let's introduce the PopOutPlayer.

This is not Photoshop. There is, just as you see, a floating video window playing the Vimeo movie that TenFourFox cannot (no built-in H.264 codec). In fact, I think this is the only way you can play Vimeo movies on Tiger now -- neither Safari nor OmniWeb work either.

Yes, it works fine with YouTube also:

Drop the application in your apps folder, drop the PopOutPlayer Enabler addon on TenFourFox, and then on any Vimeo (10.4 only) or YouTube (10.4 or 10.5) page or embedded video, right-click or SHIFT-right-click and select Pop Out Video. The video floats in its own window on top of other windows. You can close the browser tab and go look at something else while the video plays; the playback is a completely independent process. When you open another video, the window pops up in the same location where you left it. On multiprocessor Power Macs it can even get scheduled on another core for even smoother playback.

Sounds great, right? Well, there's a few reasons why I hadn't released this earlier.

First, the app itself is, and I'm actually feeling ill writing this, based on these sites' Flash players. Flash was the only reliable way to do playback and was even more performant than native H.264 in WebKit, and it also had substantially fewer user interface problems at the risk of sometimes being crashy. Flash is no safer now than it was before I condemned it from the browser, but I've learned a few lessons from SandboxSafari, of which the PopOutPlayer is actually a descendant. To remember its window location means we have to run the app with your uid (which eliminates SandboxSafari's primary means of protection), but we also have the advantage of only needing to support at most two specific video player applets, so we can design a very restrictive environment that protects the app from being subverted and rejects running video or Flash applets from other sources.

This different type of sandbox implements other restrictions, most notably preventing the applet from going full-screen. This is necessity reborn as virtue because most of our systems would not do well with full-screen playback, let alone HD (which is also blocked/unsupported), and prevents a subverted player from monkeying with the rest of your screen. The sandbox doesn't let URLs open from the applet either, and has its own Mach exception handler and CGEventTap to filter other possible avenues of exploit. However, that also means that you can't do many of the things you would expect to do if the Flash player were embedded in the browser. That won't change.

The window is fixed-size and floats. Allowing the window to resize caused lots of problems because the applets didn't expect to deal with that possibility. You get one size no matter how big your screen is, and you can only close it or move it.

Although the PopOutPlayer can play more YouTube videos than the QuickTime Enabler, there are still many it cannot play, though at least the Flash player will give you some explanation (the Vevo ones are the most notorious). The PopOutPlayer also isn't intended for generic HTML5 video playback; it doesn't replace the QTE in that sense, and the QTE is still the official video solution in general. The application will reject passing it URLs from other video sites.

The really big limitation, however, is that I could not get the Vimeo applet to run on 10.5 using the hacks I devised for 10.4. Leopard WebKit can play some Vimeo videos, so all is not lost, but no matter what I tried the PopOutPlayer simply wouldn't display any video itself. For the time being, Vimeo URLs on Leopard will generate an "Unsupported video URL" message. It is quite possible this might never be able to be fixed with the current method the PopOutPlayer uses for display, so don't expect it will necessarily be repaired in the future. For that matter, Vimeo on-demand doesn't even work with 10.4.

I consider the PopOutPlayer to be highly experimental, and when (not if) Vimeo and YouTube decommission their Flash players, it will abruptly cease to work without warning. But because I expect that time is coming sooner and not later you are welcome to use the PopOutPlayer for as long as it benefits you, and if I can solve some of these issues I might even make it a supported option in the future -- just don't hold your breath.

Download it here. It is unsupported. Source code is not currently available.

So back to TenFourFox. If you would, permit me now to indulge in some gratuitous nerderosity. Part of Operation Short Change was also to explore whether our branch stanza far calls could be made more efficient. Currently, if the target of a branch instruction exceeds the displacement the branch instruction (i.e., b(l) or bc(l)) can encode, we load the target into a general purpose register (GPR), transfer it to the counter register (a special purpose register, or SPR), and branch to that (i.e., lis/ori/mtctr/b(c)ctr(l)). The PowerPC ISA does not allow directly branching to a GPR or FPR, only to the counter register (CTR) and the link register (LR), which are both SPRs.

This would be all well and good except that the G5 groups instructions together, and IBM warns that there is a substantial execution penalty if mtctr and b(c)ctr(l) are in the same dispatch group. Since mtspr instructions like mtctr must always lead dispatch groups, the above stanza is guaranteed to put them both together (recall instruction dispatch groups are no more than four, or five with a branch, with branches being the last slot). Is it faster to insert nops and accept the code bloat? What about using the link register instead?

It's time for ... assembly language microbenchmarking!

#define REPS 0x4000
_main:
        .globl _main

        mflr r0
        stwu r0, -4(r1)

        li r3,0
        lis r5,REPS
        bl .+4
        ; the location of the following mflr is now in r4
        mflr r4
        addi r4, r4, 8
        ; now r4 points to the addi below

        addi r3,r3,1
        cmp cr0,r3,r5
        beq done
#if USE_LR
        mtlr r4
#if USE_NOPS
        nop
        nop
        nop
        nop
#endif
        blr
#else
        mtctr r4
#if USE_NOPS
        nop
        nop
        nop
        nop
#endif
        bctr
#endif

done:
        lwz r0, 0(r1)
        mtlr r0
        li r3,0
        addi r1, r1, 4
        blr
This just runs a tight loop 1,073,741,824 times, branching to the loop header with either LR or CTR, and with the mtspr instruction separated from the blr/bctr with sufficient nops to put them in separate dispatch groups or not (there must be four to prevent the branch from getting in the terminal branch slot). That gives us four variations to test with a loop so tight the cost of the branch should substantially weigh on total runtime. Let's see what we get. If you're following along on your own Power Mac, compile these like so:
gcc -o lrctr_ctr lrctr.s
gcc -DUSE_NOPS -o lrctr_ctrn lrctr.s
gcc -DUSE_LR -o lrctr_lr lrctr.s
gcc -DUSE_LR -DUSE_NOPS -o lrctr_lrn lrctr.s
If you want to confirm what was actually assembled, you can look at the result with otool -tV.

Our control will be our trusty 1.0GHz iMac G4 (256K L2 cache). There should be no difference between the SPRs, and it all fits into cache and there are no dispatch groups, so if we did this right the runtimes should be nearly identical. In this case we are only interested in the user CPU time (the first field).

luxojr% time ./lrctr_ctr
7.550u 0.077s 0:08.88 85.8%     0+0k 0+2io 0pf+0w
luxojr% time ./lrctr_ctrn
7.550u 0.071s 0:08.55 89.1%     0+0k 0+0io 0pf+0w
luxojr% time ./lrctr_lr
7.550u 0.070s 0:10.08 75.5%     0+0k 0+2io 0pf+0w
luxojr% time ./lrctr_lrn
7.550u 0.069s 0:08.43 90.2%     0+0k 0+0io 0pf+0w
Excellent. Let's run it on the Quad G5 (numbers in reduced performance mode).
bruce% time ./lrctr_ctr
4.298u 0.028s 0:04.33 99.5%     0+0k 0+2io 0pf+0w
bruce% time ./lrctr_ctrn
4.986u 0.035s 0:05.03 99.6%     0+0k 0+2io 0pf+0w
bruce% time ./lrctr_lr
13.755u 0.050s 0:13.82 99.8%    0+0k 0+1io 0pf+0w
bruce% time ./lrctr_lrn
13.752u 0.048s 0:13.82 99.7%    0+0k 0+2io 0pf+0w
Wait, what? Putting mtctr and bctr in the same dispatch group was actually the fastest of these four variations. Not only was using LR slower, it was over three times slower. Even spacing the two CTR instructions apart was marginally worse. Just to see if it was an artifact of throttling, I ran them again in highest performance. Same thing:
bruce% time ./lrctr_ctr
2.149u 0.012s 0:02.16 99.5%     0+0k 0+1io 0pf+0w
bruce% time ./lrctr_ctrn
2.492u 0.010s 0:02.50 100.0%    0+0k 0+0io 0pf+0w
bruce% time ./lrctr_lr
6.876u 0.013s 0:06.89 99.8%     0+0k 0+0io 0pf+0w
bruce% time ./lrctr_lrn
6.874u 0.017s 0:06.89 99.8%     0+0k 0+1io 0pf+0w

I found this so surprising I rewrote it for AIX and put it on my POWER6, which is also dispatch-group based and uses an evolved version of the same instruction pipeline as the POWER4 (from which the G5 is derived). And, well ...

uppsala% time ./lrctr_ctr
3.752u 0.001s 0:04.41 85.0%     0+1k 0+0io 0pf+0w
uppsala% time ./lrctr_ctrn
4.064u 0.001s 0:04.94 82.1%     0+1k 0+0io 0pf+0w
uppsala% time ./lrctr_lr
13.499u 0.001s 0:16.19 83.3%    0+1k 0+0io 0pf+0w
uppsala% time ./lrctr_lrn
13.215u 0.001s 0:15.66 84.3%    0+1k 0+0io 0pf+0w
Execution times should consider that I run this POWER6 throttled in ASMI to reduce power consumption and its microarchitectural differences, but the same relative run times hold. It's actually not faster to space the CTR and branch (that is, if there's nothing better you could be doing -- see below), and the CTR is the best SPR to use for branching on the G5 regardless of any penalty paid. It may well be that using LR fouls the CPU link cache and thus tanks runtime, but whatever the explanation, using it for far calls is clearly the worst option.

Now, as you may have guessed, I've deliberately presented a false choice here because all four of these options are patently pathological. The optimal instruction sequence would be to schedule some work between the mtctr and the bctr. We don't have much work to, uh, work with here, but here's one way.

#define REPS 0x4000
_main:
        .globl _main

        mflr r0
        stwu r0, -4(r1)

        li r3,0
        lis r5,REPS
        bl .+4
        ; the location of the following mflr is now in r4
        mflr r4
        addi r4, r4, 8
        ; now r4 points to the mtctr below

        mtctr r4
        addi r3,r3,1
        cmp cr0,r3,r5
        beq done
        bctr

done:
        lwz r0, 0(r1)
        mtlr r0
        li r3,0
        addi r1, r1, 4
        blr

bruce% gcc -o ctrop ctrop.s
bruce% time ./ctrop
4.299u 0.028s 0:04.34 99.3%     0+0k 0+1io 0pf+0w
Almost identical runtimes (in reduced mode), but the beq takes the branch slot away from the bctr, guaranteeing the SPR operations will be split into two dispatch groups without trying to space them with nops. But inexplicably, if you coalesce the beq/bctr simply into bnectr (which does occupy the same branch slot), you get even faster:
bruce% time ./ctrop2
3.824u 0.039s 0:04.02 95.7%     0+0k 0+0io 0pf+0w
Is this optimal on the G4 and POWER6 as well?
luxojr% time ./ctrop
6.472u 0.064s 0:12.05 54.1%     0+0k 0+2io 0pf+0w
luxojr% time ./ctrop2
6.471u 0.063s 0:09.33 69.9%     0+0k 0+0io 0pf+0w

uppsala% time ./ctrop
3.918u 0.001s 0:04.61 84.8%     0+1k 0+0io 0pf+0w
uppsala% time ./ctrop2
2.612u 0.001s 0:03.09 84.4%     0+1k 0+0io 0pf+0w
Yup, it is, though it's worth noting the G4 did not improve with the bnectr. (This is still pathological, mind you: the best instruction sequence would be simply addi/cmp/bne, which the G5 in reduced mode runs in 2.580u 0.029s and the POWER6 in 1.261u 0.001s, reclaiming its speed crown. But when you have a far call, you don't have a choice.)

The moral of the story? Don't fix what ain't broke.

Wednesday, April 9, 2014

Long life computing (plus: Quad G5 CPU swapping for dummies)

We are now at the point where the youngest quad G5 is almost eight years old, and TenFourFox works on any Mac that can run 10.4 and has sufficient memory, meaning theoretically even a beige 9500 with a G3 card and a full RAM loadout could be out there (and if there is, I'd love to hear about it) pushing 19 years young.

I'm committed to getting a full useful decade out of my quad G5 systems, and frankly I don't see any reason to stop there. The Quad handles all my tasks except taxes and Android development (I use an Intel mini for Eclipse and TurboTax), including Photoshop, Microsoft Office and HD video; I'd have to rebuy all that just for the dubious privilege of using an Intel Mac. When it gets to the point that TenFourFox's rendering core can't be evolved further, then I'll just throw a Linux box in the server room and run a browser over remote X11. Then I can have my cake and eat it too.

Like me, I imagine most people reading this blog will want to keep their vintage Power Macs operating for a long time as well, especially if you use your Power Mac as your daily driver like me. There are some general things I do with all of my regular use systems (my daily drivers are my Quad G5, a 1GHz iMac G4 and an iBook/G4 12" 1.33GHz, all running 10.4) and these suggestions should help you also. Plus, those of us rocking liquid-cooled G5s are probably starting to notice that the fans are coming on harder, so we're going to talk about servicing the Quad G5 LCS at the end.

Software security. If you're running TenFourFox, you're already ahead of the curve. Congratulations. Here are other security issues to consider with old versions of Mac OS X (as well as our note about OS X's internal SSL).

Save a port, ride an extension. Wait, what? Logic boards and daughterboards are expensive and precious as well as a pain in the rear to fix, and most ports are directly soldered to the logic board, so when a port wears out it can be an expensive and time-consuming swap job. For USB and FireWire, especially for the front ports on my G5 which are constantly being connected and disconnected from my mobile phone and HD video camera, I connected extensions to them and I plug the camera and phone and etc. into the extension cables; I'd rather be replacing a $5 or so extension cable than wrecking my front port daughterboard. Similarly, my Bluetooth dongle connects with its own extension cable (though this is partially so I can find the damn thing).

Rotate your hard drives. Virtually all of our Power Macs are beyond their crib death stage and the next likely failing device will be spinning hard disks. Some of you have solved this problem with solid-state drives, which are a decent if pricey upgrade and certainly immune to mechanical if not electronic failure, but not even the SATA bus in a G5 will get anywhere near the maximum throughput possible; plus, no version of PPC OS X supports TRIM, which means write speed will gradually degenerate. (Linux users might get better benefit.) In my case, I have a stock of SATA I and II spinning drives which I bought new or NOS, and every four or five years I clone the disks (boot off the Tiger DVD and use Disk Utility) to a new set and swap them out. I'm using WD Caviar Blacks which are good solid 7200rpm drives; I did a swap in 2010, my next swap is due for 2015 and I have enough disks in stock to do one more swap in 2020. The swapped out drives are still working, of course, and if the G5 is still trucking in 2025 I might start a more rapid rotation schedule with those old disks depending on how heavily it's being used.

If you're on a system using the older PATA drives, stock up now; NOS stocks are disappearing -- or find something like a Sonnet PCI SATA card, which is bootable and works fine with OS 9 and OS X.

A common question is whether SATA III (6.0Gbps) drives are compatible with G5s and PCI SATA cards, and the answer is, of course, it depends. All Power Mac compatible SATA controllers I have encountered were SATA I (1.5Gbps), including the ones in all the G5s up through the Quad, and SATA II (3.0Gbps) drives work fine with SATA I. If the SATA III drive can be jumpered to run at SATA II speeds, it will work just fine; if it does not have a SATA II jumper, it depends on the drive electronics. Some users have reported that the SATA III Hitachi Deskstars work fine with SATA I, but many SATA III SSDs will not and this can be an expensive thing to explain to vendor support.

Speaking of spare hard disks ...

Have spare RAM, spare cards and spare parts. Consider a body double. Get used to doing basic repair on your machine. Besides hard disks, RAM ages too; both my iMac G4 and my quad G5 blew DIMM sticks around the same time. The good news is that every New World Mac uses industry-standard RAM and I was even able to find brand new PC100 sticks recently for my old Sawtooth G4 file server on Amazon, 14 years after it was taken off the market. RAM is cheap. Have a stock on hand. Beige Mac RAM can often be found from used Mac vendors like MemoryX.

Stock up on PRAM batteries. Later machines like the Power Mac G5 use standard coin cells but earlier G4 systems used 1/2AA 3.6V lithium batteries which may need to be specially ordered.

Another frequent consumable is video cards on those systems with discrete video and PCI/AGP slots. Fans are often the culprit -- the nVidia 7800GT's fan quit in my G5 a year or so ago when I was out of town and I returned to discover the GPU was at a finger-searing 105 C. Amazingly, it was still working and I put a new CPU cooler on it. I have a stock of a couple spare 7800GTs since they're a decent video card that doesn't require two slots in my G5.

Regular PCI cards die as well, though admittedly not as frequently. One of my PCIe FireWire/USB cards is now refusing to recognize FireWire devices plugged into it. Time to swap that out; it's just not worth doing any sort of component level repair on these things anymore. I have a couple in stock too. Sonnet still sells many of these peripheral cards new.

Certain machines have notoriously high frequency failures in certain components. Besides the issues with many early Power Mac G5 models, which I'll talk about in a moment, the MDD G4s are infamous for having iffy power supplies. Since my MDD is my OS 9 workstation of choice, I have three MDD power supplies in stock (I've already had to replace the power supply twice on it since I bought it new in 2002, not counting the power supply replacement under Apple's recall).

If you are unlucky to have a model with a history of logic board failures, take heart in that logic board death is usually an early finding and most of the surviving Power Macs will have a better track record. However, it's often better to just keep an entire body double on hand for your mission critical systems -- a(n as much as possibly) identically configured system, waiting in storage ready to swap in when you need it. This gets you spares for everything, even the logic board, power supply and case; if you have a major electronics failure, just move everything to the body double and work on the original. I kept a spare Apple Network Server 700 in the closet to replace my Apple Network Server 500, which it had to do for a period of a few weeks while I debugged a hardware issue, and my body double quad G5 is now my current quad and the original one is now the spare (with a new CPU and LCS). I also have body doubles for my iBook, my iMac G4 and my Sawtooth G4 and MDD G4.

Prices on Power Macs are starting to bottom out as they become rarer and more interesting as collector's items. This may well be the last chance to stock up on them at a decent cost before it becomes a seller's market.

Have a strategy to recover from catastrophic failure. Besides my body double and spare disks, I have bootable Power Mac compatible discs for Alsoft DiskWarrior, Prosoft Data Rescue 3 and of course retail Tiger 10.4.6, which will boot any compatible Power Mac including the Quad G5. Alsoft even still sells a DiskWarrior for OS 9 systems, and Data Rescue 3 still works with G4 and G5 computers. Support companies that still support the Power Mac; please don't pirate. I'm not an affiliate of either company, merely a satisfied customer.

Throttle your CPU: heat (and heat caused by higher power consumption) is the enemy. Heat diminishes the lifetime of components. Heat dries up thermal compound on the heatsinks. Run your Mac in reduced mode if at all possible, particularly for G5 systems which run comparatively hot to begin with -- my G5 is usually in Reduced mode, and I only flip it to Highest if I have a task I need done quicker or a slow-to-render web page. A tool like Fast and Slow (free) will do nicely; I like CPU Speed Menu, which is a little more configurable, but it's shareware and it doesn't seem its author supports it anymore.

Power Mac G5 Special Section: Swapping the Quad G5 CPU

I have long observed that there are only two G5 computers worth owning: the air-cooled PCI dual processor "DP" 2.3GHz (the later dual core "DC" PCIe 2.3 is also air-cooled, and about 5% faster depending on the benchmark, but has comparatively lower reliability scores), and the liquid-cooled Quad G5, the fastest Power Mac ever made and the one with the best liquid cooling system. The iMac G5s are a big bag of hurt to work on, the early G5s are not substantially faster than the G4s they replaced, and the others have logic board, power supply or liquid cooling leakage issues.

Now, again, by this time in the Power Mac's lifespan most early failures have already wound up in the landfill. Similarly, most of the liquid cooling systems that were going to leak probably already have. However, liquid cooling systems, like the automotive radiators the G5 systems are based on, wear out. There are small evapourative losses from the hoses carrying the coolant, which in these systems are water-based, and thermal paste also slowly loses its moisture and starts to crumble. The very last Quad G5 to roll off the production line is almost eight years old, and if it's still on its original CPU and heat sink it is very likely it's suffering from both these problems.

At this point we should probably talk about what thermal calibration actually involves. All G5 (a/k/a PowerPC 970) systems use fan software controlled by the operating system which needs to know how effective the current cooling system is. According to IBM's technical documentation on the 970, each CPU has temperature sensors and a calibration ROM which stores data about the sensors' set points and fan speeds. Thermal calibration does not actually calibrate the sensors; thermal calibration data for the on-chip thermal diodes is burned in at the factory (IBM calls this information part of the "fuse code data") and if these sensors are bad or incorrect the only solution is to replace the CPU. Instead, what it does is try to find the fan (and, on LCSes, pump) RPM ranges that will keep the CPU in a normal temperature range even under maximal power draw, and writes this data to the calibration ROM. (This is why losing your PRAM battery doesn't screw up your fans. By the way, the PMU/SMU, contrary to popular belief, does not manage the fans either. Resetting the PMU/SMU to fix a fan problem won't help and may scramble the PMU/SMU.)

The upshot is that whenever you do anything to change the cooling characteristics of the system, such as replacing or servicing the CPUs, you need to run thermal calibration again to make sure that the computer knows which RPMs and pump speeds will work. You can't "thermal calibrate" your way out of a failing CPU assembly -- the assembly either passes or it doesn't, and on some earlier versions of the calibration tool you ran the risk of corrupting the calibration ROM if you ran it repeatedly on an iffy unit. Thermal calibration is run from the Open Firmware diagnostic tools on the Apple Service Diagnostic disc. Most people will want to use 2.6.3 with both these models of G5, and the Quad requires it, but 2.5.8 will also work fine with the DP 2.3. To avoid Apple's wrath I won't link these disc images here, but they are not difficult to find. The ambient temperature in the room when you run calibration must be below 77 F (25 C).

A utility like Temperature Monitor or iStat Pro will be useful to know if you're getting close to the edge. I threw together a little tool to monitor your G5 temperature and (max) fan or pump speed in the menu bar. (On my G4 laptop, it didn't install in the menu bar correctly and I don't know why. If it doesn't appear to work, make sure the monitoring process isn't running alone in the background soaking up CPU cycles. I'll look into this later.) The menu bar tool displays the highest temp of the CPUs and the highest RPM of the non-fixed pumps or fans; you can also use it as a command line tool (see the page for how). On single pump LCSes, the same speed is reported twice.

At least on the Quad, ordinarily the intakes idle at 970rpm (ahaha), the exhausts and drive bay fan at 1000rpm, the backside fans at 1100rpm and the PCI slots at apparently a fixed 1560rpm. The LCS pumps, for their part, idle at 1250rpm. As heat increases the CPU fan speeds will increase, as well as the liquid cooling system pumps. Under load the fastest RPM in the system is usually the LCS pumps which are rev-limited by the computer to 3600rpm.

At idle, the CPUs should be below 50 C, especially in Reduced power mode, and the CPUs should be roughly within 10 C of each other or less. (In fact, earlier this spring, my G5 observed a 35 C core, the lowest it's been in years.) The CPUs should not exceed 70 C even under load on any core. If your Quad G5 is seeing core temperatures over 70 C even when the pump speed is pegged at 3600rpm, your system can no longer cool effectively and it's time to service the processor assembly. Resist the temptation to run thermal calibration because it probably won't help you for long if it helps you at all. Switch your G5 into Reduced mode if it wasn't already; assuming you're not much over the 70 C mark, you've still got some time to get all your parts together.

Servicing the DP 2.3 is a matter of unmounting the heatsink, applying new thermal compound (Shin-Etsu X23-7783D is the typical recommendation, though others will work) and putting the CPUs back. Fortunately, most DP 2.3 systems if well-taken care of won't even need that; do so only if your Mac has random sudden sleeping episodes or you see complaints about being "overtemp" in your OS X system log.

The Quad is a different story -- the easiest way, and the only way Apple ever allowed, is to just find a new CPU and heatsink assembly. There is a lot of confusion over which will work and what LCS the Quads came with. Most systems I've encountered have a so-called "version 1" Delphi assembly with a single pump. It looks like this:

For a period of time Apple used a so-called "version 2" manufactured by Cooligy with twin Delphi pumps; despite the apparently later revision the "version 2" LCS actually has the poorer track record. The Apple service manual for the Quad does not say anything about requiring a special logic board for the version 2 LCS, and they are comparatively unusual. I will not discuss them further here. Although Apple used Panasonic LCSes on some older G5s, they never used them on the Quads (even I got this wrong until I did my research). There appears to be no problem with replacing a version 2 LCS with a version 1 LCS; in fact, a version 1 may be the only one you can get anymore.

The version 1 CPU and heatsink should come as an item. If you are buying from an Apple Certified reseller, this is the only way Apple ever sold them. Do not buy them separately unless you know what you're doing, or you're totally crazy; you will have to reassemble them. The part number for the combined CPU and heatsink is 661-3729. When shopping around for these, don't pay more than a couple hundred dollars -- I now have three spares, and the most I spent for any one of them was $135. The magic words you want to hear from the reseller are "Apple Certified Refurbished" (or, less optimally, "passes thermal calibration"). If you don't hear these phrases from them, do not buy. Prefer the Certified Refurbished parts, because these came from Apple with new thermal paste and new coolant and they'll last for years more if you treat them right.

(If you can't buy a decent used CPU, all is not lost. There are ways to service the liquid cooling system and the CPUs by hand if you're willing to do a bit of grunt work and are comfortable with draining and replacing the coolant manually. Heikki Lindholm offered many great tips while I was writing this and I direct you to his excellent treatises on servicing the Quad G5 cooling system and pump assemblies.)

In addition to the CPU, you will also need:

  • An X-acto knife or small flathead screwdriver to use as a pry tool.
  • A Philips 0 screwdriver.
  • A 3mm long-handle flathead hex driver (I used an Eklind part# 54930).
  • A 4mm long-handle ballhead hex driver (I used a Bondhus part# 13160). Both are available from Amazon and most special-order tool retailers. The tool shaft needs to be at least 8" long; shorter ones will not be able to get to the screws.
  • A grabber of some sort to go chasing screws; you can use a magnetic one as long as you keep away from the hard disks.
  • A copy of the ASD for your G5; burn it to disc and have it handy (remember that ASD 2.6.3 requires a DVD).

Power down the Mac and unplug it. Let it cool down: not only is the radiator potentially hot enough to burn you, but working on the G5 logic board when it's hot may damage the logic board. Flip the lever on the back, remove the side panel and remove the air deflector, and put them aside. Pull the front fans straight out, in front of the radiator.

The processors are covered by a heat shield with a G5 logo. If you've never serviced the CPUs before (or Apple serviced them), this shield is locked in place by a little plastic pin on top. Pry this very tenacious pin out with the X-acto knife or small flathead screwdriver verrrrrry carefully so that you don't go damaging anything else. This will destroy the pin most likely, but all our Macs are out of warranty and you may need to do stuff with the processor again in the future. The heat shield will now become very loose and mobile. Shift the shield to the left and remove it. In front of the front radiator is a little plastic intake frame; rotate it clockwise from its mooring around the radiator so it can come free from its standoffs and pull it out.

Now it's time to get the old CPU assembly out. Put the computer flat on its side. If you don't do this, the screws will fall out when you remove them and end up in the power supply compartment, and that really sucks! Follow Apple's steps exactly and loosen/remove the screws exactly in numerical order (note: the captive float plate screws are not really captive and can come out, so be careful):

(The ballhead screws in the last step may have to be accessed at an angle; that's why they're ballheads and not flat.)

Once the screws are loosened and/or removed as directed, disconnect the black fan control linkage by pulling the two halves apart, and grab the centre of the metal frame. The CPU should lift straight up and out with very little force:

This is what you should see with the CPU out. Yes, it's dusty. Clean the dust out and in particular make sure there are no dust bunnies floating over where the CPUs attach (those arrays of little square pins).
It is particularly critical not to lose any screws: in particular, the screws attaching the CPUs to the logic board are actually an integral part of the power supply connection to the processors and the computer may not be able to even power up without them.

If the screws despite your best effort do get into the power supply compartment (and don't ask me how I have experience with this), you'll need to give them an escape path. Pull the CPU out and also remove the hard drives because you're going to have to shake the computer around. Unmoor the rear exhaust fan assembly by pressing in the tabs facing you so it can move freely and won't block any flying screws (you don't have to disconnect it unless you want to). Pry up the adhesive pad on the bottom of the partition between the CPUs and the power supply (just enough to get to the screws; don't toss it) and undo both Philips-head screws to remove the partition. Unplug the power cable near the PRAM battery and thread it free as you lift the partition. The partition is flexible and you may need to bend it a bit to get it out. Turn the G5 upside down and remove one or both of the screws on the underside. This will loosen the power supply so the screws can escape. Now it's time for calisthenics with your Quad:

Get all of the screws out! Do not leave any of them loose in the machine! I had to literally put my Quad over my head and shake it to get them loose enough to fish for with the grab. Once you've got them all back, replace the screws in the underside, put the partition back (rethreading the power connector through and plugging it back into the logic board), put the screws back in the partition, replace the adhesive pad and put the rear fan assembly back into its original position, making sure the tabs lock into their little slots.

Now get the new CPU straight up out of its box, lifting it up by its metal bridge (it should be stored such that the heatsink is on top, which uses gravity to maintain the seal between the heatsink and the actual processors). Do not lift it up by the radiators or heat pipes or you will bend them and reduce the assembly's cooling performance. Used assemblies may or may not come with caps over the processor connectors; remove them if they are present, and loosen the float plate screws on the new CPU assembly like you did in the first step of removing the old CPU. Next, put the screws in their holes before installing the assembly: it's much harder to put the screws in when the CPU is already in the case. Carefully align the CPU over the standoffs and put it straight down into the computer:

The CPU should go in nice and level. Press down on the bridge only to make sure the CPU is seated; don't press anywhere else. It should give slightly with a little thunk. Do not apply significant force or you will damage the CPU, the logic board or both.

With the CPU now in place, tighten the four captive ballhead screws (the ones in the last step you did when loosening the screws before pulling the old CPU out), going in order from top to bottom, then middle top and middle bottom. Do not overtighten -- tighten only up to mild resistance. If the ballhead screws are not engaging well, the CPU is probably not seated correctly: make sure the float screws are loose, carefully pull the CPU out and reseat it. You can also try tightening the top, middle top, bottom and middle bottom in a different order; this may enable the CPU to move around a bit into a more favourable position.

Once the ballhead screws are engaged and gently tightened:

  • Tighten the remainder of the screws in the reverse order you loosened and/or removed them, finishing with tightening the captive float plate screws. Again: do not overtighten.
  • Connect the black fan control cable.
  • Put back the plastic radiator intake frame; guide its rear tab to the back around the processor standoffs and rotate it so that its clips grip the front radiator.
  • Replace the heat shield only if you want to.
  • Replace the front fans and put back the clear plastic deflector.

Connect your G5 and plug it in, cross your fingers, and hold down Opt-Cmd-O-F while turning it on from the power switch. If you did this right, one of the front red LEDs will briefly light and then turn off, the G5 will bong and you will enter the Open Firmware prompt. (If you don't get a bong, the CPU is not in place correctly or, horrors, is damaged. Loosen it and remove it. See if it will boot with the old CPU.) Release the keys, type eject cd to open the optical drive, put your ASD disk in, and close the optical drive. On my ASD 2.6.3 disk, I had to type boot cd:,\diags (yes, you need the colon, the comma and the backslash) to start the diagnostic program, the only time your G5 will ever "appear" to boot Mac OS 9. :) The fans will come on full blast; this is normal and the fans will remain loud during the entire diagnostic process.

After the diagnostic program finishes loading, select Thermal Calibration from the pull down menu. Make sure the room is below 77 F/25 C and that the front of the machine is not facing any heat source or heat exhaust. Once you begin thermal calibration on the new CPU assembly and it succeeds, you may cause issues with your Mac if you put the old failing CPU assembly back in later. This is the point of no return. If you're lucky, this is the result:

Congratulations. Now put the side panel back on, run the rest of the self-tests and keep on trucking.
(And marvel about how quiet it is now when you reboot into OS X.)

Meanwhile, I'm pulling 29 beta to transfer the changesets over for a TenFourFox 29 unstable release. Still a couple of moderate issues to fix, but it's getting there and is mostly in a state I think you'll be able to play with. More about that probably next week.

Monday, November 19, 2012

17.0 goes final; a little more discussion of locking and atomics

17.0 is now official, along with our five translations. A great job by everyone to get us to this point.

I am nearly done with the "atomic" version of 17, which will be a "17.0.1pre" and then landed on 17ESR for our consumers with stable 17.0.1. There are some interesting things I discovered along the way, including yet another episode of "Optimizing for the Mysterious G5" (see our other exciting episodes of PowerPC 970 black magic). Let's savour the tasty tidbits:

  • To recap: Atomic operations help to insure that multiple threads remain synchronized and don't step on each other, especially when multiple cores or CPUs are involved. This concept was about replacing Mozilla NSPR's built-in atomic operations which use GNU pthread_mutex_* and are therefore slow on OS X with the OS X built-in atomics where possible, and a custom "atomic set" I wrote myself that 10.4 doesn't possess, and then looking at using the built-in gcc intrinsics for 18+ when we move to gcc 4.6.3.

    This only affects atomic operations -- mutexes where the browser actually locks a value for synchronization are still going through the (Apple even admits is slow) OS X implementation of pthread_mutex_*().

  • Overall performance did indeed improve, in some cases markedly. Of our two pathological test cases, as mentioned, iFixit got a lot better just by repairing the issue for JavaScript, and got even faster when the change was extended over the entire browser. However, local AM station KFI AM 640's page is still spending a massive amount of time in semaphore lock waiting for threads to release resources, so it still seems to be relying on pthreads, and we still probably need to do something about reducing locking overhead (or use of locking) in general to solve that problem.

  • OS X atomics are actually faster than gcc atomic intrinsics, so even after we switch compilers we probably still want to use this patch. The reason is that the OS X atomics self-optimize, which you can see better illustrated in this earlier version of osfmk's atomic.s. For the atomics to work correctly on multiprocessor Power Macs, there have to be memory and instruction barriers set up so that the processor doesn't inadvertently reorder instructions or memory access in such a way that we get the wrong value out at the end. A write barrier ensures that the atomic's read instruction executes only after all previous writes are complete, and a read barrier ensures everything after the atomic's store instruction executes only sees the value it stored and not stale data. These barriers are expensive because they interfere with processor optimization and may flush pipelines and caches, and are unnecessary on a uniprocessor Mac, so the operating system actually patches the unnecessary sync instructions to no-ops on single processor Power Macs (see also Amit Singh's holy word in OS X Internals, page 400). The gcc atomic intrinsics don't do this (arguably, they can't), so they are slower than they should be on uniprocessor Power Macs, which is the majority of our user base.

  • Furthermore, 10.4 atomics lack an "atomic set" function to just set something to a value (we have swaps, bitwise ops and basic arithmetic, but no actual "set" operation), so we need to use an external atomic for that. However, we can hand-optimize our own "atomic set" better than the gcc version, because we know what our target processor will be, and we know how Gecko is using it. There are several major instructions for setting up a barrier, and some others that have it as a side-effect, but we'll only talk about a few: eieio (which you can even sing along with), sync, lwsync, isync, and absolutely nothing, which suffices for JavaScript but I don't think is sufficiently safe for the browser as a whole.

    Unfortunately, our own routine right now can't easily patch itself for the uniprocessor case, so we need to pick barrier instructions that are as low-impact as possible:

    • The prototype instruction is sync, which forces the CPU to wait until all the previous instructions have executed before running another one and locks all processors together so that everything is in a predictable state. This covers all reads and writes necessarily. However, in doing so, it will grind everything on every core to a halt until execution is finished. This is a pipeline killer and we want to avoid it.
    • eieio is mostly for ordering memory mapped I/O, but our main interest is that it prevents load-store combining and ensures memory access is coherent, including across processors. However, eieio really is only ordering stores in practice, so it is not sufficient as a read or read/write barrier on its own. It does, however, suffice as a write barrier.
    • Alternatively, we could execute an isync, which is like sync in that it forces the CPU to wait until all instructions are completed. However, it also drops all prefetched instructions as well. This also only affects the current processor, so it is only sufficient as a read barrier.
    • Finally, there is lwsync, the "lightweight sync," which forces the core to synchronize to cache and orders most memory access so that reads after the barrier are coherent and all writes complete before it. The case it does not reorder is a read to a different address than the write. This is invariably the case we don't care about, but it means that it is really only a write barrier in practice.

    So which is faster?

    Since we know if we're on a G5, the solution then is to emit lwsync isync as the write and read barriers respectively, and eieio isync on the G3/G4 (since we have to account for multi-CPU G4s). Plus, an even better solution if we implement G3-specific code paths one day would be to ditch the sync instructions entirely on G3 since no G3 was ever a multiprocessor unit (and the BeBox was the only MP 603 I've ever encountered, for that matter). There is no particularly optimized path for any PowerPC processor with gcc for the equivalent atomic intrinsic, so we should use ours for the additional benefit it brings.

    I should note that the browser works just fine with no or incomplete barriers, but this might be pushing our luck on G5, so I think we'll just stay safe. We're already a lot faster.

I hope to have this ready after Thanksgiving. Then the next question will be 18 beta or 19 aurora; I haven't decided yet.

Saturday, March 10, 2012

11.0, musings and gripes (starting the unstable branch off with a bang)

Mozilla is considering their options for the release of Firefox 11 given some recent events (more presently), but I think it is important to establish our unstable branch in a timely manner to reassure you and our studio audience that TenFourFox isn't throwing in the towel with 10. (How alliterative.) Remember, for those new to this blog, that 11 through 16 beta are unstable builds. Do not use them if you're not prepared to deal with bugs; use 10.x.

Firefox 11 is not the big leap that 10 was and there is little new user-facing, but there are some important changes in the machinery that are a big deal to us. The two most important are SPDY support (preffed off by default), and improved animated GIF performance. Many people have noticed and I commented way back in Fx4 that a big pack of animated GIFs on a page can bring the browser to a crawl. This doesn't completely get it back to Fx3.6, but it's a lot better, and at least now I can look at the smilies in 68KMLA without watching the core temperatures rise on the G5.

SPDY is another big deal, mostly because Google is pushing it hard and we are, near as I can tell, the only browser for PPC OS X that supports it in any form. SPDY is a modified HTTP with nearly ubiquitous TLS encryption and DEFLATE compression that furthermore multiplexes data transfer rather than traditional simultaneous sockets or sequential request pipelining. Personally, I'm not wild about it; it makes a moderately heavy protocol into a nightmare and my suspicion of Google knows no bounds. However, suitably written, it is faster, and it is definitely faster than SSL. Google Chrome supports it, natch, and uses it to talk to Google properties, and Twitter has recently deployed it, so the ball is rolling and the IETF is evaluating it for HTTP/2.0. It will become enabled by default in the Fx13 timeframe and like it or not, it's here to stay.

In the local changes dept., I rewrote the G3/G4 square root routine to completely avoid red zone stores and this seems to have fixed issue 134 (and made the square root routine shorter and faster to boot). Because we do not have automated test coverage and did not detect this problem with our routine testing, I have decided to leave our inline square root disabled on 10-stable unless there is a huge hue and cry over performance regressions. So, if you are using a math-heavy application, you should probably be using unstable.

Let's also have a little episode of "Optimizing for the G5, part III" (see part II and part I) in which, yet again, we discover another nasty little secret about the PowerPC 970 that Apple never told anyone about. In this episode, we focus on the mtctr and b[c]ctr[l] instructions, which act sort of like a computed GOTO. You can load any arbitrary address into a general-purpose register and use mtctr to transfer that register into the counter "CTR" special-purpose register, used both as a (surprise) loop counter and as a branch target. Thusly loaded, you can use bctr to branch there, bctrl to call a subroutine there (computed GOSUB?), or bcctr and bcctrl to do those based on a condition register status.

We already know from our previous treatise that the G5, and in fact all POWER CPUs from the POWER4 (on which the 970 is based) through today's POWER7, divvies up the instruction stream into dispatch groups of approximately 4 instructions, give or take, with an optional branch in slot 5. There are certain restrictions about the dispatch groups. While we knew that mtctr liked to be first, in fact, you can only manipulate one SPR per dispatch group, and any SPR-manipulation instruction must be in the first slot, not just mtctr. So, if you have something like mtctr r5:mflr r0 (load CTR from GPR 5; load GPR 0 from link register), this gets executed in two groups.

But wait, it gets worse! Recall we mentioned that there is an optional slot 5 where a branch instruction can be carried along for the ride. So, slicko: we can say mtctr r24:bctr and simply branch to register 24 or whatever in one group, right? Yes, you can, but you pay a specific and severe penalty for mtctr and any CTR branch in the same dispatch group. The G3 and G4 don't have this problem, only the G5 and other "big POWER" chips.

While auditing Fx11 in Shark to make sure gcc wasn't putting bad instructions like mcrxr in despite our CPU tuning parameters, I noticed that a particular routine had a disproportionate amount of access called JaegerStubVeneer. All architectures except x86 use something called a "veneer" in JavaScript JaegerMonkey, which is used to change the return address when a native C or C++ routine has to throw an exception. It is generally a performance robber -- the ARM guys estimate its penalty at around 4% -- but there is no good way around it on RISC systems because the return address is generally in a register, not on the stack, so it can't be adjusted without having a veneer routine to go through and manipulate it. There are a lot of natives available even to a JIT routine, so it gets called frequently. The PowerPC veneer is very short and looked like this:

; Stash LR in the reserved spot in the VMFrame.
mflr r0
stw r0, 124(r1)

; Call r12.
mtctr r12
bctrl

; Get LR back.
lwz r0, 124(r1)
mtlr r0
blr


In Shark, that bctrl was amazingly hot because of this limit on the G5. Now it looks like this (and in the next release, we will align it to 16-bytes to favour the G5 and G4 even more):

; Prepare to call r12.
mtctr r12

; Stash LR in the reserved spot in the VMFrame. (second group)
mflr r0
stw r0, 124(r1)
#if defined(_PPC970_)
; Keep bctrl away from mtctr! This appears to be the optimal scheduling.
; If they are together, G5 pays a huge penalty, more than other SPRs.
; It actually got worse with two nops, and putting the stw with bctrl.
nop
nop
nop
#endif

; Branch. (third group)
bctrl

; Get LR back.
lwz r0, 124(r1)
mtlr r0
blr


As you can see from the comments, this required quite a bit of empiric testing. Optimal scheduling executes this in three dispatch groups: the mtctr all by itself, and then the mtlr and stw (saving the return address so that it can be adjusted if the stub throws), and then the bctrl. We put in three nops to force the bctrl to be off in its own dispatch group and not in the branch slot of the second one. Despite being longer, this actually cuts the execution time of the veneer in half on the G5, and this small change improves V8 by over two percent!

Interestingly, changing our entire branching system to split them in dispatch groups actually made performance worse, presumably because it made the code longer and bulkier and caused less branches to fit into their standard displacement (which are always faster). Admittedly, it's hard to do instruction-level scheduling based on the current design of the JIT. Instead, we just do this in certain specific places where we know they will occur together and always occur. The net improvement is nearly 3% for what is ultimately some extra no-ops and just a few lines of code.

I found in the LLVM sources an interesting little source file on G5 hazards and designing optimal dispatch groups which we will use in future optimizations. I attached it to issue 135 for the interested.

Now for the musings and gripes. Pwn2Own has come to its typical explosive end, and the schadenfreude is thick since Google Chrome's much ballyhooed sandbox took it on the chin (but props to Google, who are paying their promised $60,000 bounty to both successful attackers, and already have fixes on the way). Naturally, Firefox fell too, and the suspicion is that this is a cross-platform flaw which I am not allowed to talk about in detail (you'll find out soon enough). If the attack is as suspected, then we are vulnerable to it, although it would require special effort to attack Power Macs.

It is not clear if this will delay Firefox 11, but details on the exact flaw are not available, and launch day is Tuesday, so Mozilla may choose to fudge on the release date until more information surfaces. There are also some issues with video drivers that do not pose an concern to us. There will definitely be a followup release for 10-stable to address the security issue (I will wait to see if Mozilla retracts the 10.0.3 RC and issues a new one; we will follow suit), and if there is a security issue on 11 (this is not yet confirmed either), I will chemspill on this branch too.

We are presently pushing upstream our JaegerMonkey-with-type-inference backend to Mozilla as bug 731110, pending a couple higher priority fixes getting in first that clash with our work. That should be a nice benefit to 10.5 PPC builders building from the tree, will work with little change on AIX, and gives our Linux, Amiga and BSD brethren a starting point to convert it to SysV ABI. But it might not be there very long because of this interesting post by David Anderson in which he gives an ETA for IonMonkey, the next generation JavaScript JIT, of about 2-3 months. And, well, that really sucks. Ostensibly IonMonkey builds on the work already done with JaegerMonkey, but looking at the in-progress Mercurial tree for the ARM version of IonMonkey (which we would be based on), I say the hell it is: it's an almost completely different set of macro-ops and requires significantly longer and more complex logic for code generation. So it's kind of Sisyphean to finally get our JIT boulder up to the top after tracejit foundered and then have it roll back to the bottom in a few short months with IonMonkey. This thing had better wash windows and do dishes after the amount of effort that we invested in JM+TI. I just hope it lands after Firefox 17 so that we have some cycles to work on it.

Getting back to less gripe-y things, I was made aware of a TenFourBird project that is building a Thunderbird for PowerPC based on our changesets, and probably a few others of their own to comm-central. There are no builds available, but there is a build wiki, and I am delighted to see the project appear because I know that people have requested such a thing in the past. Please note that I know nothing about the person(s) working on it, and am not personally involved with it myself, so the usual caveats apply. Also, if you hate our icon, you'll really have a conniption with theirs. ;) Jokes aside, please let me know if you make contact with the developer(s) or have tried to build it with their instructions.

This is also a good time to point out a couple of other community builds. Tobias is maintaining up-to-date WebKit frameworks for 10.5 and has incorporated some of the JIT work for regular expressions. You should be alert for bugs, and it does not support 10.4, but Tobias has been a valued contributor to this project and I'm sure his builds will serve those of you well who need WebKit (but also make sure you support OmniWeb, which is still 10.4-compatible).

hikerxbiker is also issuing SeaMonkey builds for 10.5 PPC. These are built more or less off the tree and don't include any of our special features right now, but will eventually include the JIT when that gets through the pipeline. This might be a good option for those of you who need SeaMonkey's additional features, such as mail-news, Chatzilla, etc.

Anyway, release notes and builds (please read comments):
  • G3 build removed until further notice due to architecture tag failure build now corrected
  • G4/7400
  • G4/7450
  • G5

Sunday, February 12, 2012

10.0.2pre available, now with awesome, plus: more G5 optimization notes

After the unexpected 10.0.1 release comes now the beta that was supposed to be 10.0.1pre and is now 10.0.2pre. This is the next big leap in JM+TI that reworks branches from the simplistic always-far calls in 10.0.0 and 10.0.1 to a set of intelligent algorithms that try to favour the branch prediction of either the G3/G4 or the G5, both written by Ben. It also includes Dave's square root routine, slightly altered for efficiency. The G3/G4 square root version improves square-root heavy code significantly over the old JavaScript stub function version; V8 Raytrace improves by almost 12% (the G5 has square root in hardware, but this is a very good implementation). If I may say, it's a nice example of why POWER ISA is, well, powerful. Besides using the fast reciprocal square root estimate instruction in the 603 and up, it also makes heavy use of the built-in FPU fused multiply-add to do Newton's method in fewer instructions. I might also add that x86 only just added FMA; AMD finally implements FMA (as FMA4) in Bulldozer, but Intel won't have what PowerPC had in 1992 until Haswell in 2013 (and even then only as FMA3). So there.

Ben's branchwork is the centrepiece of this release, however, and while it improves SunSpider by a modest amount, it improves loopy benchmarks like V8 by a huge degree. My quad G5 improves by about 45%, for example, and gets consistently around 900-950ms in SunSpider (down from around 1050). Our 1GHz 7450 G4 doesn't improve as much on SunSpider (2750 down to around 2600, so not quite at our AWOAFY? target), but still improves by about 40% on V8. Part of achieving this is splitting the way branches are handled into "big POWER" (G5) and "little POWER" (G3/G4) versions. Ben's original work did much what my code in our dear nearly-departed tracejit did, which was to have four-word branch stanzas padded with nops so that if a branch target was too big for a regular b[l] or bc[l] instruction (the normal relative branching instructions on PowerPC), we had enough room to turn it into lis ori mtctr b[c]ctr[l] which load the destination address into a register (usually r0), transfer it to the CTR, and then branch to the CTR (conditionally or always). This achieved 45% on G5 in V8 and about 35% on G4. SunSpider dropped down to less than 920 on the G5 as well.

So this was already a great start, but Ben's next brainwave was to free up the G3/G4's limited cache by reducing the branch stanzas further to two words, either branching to the target as usual, or if not possible, branching to a "trampoline" (not to be confused with the trampoline the JavaScript interpreter uses to enter JITted code, which is common to all and I handwrote in assembly language) in a construct called the constant pool, which has the actual far call. The constant pool is part of the JS runtime, provided by Mozilla normally for the ARM JIT where they dump constants to be referenced by the JIT code, but it doesn't have to be used for that. By doing it this way, Ben keeps more running code in cache, and as predicted, on the G4 this improved performance by another 3-4% in aggregate. (Ben later added another piece that only uses the trampoline when absolutely necessary, which fractionally improved this number further on G4.)

On the G5, however, this actually hurt performance and SunSpider climbed to a poorer result, nearly 1100ms; even with the later tweak to reduce trampoline usage, it was still around 970ms. Our theory is that the G5, being (in Apple's words) "very hungry, very fast and very sequential," pays too big an aggregate penalty to branch to an out-of-line branch stanza when a far call is encountered, for two reasons. First, it appears to be a smaller penalty (possibly even near zero given the aggressive ordering of the G5 dispatch unit) to have empty nops inline that take up some small proportion of instruction cache, because when those empty instructions are patched to a far call in-place the G5 does not need to introduce bubbles in its pipeline doing a branch into the trampoline just to branch again. In addition, the hypernerds amongst you will recall from our previous treatise on G5 optimization that there can only be one branch instruction in a dispatch group. The trampoline version must run in (at least) two dispatch groups, because there are two branch instructions, one to the far call in the trampoline and one in the trampoline itself, and both will each introduce a pipeline bubble of variable length. The far call in-place will still introduce a bubble, but the entire branch can in the best case execute in a single dispatch group because there is only one branch (the branch-to-CTR instruction at the end), and there will be only one bubble.

Because the G5 is really just a POWER4 with a deeper pipeline and AltiVec, this property is likely shared by later "big POWER" CPUs like the POWER5, POWER6 and POWER7, as well as "big POWER-like" CPUs such as the G5, Cell PPE and Xenon. We will likely have consumers that will want this branch optimization strategy, but we don't want to lose the gains we get on "little POWER" (such as G3, G4, e500, QorIQ, Gekko/Broadway and PowerPC 4xx) with the cache-saving trampoline approach, so we do both. On the G5, the original four-word stanza branching is compiled in; everything else (G3, 7400 and 7450) use the two-word branch stanza with the constant pool trampoline. The best of both worlds is thus achieved.

One final note on G5 optimization: I tested compiling the browser with 32-byte-aligned blocks and labels in the JIT allocator, and that slowed things down too (it is not obvious whether this can be more fine-grained). For that matter, when I tried building the browser with 32-byte-aligned loops, jumps, functions and branch targets, that too slowed the browser over the 16-byte-alignment it uses now. It appears to be all a balancing act.

10.0.2-final will come out at the same time as the ESR release. I also plan to write the debug only 11 fairly soon. Please note that I will be transferring service from the Apple Network Server to the POWER6 this coming (USA) holiday weekend, so there may be some intermittent weirdness the weekend of the 18th/19th/20th. In the meantime, please grab a beta build and give it a spin on your architecture:

Friday, April 8, 2011

Attention G5 owners: your JavaScript no longer sucks*

(* or, what Apple never told developers about the PowerPC 970)

It's time for celebration. My quad 2.5GHz G5 is now benching 1760ms on SunSpider using the internal 4.0.1pre I've whipped up, and a whopping 93 runs/sec on Dromaeo. That's a little over half the raw interpreter's SunSpider runtime (about 3370ms), and over half of the limping 3710ms it gets with the current hybrid interpreter-nanojit used by the G5 build of 4.0s. I bet you lucky dogs with dual 2.7GHz G5 systems will see even better. Everything is faster. Birds are chirping. The river is high. Gold bricks are falling from the sky, and not on people. This is so tasty it will be in 4.0.1, as so far it's just as stable as the G3 and G4 versions and runs even faster.

Since this blog is designed around some technical nerdosity, let's engage in a little, and also collect what I've learned over the difficult process of getting the nanojit tuned for the G5.

First, a little history for people who don't know what the nanojit is. Mozilla has three layers of JavaScript: the base interpreter (SpiderMonkey), the nanojit (TraceMonkey) and the methodjit (JaegerMonkey). The base interpreter is the base interpreter: it's pretty good as interpreters go, but it's just interpreting code and does not compile it. Until Firefox 3.5, this was the only way JavaScript was run in Mozilla-based browsers. On Power Macs, 3.5 and 3.6 still use it, as do Camino and SeaMonkey, and so do all the community PowerPC builds of Firefox 4 other than us.

Mozilla had been looking at a means of compiling JavaScript, and collaborated with Adobe on what was then called Tamarin, a new JavaScript engine. Tamarin overall actually turned out to be slower for the purpose, but a lasting advance from the Tamarin project was the concept of the nanojit: a "tracing just-in-time compiler" that watched for frequently executed portions of code, then recorded the atomic operations being generated in a special intermediate language called LIR, and finally compiled the LIR into machine code. This nanojit-based accelerator was christened TraceMonkey (no, I don't know why they have such a simian fetish either). Versions were immediately made for x86, and later other architectures followed, including ARM, SH4, SPARC and even MIPS. Adobe wrote up one for the PowerPC too, but it was not complete enough to be used in Firefox, and this was not rectified in Firefox 3.6. That's why all official Mac PowerPC builds of Firefox have such comparatively slow JavaScript performance.

(In Firefox 4, Mozilla added a more conventional method-oriented compiler, based in part on Apple's Nitro JIT used in Safari. Since Firefox 4 is Intel and ARM only officially, the methodjit only runs on x86, x86_64 and ARM. This combination of the nanojit and methodjit is JaegerMonkey. There is no PowerPC methodjit.)

For TenFourFox beta 9, then, we took that partially written PowerPC nanojit and finished it up, thus being the first PowerPC-based Mozilla browser to implement TraceMonkey. My first tests were on my G5, which were very disappointing. Although many operations were significantly faster, many operations were significantly slower, and I concluded that the nanojit didn't seem to be a good fit for the PowerPC ... until alert users tested it themselves and told me it was ridiculously fast on the G3 and G4. To get around this, I compulsively benchmarked various JavaScript low-level operations on the G5 and cut out the ones that seemed to be slow. This was good enough to beat the baseline score for Dromaeo and V8, and not suck too badly at SunSpider, and this got released in beta 11. At least at that time, that seemed about as good as it was going to get for the PowerPC 970.

Earlier this week, I was busy working on enabling VMX (AltiVec)-based WebM decoding (which by the way is about halfway done -- I now have it integrated into the build system and have started converting the existing assembly language code to the dain-bramaged as assembler Apple stuck in Tiger) and while investigating an oddiment in the assembler's syntax I stumbled across a key note I hadn't seen mentioned anywhere else before, let alone in Apple's documentation. As I dug around a little more, the floodgates opened and more stuff came in, including -- what a win -- the critical piece that now enables the G5 nanojit to fly. In fact, not only does it fly, it also no longer needs the shortcuts to dump those slow low-level JavaScript operations (JSOPs) because those JSOPs are no longer slow.

These are useful things to know not only for those of us trying to wring more performance out of our old Macs, but also for people using later PowerPC and POWER designs, such as Wii, Xbox 360 or PlayStation 3 hackers, because the PowerPC 970 (being a modified POWER4) is more closely related to the modern day IBM POWER systems and the Cell, Broadway and Xenon CPUs than the G3s and G4s that preceded them. So, for posterity, here's how we juiced the G5 nanojit.

The G5's data cache acts differently. The G5, because of its deep pipeline, is constantly trying to keep that pipeline full and reduce latency, and tight code trying to prime the data cache needs to be aware of the difference. The AltiVec dst (to hint the processor about where the data stream is coming from) instruction, for example, requires that pipeline to drain and can seriously impact performance. We don't manipulate the D-cache presently in the nanojit, but I mention for completeness that the more basic dcbt is preferred to dst as it does not need to be serialized; the G5 uses a 128-byte cacheline, not a 32-byte one, so dcbtl (which uses the native cacheline size) would be better still. Analogously, for zeroing out a cacheline use dcbzl, not dcbz, which only operates on 32 bytes even on the G5 and is therefore inefficient by wasting valuable cache space.

dcba and dcbi should never be used; they are illegal on the G5. Mac OS X emulates dcba on the G5 by simply ignoring it, since it's just a hint, but this causes a software interrupt to do so -- more about that in our final point.

Remember dispatch groups. The nanojit we use has a construct called the "swaptimizer," which swaps independent instructions around in such a way that more of the CPU's execution units can be running at the same time (i.e., improve instruction-level parallelism) by hoisting up instructions to run overlapped with other instructions that don't depend on that earlier step's result. In certain cases, this can be effective enough to get some instructions seemingly "for free," particularly comparisons that can write out independent comparison results (the PPC has a series of "mini-registers" for this which is quite convenient). For in-order CPUs like the G3 (remember that the G3 is essentially an evolved 603 with all the advantages and disadvantages), this is very valuable, as it only retires instructions in program order despite being superscalar, and it should also be useful for other in-order POWER chips like Xenon, the Cell PPE and POWER6. It is less valuable on the 604 and G4, which both have some limited out-of-order execution, but the G4s in most Macs don't have the reordering logic of later G4 designs.

On the other hand, the G5 is an aggressively out-of-order architecture to improve its instruction-level parallelism in hardware, and can have over 200 instructions in-flight (compared to around 30 for the G4). To reduce the amount of silicon needed to track each and every one of these flying instructions, IBM designed the G5 to take dispatch groups of instructions instead and these groups are what the CPU tracks and what travel through the pipeline. Prior to grabbing the instructions, the G5 will attempt to reorder them for maximum performance. As a result, the swaptimizer is less effective here because it's cherry-picking the low-hanging optimization fruit that the G5 already schedules for, but it does help to pack groups better so that an earlier group is less likely to need the result of a later group.

Dispatch groups actually contain operations rather than individual instructions. In most cases this is an academic point, as the operation is usually the same as the instruction. Ordinarily dispatch groups contain five operation slots: four for individual operations, and an optional branch instruction, so most dispatch groups fall between every fourth instruction. The branch instruction always terminates a dispatch group, and a dispatch group may never have more than one branch. The distinction between operations and instructions will be covered in my next point. The pieces of the group then enter the processor and are issued and executed, and the groups, not the already reordered instructions, are then retired in-order.

Because the instructions execute for most intents and purposes as a unit, certain interdependencies can really hurt, most notoriously loads and stores to nearby addresses in the same group. For example, in the LIR operation d2i that converts a double to an integer, the stfd instruction should be in an earlier group than the lwz that follows it (remember that instructions in the nanojit are emitted working down from the top of memory) because they work on memory addresses that are very close to each other. Since this could lead to a problem with aliasing if they run together in the same group, the G5 has to "undo the group" and split them apart, leading to a pipeline spill as this won't be detected until the group is formed and its addresses are calculated. It improves performance to insert a couple of nop instructions between them, which essentially act as empty space in the group, and forces the G5 to split the group ahead of time. This is tunable; our code worked best with two, and gained a small but meaningful number of points on V8. In fact, this is particularly a problem for any code that has to interconvert between floating point and integer registers, because such conversion must store in memory as an intermediate step (there are no direct FPR to GPR moves in any Power Mac processor). Shark checks for this specific situation and Apple calls it a "LSU [Load Store Unit] Reject" in ADC.

Certain instructions do better at certain positions in the group, too. For example,
mtctr (move to counter register) should be first in a dispatch group if at all possible, and I'm sure there are others (please mention them in the comments; this was the one I found in most references). We can't really leverage this because we only use CTR as an indirect branching register in constructs like mtctr bctr, so we're always branching soon after anyway. However, if you use CTR as, you know, a counter maybe 8), then you might want to group your instructions to force it first in line with a group.

Avoid microcoded and cracked instructions. I mentioned that instructions and operations can mostly, but not always, be treated synonymously. The case where they are not is if the instruction in question is cracked or microcoded.

If the instruction is cracked, it is actually two operations in one, and takes up two operations in the dispatch group; if the instruction is microcoded, it takes up all the operation slots (i.e., it can only travel alone in the dispatch group). Here is Apple's list of G5 cracked and microcoded instructions. Although these instructions do exist and do execute in hardware, they are obviously slower than other instructions. Use them only if you have to, which brings us to our final and most important point.

Never, ever, ever use mcrxr on the G5. And this might well apply to some other POWER CPUs, by the way, even though it appears in IBM's documentation. Apple doesn't mention anywhere in their documentation I could find that mcrxr is software-emulated on the G5. Yikes! In fact, simply eliminating the use of this instruction was what restored the vast majority of our speed.

The reason this hit us so badly is an oddiment of the code the nanojit generates. Some background: overflows and other math exceptions are, if the instruction requests it, annotated in a special purpose register ("SPR") called the XER. The XER, amongst other things, tracks both overflow "OV" of the last instruction, and a summary overflow "SO" which is sticky (i.e., any instruction that sets it, it stays set, unlike OV where the next instruction where overflow tracking is requested clears it). The result of XER cannot itself be used in branching: only the condition registers "CR" can be used to conditionally branch, so the CPU mirrors SO to one of the condition registers if the instruction requests it also (CR0, in case you're interested, for integer math).

The nanojit spits out lots of guard code for every arithmetic operation -- and I do mean every operation, from simple increments in a loop to computing the national debt -- so that an overflow state can be correctly trapped as an exception and appropriately handled. Most of the time, overflow does not occur, and only one instruction is being tested for overflow, so we want to use OV (or we waste cycles clearing SO constantly for instructions that are unlikely to set it). However, we can't branch on OV directly, so here comes mcrxr. mcrxr stands for move exception register to condition register, which puts the relevant bits into the CR we specify and clears those bits from the XER. In our case, this puts OV in the greater-than field of the condition register, and now we can branch on that. Problem solved! ... at least on the G3 and G4, where mcrxr is in hardware.

On the G5, mcrxr is trapped and emulated by the operating system. This means every time the instruction is encountered, there is a fault, the pipelines probably have to empty, the OS examines the instruction, sees what it is, runs equivalent code (to be discussed momentarily), and returns to regular execution. If you look at the code the nanojit generates for a simple loop, you will see that each and every time the loop runs, the increment is tested for overflow, and the mcrxr instruction is trapped and emulated. No wonder it sucked so badly! Apple doesn't mention this anywhere except if you dig through their code or find the few obscure bug reports about why a previously snappy executable on the G4 performs so badly on a G5.

So here is the one case of where a microcoded instruction is better than the alternative. We now use this equivalent code in the G5 nanojit:
mfxer r0                ; put XER into register 0, which is scratch
mtcrf 128, r0 ; put the relevant bits into condition register 0
rlwinm r0, r0, 0, 0, 28 ; clear out the relevant bits in register 0
mtxer r0 ; and put them back into XER, clearing it

You will notice that except for rlwinm every one of these instructions is microcoded and requires an entire dispatch group all to itself. There's no way around it, but it's better than triggering an illegal instruction fault and forcing software emulation. Way better. We still use mcrxr on the G3 and G4, which have it in hardware, but the G5 now uses this equivalent which is much faster on the 970. But phooey on both Apple and IBM: IBM for taking the instruction out, and Apple for not documenting it.

Well, that's enough nerdosity. It'll be in 4.0.1. It's great. More G5 docs, until Apple decides to 404 them: