Assembly Primer Part 5 — Data Types

These are my notes for where I can see both PPC and SPU varying from ia32, as presented in the video Part 5 — Data Types.  There’s not a lot to be said about this one, so there’s just the one post for both PPC and SPU architectures.

The main problem with assembling the provided VariableDemo.s is that gas doesn’t seem to like the .bss section for either PPC or SPU, producing an error.  To be able to assemble this file on these architectures, I removed the .bss line and (obviously) removed (replaced) the ia32 asm instructions.  objdump shows that “.comm LargeBuffer 10000” is placed in .bss, as intended.

(At this point, I’m quite out of my depth as to why this difference between the architectures exists — if someone can enlighten me, that’d be great :)

I was interested to see that gdb has no problem accessing the unaligned variables on the SPU.  It’s worth noting that the assembler is quite happy to let you place data wherever you like (with great power comes great etc.).  And I think I need to take a closer look at the .align directive.

Previous assembly primer notes…

Part 1 — System Organization — PPC — SPU
Part 2 — Memory Organisation — SPU
Part 3 — GDB Usage Primer — PPC & SPU
Part 4 — Hello World — PPCSPU

Assembly Primer Part 4 — Hello World — SPU

These are my notes for where I can see SPU varying from ia32, as presented in the video Part 4 — Hello World.

I’ve written about syscalls on SPU before, here.  System calls can be performed using appropriately packed data and stopcode 0x2104, which is intercepted by the kernel.

The JustExit.s example in the video uses the exit syscall, which is explicitly excluded from being called by the SPU.  For the sake of the example, we can use the time syscall instead, and so a simple syscall looks something like this:

.data
syscall_time:
    .quad 13 # syscall number and return value
    .quad 0  # parameters
    .quad 0
    .quad 0
    .quad 0
    .quad 0
    .quad 0

.text
.globl _start
_start:
    stop 0x2104
    .int syscall_time

syscall_time is the structure used by the syscall (see struct spu_syscall_block and __linux_syscall()) with 13 in the first unsigned long long. (“Obviously”, .quad is 8 bytes :\).  If there were arguments to pass to the syscall, they would be placed in the six following .quads.

The address of the syscall block must follow directly after the stop instruction.  (I did wonder if there would be some trick to mixing the address with the program code — as you can see, no trick needed)

The syscall’s return value is placed in the first 8 bytes of the syscall block.

While it’s possible to use the write syscall, it’s rather painful as it requires a valid char* ea to be passed to be written, which is not readily accessible from the SPU.  The alternative is to use the __send_to_ppe() function — write() is one of the POSIX1 functions handled by newlib+libspe.  Of course, it has a slightly different calling mechanism to to __linux_syscall(), uses the JSRE_POSIX1 stopcode of 0x2101.  This works:

.data

HelloWorldString:
    .ascii "Hello world\n"

send_to_ppe_write:
    .int 1 # stdout
    .int 0 # pad
    .int 0 # pad
    .int 0 # pad
    .int HelloWorldString # char* in local store
    .int 0 # pad
    .int 0 # pad
    .int 0 # pad
    .int 12 # length
    .int 0 # pad
    .int 0 # pad
    .int 0 # pad

.text
.globl _start

_start:
    stop 0x2101
    .int send_to_ppe_write+0x1b000000

Although I’m sure it can be expressed more elegantly.

The magic number 0x1b000000 added to the address of send_to_ppe_write is derived from the “combined” variable from __send_to_ppe() with the values from jsre.h.

Alternatively…

I just realised that this works: if /proc/sys/kernel/randomize_va_space is zero, the address of the mapped SPU LS (from /proc/$PID/maps, as seen here) of 0xf7f70000 can be used as an offset to anything in local store, so the syscall will work with offset pointers:

.data

HelloWorldString:
    .ascii "Hello World\n"

syscall_write:
    .quad 4 # write
    .quad 1 # stdout
    .int  0 # gas doesn't seem to like doing the arithmetic in a .quad
    .int 0xf7f70000 + HelloWorldString # mapped address of string
    .quad 12 # length
    .quad 0
    .quad 0
    .quad 0

.text

.globl _start

_start:
    stop 0x2104
    .int syscall_write

Hideous :)

Previous assembly primer notes…

Part 1 — System Organization — PPC — SPU
Part 2 — Memory Organisation — SPU
Part 3 — GDB Usage Primer — PPC & SPU

Assembly Primer Part 4 — Hello World — PPC

These are my notes for where I can see PPC varying from ia32, as presented in the video Part 4 — Hello World.  Let me know if I’ve missed something important, obvious or got something wrong.

http://www.ibm.com/developerworks/library/l-ppc/ gives a good starting overview of PPC asm, including syscalls.  The syscall number goes into gpr0 and the args in gpr3 and following, so JustExit.s becomes:

.text
.globl _start

_start:
    li 0,1 # load 1 into reg 0
    li 3,0 # load 0 into reg 3
    sc     # system call

Simple enough.

Modifying the provided HelloWorldProgram.s example (and using the example from the above link) yields

.data

HelloWorldString:
    .ascii "Hello World\n"

.text

.globl _start

_start:
    # Load all the arguments for write ()

    li   0, 4  # syscall number of 4 (write)
    li   3, 1  # filenumber 1 (stdout)
    lis  4, HelloWorldString@ha   # load upper 16 bits of addr
    addi 4, 4, HelloWorldString@l # add lower 16 bits of addr
    li   5, 12 # length of string
    sc

    # exit the program
    li 0,1
    li 3,0
    sc

There’s some subtlety in the @ha and @l high and low parts of addresses that I don’t yet have my head around fully, but I’ll be coming back to this in a later part.

Previous assembly primer notes…

Part 1 — System Organization — PPC — SPU
Part 2 — Memory Organisation — SPU
Part 3 — GDB Usage Primer — PPC & SPU

Assembly Primer Part 3 — GDB Usage Primer

These are my notes for where I can see both PPC and SPU varying from ia32, as presented in the video Part 3 — GDB Usage Primer.  The usage of gdb is effectively the same for all three architectures — I’ve noted here some of the differences in the program being debugged.

In the ia32 disassembly of SimpleDemo.c, the call instruction is generated for function calls.

When compiled for PPC, I see bl — branch to address offset from bl instruction, placing the address of the following instruction in the link register (lr).

When compiled for SPU, I see brsl — branch to address offset from brsl instruction, placing the address of the following instruction into the specified register (typically r0, used as link register).

Neither PPC nor SPU pass args on the stack (at least not for two scalar args as for the add function in SimpleDemo.c).  Those values can still be seen as being present on the stack when examining it in gdb.  The reason appears to be that when compiled with no optimisation, a number of registers are pushed to the stack that are not needed.  Compiling at -O1 eliminates the superfluous pushes, so the args are no longer visible there, being present in the appropriate registers when the function is called.

(This document on calling conventions from Intel seems to say that args get passed to functions in regs where possible on ia32 as well… I can see it happening for amd64, not ia32)

As noted above, PPC and SPU store the function return address in the link register (lr or r0), not on the stack.

All three architectures appear to put the return value in a register (eax or r3).

Previous assembly primer notes…

Part 1 — System Organization — PPC — SPU
Part 2 — Memory Organisation — SPU

Assembly Primer Part 2 — Memory Organisation — SPU

These are my notes for where I can see SPU varying from ia32, as presented in the video Part 2 — Virtual Memory Organization.

(I didn’t notice see any significant differences between the presented information for ia32 and PPC — apart from what was noted from the first presentation — so there’s no separate post for that arch).

To compile SimpleDemo.c to examine on the SPU, you’ll need to add the -mstdmain option to spu-gcc (or spu-elf-gcc) so that the program will correctly receive the command line options.

If you examine the /proc/$PID/maps file when running a standalone SPU program, you’ll see something like this:

00100000-00120000 r-xp 00000000 00:00 0       [vdso]
0fd70000-0fd90000 r-xp 00000000 fe:02 1590608 /lib/libgcc_s.so.1
0fd90000-0fda0000 rw-p 00010000 fe:02 1590608 /lib/libgcc_s.so.1
0fdb0000-0fdd0000 r-xp 00000000 fe:02 292441  /lib/libpthread-2.11.2.so
0fdd0000-0fde0000 rw-p 00010000 fe:02 292441  /lib/libpthread-2.11.2.so
0fdf0000-0fe00000 r-xp 00000000 fe:02 292418  /lib/librt-2.11.2.so
0fe00000-0fe10000 rw-p 00000000 fe:02 292418  /lib/librt-2.11.2.so
0fe20000-0ff90000 r-xp 00000000 fe:02 292437  /lib/libc-2.11.2.so
0ff90000-0ffa0000 rw-p 00160000 fe:02 292437  /lib/libc-2.11.2.so
0ffa0000-0ffb0000 rw-p 00000000 00:00 0
0ffc0000-0ffe0000 r-xp 00000000 fe:02 1590211 /usr/lib/libspe2.so.2.2.80
0ffe0000-0fff0000 rw-p 00010000 fe:02 1590211 /usr/lib/libspe2.so.2.2.80
10000000-10010000 r-xp 00000000 fe:02 1821445 /usr/bin/elfspe
10010000-10020000 rw-p 00000000 fe:02 1821445 /usr/bin/elfspe
10020000-10050000 rwxp 00000000 00:00 0       [heap]
f7f60000-f7f70000 rw-p 00000000 00:00 0
f7f70000-f7fb0000 rw-s 00000000 00:13 9086
                                       /spu/spethread-2971-268566640/mem
f7fb0000-f7fc0000 rw-p 00000000 fe:02 1463963
                     /home/jonathan/AssemblyLanguagePrimer/SimpleDemoSPU
f7fc0000-f7fe0000 r-xp 00000000 fe:02 292430  /lib/ld-2.11.2.so
f7fe0000-f7ff0000 rw-p 00020000 fe:02 292430  /lib/ld-2.11.2.so
ffea0000-ffff0000 rw-p 00000000 00:00 0       [stack]

This is the information for the elfspe loader for the SPU program.

(The SPU’s local store is mapped into elfspe’s address space at 0xf7f7000.  This is with randomize_va_space set to zero, so it should always be in that location. This is possibly useful…)

There is no equivalent of this for the SPU program itself as there is no virtual memory mapping required (or possible) within the local store.  The state of the SPU’s memory state may be examined externally through the spufs interface provided (in this case, the file /spu/spethread-2971-268566640/mem from the above listing may be used to access the current SPU LS state). Or, of course, using gdb.

Previous assembly primer notes…

Part 1 — System Organization — PPCSPU

Assembly Primer Part 1 — System Organization — SPU

The platform I’m using is Debian Sid on a PS3 (3.15 OtherOS) with the spu-gcc toolchain.

These are my notes for where I can see the SPU varying from the ia32, as presented in the video Part 1 — System Organization.  Let me know if I’ve missed something important, obvious or got something wrong.

For reference, I’m using the SPU ABI and ISA docs.

General Purpose Registers

  • 128 128bit registers, treated as different data types depending on the instruction used.
    • r0 (LR) — Return Address / Link Register
    • r1 (SP) — Stack pointer information.
      • Word 0 — current stack pointer (always 16-byte aligned, grows down)
      • Word 1 — bytes of available stack space
    • r2 — Environment pointer (for languages that use one)
    • r3–r74 — First 72 qwords of a function’s argument list and its return value
    • r75–r79 — Scratch registers
    • r80–r127 — Local variable registers.  Preserved across function calls.
  • FPSCR — Floating-Point Status and Control Register
  • Channels — Used for various DMA operations, access to the decrementer, mailboxes and signalling.
  • SRR0 — Used to store the address of next instruction upon interrupt
  • LSLR — Local Store Limit Register.  0x0003ffff == 218-1 == 262143

Memory model

  • .text at address 0
  • Bottom of stack at 0x3ffff, effectively earlier if using -mstdmain.  (at least, afaict — could look more closely at how -mstdmain actually works…)

Assembly Primer Part 1 — System Organization — PPC

I found the videos introducing assembly language here to be of interest as my own understanding and experience with assembly is quite limited.  The videos are focussed on the ia32 architecture and reverse engineering, particularly for security exploits, and while these aspects don’t really excite me, the videos are well made and clear and the “Assembly Primer for Hackers” videos cover general assembly programming and details of machine architecture that are more broadly applicable.

I thought it would be interesting to work from these videos and make some notes on applying the concepts to the Cell BE’s PPU and SPU.

The platform I’m using is Debian Sid on a PS3 (3.15 OtherOS) with the standard system toolchain.

These are my notes for where I can see the PPU varying from the ia32, as presented in the video Part 1 — System Organization.  Let me know if I’ve missed something important, obvious or got something wrong.

For reference, I’m using the PPC Architecture Books (also found in the Cell SDK) and documentation for the PPC64 ABI.

Registers

Branch Processor

  • CR Condition Register — 32-bit. Provides a mechanism for testing (and branching). Eight 4-bit fields.
    • CR0–CR1 — Volatile condition code register fields
    • CR2–CR4 — Nonvolatile condition code register fields
    • CR5–CR7 — Volatile condition code register fields
  • LR Link Register (volatile) — 64-bit.  Can be used to provide branch target address for Branch Conditional to Link Register instruction
  • CTR Count Register (volatile) — 64-bit.  Can be used to hold a loop count that can be decremented during execution of Branch instructions containing appropriately coded BO field.  Also can be used to provide branch target address for the Branch Conditional to Count Register instruction.

Fixed-Pt Processing

  • GPR0–GPR31 — 64-bit General Purpose registers. Byte, halfword, word or doubleword, depending on instruction flags.  Supports byte, halfword, word, doubleword operand fetches and stores to storage.
    • r0 — Volatile register used in function prologs
    • r1 — Stack frame pointer
    • r2 — TOC pointer
    • r3 — Volatile parameter and return value register
    • r4–r10 — Volatile registers used for function parameters
    • r11 — Volatile register used in calls by pointer and as an environment pointer for languages which require one
    • r12 — Volatile register used for exception handling and glink code
    • r13 — Reserved for use as system thread ID
    • r14–r31 — Nonvolatile registers used for local variables
  • XER Fixed-Point Exception Register (volatile) — 64-bit.  Book I, p 32 has the details on this one.
  • MSR Machine State Register — 64-bit.  Defines the state of the processor. See Book III, p 10.

Float-Pt Processing

  • FPR0–FPR31 Floating-Point Registers — 64-bit. Single or double precision, depending on instruction flags.  Supports word and doubleword operand fetches and stores to storage.
    • f0 — Volatile scratch register
    • f1–f4 — Volatile floating point parameter and return value registers
    • f5–f13 — Volatile floating point parameter registers
    • f14–f31 — Nonvolatile registers
  • FPSCR Floading-Point Status and Control Register (volatile) — 32-bit. Status and control bits. See Book1, pp 87–89.

VMX

  • v0–v1 — Volatile scratch registers
  • v2–v13 — Volatile vector parameters registers
  • v14–v19 — Volatile scratch registers
  • v20–v31 — Non-volatile registers
  • vrsave — Non-volatile 32-bit register

Privileged

  • SRR0 & SRR1 Machine Status Save/Restore registers — 64-bit. Used to store machine state when an interrupt occurs.
  • DAR Data Address Register — 64-bit. Set by various interrupts to effective address associated with interrupt.
  • DSISR Data Storage Interrupt Status Register — 32-bit. Set to indicate the cause of various interrupts.
  • SPRG0–SPRG3 Software-use SPRs — 64-bit.  For use by privileged software.
  • CTRL Control Register — 32-bit. Controls an external I/O pin.
  • PVR Processor Version Register — 32-bit. Read-only.
  • PIR Processor Identification Register — 32-bit.

(there’s some hypervisor regs not listed here, and probably others…)

Virtual Memory Model

  • Default/standard location for .text appears to be 0x1000000
  • stack starts at 0xffffffff

Frame times are like pancakes

Time to generate image data, no DMA: 0.015962s

Time to generate data, with DMA to framebuffer: 0.048529s.  That’s not good.

Total amount of data transferred: one 1080p frame — ~8MB.

Measured average latency of 4*16KB DMA puts: 577µs — ~1000 times slower than expected.  Something’s really not right.

Oh.

First accesses to memory will be more expensive.

Time to generate and DMA first frame: 0.048529s

Time to generate and DMA second frame: 0.016370s

Time to generate and DMA subsequent frames: 0.015944s — slightly faster than with no DMA.

There’s still plenty of work to be done before it’s functional and interesting, but I may yet hit my goal of 60 fps for this project :)

Averaging more unsigned chars

Some further thoughts, continuing on from my previous average post

Alternate methods

sumb (sum bytes in halfwords) was an instruction I had overlooked, and was pointed out to me by ralferoo.  sumb calculates the sums of the four bytes of each word in two quadwords at a time. An add, rotate and shuffle would be all that would be needed to turn the result from two sumb calls into the desired averages.

Unfortunately, the input format I’m using isn’t well suited to sumb and it would appear to require a prohibitive number of shuffles to prepare the data appropriately – that said, there’s at least one place where I shuffle data before calling average4() that may be able to utilise sumb, so I intend to keep it in mind.

The avgb instruction calculates the average of the bytes in two quadwords.  It would be nice to be able to call avgb(avgb(a,b),avgb(c,d)) and to have the final result in 9 cycles, but there’s a fix-up necessary to correct the rounding that takes place in the calculation of the first two averages, and I’ve not yet been able to wrap my head around the correct method to do so.

Approximating

There are plenty of ways to very quickly get a result that is often — but not always — correct (like avgb).  One of these methods may be suitable for my particular needs, but I won’t know until later.  My goal for now is to attain a result that is as correct as possible and consider ways of speeding it up later, if needed.

Adding

I’m annoyed with myself that I missed this one, as I’ve seen it several times recently: rounding can be performed correctly with an addition and truncation. Where I had

    // add up the lower bits
    qword L = si_a(si_a(si_andbi(a,3),si_andbi(b,3)),
                   si_a(si_andbi(c,3),si_andbi(d,3)));

    // shift right 2 bits, again masking out shifted-in high bits
    R = si_a(R, si_andbi(si_rotqmbii(L,-2), 3));

    // shift right and mask for the rounding bit
    R = si_a(R, si_andbi(si_rotqmbii(L,-1), 1));

adding 2 to each uchar before truncating with rotqmbii means that the last line can be eliminated altogether, so the whole function now looks like:

qword average4(qword a, qword b, qword c, qword d) {
    // shift each right by 2 bits, masking shifted-in bits from the result
    qword au = si_andbi(si_rotqmbii(a, -2), 0x3f);
    qword bu = si_andbi(si_rotqmbii(b, -2), 0x3f);
    qword cu = si_andbi(si_rotqmbii(c, -2), 0x3f);
    qword du = si_andbi(si_rotqmbii(d, -2), 0x3f);

    // add them all up
    qword R = si_a(si_a(au,bu), si_a(cu,du));

    // add up the lower bits
    qword L = si_a(si_a(si_andbi(a,3),si_andbi(b,3)),
                   si_a(si_andbi(c,3),si_andbi(d,3)));

    // add 2
    L = si_a(L, si_ilh(0x202));

    // shift right 2 bits, again masking out shifted-in high bits
    R = si_a(R, si_andbi(si_rotqmbii(L,-2), 3));

    return R;
}

The difference is pretty minor — a couple of instructions and (when not inlined) it’s no faster.  For the program it’s used in I’m seeing around a 1.5% runtime reduction.

ioctl() and the spu — a tale of many magics

I’d achieved a working implementation of the small spu project I’ve been messing around with and wanted to move on to start pushing particular pixels (rather than debugging in text mode). My program, up to this point, has been a simple spu-only piece of code (launched via the elfspe loader under Linux), and I was reluctant to tack on a some kind of ppu manager just to set up the framebuffer — so, I though, why not do it from the spu itself? (Why not? Because it’s a stupid idea and so on.)

What’s needed to “set up the framebuffer”?  Magic.  Fortunately, the magic has been well documented by Mike Acton and you can get the source here. The trick becomes merely to get those files compiled for the spu, and the biggest barrier to doing that is the ioctl() system call.

There was no existing way to call ioctl() directly from the spu and several possible approaches were apparent.

Callback handler in libspe

libspe provides a number of callback functions for spu programs, allowing them some degree of access to and control of the wider system.  These are built on the __send_to_ppe() function found in newlib. __send_to_ppe() packs up a function’s arguments and stops the spu, signaling to libspe which of several handlers should be utilised.

My first partially-working attempt to access ioctl() used this approach, and once I’d worked out how to debug my way into libspe and back to the spu the solution was quite straightforward.  Particularly, libspe mmaps the spu’s local store, making it possible to pass a pointer to the spu’s local store directly to ioctl().

The third argument to ioctl() can be a pointer or a value and so some decoding of the ‘request’ argument would be required to handle particular cases correctly. While that’s probably not too difficult (probably — I’m not clear on the details), it’s beyond what I was interested in pursuing. For syscalls, though, there is a ‘better’ way…

Stopcode 0x2104

With __send_to_ppe(), newlib provides a similar __linux_syscall() function.  I couldn’t make much sense of it when I first looked at it as the 0x2104 stopcode it uses is not intercepted by libspe. Instead, it is magic and is intercepted directly by the kernel for the express purpose of handling syscalls. Hooray?

Almost. If the third argument to ioctl() is a pointer, it needs to contain a valid ea. Unfortunately, there appears to be no sane way for a spu to mmap it’s own local store, meaning an lsa cannot be converted to a valid ea without some external assistance, and so we must consider other options…

__ea

Named address spaces are an extension to the C language that provide a way to access eas from a spu in a somewhat transparent fashion.  On the spu, these work by qualifying pointers with __ea to indicate that they contain an ea, and the complier handles the intervening magic (gcc-4.5 and the various versions of gcc and xlc that have shipped with the IBM SDK have support for this extension).

While this method might work, I didn’t want to give up a chunk of my local store for the software cache that the implementation in gcc uses — I have a hunch that I’ll will almost run out of space when I add some extra DMA buffers to this program. (And I’m not sure what’s needed to get  __ea storage working correctly without a separate ppu context).

A more convoluted method

In the absence of a neater approach, here’s how I got it working:

  1. mmap some scratch space in main memory (using mmap_eaddr() from newlib)
  2. call ioctl() with the address of that scratch space
  3. DMA the data from the scratch space to local store

Something like:

void* scratch = (void*)(uint32_t)mmap_eaddr(0ULL, size, PROT_READ|PROT_WRITE,
                                            MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
ioctl(fb_fd, FBIOGET_VBLANK, scratch);
struct fb_vblank vblank;
spu_mfcdma32(&vblank, (uint32_t)scratch, ROUNDUP16(sizeof(vblank)),
             0, MFC_GET_CMD);
mfc_write_tag_mask(1);
spu_mfcstat(MFC_TAG_UPDATE_ALL);

And so, ugly as it is, I can now call ioctl() from spu code.  Lather, rinse & repeat as desired.

Of course, there were a few other problems to solve: because I was compiling cp_{fb,vt}.c for the spu but using the (ppu) system headers to get the fb defns, the compiler sees the prototypes for the system mmap, munmap, printf and snprintf functions. Extra wrappers are needed for each of those (and so I now know about the v*printf family).

Once all that is done, it works. I can push pixels to the screen from the spu.

Flipping and vsync is an interesting, and slightly awkward, case as they are passed the address of a value, not the value itself (for no readily apparent reason), so the values are allocated early on and referenced as needed.

The implementation can be found here. It’s functional. :)  There are many opportunities to tidy it up and simplify it. Right now it’s a fairly direct and naive port from the original.

My thanks to Mike Acton for the original setup code, and to Ken Werner for helping me get my head around the problem and its possible solutions.