1/* { dg-do link } */
2/* { dg-require-effective-target sync_char_short } */
3/* { dg-final { simulate-thread } } */
4
5
6#include <stdio.h>
7#include "simulate-thread.h"
8
9
10/* Testing load for atomicity is a little trickier.
11
12   Set up the atomic value so that it changes value after every instruction
13   is executed.
14
15   Simply alternating between 2 values wouldn't be sufficient since a load of
16   one part, followed by the load of the second part 2 instructions later would
17   appear to be valid.
18
19   set up a table of 16 values which change a bit in every byte of the value
20   each time, this will give us a 16 instruction cycle before repetition
21   kicks in, which should be sufficient to detect any issues.  Just to be sure,
22   we also change the table cycle size during execution.
23
24   The end result is that all loads should always get one of the values from
25   the table. Any other pattern means the load failed.  */
26
27unsigned short ret;
28unsigned short value = 0;
29unsigned short result = 0;
30unsigned short table[16] = {
310x0000,
320x1111,
330x2222,
340x3333,
350x4444,
360x5555,
370x6666,
380x7777,
390x8888,
400x9999,
410xAAAA,
420xBBBB,
430xCCCC,
440xDDDD,
450xEEEE,
460xFFFF
47};
48
49int table_cycle_size = 16;
50
51/* Return 0 if 'result' is a valid value to have loaded.  */
52int verify_result ()
53{
54  int x;
55  int found = 0;
56
57  /* Check entire table for valid values.  */
58  for (x = 0; x < 16 ; x++)
59    if (result == table[x])
60      {
61	found = 1;
62	break;
63      }
64
65  if (!found)
66    printf("FAIL: Invalid result returned from fetch\n");
67
68  return !found;
69}
70
71/* Iterate VALUE through the different valid values. */
72void simulate_thread_other_threads ()
73{
74  static int current = 0;
75
76  if (++current >= table_cycle_size)
77    current = 0;
78  value = table[current];
79}
80
81int simulate_thread_step_verify ()
82{
83  return verify_result ();
84}
85
86int simulate_thread_final_verify ()
87{
88  return verify_result ();
89}
90
91__attribute__((noinline))
92void simulate_thread_main()
93{
94  int x;
95
96  /* Execute loads with value changing at various cyclic values.  */
97  for (table_cycle_size = 16; table_cycle_size > 4 ; table_cycle_size--)
98    {
99      ret = __atomic_load_n (&value, __ATOMIC_SEQ_CST);
100      /* In order to verify the returned value (which is not atomic), it needs
101	 to be atomically stored into another variable and check that.  */
102      __atomic_store_n (&result, ret, __ATOMIC_SEQ_CST);
103
104      /* Execute the fetch/store a couple of times just to ensure the cycles
105         have a chance to be interesting.  */
106      ret = __atomic_load_n (&value, __ATOMIC_SEQ_CST);
107      __atomic_store_n (&result, ret, __ATOMIC_SEQ_CST);
108    }
109}
110
111int
112main()
113{
114  simulate_thread_main ();
115  simulate_thread_done ();
116  return 0;
117}
118