
#include <stdio.h>
#include <strings.h>

#define	IC_SIZE			(16*1024)		// icache size;
#define	IC_LINE			32				// icache line size;
#define	IC_LINES		(IC_SIZE / IC_LINE)	// icache line size;
#define	N_HIT_JMPS		(IC_SIZE/4)		// icache size / instr len;
#define	N_MISS_JMPS		(2*N_HIT_JMPS)	// jump between cache aliases;

int hits[N_HIT_JMPS];
int miss[N_MISS_JMPS];
unsigned short tags[IC_LINES];

// make jump maze;

int
main(int argc, char **argv)
{
	int n, at, to;
	int line, addr, tag;
	int used, hit;

	// hit maze;
	// hit in line once it was brought in;

	printf(
		"/* ijm.s jump maze for cache tests */\n"
		"\n"
		"/* hit maze, after icache fill, all hits */\n"
		"\t.section .ijh, \"ax\"\n"
		"\t.code 32\n"
		"\t.global JmpMazeHit\n"
		"JmpMazeHit:\n"
	);
	bzero(hits, sizeof(hits));
	at = 0;
	for(n = 0; n < N_HIT_JMPS; n++) {
		hits[at] = -1;				// can't jump to itself;
		if(n == (N_HIT_JMPS - 1)) {
			to = N_HIT_JMPS;
		} else {
			do {
				to = random() & (N_HIT_JMPS - 1);
				used = hits[to];
			} while(used);
		}
		hits[at] = to;
		at = to;
	}

	at = 0;
	for(n = 0; n < N_HIT_JMPS; n++) {
		if((n & 7) == 0)
			printf("\n");
		to = hits[n];
		if(to == N_HIT_JMPS)
			printf("ijh%04x: bx lr\n", at);
		else
			printf("ijh%04x: b ijh%04x\n", at, to * 4);
		at += 4;
	}
	printf("\n");

	// miss maze;
	// miss on cache alias line all the time,
	// so all lines are brought in again;
	// cache is filled with lines from hit test,
	// so all fetches from miss region are misses;

	printf(
		"/* miss maze, always a miss on jump target */\n"
		"\t.section .ijm, \"ax\"\n"
		"\t.code 32\n"
		"\t.global JmpMazeMiss\n"
		"JmpMazeMiss:\n"
	);
	bzero(miss, sizeof(miss));
	bzero(tags, sizeof(tags));		// all lines are miss;
	at = 0;
	for(n = 0; n < N_MISS_JMPS; n++) {
		miss[at] = -1;				// can't jump to itself;
		if(n == (N_MISS_JMPS - 1)) {
			to = N_MISS_JMPS;
		} else {
			do {
				to = random() & (N_MISS_JMPS - 1);
				line = (to >> 3) & (IC_LINES - 1);
				addr = (to >> 3) / IC_LINES;
				tag = tags[line];
				hit = (tag & 0x8000) && (tag == addr);
				used = miss[to];
			} while(hit | used);
			tags[line] = 0x8000 | addr;		// store tag;
		}
		miss[at] = to;
		at = to;
	}

	at = 0;
	for(n = 0; n < N_MISS_JMPS; n++) {
		if((n & 7) == 0)
			printf("\n");
		to = miss[n];
		if(to == N_MISS_JMPS)
			printf("ijm%04x: bx lr\n", at);
		else
			printf("ijm%04x: b ijm%04x\n", at, to * 4);
		at += 4;
	}
	printf("\n");
	return(0);
}

