/*
 * Try to tickle erratum 16 in the MaverickCrunch,
 * whereby the result of a cfaddd is picked up wrong by cfstrd
 * if the cfstrd occurs in exactly the moment when the result is(n't!) ready.
 */

/* Invent a sum that will leave something interesting in both 32-bit halves of the result */
volatile double a = 420000000000.0, b = 42.0, c = 0;
volatile double x = 430000000086.0, y = 43.0, z = 0;

int scratch[2];

/* Do c = a * b, z = x - y
 * The time between the add and the result being taken by cfstrd is critical
 * so ensure there are no wait states involved by preloading all arguments in advance.
 */
void
erratum16()
{
	register volatile double *ap asm("r0") = &a;
	register volatile double *bp asm("r1") = &b;
	register volatile double *cp asm("r2") = &c;
	register volatile double *xp asm("r3") = &x;
	register volatile double *yp asm("r4") = &y;
	register volatile double *zp asm("r5") = &z;
	register volatile int *r7 asm("r7") = scratch;
	/* We don't bother declaring the maverick registers as mvd0-8 are function scratch
	 * registers and nothing else should use them */

	asm("cfldrd	mvd0, [r0]" : : "r"(ap));
	asm("cfldrd	mvd1, [r1]" : : "r"(bp));
	asm("cfldrd	mvd3, [r3]" : : "r"(xp));
	asm("cfldrd	mvd4, [r4]" : : "r"(yp));
	/* wait until they are definitely in the registers: 16 ARM cycles */
	asm("nop;nop;nop;nop;nop;nop;nop;nop");
	asm("nop;nop;nop;nop;nop;nop;nop;nop");
	asm("cfaddd	mvd2, mvd0, mvd1");
	asm("cfsubd	mvd5, mvd3, mvd4");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("nop");
	asm("cfstrd	mvd2, [r2]"   : : "r"(cp) );
	asm("stm	r7, {r5, r6}" : : "r"(r7) );
	asm("cfstrd	mvd5, [r5]"   : : "r"(zp) );
	asm("nop;nop;nop;nop");			/* Just for luck */
}

#include <stdio.h>
#include <stdlib.h>

main()
{
	erratum16();

	if (c != a + b) fprintf(stderr, "c = %f\n", c);
	if (z != x - y) fprintf(stderr, "z = %f\n", z);
	exit (c != 420000000042.0 || z != 430000000043.0);	/* 0 in success, 1 on failure */
}
