Add start of an architecture port to the Atmel USB XMEGA devices.
[pub/USBasp.git] / LUFA / Common / Common.h
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2011.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2011 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, distribute, and sell this
13 software and its documentation for any purpose is hereby granted
14 without fee, provided that the above copyright notice appear in
15 all copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
20
21 The author disclaim all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
28 this software.
29 */
30
31 /** \file
32 * \brief Common library convenience headers, macros and functions.
33 *
34 * \copydetails Group_Common
35 */
36
37 /** \defgroup Group_Common Common Utility Headers - LUFA/Drivers/Common/Common.h
38 * \brief Common library convenience headers, macros and functions.
39 *
40 * Common utility headers containing macros, functions, enums and types which are common to all
41 * aspects of the library.
42 *
43 * @{
44 */
45
46 /** \defgroup Group_Debugging Debugging Macros
47 * \brief Convenience macros to aid in debugging applications.
48 *
49 * Macros to aid debugging of a user application.
50 */
51
52 /** \defgroup Group_GlobalInt Global Interrupt Macros
53 * \brief Convenience macros for the management of interrupts globally within the device.
54 *
55 * Macros and functions to create and control global interrupts within the device.
56 */
57
58 #ifndef __LUFA_COMMON_H__
59 #define __LUFA_COMMON_H__
60
61 /* Macros: */
62 #define __INCLUDE_FROM_COMMON_H
63
64 /* Includes: */
65 #include <stdint.h>
66 #include <stdbool.h>
67 #include <string.h>
68 #include <stddef.h>
69
70 #if defined(USE_LUFA_CONFIG_HEADER)
71 #include "LUFAConfig.h"
72 #endif
73
74 #include "CompilerSpecific.h"
75 #include "Architectures.h"
76 #include "Attributes.h"
77 #include "BoardTypes.h"
78
79 /* Enable C linkage for C++ Compilers: */
80 #if defined(__cplusplus)
81 extern "C" {
82 #endif
83
84 /* Architecture specific utility includes: */
85 #if defined(__DOXYGEN__)
86 /** Type define for an unsigned integer the same width as the selected architecture's machine register.
87 * This is distinct from the non-specific standard int data type, whose width is machine dependant but
88 * which may not reflect the actual machine register width on some targets (e.g. AVR8).
89 */
90 typedef MACHINE_REG_t uint_reg_t;
91 #elif (ARCH == ARCH_AVR8)
92 #include <avr/io.h>
93 #include <avr/interrupt.h>
94 #include <avr/pgmspace.h>
95 #include <avr/eeprom.h>
96 #include <avr/boot.h>
97 #include <util/delay.h>
98
99 typedef uint8_t uint_reg_t;
100
101 #define ARCH_HAS_EEPROM_ADDRESS_SPACE
102 #define ARCH_HAS_FLASH_ADDRESS_SPACE
103 #define ARCH_HAS_MULTI_ADDRESS_SPACE
104 #define ARCH_LITTLE_ENDIAN
105
106 #include "Endianness.h"
107 #elif (ARCH == ARCH_UC3)
108 #include <avr32/io.h>
109
110 // === TODO: Find abstracted way to handle these ===
111 #define PROGMEM const
112 #define pgm_read_byte(x) *x
113 #define memcmp_P(...) memcmp(__VA_ARGS__)
114 #define memcpy_P(...) memcpy(__VA_ARGS__)
115 // =================================================
116
117 typedef uint32_t uint_reg_t;
118
119 #define ARCH_BIG_ENDIAN
120
121 #include "Endianness.h"
122 #elif (ARCH == ARCH_XMEGA)
123 #include <avr/io.h>
124 #include <avr/interrupt.h>
125 #include <avr/pgmspace.h>
126 #include <avr/eeprom.h>
127 #include <util/delay.h>
128
129 typedef uint8_t uint_reg_t;
130
131 #define ARCH_HAS_EEPROM_ADDRESS_SPACE
132 #define ARCH_HAS_FLASH_ADDRESS_SPACE
133 #define ARCH_HAS_MULTI_ADDRESS_SPACE
134 #define ARCH_LITTLE_ENDIAN
135
136 #include "Endianness.h"
137 #else
138 #error Unknown device architecture specified.
139 #endif
140
141 /* Public Interface - May be used in end-application: */
142 /* Macros: */
143 /** Macro for encasing other multi-statement macros. This should be used along with an opening brace
144 * before the start of any multi-statement macro, so that the macros contents as a whole are treated
145 * as a discrete block and not as a list of separate statements which may cause problems when used as
146 * a block (such as inline \c if statements).
147 */
148 #define MACROS do
149
150 /** Macro for encasing other multi-statement macros. This should be used along with a preceding closing
151 * brace at the end of any multi-statement macro, so that the macros contents as a whole are treated
152 * as a discrete block and not as a list of separate statements which may cause problems when used as
153 * a block (such as inline \c if statements).
154 */
155 #define MACROE while (0)
156
157 /** Convenience macro to determine the larger of two values.
158 *
159 * \note This macro should only be used with operands that do not have side effects from being evaluated
160 * multiple times.
161 *
162 * \param[in] x First value to compare
163 * \param[in] y First value to compare
164 *
165 * \return The larger of the two input parameters
166 */
167 #if !defined(MAX) || defined(__DOXYGEN__)
168 #define MAX(x, y) ((x > y) ? x : y)
169 #endif
170
171 /** Convenience macro to determine the smaller of two values.
172 *
173 * \note This macro should only be used with operands that do not have side effects from being evaluated
174 * multiple times.
175 *
176 * \param[in] x First value to compare
177 * \param[in] y First value to compare
178 *
179 * \return The smaller of the two input parameters
180 */
181 #if !defined(MIN) || defined(__DOXYGEN__)
182 #define MIN(x, y) ((x < y) ? x : y)
183 #endif
184
185 #if (ARCH == ARCH_AVR8) || defined(__DOXYGEN__)
186 /** Defines a volatile \c NOP statement which cannot be optimized out by the compiler, and thus can always
187 * be set as a breakpoint in the resulting code. Useful for debugging purposes, where the optimizer
188 * removes/reorders code to the point where break points cannot reliably be set.
189 *
190 * \note This macro is not available for all architectures.
191 *
192 * \ingroup Group_Debugging
193 */
194 #define JTAG_DEBUG_POINT() __asm__ __volatile__ ("NOP" ::)
195
196 /** Defines an explicit JTAG break point in the resulting binary via the assembly \c BREAK statement. When
197 * a JTAG is used, this causes the program execution to halt when reached until manually resumed.
198 *
199 * \note This macro is not available for all architectures.
200 *
201 * \ingroup Group_Debugging
202 */
203 #define JTAG_DEBUG_BREAK() __asm__ __volatile__ ("BREAK" ::)
204
205 /** Macro for testing condition "x" and breaking via \ref JTAG_DEBUG_BREAK() if the condition is false.
206 *
207 * \note This macro is not available for all architectures.
208 *
209 * \param[in] Condition Condition that will be evaluated.
210 *
211 * \ingroup Group_Debugging
212 */
213 #define JTAG_DEBUG_ASSERT(Condition) MACROS{ if (!(Condition)) { JTAG_DEBUG_BREAK(); } }MACROE
214
215 /** Macro for testing condition "x" and writing debug data to the stdout stream if \c false. The stdout stream
216 * must be pre-initialized before this macro is run and linked to an output device, such as the microcontroller's
217 * USART peripheral.
218 *
219 * The output takes the form "{FILENAME}: Function {FUNCTION NAME}, Line {LINE NUMBER}: Assertion {Condition} failed."
220 *
221 * \note This macro is not available for all architectures.
222 *
223 * \param[in] Condition Condition that will be evaluated,
224 *
225 * \ingroup Group_Debugging
226 */
227 #define STDOUT_ASSERT(Condition) MACROS{ if (!(x)) { printf_P(PSTR("%s: Function \"%s\", Line %d: " \
228 "Assertion \"%s\" failed.\r\n"), \
229 __FILE__, __func__, __LINE__, #Condition); } }MACROE
230
231 #if !defined(pgm_read_ptr) || defined(__DOXYGEN__)
232 /** Reads a pointer out of PROGMEM space on the AVR8 architecture. This is currently a wrapper for the
233 * avr-libc \c pgm_read_ptr() macro with a \c void* cast, so that its value can be assigned directly
234 * to a pointer variable or used in pointer arithmetic without further casting in C. In a future
235 * avr-libc distribution this will be part of the standard API and will be implemented in a more formal
236 * manner.
237 *
238 * \note This macro is not available for all architectures.
239 *
240 * \param[in] Address Address of the pointer to read.
241 *
242 * \return Pointer retrieved from PROGMEM space.
243 */
244 #define pgm_read_ptr(Address) (void*)pgm_read_word(Address)
245 #endif
246 #endif
247
248 #if !defined(ISR) || defined(__DOXYGEN__)
249 /** Macro for the definition of interrupt service routines, so that the compiler can insert the required
250 * prologue and epilogue code to properly manage the interrupt routine without affecting the main thread's
251 * state with unintentional side-effects.
252 *
253 * Interrupt handlers written using this macro may still need to be registered with the microcontroller's
254 * Interrupt Controller (if present) before they will properly handle incoming interrupt events.
255 *
256 * \note This macro is only supplied on some architectures, where the standard library does not include a valid
257 * definition. If an existing definition exists, the alternative definition here will be ignored.
258 *
259 * \ingroup Group_GlobalInt
260 *
261 * \param Name Unique name of the interrupt service routine.
262 */
263 #define ISR(Name, ...) void Name (void) __attribute__((__interrupt__)) __VA_ARGS__; void Name (void)
264 #endif
265
266 /* Inline Functions: */
267 /** Function to reverse the individual bits in a byte - i.e. bit 7 is moved to bit 0, bit 6 to bit 1,
268 * etc.
269 *
270 * \param[in] Byte Byte of data whose bits are to be reversed.
271 */
272 static inline uint8_t BitReverse(uint8_t Byte) ATTR_WARN_UNUSED_RESULT ATTR_CONST;
273 static inline uint8_t BitReverse(uint8_t Byte)
274 {
275 Byte = (((Byte & 0xF0) >> 4) | ((Byte & 0x0F) << 4));
276 Byte = (((Byte & 0xCC) >> 2) | ((Byte & 0x33) << 2));
277 Byte = (((Byte & 0xAA) >> 1) | ((Byte & 0x55) << 1));
278
279 return Byte;
280 }
281
282 /** Function to perform a blocking delay for a specified number of milliseconds. The actual delay will be
283 * at a minimum the specified number of milliseconds, however due to loop overhead and internal calculations
284 * may be slightly higher.
285 *
286 * \param[in] Milliseconds Number of milliseconds to delay
287 */
288 static inline void Delay_MS(uint8_t Milliseconds) ATTR_ALWAYS_INLINE;
289 static inline void Delay_MS(uint8_t Milliseconds)
290 {
291 #if (ARCH == ARCH_AVR8)
292 if (GCC_IS_COMPILE_CONST(Milliseconds))
293 {
294 _delay_ms(Milliseconds);
295 }
296 else
297 {
298 while (Milliseconds--)
299 _delay_ms(1);
300 }
301 #elif (ARCH == ARCH_UC3)
302 while (Milliseconds--)
303 {
304 __builtin_mtsr(AVR32_COUNT, 0);
305 while (__builtin_mfsr(AVR32_COUNT) < (F_CPU / 1000));
306 }
307 #elif (ARCH == ARCH_XMEGA)
308 if (GCC_IS_COMPILE_CONST(Milliseconds))
309 {
310 _delay_ms(Milliseconds);
311 }
312 else
313 {
314 while (Milliseconds--)
315 _delay_ms(1);
316 }
317 #endif
318 }
319
320 /** Retrieves a mask which contains the current state of the global interrupts for the device. This
321 * value can be stored before altering the global interrupt enable state, before restoring the
322 * flag(s) back to their previous values after a critical section using \ref SetGlobalInterruptMask().
323 *
324 * \ingroup Group_GlobalInt
325 *
326 * \return Mask containing the current Global Interrupt Enable Mask bit(s).
327 */
328 static inline uint_reg_t GetGlobalInterruptMask(void) ATTR_ALWAYS_INLINE ATTR_WARN_UNUSED_RESULT;
329 static inline uint_reg_t GetGlobalInterruptMask(void)
330 {
331 GCC_MEMORY_BARRIER();
332
333 #if (ARCH == ARCH_AVR8)
334 return SREG;
335 #elif (ARCH == ARCH_UC3)
336 return __builtin_mfsr(AVR32_SR);
337 #elif (ARCH == ARCH_XMEGA)
338 return SREG;
339 #endif
340
341 GCC_MEMORY_BARRIER();
342 }
343
344 /** Sets the global interrupt enable state of the microcontroller to the mask passed into the function.
345 * This can be combined with \ref GetGlobalInterruptMask() to save and restore the Global Interrupt Enable
346 * Mask bit(s) of the device after a critical section has completed.
347 *
348 * \ingroup Group_GlobalInt
349 *
350 * \param[in] GlobalIntState Global Interrupt Enable Mask value to use
351 */
352 static inline void SetGlobalInterruptMask(const uint_reg_t GlobalIntState) ATTR_ALWAYS_INLINE;
353 static inline void SetGlobalInterruptMask(const uint_reg_t GlobalIntState)
354 {
355 GCC_MEMORY_BARRIER();
356
357 #if (ARCH == ARCH_AVR8)
358 SREG = GlobalIntState;
359 #elif (ARCH == ARCH_UC3)
360 if (GlobalIntState & AVR32_SR_GM)
361 __builtin_ssrf(AVR32_SR_GM_OFFSET);
362 else
363 __builtin_csrf(AVR32_SR_GM_OFFSET);
364 #elif (ARCH == ARCH_XMEGA)
365 SREG = GlobalIntState;
366 #endif
367
368 GCC_MEMORY_BARRIER();
369 }
370
371 /** Enables global interrupt handling for the device, allowing interrupts to be handled.
372 *
373 * \ingroup Group_GlobalInt
374 */
375 static inline void GlobalInterruptEnable(void) ATTR_ALWAYS_INLINE;
376 static inline void GlobalInterruptEnable(void)
377 {
378 GCC_MEMORY_BARRIER();
379
380 #if (ARCH == ARCH_AVR8)
381 sei();
382 #elif (ARCH == ARCH_UC3)
383 __builtin_csrf(AVR32_SR_GM_OFFSET);
384 #elif (ARCH == ARCH_XMEGA)
385 sei();
386 #endif
387
388 GCC_MEMORY_BARRIER();
389 }
390
391 /** Disabled global interrupt handling for the device, preventing interrupts from being handled.
392 *
393 * \ingroup Group_GlobalInt
394 */
395 static inline void GlobalInterruptDisable(void) ATTR_ALWAYS_INLINE;
396 static inline void GlobalInterruptDisable(void)
397 {
398 GCC_MEMORY_BARRIER();
399
400 #if (ARCH == ARCH_AVR8)
401 cli();
402 #elif (ARCH == ARCH_UC3)
403 __builtin_ssrf(AVR32_SR_GM_OFFSET);
404 #elif (ARCH == ARCH_XMEGA)
405 cli();
406 #endif
407
408 GCC_MEMORY_BARRIER();
409 }
410
411 /* Disable C linkage for C++ Compilers: */
412 #if defined(__cplusplus)
413 }
414 #endif
415
416 #endif
417
418 /** @} */
419