1/*
2 * asm/tbx.h
3 *
4 * Copyright (C) 2000-2012 Imagination Technologies.
5 *
6 * This program is free software; you can redistribute it and/or modify it under
7 * the terms of the GNU General Public License version 2 as published by the
8 * Free Software Foundation.
9 *
10 * Thread binary interface header
11 */
12
13#ifndef _ASM_METAG_TBX_H_
14#define _ASM_METAG_TBX_H_
15
16/* for CACHEW_* values */
17#include <asm/metag_isa.h>
18/* for LINSYSEVENT_* addresses */
19#include <asm/metag_mem.h>
20
21#ifdef  TBI_1_4
22#ifndef TBI_MUTEXES_1_4
23#define TBI_MUTEXES_1_4
24#endif
25#ifndef TBI_SEMAPHORES_1_4
26#define TBI_SEMAPHORES_1_4
27#endif
28#ifndef TBI_ASYNC_SWITCH_1_4
29#define TBI_ASYNC_SWITCH_1_4
30#endif
31#ifndef TBI_FASTINT_1_4
32#define TBI_FASTINT_1_4
33#endif
34#endif
35
36
37/* Id values in the TBI system describe a segment using an arbitrary
38   integer value and flags in the bottom 8 bits, the SIGPOLL value is
39   used in cases where control over blocking or polling behaviour is
40   needed. */
41#define TBID_SIGPOLL_BIT    0x02 /* Set bit in an Id value to poll vs block */
42/* Extended segment identifiers use strings in the string table */
43#define TBID_IS_SEGSTR( Id ) (((Id) & (TBID_SEGTYPE_BITS>>1)) == 0)
44
45/* Segment identifiers contain the following related bit-fields */
46#define TBID_SEGTYPE_BITS   0x0F /* One of the predefined segment types */
47#define TBID_SEGTYPE_S      0
48#define TBID_SEGSCOPE_BITS  0x30 /* Indicates the scope of the segment */
49#define TBID_SEGSCOPE_S     4
50#define TBID_SEGGADDR_BITS  0xC0 /* Indicates access possible via pGAddr */
51#define TBID_SEGGADDR_S     6
52
53/* Segments of memory can only really contain a few types of data */
54#define TBID_SEGTYPE_TEXT   0x02 /* Code segment */
55#define TBID_SEGTYPE_DATA   0x04 /* Data segment */
56#define TBID_SEGTYPE_STACK  0x06 /* Stack segment */
57#define TBID_SEGTYPE_HEAP   0x0A /* Heap segment */
58#define TBID_SEGTYPE_ROOT   0x0C /* Root block segments */
59#define TBID_SEGTYPE_STRING 0x0E /* String table segment */
60
61/* Segments have one of three possible scopes */
62#define TBID_SEGSCOPE_INIT     0 /* Temporary area for initialisation phase */
63#define TBID_SEGSCOPE_LOCAL    1 /* Private to this thread */
64#define TBID_SEGSCOPE_GLOBAL   2 /* Shared globally throughout the system */
65#define TBID_SEGSCOPE_SHARED   3 /* Limited sharing between local/global */
66
67/* For segment specifier a further field in two of the remaining bits
68   indicates the usefulness of the pGAddr field in the segment descriptor
69   descriptor. */
70#define TBID_SEGGADDR_NULL     0 /* pGAddr is NULL -> SEGSCOPE_(LOCAL|INIT) */
71#define TBID_SEGGADDR_READ     1 /* Only read    via pGAddr */
72#define TBID_SEGGADDR_WRITE    2 /* Full access  via pGAddr */
73#define TBID_SEGGADDR_EXEC     3 /* Only execute via pGAddr */
74
75/* The following values are common to both segment and signal Id value and
76   live in the top 8 bits of the Id values. */
77
78/* The ISTAT bit indicates if segments are related to interrupt vs
79   background level interfaces a thread can still handle all triggers at
80   either level, but can also split these up if it wants to. */
81#define TBID_ISTAT_BIT    0x01000000
82#define TBID_ISTAT_S      24
83
84/* Privilege needed to access a segment is indicated by the next bit.
85
86   This bit is set to mirror the current privilege level when starting a
87   search for a segment - setting it yourself toggles the automatically
88   generated state which is only useful to emulate unprivileged behaviour
89   or access unprivileged areas of memory while at privileged level. */
90#define TBID_PSTAT_BIT    0x02000000
91#define TBID_PSTAT_S      25
92
93/* The top six bits of a signal/segment specifier identifies a thread within
94   the system. This represents a segments owner. */
95#define TBID_THREAD_BITS  0xFC000000
96#define TBID_THREAD_S     26
97
98/* Special thread id values */
99#define TBID_THREAD_NULL   (-32) /* Never matches any thread/segment id used */
100#define TBID_THREAD_GLOBAL (-31) /* Things global to all threads */
101#define TBID_THREAD_HOST   ( -1) /* Host interface */
102#define TBID_THREAD_EXTIO  (TBID_THREAD_HOST)   /* Host based ExtIO i/f */
103
104/* Virtual Id's are used for external thread interface structures or the
105   above special Id's */
106#define TBID_IS_VIRTTHREAD( Id ) ((Id) < 0)
107
108/* Real Id's are used for actual hardware threads that are local */
109#define TBID_IS_REALTHREAD( Id ) ((Id) >= 0)
110
111/* Generate a segment Id given Thread, Scope, and Type */
112#define TBID_SEG( Thread, Scope, Type )                           (\
113    ((Thread)<<TBID_THREAD_S) + ((Scope)<<TBID_SEGSCOPE_S) + (Type))
114
115/* Generate a signal Id given Thread and SigNum */
116#define TBID_SIG( Thread, SigNum )                                        (\
117    ((Thread)<<TBID_THREAD_S) + ((SigNum)<<TBID_SIGNUM_S) + TBID_SIGNAL_BIT)
118
119/* Generate an Id that solely represents a thread - useful for cache ops */
120#define TBID_THD( Thread ) ((Thread)<<TBID_THREAD_S)
121#define TBID_THD_NULL      ((TBID_THREAD_NULL)  <<TBID_THREAD_S)
122#define TBID_THD_GLOBAL    ((TBID_THREAD_GLOBAL)<<TBID_THREAD_S)
123
124/* Common exception handler (see TBID_SIGNUM_XXF below) receives hardware
125   generated fault codes TBIXXF_SIGNUM_xxF in it's SigNum parameter */
126#define TBIXXF_SIGNUM_IIF   0x01 /* General instruction fault */
127#define TBIXXF_SIGNUM_PGF   0x02 /* Privilege general fault */
128#define TBIXXF_SIGNUM_DHF   0x03 /* Data access watchpoint HIT */
129#define TBIXXF_SIGNUM_IGF   0x05 /* Code fetch general read failure */
130#define TBIXXF_SIGNUM_DGF   0x07 /* Data access general read/write fault */
131#define TBIXXF_SIGNUM_IPF   0x09 /* Code fetch page fault */
132#define TBIXXF_SIGNUM_DPF   0x0B /* Data access page fault */
133#define TBIXXF_SIGNUM_IHF   0x0D /* Instruction breakpoint HIT */
134#define TBIXXF_SIGNUM_DWF   0x0F /* Data access read-only fault */
135
136/* Hardware signals communicate events between processing levels within a
137   single thread all the _xxF cases are exceptions and are routed via a
138   common exception handler, _SWx are software trap events and kicks including
139   __TBISignal generated kicks, and finally _TRx are hardware triggers */
140#define TBID_SIGNUM_SW0     0x00 /* SWITCH GROUP 0 - Per thread user */
141#define TBID_SIGNUM_SW1     0x01 /* SWITCH GROUP 1 - Per thread system */
142#define TBID_SIGNUM_SW2     0x02 /* SWITCH GROUP 2 - Internal global request */
143#define TBID_SIGNUM_SW3     0x03 /* SWITCH GROUP 3 - External global request */
144#ifdef TBI_1_4
145#define TBID_SIGNUM_FPE     0x04 /* Deferred exception - Any IEEE 754 exception */
146#define TBID_SIGNUM_FPD     0x05 /* Deferred exception - Denormal exception */
147/* Reserved 0x6 for a reserved deferred exception */
148#define TBID_SIGNUM_BUS     0x07 /* Deferred exception - Bus Error */
149/* Reserved 0x08-0x09 */
150#else
151/* Reserved 0x04-0x09 */
152#endif
153/* Reserved 0x0A-0x0F */
154#define TBID_SIGNUM_TRT     0x10 /* Timer trigger */
155#define TBID_SIGNUM_LWK     0x11 /* Low level kick */
156#define TBID_SIGNUM_XXF     0x12 /* Fault handler - receives ALL _xxF sigs */
157#ifdef TBI_1_4
158#define TBID_SIGNUM_DFR     0x13 /* Deferred Exception handler */
159#else
160#define TBID_SIGNUM_FPE     0x13 /* FPE Exception handler */
161#endif
162/* External trigger one group 0x14 to 0x17 - per thread */
163#define TBID_SIGNUM_TR1(Thread) (0x14+(Thread))
164#define TBID_SIGNUM_T10     0x14
165#define TBID_SIGNUM_T11     0x15
166#define TBID_SIGNUM_T12     0x16
167#define TBID_SIGNUM_T13     0x17
168/* External trigger two group 0x18 to 0x1b - per thread */
169#define TBID_SIGNUM_TR2(Thread) (0x18+(Thread))
170#define TBID_SIGNUM_T20     0x18
171#define TBID_SIGNUM_T21     0x19
172#define TBID_SIGNUM_T22     0x1A
173#define TBID_SIGNUM_T23     0x1B
174#define TBID_SIGNUM_TR3     0x1C /* External trigger N-4 (global) */
175#define TBID_SIGNUM_TR4     0x1D /* External trigger N-3 (global) */
176#define TBID_SIGNUM_TR5     0x1E /* External trigger N-2 (global) */
177#define TBID_SIGNUM_TR6     0x1F /* External trigger N-1 (global) */
178#define TBID_SIGNUM_MAX     0x1F
179
180/* Return the trigger register(TXMASK[I]/TXSTAT[I]) bits related to
181   each hardware signal, sometimes this is a many-to-one relationship. */
182#define TBI_TRIG_BIT(SigNum)                                      (\
183    ((SigNum) >= TBID_SIGNUM_TRT) ? 1<<((SigNum)-TBID_SIGNUM_TRT) :\
184    ((SigNum) == TBID_SIGNUM_LWK) ?                                \
185                         TXSTAT_KICK_BIT : TXSTATI_BGNDHALT_BIT    )
186
187/* Return the hardware trigger vector number for entries in the
188   HWVEC0EXT table that will generate the required internal trigger. */
189#define TBI_TRIG_VEC(SigNum)                                      (\
190    ((SigNum) >= TBID_SIGNUM_T10) ? ((SigNum)-TBID_SIGNUM_TRT) : -1)
191
192/* Default trigger masks for each thread at background/interrupt level */
193#define TBI_TRIGS_INIT( Thread )                           (\
194    TXSTAT_KICK_BIT + TBI_TRIG_BIT(TBID_SIGNUM_TR1(Thread)) )
195#define TBI_INTS_INIT( Thread )                            (\
196    TXSTAT_KICK_BIT + TXSTATI_BGNDHALT_BIT                  \
197                    + TBI_TRIG_BIT(TBID_SIGNUM_TR2(Thread)) )
198
199#ifndef __ASSEMBLY__
200/* A spin-lock location is a zero-initialised location in memory */
201typedef volatile int TBISPIN, *PTBISPIN;
202
203/* A kick location is a hardware location you can write to
204 * in order to cause a kick
205 */
206typedef volatile int *PTBIKICK;
207
208#if defined(METAC_1_0) || defined(METAC_1_1)
209/* Macro to perform a kick */
210#define TBI_KICK( pKick ) do { pKick[0] = 1; } while (0)
211#else
212/* #define METAG_LIN_VALUES before including machine.h if required */
213#ifdef LINSYSEVENT_WR_COMBINE_FLUSH
214/* Macro to perform a kick - write combiners must be flushed */
215#define TBI_KICK( pKick )                                                do {\
216    volatile int *pFlush = (volatile int *) LINSYSEVENT_WR_COMBINE_FLUSH;    \
217    pFlush[0] = 0;                                                           \
218    pKick[0]  = 1;                                                } while (0)
219#endif
220#endif /* if defined(METAC_1_0) || defined(METAC_1_1) */
221#endif /* ifndef __ASSEMBLY__ */
222
223#ifndef __ASSEMBLY__
224/* 64-bit dual unit state value */
225typedef struct _tbidual_tag_ {
226    /* 32-bit value from a pair of registers in data or address units */
227    int U0, U1;
228} TBIDUAL, *PTBIDUAL;
229#endif /* ifndef __ASSEMBLY__ */
230
231/* Byte offsets of fields within TBIDUAL */
232#define TBIDUAL_U0      (0)
233#define TBIDUAL_U1      (4)
234
235#define TBIDUAL_BYTES   (8)
236
237#define TBICTX_CRIT_BIT 0x0001  /* ASync state saved in TBICTX */
238#define TBICTX_SOFT_BIT 0x0002  /* Sync state saved in TBICTX (other bits 0) */
239#ifdef TBI_FASTINT_1_4
240#define TBICTX_FINT_BIT 0x0004  /* Using Fast Interrupts */
241#endif
242#define TBICTX_FPAC_BIT 0x0010  /* FPU state in TBICTX, FPU active on entry */
243#define TBICTX_XMCC_BIT 0x0020  /* Bit to identify a MECC task */
244#define TBICTX_CBUF_BIT 0x0040  /* Hardware catch buffer flag from TXSTATUS */
245#define TBICTX_CBRP_BIT 0x0080  /* Read pipeline dirty from TXDIVTIME */
246#define TBICTX_XDX8_BIT 0x0100  /* Saved DX.8 to DX.15 too */
247#define TBICTX_XAXX_BIT 0x0200  /* Save remaining AX registers to AX.7 */
248#define TBICTX_XHL2_BIT 0x0400  /* Saved hardware loop registers too */
249#define TBICTX_XTDP_BIT 0x0800  /* Saved DSP registers too */
250#define TBICTX_XEXT_BIT 0x1000  /* Set if TBICTX.Ext.Ctx contains extended
251                                   state save area, otherwise TBICTX.Ext.AX2
252                                   just holds normal A0.2 and A1.2 states */
253#define TBICTX_WAIT_BIT 0x2000  /* Causes wait for trigger - sticky toggle */
254#define TBICTX_XCBF_BIT 0x4000  /* Catch buffer or RD extracted into TBICTX */
255#define TBICTX_PRIV_BIT 0x8000  /* Set if system uses 'privileged' model */
256
257#ifdef METAC_1_0
258#define TBICTX_XAX3_BIT 0x0200  /* Saved AX.5 to AX.7 for XAXX */
259#define TBICTX_AX_REGS  5       /* Ax.0 to Ax.4 are core GP regs on CHORUS */
260#else
261#define TBICTX_XAX4_BIT 0x0200  /* Saved AX.4 to AX.7 for XAXX */
262#define TBICTX_AX_REGS  4       /* Default is Ax.0 to Ax.3 */
263#endif
264
265#ifdef TBI_1_4
266#define TBICTX_CFGFPU_FX16_BIT  0x00010000               /* Save FX.8 to FX.15 too */
267
268/* The METAC_CORE_ID_CONFIG field indicates omitted DSP resources */
269#define METAC_COREID_CFGXCTX_MASK( Value )                                 (\
270	( (((Value & METAC_COREID_CFGDSP_BITS)>>                                \
271	             METAC_COREID_CFGDSP_S      ) == METAC_COREID_CFGDSP_MIN) ? \
272	         ~(TBICTX_XHL2_BIT+TBICTX_XTDP_BIT+                             \
273	           TBICTX_XAXX_BIT+TBICTX_XDX8_BIT ) : ~0U )                    )
274#endif
275
276/* Extended context state provides a standardised method for registering the
277   arguments required by __TBICtxSave to save the additional register states
278   currently in use by non general purpose code. The state of the __TBIExtCtx
279   variable in the static space of the thread forms an extension of the base
280   context of the thread.
281
282   If ( __TBIExtCtx.Ctx.SaveMask == 0 ) then pExt is assumed to be NULL and
283   the empty state of  __TBIExtCtx is represented by the fact that
284   TBICTX.SaveMask does not have the bit TBICTX_XEXT_BIT set.
285
286   If ( __TBIExtCtx.Ctx.SaveMask != 0 ) then pExt should point at a suitably
287   sized extended context save area (usually at the end of the stack space
288   allocated by the current routine). This space should allow for the
289   displaced state of A0.2 and A1.2 to be saved along with the other extended
290   states indicated via __TBIExtCtx.Ctx.SaveMask. */
291#ifndef __ASSEMBLY__
292typedef union _tbiextctx_tag_ {
293    long long Val;
294    TBIDUAL AX2;
295    struct _tbiextctxext_tag {
296#ifdef TBI_1_4
297        short DspramSizes;      /* DSPRAM sizes. Encoding varies between
298                                   TBICtxAlloc and the ECH scheme. */
299#else
300        short Reserved0;
301#endif
302        short SaveMask;         /* Flag bits for state saved */
303        PTBIDUAL pExt;          /* AX[2] state saved first plus Xxxx state */
304
305    } Ctx;
306
307} TBIEXTCTX, *PTBIEXTCTX;
308
309/* Automatic registration of extended context save for __TBINestInts */
310extern TBIEXTCTX __TBIExtCtx;
311#endif /* ifndef __ASSEMBLY__ */
312
313/* Byte offsets of fields within TBIEXTCTX */
314#define TBIEXTCTX_AX2           (0)
315#define TBIEXTCTX_Ctx           (0)
316#define TBIEXTCTX_Ctx_SaveMask  (TBIEXTCTX_Ctx + 2)
317#define TBIEXTCTX_Ctx_pExt      (TBIEXTCTX_Ctx + 2 + 2)
318
319/* Extended context data size calculation constants */
320#define TBICTXEXT_BYTES          (8)
321#define TBICTXEXTBB8_BYTES     (8*8)
322#define TBICTXEXTAX3_BYTES     (3*8)
323#define TBICTXEXTAX4_BYTES     (4*8)
324#ifdef METAC_1_0
325#define TBICTXEXTAXX_BYTES     TBICTXEXTAX3_BYTES
326#else
327#define TBICTXEXTAXX_BYTES     TBICTXEXTAX4_BYTES
328#endif
329#define TBICTXEXTHL2_BYTES     (3*8)
330#define TBICTXEXTTDR_BYTES    (27*8)
331#define TBICTXEXTTDP_BYTES TBICTXEXTTDR_BYTES
332
333#ifdef TBI_1_4
334#define TBICTXEXTFX8_BYTES	(4*8)
335#define TBICTXEXTFPAC_BYTES	(1*4 + 2*2 + 4*8)
336#define TBICTXEXTFACF_BYTES	(3*8)
337#endif
338
339/* Maximum flag bits to be set via the TBICTX_EXTSET macro */
340#define TBICTXEXT_MAXBITS  (TBICTX_XEXT_BIT|                \
341                            TBICTX_XDX8_BIT|TBICTX_XAXX_BIT|\
342                            TBICTX_XHL2_BIT|TBICTX_XTDP_BIT )
343
344/* Maximum size of the extended context save area for current variant */
345#define TBICTXEXT_MAXBYTES (TBICTXEXT_BYTES+TBICTXEXTBB8_BYTES+\
346                         TBICTXEXTAXX_BYTES+TBICTXEXTHL2_BYTES+\
347                                            TBICTXEXTTDP_BYTES )
348
349#ifdef TBI_FASTINT_1_4
350/* Maximum flag bits to be set via the TBICTX_EXTSET macro */
351#define TBICTX2EXT_MAXBITS (TBICTX_XDX8_BIT|TBICTX_XAXX_BIT|\
352                            TBICTX_XHL2_BIT|TBICTX_XTDP_BIT )
353
354/* Maximum size of the extended context save area for current variant */
355#define TBICTX2EXT_MAXBYTES (TBICTXEXTBB8_BYTES+TBICTXEXTAXX_BYTES\
356                             +TBICTXEXTHL2_BYTES+TBICTXEXTTDP_BYTES )
357#endif
358
359/* Specify extended resources being used by current routine, code must be
360   assembler generated to utilise extended resources-
361
362        MOV     D0xxx,A0StP             ; Perform alloca - routine should
363        ADD     A0StP,A0StP,#SaveSize   ; setup/use A0FrP to access locals
364        MOVT    D1xxx,#SaveMask         ; TBICTX_XEXT_BIT MUST be set
365        SETL    [A1GbP+#OG(___TBIExtCtx)],D0xxx,D1xxx
366
367    NB: OG(___TBIExtCtx) is a special case supported for SETL/GETL operations
368        on 64-bit sizes structures only, other accesses must be based on use
369        of OGA(___TBIExtCtx).
370
371   At exit of routine-
372
373        MOV     D0xxx,#0                ; Clear extended context save state
374        MOV     D1xxx,#0
375        SETL    [A1GbP+#OG(___TBIExtCtx)],D0xxx,D1xxx
376        SUB     A0StP,A0StP,#SaveSize   ; If original A0StP required
377
378    NB: Both the setting and clearing of the whole __TBIExtCtx MUST be done
379        atomically in one 64-bit write operation.
380
381   For simple interrupt handling only via __TBINestInts there should be no
382   impact of the __TBIExtCtx system. If pre-emptive scheduling is being
383   performed however (assuming __TBINestInts has already been called earlier
384   on) then the following logic will correctly call __TBICtxSave if required
385   and clear out the currently selected background task-
386
387        if ( __TBIExtCtx.Ctx.SaveMask & TBICTX_XEXT_BIT )
388        {
389            / * Store extended states in pCtx * /
390            State.Sig.SaveMask |= __TBIExtCtx.Ctx.SaveMask;
391
392            (void) __TBICtxSave( State, (void *) __TBIExtCtx.Ctx.pExt );
393            __TBIExtCtx.Val   = 0;
394        }
395
396    and when restoring task states call __TBICtxRestore-
397
398        / * Restore state from pCtx * /
399        State.Sig.pCtx     = pCtx;
400        State.Sig.SaveMask = pCtx->SaveMask;
401
402        if ( State.Sig.SaveMask & TBICTX_XEXT_BIT )
403        {
404            / * Restore extended states from pCtx * /
405            __TBIExtCtx.Val = pCtx->Ext.Val;
406
407            (void) __TBICtxRestore( State, (void *) __TBIExtCtx.Ctx.pExt );
408        }
409
410 */
411
412/* Critical thread state save area */
413#ifndef __ASSEMBLY__
414typedef struct _tbictx_tag_ {
415    /* TXSTATUS_FLAG_BITS and TXSTATUS_LSM_STEP_BITS from TXSTATUS */
416    short Flags;
417    /* Mask indicates any extended context state saved; 0 -> Never run */
418    short SaveMask;
419    /* Saved PC value */
420    int CurrPC;
421    /* Saved critical register states */
422    TBIDUAL DX[8];
423    /* Background control register states - for cores without catch buffer
424       base in DIVTIME the TXSTATUS bits RPVALID and RPMASK are stored with
425       the real state TXDIVTIME in CurrDIVTIME */
426    int CurrRPT, CurrBPOBITS, CurrMODE, CurrDIVTIME;
427    /* Saved AX register states */
428    TBIDUAL AX[2];
429    TBIEXTCTX Ext;
430    TBIDUAL AX3[TBICTX_AX_REGS-3];
431
432    /* Any CBUF state to be restored by a handler return must be stored here.
433       Other extended state can be stored anywhere - see __TBICtxSave and
434       __TBICtxRestore. */
435
436} TBICTX, *PTBICTX;
437
438#ifdef TBI_FASTINT_1_4
439typedef struct _tbictx2_tag_ {
440    TBIDUAL AX[2];    /* AU.0, AU.1 */
441    TBIDUAL DX[2];    /* DU.0, DU.4 */
442    int     CurrMODE;
443    int     CurrRPT;
444    int     CurrSTATUS;
445    void   *CurrPC;   /* PC in PC address space */
446} TBICTX2, *PTBICTX2;
447/* TBICTX2 is followed by:
448 *   TBICTXEXTCB0                if TXSTATUS.CBMarker
449 *   TBIDUAL * TXSTATUS.IRPCount if TXSTATUS.IRPCount > 0
450 *   TBICTXGP                    if using __TBIStdRootIntHandler or __TBIStdCtxSwitchRootIntHandler
451 */
452
453typedef struct _tbictxgp_tag_ {
454    short    DspramSizes;
455    short    SaveMask;
456    void    *pExt;
457    TBIDUAL  DX[6]; /* DU.1-DU.3, DU.5-DU.7 */
458    TBIDUAL  AX[2]; /* AU.2-AU.3 */
459} TBICTXGP, *PTBICTXGP;
460
461#define TBICTXGP_DspramSizes (0)
462#define TBICTXGP_SaveMask    (TBICTXGP_DspramSizes + 2)
463#define TBICTXGP_MAX_BYTES   (2 + 2 + 4 + 8*(6+2))
464
465#endif
466#endif /* ifndef __ASSEMBLY__ */
467
468/* Byte offsets of fields within TBICTX */
469#define TBICTX_Flags            (0)
470#define TBICTX_SaveMask         (2)
471#define TBICTX_CurrPC           (4)
472#define TBICTX_DX               (2 + 2 + 4)
473#define TBICTX_CurrRPT          (2 + 2 + 4 + 8 * 8)
474#define TBICTX_CurrMODE         (2 + 2 + 4 + 8 * 8 + 4 + 4)
475#define TBICTX_AX               (2 + 2 + 4 + 8 * 8 + 4 + 4 + 4 + 4)
476#define TBICTX_Ext              (2 + 2 + 4 + 8 * 8 + 4 + 4 + 4 + 4 + 2 * 8)
477#define TBICTX_Ext_AX2          (TBICTX_Ext + TBIEXTCTX_AX2)
478#define TBICTX_Ext_AX2_U0       (TBICTX_Ext + TBIEXTCTX_AX2 + TBIDUAL_U0)
479#define TBICTX_Ext_AX2_U1       (TBICTX_Ext + TBIEXTCTX_AX2 + TBIDUAL_U1)
480#define TBICTX_Ext_Ctx_pExt     (TBICTX_Ext + TBIEXTCTX_Ctx_pExt)
481#define TBICTX_Ext_Ctx_SaveMask (TBICTX_Ext + TBIEXTCTX_Ctx_SaveMask)
482
483#ifdef TBI_FASTINT_1_4
484#define TBICTX2_BYTES (8 * 2 + 8 * 2 + 4 + 4 + 4 + 4)
485#define TBICTXEXTCB0_BYTES (4 + 4 + 8)
486
487#define TBICTX2_CRIT_MAX_BYTES (TBICTX2_BYTES + TBICTXEXTCB0_BYTES + 6 * TBIDUAL_BYTES)
488#define TBI_SWITCH_NEXT_PC(PC, EXTRA) ((PC) + (EXTRA & 1) ? 8 : 4)
489#endif
490
491#ifndef __ASSEMBLY__
492/* Extended thread state save areas - catch buffer state element */
493typedef struct _tbictxextcb0_tag_ {
494    /* Flags data and address value - see METAC_CATCH_VALUES in machine.h */
495    unsigned long CBFlags, CBAddr;
496    /* 64-bit data */
497    TBIDUAL CBData;
498
499} TBICTXEXTCB0, *PTBICTXEXTCB0;
500
501/* Read pipeline state saved on later cores after single catch buffer slot */
502typedef struct _tbictxextrp6_tag_ {
503    /* RPMask is TXSTATUS_RPMASK_BITS only, reserved is undefined */
504    unsigned long RPMask, Reserved0;
505    TBIDUAL CBData[6];
506
507} TBICTXEXTRP6, *PTBICTXEXTRP6;
508
509/* Extended thread state save areas - 8 DU register pairs */
510typedef struct _tbictxextbb8_tag_ {
511    /* Remaining Data unit registers in 64-bit pairs */
512    TBIDUAL UX[8];
513
514} TBICTXEXTBB8, *PTBICTXEXTBB8;
515
516/* Extended thread state save areas - 3 AU register pairs */
517typedef struct _tbictxextbb3_tag_ {
518    /* Remaining Address unit registers in 64-bit pairs */
519    TBIDUAL UX[3];
520
521} TBICTXEXTBB3, *PTBICTXEXTBB3;
522
523/* Extended thread state save areas - 4 AU register pairs or 4 FX pairs */
524typedef struct _tbictxextbb4_tag_ {
525    /* Remaining Address unit or FPU registers in 64-bit pairs */
526    TBIDUAL UX[4];
527
528} TBICTXEXTBB4, *PTBICTXEXTBB4;
529
530/* Extended thread state save areas - Hardware loop states (max 2) */
531typedef struct _tbictxexthl2_tag_ {
532    /* Hardware looping register states */
533    TBIDUAL Start, End, Count;
534
535} TBICTXEXTHL2, *PTBICTXEXTHL2;
536
537/* Extended thread state save areas - DSP register states */
538typedef struct _tbictxexttdp_tag_ {
539    /* DSP 32-bit accumulator register state (Bits 31:0 of ACX.0) */
540    TBIDUAL Acc32[1];
541    /* DSP > 32-bit accumulator bits 63:32 of ACX.0 (zero-extended) */
542    TBIDUAL Acc64[1];
543    /* Twiddle register state, and three phase increment states */
544    TBIDUAL PReg[4];
545    /* Modulo region size, padded to 64-bits */
546    int CurrMRSIZE, Reserved0;
547
548} TBICTXEXTTDP, *PTBICTXEXTTDP;
549
550/* Extended thread state save areas - DSP register states including DSP RAM */
551typedef struct _tbictxexttdpr_tag_ {
552    /* DSP 32-bit accumulator register state (Bits 31:0 of ACX.0) */
553    TBIDUAL Acc32[1];
554    /* DSP 40-bit accumulator register state (Bits 39:8 of ACX.0) */
555    TBIDUAL Acc40[1];
556    /* DSP RAM Pointers */
557    TBIDUAL RP0[2],  WP0[2],  RP1[2],  WP1[2];
558    /* DSP RAM Increments */
559    TBIDUAL RPI0[2], WPI0[2], RPI1[2], WPI1[2];
560    /* Template registers */
561    unsigned long Tmplt[16];
562    /* Modulo address region size and DSP RAM module region sizes */
563    int CurrMRSIZE, CurrDRSIZE;
564
565} TBICTXEXTTDPR, *PTBICTXEXTTDPR;
566
567#ifdef TBI_1_4
568/* The METAC_ID_CORE register state is a marker for the FPU
569   state that is then stored after this core header structure.  */
570#define TBICTXEXTFPU_CONFIG_MASK  ( (METAC_COREID_NOFPACC_BIT+     \
571                                     METAC_COREID_CFGFPU_BITS ) << \
572                                     METAC_COREID_CONFIG_BITS       )
573
574/* Recorded FPU exception state from TXDEFR in DefrFpu */
575#define TBICTXEXTFPU_DEFRFPU_MASK (TXDEFR_FPU_FE_BITS)
576
577/* Extended thread state save areas - FPU register states */
578typedef struct _tbictxextfpu_tag_ {
579    /* Stored METAC_CORE_ID CONFIG */
580    int CfgFpu;
581    /* Stored deferred TXDEFR bits related to FPU
582     *
583     * This is encoded as follows in order to fit into 16-bits:
584     * DefrFPU:15 - 14 <= 0
585     *        :13 -  8 <= TXDEFR:21-16
586     *        : 7 -  6 <= 0
587     *        : 5 -  0 <= TXDEFR:5-0
588     */
589    short DefrFpu;
590
591    /* TXMODE bits related to FPU */
592    short ModeFpu;
593
594    /* FPU Even/Odd register states */
595    TBIDUAL FX[4];
596
597    /* if CfgFpu & TBICTX_CFGFPU_FX16_BIT  -> 1 then TBICTXEXTBB4 holds FX.8-15 */
598    /* if CfgFpu & TBICTX_CFGFPU_NOACF_BIT -> 0 then TBICTXEXTFPACC holds state */
599} TBICTXEXTFPU, *PTBICTXEXTFPU;
600
601/* Extended thread state save areas - FPU accumulator state */
602typedef struct _tbictxextfpacc_tag_ {
603    /* FPU accumulator register state - three 64-bit parts */
604    TBIDUAL FAcc32[3];
605
606} TBICTXEXTFPACC, *PTBICTXEXTFPACC;
607#endif
608
609/* Prototype TBI structure */
610struct _tbi_tag_ ;
611
612/* A 64-bit return value used commonly in the TBI APIs */
613typedef union _tbires_tag_ {
614    /* Save and load this value to get/set the whole result quickly */
615    long long Val;
616
617    /* Parameter of a fnSigs or __TBICtx* call */
618    struct _tbires_sig_tag_ {
619        /* TXMASK[I] bits zeroed upto and including current trigger level */
620        unsigned short TrigMask;
621        /* Control bits for handlers - see PTBIAPIFN documentation below */
622        unsigned short SaveMask;
623        /* Pointer to the base register context save area of the thread */
624        PTBICTX pCtx;
625    } Sig;
626
627    /* Result of TBIThrdPrivId call */
628    struct _tbires_thrdprivid_tag_ {
629        /* Basic thread identifier; just TBID_THREAD_BITS */
630        int Id;
631        /* None thread number bits; TBID_ISTAT_BIT+TBID_PSTAT_BIT */
632        int Priv;
633    } Thrd;
634
635    /* Parameter and Result of a __TBISwitch call */
636    struct _tbires_switch_tag_ {
637        /* Parameter passed across context switch */
638        void *pPara;
639        /* Thread context of other Thread includng restore flags */
640        PTBICTX pCtx;
641    } Switch;
642
643    /* For extended S/W events only */
644    struct _tbires_ccb_tag_ {
645        void *pCCB;
646        int COff;
647    } CCB;
648
649    struct _tbires_tlb_tag_ {
650        int Leaf;  /* TLB Leaf data */
651        int Flags; /* TLB Flags */
652    } Tlb;
653
654#ifdef TBI_FASTINT_1_4
655    struct _tbires_intr_tag_ {
656      short    TrigMask;
657      short    SaveMask;
658      PTBICTX2 pCtx;
659    } Intr;
660#endif
661
662} TBIRES, *PTBIRES;
663#endif /* ifndef __ASSEMBLY__ */
664
665#ifndef __ASSEMBLY__
666/* Prototype for all signal handler functions, called via ___TBISyncTrigger or
667   ___TBIASyncTrigger.
668
669   State.Sig.TrigMask will indicate the bits set within TXMASKI at
670          the time of the handler call that have all been cleared to prevent
671          nested interrupt occuring immediately.
672
673   State.Sig.SaveMask is a bit-mask which will be set to Zero when a trigger
674          occurs at background level and TBICTX_CRIT_BIT and optionally
675          TBICTX_CBUF_BIT when a trigger occurs at interrupt level.
676
677          TBICTX_CBUF_BIT reflects the state of TXSTATUS_CBMARKER_BIT for
678          the interrupted background thread.
679
680   State.Sig.pCtx will point at a TBICTX structure generated to hold the
681          critical state of the interrupted thread at interrupt level and
682          should be set to NULL when called at background level.
683
684   Triggers will indicate the status of TXSTAT or TXSTATI sampled by the
685          code that called the handler.
686
687   Inst is defined as 'Inst' if the SigNum is TBID_SIGNUM_SWx and holds the
688          actual SWITCH instruction detected, in other cases the value of this
689          parameter is undefined.
690
691   pTBI   points at the PTBI structure related to the thread and processing
692          level involved.
693
694   TBIRES return value at both processing levels is similar in terms of any
695          changes that the handler makes. By default the State argument value
696          passed in should be returned.
697
698      Sig.TrigMask value is bits to OR back into TXMASKI when the handler
699          completes to enable currently disabled interrupts.
700
701      Sig.SaveMask value is ignored.
702
703      Sig.pCtx is ignored.
704
705 */
706typedef TBIRES (*PTBIAPIFN)( TBIRES State, int SigNum,
707                             int Triggers, int Inst,
708                             volatile struct _tbi_tag_ *pTBI );
709#endif /* ifndef __ASSEMBLY__ */
710
711#ifndef __ASSEMBLY__
712/* The global memory map is described by a list of segment descriptors */
713typedef volatile struct _tbiseg_tag_ {
714    volatile struct _tbiseg_tag_ *pLink;
715    int Id;                           /* Id of the segment */
716    TBISPIN Lock;                     /* Spin-lock for struct (normally 0) */
717    unsigned int Bytes;               /* Size of region in bytes */
718    void *pGAddr;                     /* Base addr of region in global space */
719    void *pLAddr;                     /* Base addr of region in local space */
720    int Data[2];                      /* Segment specific data (may be extended) */
721
722} TBISEG, *PTBISEG;
723#endif /* ifndef __ASSEMBLY__ */
724
725/* Offsets of fields in TBISEG structure */
726#define TBISEG_pLink    ( 0)
727#define TBISEG_Id       ( 4)
728#define TBISEG_Lock     ( 8)
729#define TBISEG_Bytes    (12)
730#define TBISEG_pGAddr   (16)
731#define TBISEG_pLAddr   (20)
732#define TBISEG_Data     (24)
733
734#ifndef __ASSEMBLY__
735typedef volatile struct _tbi_tag_ {
736    int SigMask;                      /* Bits set to represent S/W events */
737    PTBIKICK pKick;                   /* Kick addr for S/W events */
738    void *pCCB;                       /* Extended S/W events */
739    PTBISEG pSeg;                     /* Related segment structure */
740    PTBIAPIFN fnSigs[TBID_SIGNUM_MAX+1];/* Signal handler API table */
741} *PTBI, TBI;
742#endif /* ifndef __ASSEMBLY__ */
743
744/* Byte offsets of fields within TBI */
745#define TBI_SigMask     (0)
746#define TBI_pKick       (4)
747#define TBI_pCCB        (8)
748#define TBI_pSeg       (12)
749#define TBI_fnSigs     (16)
750
751#ifdef TBI_1_4
752#ifndef __ASSEMBLY__
753/* This handler should be used for TBID_SIGNUM_DFR */
754extern TBIRES __TBIHandleDFR ( TBIRES State, int SigNum,
755                               int Triggers, int Inst,
756                               volatile struct _tbi_tag_ *pTBI );
757#endif
758#endif
759
760/* String table entry - special values */
761#define METAG_TBI_STRS (0x5300) /* Tag      : If entry is valid */
762#define METAG_TBI_STRE (0x4500) /* Tag      : If entry is end of table */
763#define METAG_TBI_STRG (0x4700) /* Tag      : If entry is a gap */
764#define METAG_TBI_STRX (0x5A00) /* TransLen : If no translation present */
765
766#ifndef __ASSEMBLY__
767typedef volatile struct _tbistr_tag_ {
768    short Bytes;                      /* Length of entry in Bytes */
769    short Tag;                        /* Normally METAG_TBI_STRS(0x5300) */
770    short Len;                        /* Length of the string entry (incl null) */
771    short TransLen;                   /* Normally METAG_TBI_STRX(0x5A00) */
772    char String[8];                   /* Zero terminated (may-be bigger) */
773
774} TBISTR, *PTBISTR;
775#endif /* ifndef __ASSEMBLY__ */
776
777/* Cache size information - available as fields of Data[1] of global heap
778   segment */
779#define METAG_TBI_ICACHE_SIZE_S    0             /* see comments below */
780#define METAG_TBI_ICACHE_SIZE_BITS 0x0000000F
781#define METAG_TBI_ICACHE_FILL_S    4
782#define METAG_TBI_ICACHE_FILL_BITS 0x000000F0
783#define METAG_TBI_DCACHE_SIZE_S    8
784#define METAG_TBI_DCACHE_SIZE_BITS 0x00000F00
785#define METAG_TBI_DCACHE_FILL_S    12
786#define METAG_TBI_DCACHE_FILL_BITS 0x0000F000
787
788/* METAG_TBI_xCACHE_SIZE
789   Describes the physical cache size rounded up to the next power of 2
790   relative to a 16K (2^14) cache. These sizes are encoded as a signed addend
791   to this base power of 2, for example
792      4K -> 2^12 -> -2  (i.e. 12-14)
793      8K -> 2^13 -> -1
794     16K -> 2^14 ->  0
795     32K -> 2^15 -> +1
796     64K -> 2^16 -> +2
797    128K -> 2^17 -> +3
798
799   METAG_TBI_xCACHE_FILL
800   Describes the physical cache size within the power of 2 area given by
801   the value above. For example a 10K cache may be represented as having
802   nearest size 16K with a fill of 10 sixteenths. This is encoded as the
803   number of unused 1/16ths, for example
804     0000 ->  0 -> 16/16
805     0001 ->  1 -> 15/16
806     0010 ->  2 -> 14/16
807     ...
808     1111 -> 15 ->  1/16
809 */
810
811#define METAG_TBI_CACHE_SIZE_BASE_LOG2 14
812
813/* Each declaration made by this macro generates a TBISTR entry */
814#ifndef __ASSEMBLY__
815#define TBISTR_DECL( Name, Str )                                       \
816    __attribute__ ((__section__ (".tbistr") )) const char Name[] = #Str
817#endif
818
819/* META timer values - see below for Timer support routines */
820#define TBI_TIMERWAIT_MIN (-16)         /* Minimum 'recommended' period */
821#define TBI_TIMERWAIT_MAX (-0x7FFFFFFF) /* Maximum 'recommended' period */
822
823#ifndef __ASSEMBLY__
824/* These macros allow direct access from C to any register known to the
825   assembler or defined in machine.h. Example candidates are TXTACTCYC,
826   TXIDLECYC, and TXPRIVEXT. Note that when higher level macros and routines
827   like the timer and trigger handling features below these should be used in
828   preference to this direct low-level access mechanism. */
829#define TBI_GETREG( Reg )                                  __extension__ ({\
830   int __GRValue;                                                          \
831   __asm__ volatile ("MOV\t%0," #Reg "\t/* (*TBI_GETREG OK) */" :          \
832                     "=r" (__GRValue) );                                   \
833    __GRValue;                                                            })
834
835#define TBI_SETREG( Reg, Value )                                       do {\
836   int __SRValue = Value;                                                  \
837   __asm__ volatile ("MOV\t" #Reg ",%0\t/* (*TBI_SETREG OK) */" :          \
838                     : "r" (__SRValue) );                       } while (0)
839
840#define TBI_SWAPREG( Reg, Value )                                      do {\
841   int __XRValue = (Value);                                                \
842   __asm__ volatile ("SWAP\t" #Reg ",%0\t/* (*TBI_SWAPREG OK) */" :        \
843                     "=r" (__XRValue) : "0" (__XRValue) );                 \
844   Value = __XRValue;                                           } while (0)
845
846/* Obtain and/or release global critical section lock given that interrupts
847   are already disabled and/or should remain disabled. */
848#define TBI_NOINTSCRITON                                             do {\
849   __asm__ volatile ("LOCK1\t\t/* (*TBI_NOINTSCRITON OK) */");} while (0)
850#define TBI_NOINTSCRITOFF                                             do {\
851   __asm__ volatile ("LOCK0\t\t/* (*TBI_NOINTSCRITOFF OK) */");} while (0)
852/* Optimised in-lining versions of the above macros */
853
854#define TBI_LOCK( TrigState )                                          do {\
855   int __TRValue;                                                          \
856   int __ALOCKHI = LINSYSEVENT_WR_ATOMIC_LOCK & 0xFFFF0000;                \
857   __asm__ volatile ("MOV %0,#0\t\t/* (*TBI_LOCK ... */\n\t"               \
858                     "SWAP\t%0,TXMASKI\t/* ... */\n\t"                     \
859                     "LOCK2\t\t/* ... */\n\t"                              \
860                     "SETD\t[%1+#0x40],D1RtP /* ... OK) */" :              \
861                     "=r&" (__TRValue) : "u" (__ALOCKHI) );                \
862   TrigState = __TRValue;                                       } while (0)
863#define TBI_CRITON( TrigState )                                        do {\
864   int __TRValue;                                                          \
865   __asm__ volatile ("MOV %0,#0\t\t/* (*TBI_CRITON ... */\n\t"             \
866                     "SWAP\t%0,TXMASKI\t/* ... */\n\t"                     \
867                     "LOCK1\t\t/* ... OK) */" :                            \
868                     "=r" (__TRValue) );                                   \
869   TrigState = __TRValue;                                       } while (0)
870
871#define TBI_INTSX( TrigState )                                         do {\
872   int __TRValue = TrigState;                                              \
873   __asm__ volatile ("SWAP\t%0,TXMASKI\t/* (*TBI_INTSX OK) */" :           \
874                     "=r" (__TRValue) : "0" (__TRValue) );                 \
875   TrigState = __TRValue;                                       } while (0)
876
877#define TBI_UNLOCK( TrigState )                                        do {\
878   int __TRValue = TrigState;                                              \
879   int __ALOCKHI = LINSYSEVENT_WR_ATOMIC_LOCK & 0xFFFF0000;                \
880   __asm__ volatile ("SETD\t[%1+#0x00],D1RtP\t/* (*TBI_UNLOCK ... */\n\t"  \
881                     "LOCK0\t\t/* ... */\n\t"                              \
882                     "MOV\tTXMASKI,%0\t/* ... OK) */" :                    \
883                     : "r" (__TRValue), "u" (__ALOCKHI) );      } while (0)
884
885#define TBI_CRITOFF( TrigState )                                       do {\
886   int __TRValue = TrigState;                                              \
887   __asm__ volatile ("LOCK0\t\t/* (*TBI_CRITOFF ... */\n\t"                \
888                     "MOV\tTXMASKI,%0\t/* ... OK) */" :                    \
889                     : "r" (__TRValue) );                       } while (0)
890
891#define TBI_TRIGSX( SrcDst ) do { TBI_SWAPREG( TXMASK, SrcDst );} while (0)
892
893/* Composite macros to perform logic ops on INTS or TRIGS masks */
894#define TBI_INTSOR( Bits )                                              do {\
895    int __TT = 0; TBI_INTSX(__TT);                                          \
896    __TT |= (Bits); TBI_INTSX(__TT);                             } while (0)
897
898#define TBI_INTSAND( Bits )                                             do {\
899    int __TT = 0; TBI_INTSX(__TT);                                          \
900    __TT &= (Bits); TBI_INTSX(__TT);                             } while (0)
901
902#ifdef TBI_1_4
903#define TBI_DEFRICTRLSOR( Bits )                                        do {\
904    int __TT = TBI_GETREG( CT.20 );                                         \
905    __TT |= (Bits); TBI_SETREG( CT.20, __TT);                    } while (0)
906
907#define TBI_DEFRICTRLSAND( Bits )                                       do {\
908    int __TT = TBI_GETREG( TXDEFR );                                        \
909    __TT &= (Bits); TBI_SETREG( CT.20, __TT);                    } while (0)
910#endif
911
912#define TBI_TRIGSOR( Bits )                                             do {\
913    int __TT = TBI_GETREG( TXMASK );                                        \
914    __TT |= (Bits); TBI_SETREG( TXMASK, __TT);                   } while (0)
915
916#define TBI_TRIGSAND( Bits )                                            do {\
917    int __TT = TBI_GETREG( TXMASK );                                        \
918    __TT &= (Bits); TBI_SETREG( TXMASK, __TT);                   } while (0)
919
920/* Macros to disable and re-enable interrupts using TBI_INTSX, deliberate
921   traps and exceptions can still be handled within the critical section. */
922#define TBI_STOPINTS( Value )                                           do {\
923    int __TT = TBI_GETREG( TXMASKI );                                       \
924    __TT &= TXSTATI_BGNDHALT_BIT; TBI_INTSX( __TT );                        \
925    Value = __TT;                                                } while (0)
926#define TBI_RESTINTS( Value )                                           do {\
927    int __TT = Value; TBI_INTSX( __TT );                         } while (0)
928
929/* Return pointer to segment list at current privilege level */
930PTBISEG __TBISegList( void );
931
932/* Search the segment list for a match given Id, pStart can be NULL */
933PTBISEG __TBIFindSeg( PTBISEG pStart, int Id );
934
935/* Prepare a new segment structure using space from within another */
936PTBISEG __TBINewSeg( PTBISEG pFromSeg, int Id, unsigned int Bytes );
937
938/* Prepare a new segment using any global or local heap segments available */
939PTBISEG __TBIMakeNewSeg( int Id, unsigned int Bytes );
940
941/* Insert a new segment into the segment list so __TBIFindSeg can locate it */
942void __TBIAddSeg( PTBISEG pSeg );
943#define __TBIADDSEG_DEF     /* Some versions failed to define this */
944
945/* Return Id of current thread; TBID_ISTAT_BIT+TBID_THREAD_BITS */
946int __TBIThreadId( void );
947
948/* Return TBIRES.Thrd data for current thread */
949TBIRES __TBIThrdPrivId( void );
950
951/* Return pointer to current threads TBI root block.
952   Id implies whether Int or Background root block is required */
953PTBI __TBI( int Id );
954
955/* Try to set Mask bit using the spin-lock protocol, return 0 if fails and
956   new state if succeeds */
957int __TBIPoll( PTBISPIN pLock, int Mask );
958
959/* Set Mask bits via the spin-lock protocol in *pLock, return new state */
960int __TBISpin( PTBISPIN pLock, int Mask );
961
962/* Default handler set up for all TBI.fnSigs entries during initialisation */
963TBIRES __TBIUnExpXXX( TBIRES State, int SigNum,
964                   int Triggers, int Inst, PTBI pTBI );
965
966/* Call this routine to service triggers at background processing level. The
967   TBID_POLL_BIT of the Id parameter value will be used to indicate that the
968   routine should return if no triggers need to be serviced initially. If this
969   bit is not set the routine will block until one trigger handler is serviced
970   and then behave like the poll case servicing any remaining triggers
971   actually outstanding before returning. Normally the State parameter should
972   be simply initialised to zero and the result should be ignored, other
973   values/options are for internal use only. */
974TBIRES __TBISyncTrigger( TBIRES State, int Id );
975
976/* Call this routine to enable processing of triggers by signal handlers at
977   interrupt level. The State parameter value passed is returned by this
978   routine. The State.Sig.TrigMask field also specifies the initial
979   state of the interrupt mask register TXMASKI to be setup by the call.
980   The other parts of the State parameter are ignored unless the PRIV bit is
981   set in the SaveMask field. In this case the State.Sig.pCtx field specifies
982   the base of the stack to which the interrupt system should switch into
983   as it saves the state of the previously executing code. In the case the
984   thread will be unprivileged as it continues execution at the return
985   point of this routine and it's future state will be effectively never
986   trusted to be valid. */
987TBIRES __TBIASyncTrigger( TBIRES State );
988
989/* Call this to swap soft threads executing at the background processing level.
990   The TBIRES returned to the new thread will be the same as the NextThread
991   value specified to the call. The NextThread.Switch.pCtx value specifies
992   which thread context to restore and the NextThread.Switch.Para value can
993   hold an arbitrary expression to be passed between the threads. The saved
994   state of the previous thread will be stored in a TBICTX descriptor created
995   on it's stack and the address of this will be stored into the *rpSaveCtx
996   location specified. */
997TBIRES __TBISwitch( TBIRES NextThread, PTBICTX *rpSaveCtx );
998
999/* Call this to initialise a stack frame ready for further use, up to four
1000   32-bit arguments may be specified after the fixed args to be passed via
1001   the new stack pStack to the routine specified via fnMain. If the
1002   main-line routine ever returns the thread will operate as if main itself
1003   had returned and terminate with the return code given. */
1004typedef int (*PTBIMAINFN)( TBIRES Arg /*, <= 4 additional 32-bit args */ );
1005PTBICTX __TBISwitchInit( void *pStack, PTBIMAINFN fnMain, ... );
1006
1007/* Call this to resume a thread from a saved synchronous TBICTX state.
1008   The TBIRES returned to the new thread will be the same as the NextThread
1009   value specified to the call. The NextThread.Switch.pCtx value specifies
1010   which thread context to restore and the NextThread.Switch.Para value can
1011   hold an arbitrary expression to be passed between the threads. The context
1012   of the calling thread is lost and this routine never returns to the
1013   caller. The TrigsMask value supplied is ored into TXMASKI to enable
1014   interrupts after the context of the new thread is established. */
1015void __TBISyncResume( TBIRES NextThread, int TrigsMask );
1016
1017/* Call these routines to save and restore the extended states of
1018   scheduled tasks. */
1019void *__TBICtxSave( TBIRES State, void *pExt );
1020void *__TBICtxRestore( TBIRES State, void *pExt );
1021
1022#ifdef TBI_1_4
1023#ifdef TBI_FASTINT_1_4
1024/* Call these routines to copy the GP state to a separate buffer
1025 * Only necessary for context switching.
1026 */
1027PTBICTXGP __TBICtx2SaveCrit( PTBICTX2 pCurrentCtx, PTBICTX2 pSaveCtx );
1028void *__TBICtx2SaveGP( PTBICTXGP pCurrentCtxGP, PTBICTXGP pSaveCtxGP );
1029
1030/* Call these routines to save and restore the extended states of
1031   scheduled tasks. */
1032void *__TBICtx2Save( PTBICTXGP pCtxGP, short SaveMask, void *pExt );
1033void *__TBICtx2Restore( PTBICTX2 pCtx, short SaveMask, void *pExt );
1034#endif
1035
1036/* If FPAC flag is set then significant FPU context exists. Call these routine
1037   to save and restore it */
1038void *__TBICtxFPUSave( TBIRES State, void *pExt );
1039void *__TBICtxFPURestore( TBIRES State, void *pExt );
1040
1041#ifdef TBI_FASTINT_1_4
1042extern void *__TBICtx2FPUSave (PTBICTXGP, short, void*);
1043extern void *__TBICtx2FPURestore (PTBICTXGP, short, void*);
1044#endif
1045#endif
1046
1047#ifdef TBI_1_4
1048/* Call these routines to save and restore DSPRAM. */
1049void *__TBIDspramSaveA (short DspramSizes, void *pExt);
1050void *__TBIDspramSaveB (short DspramSizes, void *pExt);
1051void *__TBIDspramRestoreA (short DspramSizes, void *pExt);
1052void *__TBIDspramRestoreB (short DspramSizes, void *pExt);
1053#endif
1054
1055/* This routine should be used at the entrypoint of interrupt handlers to
1056   re-enable higher priority interrupts and/or save state from the previously
1057   executing background code. State is a TBIRES.Sig parameter with NoNestMask
1058   indicating the triggers (if any) that should remain disabled and SaveMask
1059   CBUF bit indicating the if the hardware catch buffer is dirty. Optionally
1060   any number of extended state bits X??? including XCBF can be specified to
1061   force a nested state save call to __TBICtxSave before the current routine
1062   continues. (In the latter case __TBICtxRestore should be called to restore
1063   any extended states before the background thread of execution is resumed)
1064
1065   By default (no X??? bits specified in SaveMask) this routine performs a
1066   sub-call to __TBICtxSave with the pExt and State parameters specified IF
1067   some triggers could be serviced while the current interrupt handler
1068   executes and the hardware catch buffer is actually dirty. In this case
1069   this routine provides the XCBF bit in State.Sig.SaveMask to force the
1070   __TBICtxSave to extract the current catch state.
1071
1072   The NoNestMask parameter should normally indicate that the same or lower
1073   triggers than those provoking the current handler call should not be
1074   serviced in nested calls, zero may be specified if all possible interrupts
1075   are to be allowed.
1076
1077   The TBIRES.Sig value returned will be similar to the State parameter
1078   specified with the XCBF bit ORed into it's SaveMask if a context save was
1079   required and fewer bits set in it's TrigMask corresponding to the same/lower
1080   priority interrupt triggers still not enabled. */
1081TBIRES __TBINestInts( TBIRES State, void *pExt, int NoNestMask );
1082
1083/* This routine causes the TBICTX structure specified in State.Sig.pCtx to
1084   be restored. This implies that execution will not return to the caller.
1085   The State.Sig.TrigMask field will be restored during the context switch
1086   such that any immediately occuring interrupts occur in the context of the
1087   newly specified task. The State.Sig.SaveMask parameter is ignored. */
1088void __TBIASyncResume( TBIRES State );
1089
1090/* Call this routine to enable fastest possible processing of one or more
1091   interrupt triggers via a unified signal handler. The handler concerned
1092   must simple return after servicing the related hardware.
1093   The State.Sig.TrigMask parameter indicates the interrupt triggers to be
1094   enabled and the Thin.Thin.fnHandler specifies the routine to call and
1095   the whole Thin parameter value will be passed to this routine unaltered as
1096   it's first parameter. */
1097void __TBIASyncThin( TBIRES State, TBIRES Thin );
1098
1099/* Do this before performing your own direct spin-lock access - use TBI_LOCK */
1100int __TBILock( void );
1101
1102/* Do this after performing your own direct spin-lock access - use TBI_UNLOCK */
1103void __TBIUnlock( int TrigState );
1104
1105/* Obtain and release global critical section lock - only stops execution
1106   of interrupts on this thread and similar critical section code on other
1107   local threads - use TBI_CRITON or TBI_CRITOFF */
1108int __TBICritOn( void );
1109void __TBICritOff( int TrigState );
1110
1111/* Change INTS (TXMASKI) - return old state - use TBI_INTSX */
1112int __TBIIntsX( int NewMask );
1113
1114/* Change TRIGS (TXMASK) - return old state - use TBI_TRIGSX */
1115int __TBITrigsX( int NewMask );
1116
1117/* This function initialises a timer for first use, only the TBID_ISTAT_BIT
1118   of the Id parameter is used to indicate which timer is to be modified. The
1119   Wait value should either be zero to disable the timer concerned or be in
1120   the recommended TBI_TIMERWAIT_* range to specify the delay required before
1121   the first timer trigger occurs.
1122
1123   The TBID_ISTAT_BIT of the Id parameter similar effects all other timer
1124   support functions (see below). */
1125void __TBITimerCtrl( int Id, int Wait );
1126
1127/* This routine returns a 64-bit time stamp value that is initialised to zero
1128   via a __TBITimerCtrl timer enabling call. */
1129long long __TBITimeStamp( int Id );
1130
1131/* To manage a periodic timer each period elapsed should be subracted from
1132   the current timer value to attempt to set up the next timer trigger. The
1133   Wait parameter should be a value in the recommended TBI_TIMERWAIT_* range.
1134   The return value is the new aggregate value that the timer was updated to,
1135   if this is less than zero then a timer trigger is guaranteed to be
1136   generated after the number of ticks implied, if a positive result is
1137   returned either itterative or step-wise corrective action must be taken to
1138   resynchronise the timer and hence provoke a future timer trigger. */
1139int __TBITimerAdd( int Id, int Wait );
1140
1141/* String table search function, pStart is first entry to check or NULL,
1142   pStr is string data to search for and MatchLen is either length of string
1143   to compare for an exact match or negative length to compare for partial
1144   match. */
1145const TBISTR *__TBIFindStr( const TBISTR *pStart,
1146                            const char *pStr, int MatchLen );
1147
1148/* String table translate function, pStr is text to translate and Len is
1149   it's length. Value returned may not be a string pointer if the
1150   translation value is really some other type, 64-bit alignment of the return
1151   pointer is guaranteed so almost any type including a structure could be
1152   located with this routine. */
1153const void *__TBITransStr( const char *pStr, int Len );
1154
1155
1156
1157/* Arbitrary physical memory access windows, use different Channels to avoid
1158   conflict/thrashing within a single piece of code. */
1159void *__TBIPhysAccess( int Channel, int PhysAddr, int Bytes );
1160void __TBIPhysRelease( int Channel, void *pLinAddr );
1161
1162#ifdef METAC_1_0
1163/* Data cache function nullified because data cache is off */
1164#define TBIDCACHE_FLUSH( pAddr )
1165#define TBIDCACHE_PRELOAD( Type, pAddr ) ((Type) (pAddr))
1166#define TBIDCACHE_REFRESH( Type, pAddr ) ((Type) (pAddr))
1167#endif
1168#ifdef METAC_1_1
1169/* To flush a single cache line from the data cache using a linear address */
1170#define TBIDCACHE_FLUSH( pAddr )          ((volatile char *) \
1171                 (((unsigned int) (pAddr))>>LINSYSLFLUSH_S))[0] = 0
1172
1173extern void * __builtin_dcache_preload (void *);
1174
1175/* Try to ensure that the data at the address concerned is in the cache */
1176#define TBIDCACHE_PRELOAD( Type, Addr )                                    \
1177  ((Type) __builtin_dcache_preload ((void *)(Addr)))
1178
1179extern void * __builtin_dcache_refresh (void *);
1180
1181/* Flush any old version of data from address and re-load a new copy */
1182#define TBIDCACHE_REFRESH( Type, Addr )                   __extension__ ({ \
1183  Type __addr = (Type)(Addr);                                              \
1184  (void)__builtin_dcache_refresh ((void *)(((unsigned int)(__addr))>>6));  \
1185  __addr; })
1186
1187#endif
1188#ifndef METAC_1_0
1189#ifndef METAC_1_1
1190/* Support for DCACHE builtin */
1191extern void __builtin_dcache_flush (void *);
1192
1193/* To flush a single cache line from the data cache using a linear address */
1194#define TBIDCACHE_FLUSH( Addr )                                            \
1195  __builtin_dcache_flush ((void *)(Addr))
1196
1197extern void * __builtin_dcache_preload (void *);
1198
1199/* Try to ensure that the data at the address concerned is in the cache */
1200#define TBIDCACHE_PRELOAD( Type, Addr )                                    \
1201  ((Type) __builtin_dcache_preload ((void *)(Addr)))
1202
1203extern void * __builtin_dcache_refresh (void *);
1204
1205/* Flush any old version of data from address and re-load a new copy */
1206#define TBIDCACHE_REFRESH( Type, Addr )                                    \
1207  ((Type) __builtin_dcache_refresh ((void *)(Addr)))
1208
1209#endif
1210#endif
1211
1212/* Flush the MMCU cache */
1213#define TBIMCACHE_FLUSH() { ((volatile int *) LINSYSCFLUSH_MMCU)[0] = 0; }
1214
1215#ifdef METAC_2_1
1216/* Obtain the MMU table entry for the specified address */
1217#define TBIMTABLE_LEAFDATA(ADDR) TBIXCACHE_RD((int)(ADDR) & (-1<<6))
1218
1219#ifndef __ASSEMBLY__
1220/* Obtain the full MMU table entry for the specified address */
1221#define TBIMTABLE_DATA(ADDR) __extension__ ({ TBIRES __p;                     \
1222                                              __p.Val = TBIXCACHE_RL((int)(ADDR) & (-1<<6));   \
1223                                              __p; })
1224#endif
1225#endif
1226
1227/* Combine a physical base address, and a linear address
1228 * Internal use only
1229 */
1230#define _TBIMTABLE_LIN2PHYS(PHYS, LIN, LMASK) (void*)(((int)(PHYS)&0xFFFFF000)\
1231                                               +((int)(LIN)&(LMASK)))
1232
1233/* Convert a linear to a physical address */
1234#define TBIMTABLE_LIN2PHYS(LEAFDATA, ADDR)                                    \
1235          (((LEAFDATA) & CRLINPHY0_VAL_BIT)                                   \
1236              ? _TBIMTABLE_LIN2PHYS(LEAFDATA, ADDR, 0x00000FFF)               \
1237              : 0)
1238
1239/* Debug support - using external debugger or host */
1240void __TBIDumpSegListEntries( void );
1241void __TBILogF( const char *pFmt, ... );
1242void __TBIAssert( const char *pFile, int LineNum, const char *pExp );
1243void __TBICont( const char *pMsg, ... ); /* TBIAssert -> 'wait for continue' */
1244
1245/* Array of signal name data for debug messages */
1246extern const char __TBISigNames[];
1247#endif /* ifndef __ASSEMBLY__ */
1248
1249
1250
1251/* Scale of sub-strings in the __TBISigNames string list */
1252#define TBI_SIGNAME_SCALE   4
1253#define TBI_SIGNAME_SCALE_S 2
1254
1255#define TBI_1_3
1256
1257#ifdef TBI_1_3
1258
1259#ifndef __ASSEMBLY__
1260#define TBIXCACHE_RD(ADDR)                                 __extension__ ({\
1261    void * __Addr = (void *)(ADDR);                                        \
1262    int __Data;                                                            \
1263    __asm__ volatile ( "CACHERD\t%0,[%1+#0]" :                             \
1264                       "=r" (__Data) : "r" (__Addr) );                     \
1265    __Data;                                                               })
1266
1267#define TBIXCACHE_RL(ADDR)                                 __extension__ ({\
1268    void * __Addr = (void *)(ADDR);                                        \
1269    long long __Data;                                                      \
1270    __asm__ volatile ( "CACHERL\t%0,%t0,[%1+#0]" :                         \
1271                       "=d" (__Data) : "r" (__Addr) );                     \
1272    __Data;                                                               })
1273
1274#define TBIXCACHE_WD(ADDR, DATA)                                      do {\
1275    void * __Addr = (void *)(ADDR);                                       \
1276    int __Data = DATA;                                                    \
1277    __asm__ volatile ( "CACHEWD\t[%0+#0],%1" :                            \
1278                       : "r" (__Addr), "r" (__Data) );          } while(0)
1279
1280#define TBIXCACHE_WL(ADDR, DATA)                                      do {\
1281    void * __Addr = (void *)(ADDR);                                       \
1282    long long __Data = DATA;                                              \
1283    __asm__ volatile ( "CACHEWL\t[%0+#0],%1,%t1" :                        \
1284                       : "r" (__Addr), "r" (__Data) );          } while(0)
1285
1286#ifdef TBI_4_0
1287
1288#define TBICACHE_FLUSH_L1D_L2(ADDR)                                       \
1289  TBIXCACHE_WD(ADDR, CACHEW_FLUSH_L1D_L2)
1290#define TBICACHE_WRITEBACK_L1D_L2(ADDR)                                   \
1291  TBIXCACHE_WD(ADDR, CACHEW_WRITEBACK_L1D_L2)
1292#define TBICACHE_INVALIDATE_L1D(ADDR)                                     \
1293  TBIXCACHE_WD(ADDR, CACHEW_INVALIDATE_L1D)
1294#define TBICACHE_INVALIDATE_L1D_L2(ADDR)                                  \
1295  TBIXCACHE_WD(ADDR, CACHEW_INVALIDATE_L1D_L2)
1296#define TBICACHE_INVALIDATE_L1DTLB(ADDR)                                  \
1297  TBIXCACHE_WD(ADDR, CACHEW_INVALIDATE_L1DTLB)
1298#define TBICACHE_INVALIDATE_L1I(ADDR)                                     \
1299  TBIXCACHE_WD(ADDR, CACHEW_INVALIDATE_L1I)
1300#define TBICACHE_INVALIDATE_L1ITLB(ADDR)                                  \
1301  TBIXCACHE_WD(ADDR, CACHEW_INVALIDATE_L1ITLB)
1302
1303#endif /* TBI_4_0 */
1304#endif /* ifndef __ASSEMBLY__ */
1305
1306/*
1307 * Calculate linear PC value from real PC and Minim mode control, the LSB of
1308 * the result returned indicates if address compression has occured.
1309 */
1310#ifndef __ASSEMBLY__
1311#define METAG_LINPC( PCVal )                                              (\
1312    ( (TBI_GETREG(TXPRIVEXT) & TXPRIVEXT_MINIMON_BIT) != 0 ) ?           ( \
1313        ( ((PCVal) & 0x00900000) == 0x00900000 ) ?                         \
1314          (((PCVal) & 0xFFE00000) + (((PCVal) & 0x001FFFFC)>>1) + 1) :     \
1315        ( ((PCVal) & 0x00800000) == 0x00000000 ) ?                         \
1316          (((PCVal) & 0xFF800000) + (((PCVal) & 0x007FFFFC)>>1) + 1) :     \
1317                                                             (PCVal)   )   \
1318                                                                 : (PCVal) )
1319#define METAG_LINPC_X2BIT 0x00000001       /* Make (Size>>1) if compressed */
1320
1321/* Convert an arbitrary Linear address into a valid Minim PC or return 0 */
1322#define METAG_PCMINIM( LinVal )                                           (\
1323        (((LinVal) & 0x00980000) == 0x00880000) ?                          \
1324            (((LinVal) & 0xFFE00000) + (((LinVal) & 0x000FFFFE)<<1)) :     \
1325        (((LinVal) & 0x00C00000) == 0x00000000) ?                          \
1326            (((LinVal) & 0xFF800000) + (((LinVal) & 0x003FFFFE)<<1)) : 0   )
1327
1328/* Reverse a METAG_LINPC conversion step to return the original PCVal */
1329#define METAG_PCLIN( LinVal )                              ( 0xFFFFFFFC & (\
1330        ( (LinVal & METAG_LINPC_X2BIT) != 0 ) ? METAG_PCMINIM( LinVal ) :  \
1331                                                               (LinVal)   ))
1332
1333/*
1334 * Flush the MMCU Table cache privately for each thread. On cores that do not
1335 * support per-thread flushing it will flush all threads mapping data.
1336 */
1337#define TBIMCACHE_TFLUSH(Thread)                                   do {\
1338    ((volatile int *)( LINSYSCFLUSH_TxMMCU_BASE            +           \
1339                      (LINSYSCFLUSH_TxMMCU_STRIDE*(Thread)) ))[0] = 0; \
1340                                                             } while(0)
1341
1342/*
1343 * To flush a single linear-matched cache line from the code cache. In
1344 * cases where Minim is possible the METAC_LINPC operation must be used
1345 * to pre-process the address being flushed.
1346 */
1347#define TBIICACHE_FLUSH( pAddr ) TBIXCACHE_WD (pAddr, CACHEW_ICACHE_BIT)
1348
1349/* To flush a single linear-matched mapping from code/data MMU table cache */
1350#define TBIMCACHE_AFLUSH( pAddr, SegType )                                \
1351    TBIXCACHE_WD(pAddr, CACHEW_TLBFLUSH_BIT + (                           \
1352                 ((SegType) == TBID_SEGTYPE_TEXT) ? CACHEW_ICACHE_BIT : 0 ))
1353
1354/*
1355 * To flush translation data corresponding to a range of addresses without
1356 * using TBITCACHE_FLUSH to flush all of this threads translation data. It
1357 * is necessary to know what stride (>= 4K) must be used to flush a specific
1358 * region.
1359 *
1360 * For example direct mapped regions use the maximum page size (512K) which may
1361 * mean that only one flush is needed to cover the sub-set of the direct
1362 * mapped area used since it was setup.
1363 *
1364 * The function returns the stride on which flushes should be performed.
1365 *
1366 * If 0 is returned then the region is not subject to MMU caching, if -1 is
1367 * returned then this indicates that only TBIMCACHE_TFLUSH can be used to
1368 * flush the region concerned rather than TBIMCACHE_AFLUSH which this
1369 * function is designed to support.
1370 */
1371int __TBIMMUCacheStride( const void *pStart, int Bytes );
1372
1373/*
1374 * This function will use the above lower level functions to achieve a MMU
1375 * table data flush in an optimal a fashion as possible. On a system that
1376 * supports linear address based caching this function will also call the
1377 * code or data cache flush functions to maintain address/data coherency.
1378 *
1379 * SegType should be TBID_SEGTYPE_TEXT if the address range is for code or
1380 * any other value such as TBID_SEGTYPE_DATA for data. If an area is
1381 * used in both ways then call this function twice; once for each.
1382 */
1383void __TBIMMUCacheFlush( const void *pStart, int Bytes, int SegType );
1384
1385/*
1386 * Cached Core mode setup and flush functions allow one code and one data
1387 * region of the corresponding global or local cache partion size to be
1388 * locked into the corresponding cache memory. This prevents normal LRU
1389 * logic discarding the code or data and avoids write-thru bandwidth in
1390 * data areas. Code mappings are selected by specifying TBID_SEGTYPE_TEXT
1391 * for SegType, otherwise data mappings are created.
1392 *
1393 * Mode supplied should always contain the VALID bit and WINx selection data.
1394 * Data areas will be mapped read-only if the WRITE bit is not added.
1395 *
1396 * The address returned by the Opt function will either be the same as that
1397 * passed in (if optimisation cannot be supported) or the base of the new core
1398 * cached region in linear address space. The returned address must be passed
1399 * into the End function to remove the mapping when required. If a non-core
1400 * cached memory address is passed into it the End function has no effect.
1401 * Note that the region accessed MUST be flushed from the appropriate cache
1402 * before the End function is called to deliver correct operation.
1403 */
1404void *__TBICoreCacheOpt( const void *pStart, int Bytes, int SegType, int Mode );
1405void __TBICoreCacheEnd( const void *pOpt, int Bytes, int SegType );
1406
1407/*
1408 * Optimise physical access channel and flush side effects before releasing
1409 * the channel. If pStart is NULL the whole region must be flushed and this is
1410 * done automatically by the channel release function if optimisation is
1411 * enabled. Flushing the specific region that may have been accessed before
1412 * release should optimises this process. On physically cached systems we do
1413 * not flush the code/data caches only the MMU table data needs flushing.
1414 */
1415void __TBIPhysOptim( int Channel, int IMode, int DMode );
1416void __TBIPhysFlush( int Channel, const void *pStart, int Bytes );
1417#endif
1418#endif /* ifdef TBI_1_3 */
1419
1420#endif /* _ASM_METAG_TBX_H_ */
1421