]> git.sur5r.net Git - freertos/blob - FreeRTOS-Plus/Source/FreeRTOS-Plus-Trace/trcUser.c
5391789716b2ed1d98319a5d851bdd6a80fde1db
[freertos] / FreeRTOS-Plus / Source / FreeRTOS-Plus-Trace / trcUser.c
1 /*******************************************************************************\r
2  * Tracealyzer v3.0.2 Recorder Library\r
3  * Percepio AB, www.percepio.com\r
4  *\r
5  * trcUser.c\r
6  *\r
7  * The public API of the trace recorder library.\r
8  *\r
9  * Terms of Use\r
10  * This software is copyright Percepio AB. The recorder library is free for\r
11  * use together with Percepio products. You may distribute the recorder library\r
12  * in its original form, including modifications in trcHardwarePort.c/.h\r
13  * given that these modification are clearly marked as your own modifications\r
14  * and documented in the initial comment section of these source files.\r
15  * This software is the intellectual property of Percepio AB and may not be\r
16  * sold or in other ways commercially redistributed without explicit written\r
17  * permission by Percepio AB.\r
18  *\r
19  * Disclaimer\r
20  * The trace tool and recorder library is being delivered to you AS IS and\r
21  * Percepio AB makes no warranty as to its use or performance. Percepio AB does\r
22  * not and cannot warrant the performance or results you may obtain by using the\r
23  * software or documentation. Percepio AB make no warranties, express or\r
24  * implied, as to noninfringement of third party rights, merchantability, or\r
25  * fitness for any particular purpose. In no event will Percepio AB, its\r
26  * technology partners, or distributors be liable to you for any consequential,\r
27  * incidental or special damages, including any lost profits or lost savings,\r
28  * even if a representative of Percepio AB has been advised of the possibility\r
29  * of such damages, or for any claim by any third party. Some jurisdictions do\r
30  * not allow the exclusion or limitation of incidental, consequential or special\r
31  * damages, or the exclusion of implied warranties or limitations on how long an\r
32  * implied warranty may last, so the above limitations may not apply to you.\r
33  *\r
34  * Tabs are used for indent in this file (1 tab = 4 spaces)\r
35  *\r
36  * Copyright Percepio AB, 2014.\r
37  * www.percepio.com\r
38  ******************************************************************************/\r
39 #include "trcUser.h"\r
40 \r
41 #if (USE_TRACEALYZER_RECORDER == 1)\r
42 \r
43 #include <string.h>\r
44 #include <stdarg.h>\r
45 #include <stdint.h>\r
46 \r
47 TRACE_STOP_HOOK vTraceStopHookPtr = (TRACE_STOP_HOOK)0;\r
48 \r
49 extern uint8_t inExcludedTask;\r
50 extern int8_t nISRactive;\r
51 extern objectHandleType handle_of_last_logged_task;\r
52 extern uint32_t dts_min;\r
53 extern uint32_t hwtc_count_max_after_tick;\r
54 extern uint32_t hwtc_count_sum_after_tick;\r
55 extern uint32_t hwtc_count_sum_after_tick_counter;\r
56 extern char* traceErrorMessage;\r
57 \r
58 /*** Private functions *******************************************************/\r
59 void vTracePrintF_Helper(traceLabel eventLabel, const char* formatStr, va_list vl);\r
60 \r
61 #if (USE_SEPARATE_USER_EVENT_BUFFER == 1)\r
62 void vTraceChannelPrintF_Helper(UserEventChannel channelPair, va_list vl);\r
63 static void prvTraceUserEventHelper1(UserEventChannel channel, traceLabel eventLabel, traceLabel formatLabel, va_list vl);\r
64 static void prvTraceUserEventHelper2(UserEventChannel channel, uint32_t* data, uint32_t noOfSlots);\r
65 #endif\r
66 \r
67 static void prvTraceTaskInstanceFinish(int8_t direct);\r
68 \r
69 \r
70 /*******************************************************************************\r
71  * vTraceInitTraceData\r
72  *\r
73  * Allocates, if necessary, and initializes the recorder data structure, based\r
74  * on the constants in trcConfig.h.\r
75  ******************************************************************************/\r
76 void vTraceInitTraceData(void)\r
77 {\r
78         prvTraceInitTraceData();\r
79 }\r
80 \r
81 /*******************************************************************************\r
82  * vTraceSetRecorderData\r
83  *\r
84  * If custom allocation is used, this function must be called so the recorder\r
85  * library knows where to save the trace data.\r
86  ******************************************************************************/\r
87 #if TRACE_DATA_ALLOCATION == TRACE_DATA_ALLOCATION_CUSTOM\r
88 void vTraceSetRecorderData(void* pRecorderData)\r
89 {\r
90         TRACE_ASSERT(pRecorderData != NULL, "vTraceSetTraceData, pRecorderData == NULL", );\r
91         RecorderDataPtr = pRecorderData;\r
92 }\r
93 #endif\r
94 \r
95 /*******************************************************************************\r
96  * vTraceSetStopHook\r
97  *\r
98  * Sets a function to be called when the recorder is stopped.\r
99  ******************************************************************************/\r
100 void vTraceSetStopHook(TRACE_STOP_HOOK stopHookFunction)\r
101 {\r
102         vTraceStopHookPtr = stopHookFunction;\r
103 }\r
104 \r
105 /*******************************************************************************\r
106  * vTraceClear\r
107  *\r
108  * Resets the recorder. Only necessary if a restart is desired - this is not\r
109  * needed in the startup initialization.\r
110  ******************************************************************************/\r
111 void vTraceClear(void)\r
112 {\r
113         TRACE_SR_ALLOC_CRITICAL_SECTION();\r
114         trcCRITICAL_SECTION_BEGIN();\r
115 \r
116         RecorderDataPtr->absTimeLastEventSecond = 0;\r
117 \r
118         RecorderDataPtr->absTimeLastEvent = 0;\r
119         RecorderDataPtr->nextFreeIndex = 0;\r
120         RecorderDataPtr->numEvents = 0;\r
121         RecorderDataPtr->bufferIsFull = 0;\r
122         traceErrorMessage = NULL;\r
123         RecorderDataPtr->internalErrorOccured = 0;\r
124 \r
125         memset(RecorderDataPtr->eventData, 0, RecorderDataPtr->maxEvents * 4);\r
126 \r
127         handle_of_last_logged_task = 0;\r
128         \r
129         trcCRITICAL_SECTION_END();\r
130 \r
131 }\r
132 \r
133 /*******************************************************************************\r
134  * uiTraceStart\r
135  *\r
136  * Starts the recorder. The recorder will not be started if an error has been\r
137  * indicated using vTraceError, e.g. if any of the Nx constants in trcConfig.h\r
138  * has a too small value (NTASK, NQUEUE, etc).\r
139  *\r
140  * Returns 1 if the recorder was started successfully.\r
141  * Returns 0 if the recorder start was prevented due to a previous internal\r
142  * error. In that case, check vTraceGetLastError to get the error message.\r
143  * Any error message is also presented when opening a trace file.\r
144  ******************************************************************************/\r
145 \r
146 uint32_t uiTraceStart(void)\r
147 {\r
148         objectHandleType handle;\r
149         TRACE_SR_ALLOC_CRITICAL_SECTION();\r
150 \r
151         handle = 0;\r
152 \r
153         if (RecorderDataPtr == NULL)\r
154         {\r
155                 vTraceError("RecorderDataPtr is NULL. Call vTraceInitTraceData() before starting trace.");\r
156                 return 0;\r
157         }\r
158 \r
159         if (traceErrorMessage == NULL)\r
160         {\r
161                 trcCRITICAL_SECTION_BEGIN();\r
162                 RecorderDataPtr->recorderActive = 1;\r
163 \r
164                 handle = TRACE_GET_TASK_NUMBER(TRACE_GET_CURRENT_TASK());\r
165                 if (handle == 0)\r
166                 {\r
167                         /* This occurs if the scheduler is not yet started.\r
168                         This creates a dummy "(startup)" task entry internally in the\r
169                         recorder */\r
170                         handle = xTraceGetObjectHandle(TRACE_CLASS_TASK);\r
171                         vTraceSetObjectName(TRACE_CLASS_TASK, handle, "(startup)");\r
172 \r
173                         vTraceSetPriorityProperty(TRACE_CLASS_TASK, handle, 0);\r
174                 }\r
175 \r
176                 vTraceStoreTaskswitch(handle); /* Register the currently running task */\r
177                 trcCRITICAL_SECTION_END();\r
178         }\r
179 \r
180         return RecorderDataPtr->recorderActive;\r
181 }\r
182 \r
183 /*******************************************************************************\r
184  * vTraceStart\r
185  *\r
186  * Starts the recorder. The recorder will not be started if an error has been\r
187  * indicated using vTraceError, e.g. if any of the Nx constants in trcConfig.h\r
188  * has a too small value (NTASK, NQUEUE, etc).\r
189  *\r
190  * This function is obsolete, but has been saved for backwards compatibility.\r
191  * We recommend using uiTraceStart instead.\r
192  ******************************************************************************/\r
193 void vTraceStart(void)\r
194 {\r
195         (void)uiTraceStart();\r
196 }\r
197 \r
198 /*******************************************************************************\r
199  * vTraceStop\r
200  *\r
201  * Stops the recorder. The recording can be resumed by calling vTraceStart.\r
202  * This does not reset the recorder. Use vTraceClear if that is desired.\r
203  ******************************************************************************/\r
204 void vTraceStop(void)\r
205 {\r
206         RecorderDataPtr->recorderActive = 0;\r
207 \r
208         if (vTraceStopHookPtr != (TRACE_STOP_HOOK)0)\r
209         {\r
210                 (*vTraceStopHookPtr)();                 /* An application call-back function. */\r
211         }\r
212 }\r
213 \r
214 /*******************************************************************************\r
215  * xTraceGetLastError\r
216  *\r
217  * Gives the last error message, if any. NULL if no error message is stored.\r
218  * Any error message is also presented when opening a trace file.\r
219  ******************************************************************************/\r
220 char* xTraceGetLastError(void)\r
221 {\r
222         return traceErrorMessage;\r
223 }\r
224 \r
225 /*******************************************************************************\r
226 * vTraceClearError\r
227 *\r
228 * Removes any previous error message generated by recorder calling vTraceError.\r
229 * By calling this function, it may be possible to start/restart the trace\r
230 * despite errors in the recorder, but there is no guarantee that the trace\r
231 * recorder will work correctly in that case, depending on the type of error.\r
232 ******************************************************************************/\r
233 void vTraceClearError(int resetErrorMessage)\r
234 {\r
235         ( void ) resetErrorMessage;\r
236         traceErrorMessage = NULL;\r
237         RecorderDataPtr->internalErrorOccured = 0;\r
238 }\r
239 \r
240 /*******************************************************************************\r
241  * vTraceGetTraceBuffer\r
242  *\r
243  * Returns a pointer to the recorder data structure. Use this together with\r
244  * uiTraceGetTraceBufferSize if you wish to implement an own store/upload\r
245  * solution, e.g., in case a debugger connection is not available for uploading\r
246  * the data.\r
247  ******************************************************************************/\r
248 void* vTraceGetTraceBuffer(void)\r
249 {\r
250         return RecorderDataPtr;\r
251 }\r
252 \r
253 /*******************************************************************************\r
254  * uiTraceGetTraceBufferSize\r
255  *\r
256  * Gets the size of the recorder data structure. For use together with\r
257  * vTraceGetTraceBuffer if you wish to implement an own store/upload solution,\r
258  * e.g., in case a debugger connection is not available for uploading the data.\r
259  ******************************************************************************/\r
260 uint32_t uiTraceGetTraceBufferSize(void)\r
261 {\r
262         return sizeof(RecorderDataType);\r
263 }\r
264 \r
265 /******************************************************************************\r
266  * prvTraceTaskInstanceFinish.\r
267  *\r
268  * Private common function for the vTraceTaskInstanceFinishXXX functions.\r
269  * \r
270  *****************************************************************************/\r
271 void prvTraceTaskInstanceFinish(int8_t direct)\r
272 {\r
273         TaskInstanceStatusEvent* tis;\r
274         uint8_t dts45;\r
275 \r
276         TRACE_SR_ALLOC_CRITICAL_SECTION();\r
277 \r
278         trcCRITICAL_SECTION_BEGIN();\r
279         if (RecorderDataPtr->recorderActive && (! inExcludedTask || nISRactive) && handle_of_last_logged_task)\r
280         {\r
281                 dts45 = (uint8_t)prvTraceGetDTS(0xFF);\r
282                 tis = (TaskInstanceStatusEvent*) xTraceNextFreeEventBufferSlot();\r
283                 if (tis != NULL)\r
284                 {\r
285                         if (direct == 0)\r
286                                 tis->type = TASK_INSTANCE_FINISHED_NEXT_KSE;\r
287                         else\r
288                                 tis->type = TASK_INSTANCE_FINISHED_DIRECT;\r
289 \r
290                         tis->dts = dts45;\r
291                         prvTraceUpdateCounters();\r
292                 }\r
293         }\r
294         trcCRITICAL_SECTION_END();\r
295 }\r
296 \r
297 /******************************************************************************\r
298  * vTraceTaskInstanceFinish(void)\r
299  *\r
300  * Marks the current task instance as finished on the next kernel call.\r
301  *\r
302  * If that kernel call is blocking, the instance ends after the blocking event\r
303  * and the corresponding return event is then the start of the next instance.\r
304  * If the kernel call is not blocking, the viewer instead splits the current\r
305  * fragment right before the kernel call, which makes this call the first event\r
306  * of the next instance.\r
307  *\r
308  * See also USE_IMPLICIT_IFE_RULES in trcConfig.h\r
309  *\r
310  * Example:\r
311  *\r
312  *              while(1)\r
313  *              {\r
314  *                      xQueueReceive(CommandQueue, &command, timeoutDuration);\r
315  *                      processCommand(command);\r
316  *          vTraceInstanceFinish();\r
317  *              }\r
318  *\r
319  * Note: This is only supported in Tracealyzer tools v2.7 or later\r
320  *\r
321  *****************************************************************************/\r
322 void vTraceTaskInstanceFinish(void)\r
323 {\r
324     prvTraceTaskInstanceFinish(0);\r
325 }\r
326 \r
327 /******************************************************************************\r
328  * vTraceTaskInstanceFinishDirect(void)\r
329  *\r
330  * Marks the current task instance as finished at this very instant.\r
331  * This makes the viewer to splits the current fragment at this point and begin\r
332  * a new actor instance.\r
333  *\r
334  * See also USE_IMPLICIT_IFE_RULES in trcConfig.h\r
335  *\r
336  * Example:\r
337  *\r
338  *              This example will generate two instances for each loop iteration.\r
339  *              The first instance ends at vTraceInstanceFinishDirect(), while the second\r
340  *      instance ends at the next xQueueReceive call.\r
341  *\r
342  *              while (1)\r
343  *              {\r
344  *          xQueueReceive(CommandQueue, &command, timeoutDuration);\r
345  *                      ProcessCommand(command);\r
346  *                      vTraceInstanceFinishDirect();\r
347  *                      DoSometingElse();\r
348  *          vTraceInstanceFinish();\r
349  *      }\r
350  *\r
351  * Note: This is only supported in Tracealyzer tools v2.7 or later\r
352  *\r
353  *****************************************************************************/\r
354 void vTraceTaskInstanceFinishDirect(void)\r
355 {\r
356         prvTraceTaskInstanceFinish(1);\r
357 }\r
358 \r
359 /*******************************************************************************\r
360  * Interrupt recording functions\r
361  ******************************************************************************/\r
362 \r
363 #if (INCLUDE_ISR_TRACING == 1)\r
364 \r
365 #define MAX_ISR_NESTING 16\r
366 static uint8_t isrstack[MAX_ISR_NESTING];\r
367 int32_t isPendingContextSwitch = 0;\r
368 \r
369 /*******************************************************************************\r
370  * vTraceSetISRProperties\r
371  *\r
372  * Registers an Interrupt Service Routine in the recorder library, This must be\r
373  * called before using vTraceStoreISRBegin to store ISR events. This is\r
374  * typically called in the startup of the system, before the scheduler is\r
375  * started.\r
376  *\r
377  * Example:\r
378  *       #define ID_ISR_TIMER1 1                // lowest valid ID is 1\r
379  *       #define PRIO_OF_ISR_TIMER1 3 // the hardware priority of the interrupt\r
380  *       ...\r
381  *       vTraceSetISRProperties(ID_ISR_TIMER1, "ISRTimer1", PRIO_OF_ISR_TIMER1);\r
382  *       ...\r
383  *       void ISR_handler()\r
384  *       {\r
385  *               vTraceStoreISRBegin(ID_OF_ISR_TIMER1);\r
386  *               ...\r
387  *               vTraceStoreISREnd(0);\r
388  *       }\r
389  *\r
390  * NOTE: To safely record ISRs, you need to make sure that all traced\r
391  * interrupts actually are disabled by trcCRITICAL_SECTION_BEGIN(). However,\r
392  * in some ports this does not disable high priority interrupts!\r
393  * If an ISR calls vTraceStoreISRBegin while the recorder is busy, it will\r
394  * stop the recording and give an error message.\r
395  ******************************************************************************/\r
396 void vTraceSetISRProperties(objectHandleType handle, const char* name, char priority)\r
397 {\r
398         TRACE_ASSERT(handle <= RecorderDataPtr->ObjectPropertyTable.NumberOfObjectsPerClass[TRACE_CLASS_ISR], "vTraceSetISRProperties: Invalid value for handle", );\r
399         TRACE_ASSERT(name != NULL, "vTraceSetISRProperties: name == NULL", );\r
400 \r
401         vTraceSetObjectName(TRACE_CLASS_ISR, handle, name);\r
402         vTraceSetPriorityProperty(TRACE_CLASS_ISR, handle, priority);\r
403 }\r
404 \r
405 #if (SELECTED_PORT == PORT_ARM_CortexM)\r
406 /******************************************************************************\r
407  * (Advanced...)\r
408  *\r
409  * ISR_TAILCHAINING_THRESHOLD (For Cortex-M devices only)\r
410  *\r
411  * ARM Cortex-M devices may execute ISRs back-to-back (tail-chained) without\r
412  * resuming the previous context in between. Since this is decided in\r
413  * hardware, we can only detect this indirectly, in the following manner:\r
414  *\r
415  * When entering vTraceStoreISRBegin, we check the number of CPU cycles since\r
416  * the last return of vTraceStoreISREnd. If less or equal to the constant\r
417  * ISR_TAILCHAINING_THRESHOLD it is assumed that the ISRs executed back-to-back\r
418  * (tail-chained). In that case, the previously stored RESUME event\r
419  * (pointed to by ptrLastISRExitEvent) is then deleted to avoid showing a\r
420  * fragment of the previous context in between the ISR events. The delete is\r
421  * made by replacing the event code with a XTS16L event, that serves to keep\r
422  * the differential timestamp from the earlier event.\r
423  *\r
424  * The value of ISR_TAILCHAINING_THRESHOLD depends on the interrupt latency of\r
425  * the processor, on the compiler and on the compiler settings, but should be\r
426  * around 70 cycles. The default value is 66 cycles, which should be correct when\r
427  * using GCC with optimizations disabled (-O0) and Cortex-M3/M4.\r
428  *\r
429  * To measure this value, see MEASURE_ISR_TAILCHAINING_THRESHOLD below.\r
430  *\r
431  * If this value set too low, tail-chained ISRs will incorrectly be shown\r
432  * separated, with a short fragment of the previous task or ISR in between.\r
433  * If this value is set too high, you get the opposite effect - separate ISRs\r
434  * will appear to execute tail-chained and will appear to have higher execution\r
435  * time and response time (maximum ISR_TAILCHAINING_THRESHOLD cycles more).\r
436  *\r
437  * Read the blog post explaining this on our website:\r
438  * http://percepio.com/2014/05/06/sw-based-exc-tracing-arm-cortex-m/\r
439  *\r
440  *****************************************************************************/\r
441 #define ISR_TAILCHAINING_THRESHOLD 66\r
442 \r
443 uint8_t* ptrLastISRExitEvent = NULL;\r
444 uint32_t DWTCycleCountAtLastISRExit = 0;\r
445 \r
446 /******************************************************************************\r
447  * (Advanced...)\r
448  *\r
449  * MEASURE_ISR_TAILCHAINING_THRESHOLD (For Cortex-M devices only)\r
450  *\r
451  * Allows for calibrating the value of ISR_TAILCHAINING_THRESHOLD (see above).\r
452  *\r
453  * This is intended to measure the minimum number of clock cycles from the end\r
454  * of vTraceStoreISREnd to the beginning of the following vTraceStoreISRBegin.\r
455  * For this purpose, we assume a test setup using the SysTick interrupt, which\r
456  * is available on most Cortex-M devices and typically used by the RTOS kernel.\r
457  * To do the measurement, follow these steps:\r
458  *\r
459  * 1. Make sure MEASURE_ISR_TAILCHAINING_THRESHOLD is enabled (defined as 1)\r
460  *\r
461  * 2. Temporarily replace your SysTick handler with the following:\r
462  *\r
463  *      void xPortSysTickHandler( void )\r
464  *      {\r
465  *              vTraceStoreISRBegin(1);\r
466  *              vTraceStoreISREnd(0);\r
467  *      }\r
468  *\r
469  * 3. To make sure that the ISRs execute back-to-back, increase the OS tick\r
470  *      frequency to a very high level so that the OS tick interrupt execute\r
471  *      continuously with no application tasks in between, e.g. 10 MHz.\r
472  *\r
473  * 4. Put a breakpoint in the highest priority task and make sure it is not\r
474  *      reached. This means that the SysTick handler is executing at maximum rate\r
475  *      and thereby tail-chained, where the interrupt latency is 6 cycles.\r
476  *\r
477  * 5. Let the system run without breakpoints and inspect the value of\r
478  *      threshold_low_watermark. This is the minimum total latency observed.\r
479  *      The hardware latency is 6 clock cycles due to the tail-chaining, so the\r
480  *      software latency (SL) is then SL = threshold_low_watermark - 6.\r
481  *\r
482  * The threshold value ISR_TAILCHAINING_THRESHOLD should be SL + 2 * HL, where\r
483  * HL is the normal hardware interrupt latency, i.e., the number of CPU\r
484  * cycles to enter or exit the exception handler for an exception in task\r
485  * context. The HL value is 12-16 depending on core, as shown below.\r
486  *\r
487  * Values for ISR_TAILCHAINING_THRESHOLD, assuming SL = 42\r
488  *      Cortex-M3 and M4 (HL = 12):     66 cycles\r
489  *      Cortex-M0 (HL = 16):            74 cycles\r
490  *      Cortex-M0+ (HL = 15):           72 cycles\r
491  *\r
492  * If the ISR_TAILCHAINING_THRESHOLD value is set too low, some tail-chained\r
493  * ISRs be shown separated, with a short fragment of the previous context\r
494  * in between. On the other hand, if the value is set too high, ISRs that \r
495  * actually are separated may appear to execute back-to-back (tail-chained).\r
496  *\r
497  * Read the blog post explaining this on our website:\r
498  * http://percepio.com/2014/05/06/sw-based-exc-tracing-arm-cortex-m/\r
499  *\r
500  *****************************************************************************/\r
501 #define MEASURE_ISR_TAILCHAINING_THRESHOLD 1\r
502 \r
503 #if (MEASURE_ISR_TAILCHAINING_THRESHOLD == 1)\r
504 volatile uint32_t threshold_low_watermark = 2000000000;\r
505 #endif\r
506 \r
507 #endif\r
508 \r
509 /*******************************************************************************\r
510  * vTraceStoreISRBegin\r
511  *\r
512  * Registers the beginning of an Interrupt Service Routine.\r
513  *\r
514  * Example:\r
515  *       #define ID_ISR_TIMER1 1                // lowest valid ID is 1\r
516  *       #define PRIO_OF_ISR_TIMER1 3 // the hardware priority of the interrupt\r
517  *       ...\r
518  *       vTraceSetISRProperties(ID_ISR_TIMER1, "ISRTimer1", PRIO_OF_ISR_TIMER1);\r
519  *       ...\r
520  *       void ISR_handler()\r
521  *       {\r
522  *               vTraceStoreISRBegin(ID_OF_ISR_TIMER1);\r
523  *               ...\r
524  *               vTraceStoreISREnd(0);\r
525  *       }\r
526  *\r
527  ******************************************************************************/\r
528 void vTraceStoreISRBegin(objectHandleType handle)\r
529 {\r
530         uint16_t dts4;\r
531         #if (SELECTED_PORT == PORT_ARM_CortexM)\r
532         uint32_t CPUCyclesSinceLastISRExit = REG_DWT_CYCCNT - DWTCycleCountAtLastISRExit;\r
533         #endif\r
534         TSEvent* ts;\r
535         TRACE_SR_ALLOC_CRITICAL_SECTION();\r
536 \r
537         ts = NULL;\r
538 \r
539 #if (SELECTED_PORT == PORT_ARM_CortexM)\r
540         if (DWTCycleCountAtLastISRExit > 0)\r
541         {\r
542                 #if (MEASURE_ISR_TAILCHAINING_THRESHOLD == 1)\r
543                 /* Allows for verifying the value of ISR_TAILCHAINING_THRESHOLD */\r
544                 if (CPUCyclesSinceLastISRExit < threshold_low_watermark)\r
545                 {\r
546                         threshold_low_watermark = CPUCyclesSinceLastISRExit;\r
547                 }\r
548                 #endif\r
549 \r
550                 if (CPUCyclesSinceLastISRExit <= ISR_TAILCHAINING_THRESHOLD)\r
551                 {\r
552                         /* This is judged to be a case of ISR tail-chaining since the\r
553                         number of cycles since the last vTraceStoreISREnd is shorter or equal to\r
554                         the threshold (ISR_TAILCHAINING_THRESHOLD) */\r
555 \r
556                         if (ptrLastISRExitEvent != NULL)\r
557                         {\r
558                                 /* Overwrite the last ISR exit event with a "neutral" event that only\r
559                                         accounts for the time passed */\r
560                                 *ptrLastISRExitEvent = XTS16L;\r
561                         }\r
562                 }\r
563 \r
564         }\r
565 #endif\r
566 \r
567         if (recorder_busy)\r
568         {\r
569          vTraceError("Illegal call to vTraceStoreISRBegin, recorder busy!");\r
570          return;\r
571         }\r
572         trcCRITICAL_SECTION_BEGIN();\r
573         \r
574         if (nISRactive == 0)\r
575                 isPendingContextSwitch = 0;     /* We are at the start of a possible ISR chain. No context switches should have been triggered now. */\r
576         \r
577         if (RecorderDataPtr->recorderActive && handle_of_last_logged_task)\r
578         {\r
579 \r
580                 TRACE_ASSERT(handle <= RecorderDataPtr->ObjectPropertyTable.NumberOfObjectsPerClass[TRACE_CLASS_ISR], "vTraceStoreISRBegin: Invalid value for handle", );\r
581                 \r
582                 dts4 = (uint16_t)prvTraceGetDTS(0xFFFF);\r
583 \r
584                 if (RecorderDataPtr->recorderActive) /* Need to repeat this check! */\r
585                 {\r
586                         if (nISRactive < MAX_ISR_NESTING)\r
587                         {\r
588                                 uint8_t hnd8 = prvTraceGet8BitHandle(handle);\r
589                                 isrstack[nISRactive] = handle;\r
590                                 nISRactive++;\r
591                                 ts = (TSEvent*)xTraceNextFreeEventBufferSlot();\r
592                                 if (ts != NULL)\r
593                                 {\r
594                                         ts->type = TS_ISR_BEGIN;\r
595                                         ts->dts = dts4;\r
596                                         ts->objHandle = hnd8;\r
597                                         prvTraceUpdateCounters();\r
598                                 }\r
599                         }\r
600                         else\r
601                         {\r
602                                 /* This should not occur unless something is very wrong */\r
603                                 vTraceError("Too many nested interrupts!");\r
604                         }\r
605                 }\r
606         }\r
607         trcCRITICAL_SECTION_END();\r
608 }\r
609 \r
610 /*******************************************************************************\r
611  * vTraceStoreISREnd\r
612  *\r
613  * Registers the end of an Interrupt Service Routine.\r
614  *\r
615  * The parameter pendingISR indicates if the interrupt has requested a\r
616  * task-switch (= 1) or if the interrupt returns to the earlier context (= 0)\r
617  *\r
618  * Example:\r
619  *\r
620  *       #define ID_ISR_TIMER1 1                // lowest valid ID is 1\r
621  *       #define PRIO_OF_ISR_TIMER1 3 // the hardware priority of the interrupt\r
622  *       ...\r
623  *       vTraceSetISRProperties(ID_ISR_TIMER1, "ISRTimer1", PRIO_OF_ISR_TIMER1);\r
624  *       ...\r
625  *       void ISR_handler()\r
626  *       {\r
627  *               vTraceStoreISRBegin(ID_OF_ISR_TIMER1);\r
628  *               ...\r
629  *               vTraceStoreISREnd(0);\r
630  *       }\r
631  *\r
632  ******************************************************************************/\r
633 void vTraceStoreISREnd(int pendingISR)\r
634 {\r
635         TSEvent* ts;\r
636         uint16_t dts5;\r
637         uint8_t hnd8 = 0, type = 0;\r
638         \r
639         TRACE_SR_ALLOC_CRITICAL_SECTION();\r
640 \r
641         if (! RecorderDataPtr->recorderActive ||  ! handle_of_last_logged_task)\r
642         {\r
643                 return;\r
644         }\r
645 \r
646         if (recorder_busy)\r
647         {\r
648                 vTraceError("Illegal call to vTraceStoreISREnd, recorder busy!");\r
649                 return;\r
650         }\r
651         \r
652         if (nISRactive == 0)\r
653         {\r
654                 vTraceError("Unmatched call to vTraceStoreISREnd (nISRactive == 0, expected > 0)");\r
655                 return;\r
656         }\r
657 \r
658         trcCRITICAL_SECTION_BEGIN();\r
659         isPendingContextSwitch |= pendingISR;   /* Is there a pending context switch right now? */\r
660         nISRactive--;\r
661         if (nISRactive > 0)\r
662         {\r
663                 /* Return to another isr */\r
664                 type = TS_ISR_RESUME;\r
665                 hnd8 = prvTraceGet8BitHandle(isrstack[nISRactive - 1]); /* isrstack[nISRactive] is the handle of the ISR we're currently exiting. isrstack[nISRactive - 1] is the handle of the ISR that was executing previously. */\r
666         }\r
667         else if (isPendingContextSwitch == 0)\r
668         {\r
669                 /* No context switch has been triggered by any ISR in the chain. Return to task */\r
670                 type = TS_TASK_RESUME;\r
671                 hnd8 = prvTraceGet8BitHandle(handle_of_last_logged_task);\r
672         }\r
673         else\r
674         {\r
675                 /* Context switch has been triggered by some ISR. We expect a proper context switch event shortly so we do nothing. */\r
676         }\r
677 \r
678         if (type != 0)\r
679         {\r
680                 dts5 = (uint16_t)prvTraceGetDTS(0xFFFF);\r
681                 ts = (TSEvent*)xTraceNextFreeEventBufferSlot();\r
682                 if (ts != NULL)\r
683                 {\r
684                         ts->type = type;\r
685                         ts->objHandle = hnd8;\r
686                         ts->dts = dts5;\r
687                         prvTraceUpdateCounters();\r
688                 }\r
689 \r
690                 #if (SELECTED_PORT == PORT_ARM_CortexM)\r
691                 /* Remember the last ISR exit event, as the event needs to be modified in case of a following ISR entry (if tail-chained ISRs) */\r
692                 ptrLastISRExitEvent = (uint8_t*)ts;\r
693                 #endif          \r
694         }\r
695 \r
696         #if (SELECTED_PORT == PORT_ARM_CortexM)\r
697         DWTCycleCountAtLastISRExit = REG_DWT_CYCCNT;\r
698         #endif\r
699 \r
700         trcCRITICAL_SECTION_END();\r
701 }\r
702 \r
703 #else\r
704 \r
705 /* ISR tracing is turned off */\r
706 void vTraceIncreaseISRActive(void)\r
707 {\r
708         if (RecorderDataPtr->recorderActive && handle_of_last_logged_task)\r
709                 nISRactive++;\r
710 }\r
711 \r
712 void vTraceDecreaseISRActive(void)\r
713 {\r
714         if (RecorderDataPtr->recorderActive && handle_of_last_logged_task)\r
715                 nISRactive--;\r
716 }\r
717 #endif\r
718 \r
719 \r
720 /********************************************************************************/\r
721 /* User Event functions                                                                                                                 */\r
722 /********************************************************************************/\r
723 \r
724 #if (INCLUDE_USER_EVENTS == 1)\r
725 \r
726 #define MAX_ARG_SIZE (4+32)\r
727 /*** Locally used in vTracePrintF ***/\r
728 static uint8_t writeInt8(void * buffer, uint8_t i, uint8_t value)\r
729 {\r
730         TRACE_ASSERT(buffer != NULL, "writeInt8: buffer == NULL", 0);\r
731 \r
732         if (i >= MAX_ARG_SIZE)\r
733         {\r
734                 return 255;\r
735         }\r
736 \r
737         ((uint8_t*)buffer)[i] = value;\r
738 \r
739         if (i + 1 > MAX_ARG_SIZE)\r
740         {\r
741                 return 255;\r
742         }\r
743 \r
744         return i + 1;\r
745 }\r
746 \r
747 /*** Locally used in vTracePrintF ***/\r
748 static uint8_t writeInt16(void * buffer, uint8_t i, uint16_t value)\r
749 {\r
750         TRACE_ASSERT(buffer != NULL, "writeInt16: buffer == NULL", 0);\r
751 \r
752         /* Align to multiple of 2 */\r
753         while ((i % 2) != 0)\r
754         {\r
755                 if (i >= MAX_ARG_SIZE)\r
756                 {\r
757                         return 255;\r
758                 }\r
759 \r
760                 ((uint8_t*)buffer)[i] = 0;\r
761                 i++;\r
762         }\r
763 \r
764         if (i + 2 > MAX_ARG_SIZE)\r
765         {\r
766                 return 255;\r
767         }\r
768 \r
769         ((uint16_t*)buffer)[i/2] = value;\r
770 \r
771         return i + 2;\r
772 }\r
773 \r
774 /*** Locally used in vTracePrintF ***/\r
775 static uint8_t writeInt32(void * buffer, uint8_t i, uint32_t value)\r
776 {\r
777         TRACE_ASSERT(buffer != NULL, "writeInt32: buffer == NULL", 0);\r
778 \r
779         /* A 32 bit value should begin at an even 4-byte address */\r
780         while ((i % 4) != 0)\r
781         {\r
782                 if (i >= MAX_ARG_SIZE)\r
783                 {\r
784                         return 255;\r
785                 }\r
786 \r
787                 ((uint8_t*)buffer)[i] = 0;\r
788                 i++;\r
789         }\r
790 \r
791         if (i + 4 > MAX_ARG_SIZE)\r
792         {\r
793                 return 255;\r
794         }\r
795 \r
796         ((uint32_t*)buffer)[i/4] = value;\r
797 \r
798         return i + 4;\r
799 }\r
800 \r
801 #if (INCLUDE_FLOAT_SUPPORT)\r
802 \r
803 /*** Locally used in vTracePrintF ***/\r
804 static uint8_t writeFloat(void * buffer, uint8_t i, float value)\r
805 {\r
806         TRACE_ASSERT(buffer != NULL, "writeFloat: buffer == NULL", 0);\r
807 \r
808         /* A 32 bit value should begin at an even 4-byte address */\r
809         while ((i % 4) != 0)\r
810         {\r
811                 if (i >= MAX_ARG_SIZE)\r
812                 {\r
813                         return 255;\r
814                 }\r
815 \r
816                 ((uint8_t*)buffer)[i] = 0;\r
817                 i++;\r
818         }\r
819 \r
820         if (i + 4 > MAX_ARG_SIZE)\r
821         {\r
822                 return 255;\r
823         }\r
824 \r
825         ((float*)buffer)[i/4] = value;\r
826 \r
827         return i + 4;\r
828 }\r
829 \r
830 /*** Locally used in vTracePrintF ***/\r
831 static uint8_t writeDouble(void * buffer, uint8_t i, double value)\r
832 {\r
833         uint32_t * dest;\r
834         uint32_t * src = (uint32_t*)&value;\r
835 \r
836         TRACE_ASSERT(buffer != NULL, "writeDouble: buffer == NULL", 0);\r
837 \r
838         /* The double is written as two 32 bit values, and should begin at an even\r
839         4-byte address (to avoid having to align with 8 byte) */\r
840         while (i % 4 != 0)\r
841         {\r
842                 if (i >= MAX_ARG_SIZE)\r
843                 {\r
844                         return 255;\r
845                 }\r
846 \r
847                 ((uint8_t*)buffer)[i] = 0;\r
848                 i++;\r
849         }\r
850 \r
851         if (i + 8 > MAX_ARG_SIZE)\r
852         {\r
853                 return 255;\r
854         }\r
855 \r
856         dest = &(((uint32_t *)buffer)[i/4]);\r
857 \r
858         dest[0] = src[0];\r
859         dest[1] = src[1];\r
860 \r
861         return i + 8;\r
862 }\r
863 \r
864 #endif\r
865 \r
866 /*******************************************************************************\r
867  * prvTraceUserEventFormat\r
868  *\r
869  * Parses the format string and stores the arguments in the buffer.\r
870  ******************************************************************************/\r
871 static uint8_t prvTraceUserEventFormat(const char* formatStr, va_list vl, uint8_t* buffer, uint8_t byteOffset)\r
872 {\r
873         uint16_t formatStrIndex = 0;\r
874         uint8_t argCounter = 0;\r
875         uint8_t i = byteOffset;\r
876 \r
877         while (formatStr[formatStrIndex] != '\0')\r
878         {\r
879                 if (formatStr[formatStrIndex] == '%')\r
880                 {\r
881                         argCounter++;\r
882 \r
883                         if (argCounter > 15)\r
884                         {\r
885                                 vTraceError("vTracePrintF - Too many arguments, max 15 allowed!");\r
886                                 return 0;\r
887                         }\r
888 \r
889                         /*******************************************************************************\r
890                         * These below code writes raw data (primitive datatypes) in the event buffer,\r
891                         * instead of the normal event structs (where byte 0 is event type).\r
892                         * These data entries must never be interpreted as real event data, as the type\r
893                         * field would be misleading since used for payload data.\r
894                         *\r
895                         * The correctness of this encoding depends on two mechanisms:\r
896                         *\r
897                         * 1. An initial USER_EVENT, which type code tells the number of 32-bit data\r
898                         * entires that follows. (code - USER_EVENT = number of data entries).\r
899                         * Note that a data entry corresponds to the slots that normally corresponds to\r
900                         * one (1) event, i.e., 32 bits. vTracePrintF may encode several pieces of data\r
901                         * in one data entry, e.g., two 16-bit values or four 8-bit values, one 16-bit\r
902                         * value followed by two 8-bit values, etc.\r
903                         *\r
904                         * 2. A two-phase commit procedure, where the USER_EVENT and data entries are\r
905                         * written to a local buffer at first, and when all checks are OK then copied to\r
906                         * the main event buffer using a fast memcpy. The event code is finalized as the\r
907                         * very last step. Before that step, the event code indicates an unfinished\r
908                         * event, which causes it to be ignored and stop the loading of the file (since\r
909                         * an unfinished event is the last event in the trace).\r
910                         *******************************************************************************/\r
911                         formatStrIndex++;\r
912 \r
913                         while ((formatStr[formatStrIndex] >= '0' && formatStr[formatStrIndex] <= '9') || formatStr[formatStrIndex] == '#' || formatStr[formatStrIndex] == '.')\r
914                                 formatStrIndex++;\r
915 \r
916                         if (formatStr[formatStrIndex] != '\0')\r
917                         {\r
918                                 switch (formatStr[formatStrIndex])\r
919                                 {\r
920                                         case 'd':       i = writeInt32( buffer,\r
921                                                                                                 i,\r
922                                                                                                 (uint32_t)va_arg(vl, uint32_t));\r
923                                                                 break;\r
924                                         case 'x':\r
925                                         case 'X':\r
926                                         case 'u':       i = writeInt32( buffer,\r
927                                                                                                 i,\r
928                                                                                                 (uint32_t)va_arg(vl, uint32_t));\r
929                                                                 break;\r
930                                         case 's':       i = writeInt16( buffer,\r
931                                                                                                 i,\r
932                                                                                                 (uint16_t)xTraceOpenLabel((char*)va_arg(vl, char*)));\r
933                                                                 break;\r
934 \r
935 #if (INCLUDE_FLOAT_SUPPORT)\r
936                                         /* Yes, "double" as type also in the float\r
937                                         case. This since "float" is promoted into "double"\r
938                                         by the va_arg stuff. */\r
939                                         case 'f':       i = writeFloat( buffer,\r
940                                                                                                 i,\r
941                                                                                                 (float)va_arg(vl, double));\r
942                                                                 break;\r
943 #else\r
944                                         /* No support for floats, but attempt to store a float user event\r
945                                         avoid a possible crash due to float reference. Instead store the\r
946                                         data on uint_32 format (will not be displayed anyway). This is just\r
947                                         to keep va_arg and i consistent. */\r
948 \r
949                                         case 'f':       i = writeInt32( buffer,\r
950                                                                                                 i,\r
951                                                                                                 (uint32_t)va_arg(vl, double));\r
952                                                                 break;\r
953 #endif\r
954                                         case 'l':\r
955                                                                 formatStrIndex++;\r
956                                                                 switch (formatStr[formatStrIndex])\r
957                                                                 {\r
958 #if (INCLUDE_FLOAT_SUPPORT)\r
959                                                                         case 'f':       i = writeDouble(buffer,\r
960                                                                                                                                 i,\r
961                                                                                                                                 (double)va_arg(vl, double));\r
962                                                                                                 break;\r
963 #else\r
964                                                                         /* No support for floats, but attempt to store a float user event\r
965                                                                         avoid a possible crash due to float reference. Instead store the\r
966                                                                         data on uint_32 format (will not be displayed anyway). This is just\r
967                                                                         to keep va_arg and i consistent. */\r
968                                                                         case 'f':       i = writeInt32( buffer, /* In this case, the value will not be shown anyway */\r
969                                                                                                                                 i,\r
970                                                                                                                                 (uint32_t)va_arg(vl, double));\r
971 \r
972                                                                                                 i = writeInt32( buffer, /* Do it twice, to write in total 8 bytes */\r
973                                                                                                                                 i,\r
974                                                                                                                                 (uint32_t)va_arg(vl, double));\r
975                                                                                 break;\r
976 #endif\r
977 \r
978                                                                 }\r
979                                                                 break;\r
980                                         case 'h':\r
981                                                                 formatStrIndex++;\r
982                                                                 switch (formatStr[formatStrIndex])\r
983                                                                 {\r
984                                                                         case 'd':       i = writeInt16( buffer,\r
985                                                                                                                                 i,\r
986                                                                                                                                 (uint16_t)va_arg(vl, uint32_t));\r
987                                                                                                 break;\r
988                                                                         case 'u':       i = writeInt16( buffer,\r
989                                                                                                                                 i,\r
990                                                                                                                                 (uint16_t)va_arg(vl, uint32_t));\r
991                                                                                                 break;\r
992                                                                 }\r
993                                                                 break;\r
994                                         case 'b':\r
995                                                                 formatStrIndex++;\r
996                                                                 switch (formatStr[formatStrIndex])\r
997                                                                 {\r
998                                                                         case 'd':       i = writeInt8(  buffer,\r
999                                                                                                                                 i,\r
1000                                                                                                                                 (uint8_t)va_arg(vl, uint32_t));\r
1001                                                                                                 break;\r
1002 \r
1003                                                                         case 'u':       i = writeInt8(  buffer,\r
1004                                                                                                                                 i,\r
1005                                                                                                                                 (uint8_t)va_arg(vl, uint32_t));\r
1006                                                                                                 break;\r
1007                                                                 }\r
1008                                                                 break;\r
1009                                 }\r
1010                         }\r
1011                         else\r
1012                                 break;\r
1013                 }\r
1014                 formatStrIndex++;\r
1015                 if (i == 255)\r
1016                 {\r
1017                         vTraceError("vTracePrintF - Too large arguments, max 32 byte allowed!");\r
1018                         return 0;\r
1019                 }\r
1020         }\r
1021         return (i+3)/4;\r
1022 }\r
1023 \r
1024 #if (USE_SEPARATE_USER_EVENT_BUFFER == 1)\r
1025 \r
1026 /*******************************************************************************\r
1027  * prvTraceClearChannelBuffer\r
1028  *\r
1029  * Clears a number of items in the channel buffer, starting from nextSlotToWrite.\r
1030  ******************************************************************************/\r
1031 static void prvTraceClearChannelBuffer(uint32_t count)\r
1032 {\r
1033         uint32_t slots;\r
1034 \r
1035         TRACE_ASSERT(USER_EVENT_BUFFER_SIZE >= count,\r
1036                 "prvTraceClearChannelBuffer: USER_EVENT_BUFFER_SIZE is too small to handle this event.", );\r
1037 \r
1038         /* Check if we're close to the end of the buffer */\r
1039         if (RecorderDataPtr->userEventBuffer.nextSlotToWrite + count > USER_EVENT_BUFFER_SIZE)\r
1040         {\r
1041                 slots = USER_EVENT_BUFFER_SIZE - RecorderDataPtr->userEventBuffer.nextSlotToWrite; /* Number of slots before end of buffer */\r
1042                 (void)memset(&RecorderDataPtr->userEventBuffer.channelBuffer[RecorderDataPtr->userEventBuffer.nextSlotToWrite], 0, slots);\r
1043                 (void)memset(&RecorderDataPtr->userEventBuffer.channelBuffer[0], 0, (count - slots));\r
1044         }\r
1045         else\r
1046                 (void)memset(&RecorderDataPtr->userEventBuffer.channelBuffer[RecorderDataPtr->userEventBuffer.nextSlotToWrite], 0, count);\r
1047 }\r
1048 \r
1049 /*******************************************************************************\r
1050  * prvTraceCopyToDataBuffer\r
1051  *\r
1052  * Copies a number of items to the data buffer, starting from nextSlotToWrite.\r
1053  ******************************************************************************/\r
1054 static void prvTraceCopyToDataBuffer(uint32_t* data, uint32_t count)\r
1055 {\r
1056         TRACE_ASSERT(data != NULL,\r
1057                 "prvTraceCopyToDataBuffer: data == NULL.", );\r
1058         TRACE_ASSERT(count <= USER_EVENT_BUFFER_SIZE,\r
1059                 "prvTraceCopyToDataBuffer: USER_EVENT_BUFFER_SIZE is too small to handle this event.", );\r
1060 \r
1061         uint32_t slots;\r
1062         /* Check if we're close to the end of the buffer */\r
1063         if (RecorderDataPtr->userEventBuffer.nextSlotToWrite + count > USER_EVENT_BUFFER_SIZE)\r
1064         {\r
1065                 slots = USER_EVENT_BUFFER_SIZE - RecorderDataPtr->userEventBuffer.nextSlotToWrite; /* Number of slots before end of buffer */\r
1066                 (void)memcpy(&RecorderDataPtr->userEventBuffer.dataBuffer[RecorderDataPtr->userEventBuffer.nextSlotToWrite * 4], data, slots * 4);\r
1067                 (void)memcpy(&RecorderDataPtr->userEventBuffer.dataBuffer[0], data + slots, (count - slots) * 4);\r
1068         }\r
1069         else\r
1070         {\r
1071                 (void)memcpy(&RecorderDataPtr->userEventBuffer.dataBuffer[RecorderDataPtr->userEventBuffer.nextSlotToWrite * 4], data, count * 4);\r
1072         }\r
1073 }\r
1074 \r
1075 /*******************************************************************************\r
1076  * prvTraceUserEventHelper1\r
1077  *\r
1078  * Calls on prvTraceUserEventFormat() to do the actual formatting, then goes on\r
1079  * to the next helper function.\r
1080  ******************************************************************************/\r
1081 static void prvTraceUserEventHelper1(UserEventChannel channel, traceLabel eventLabel, traceLabel formatLabel, va_list vl)\r
1082 {\r
1083         uint32_t data[(3 + MAX_ARG_SIZE) / 4];\r
1084         uint8_t byteOffset = 4; /* Need room for timestamp */\r
1085         uint8_t noOfSlots;\r
1086 \r
1087         if (channel == 0)\r
1088         {\r
1089                 /* We are dealing with an unknown channel format pair */\r
1090                 byteOffset += 4; /* Also need room for channel and format */\r
1091                 ((uint16_t*)data)[2] = eventLabel;\r
1092                 ((uint16_t*)data)[3] = formatLabel;\r
1093         }\r
1094 \r
1095         noOfSlots = prvTraceUserEventFormat((char*)&(RecorderDataPtr->SymbolTable.symbytes[formatLabel+4]), vl, (uint8_t*)data, byteOffset);\r
1096 \r
1097         prvTraceUserEventHelper2(channel, data, noOfSlots);\r
1098 }\r
1099 \r
1100 /*******************************************************************************\r
1101  * prvTraceUserEventHelper2\r
1102  *\r
1103  * This function simply copies the data buffer to the actual user event buffer.\r
1104  ******************************************************************************/\r
1105 static void prvTraceUserEventHelper2(UserEventChannel channel, uint32_t* data, uint32_t noOfSlots)\r
1106 {\r
1107         static uint32_t old_timestamp = 0;\r
1108         uint32_t old_nextSlotToWrite = 0;\r
1109 \r
1110         TRACE_ASSERT(USER_EVENT_BUFFER_SIZE >= noOfSlots, "vTracePrintF: USER_EVENT_BUFFER_SIZE is too small to handle this event.", );\r
1111 \r
1112         trcCRITICAL_SECTION_BEGIN();\r
1113         /* Store the timestamp */\r
1114         vTracePortGetTimeStamp(data);\r
1115 \r
1116         if (*data < old_timestamp)\r
1117         {\r
1118                 RecorderDataPtr->userEventBuffer.wraparoundCounter++;\r
1119         }\r
1120 \r
1121         old_timestamp = *data;\r
1122 \r
1123         /* Start by erasing any information in the channel buffer */\r
1124         prvTraceClearChannelBuffer(noOfSlots);\r
1125 \r
1126         prvTraceCopyToDataBuffer(data, noOfSlots); /* Will wrap around the data if necessary */\r
1127 \r
1128         old_nextSlotToWrite = RecorderDataPtr->userEventBuffer.nextSlotToWrite; /* Save the index that we want to write the channel data at when we're done */\r
1129         RecorderDataPtr->userEventBuffer.nextSlotToWrite = (RecorderDataPtr->userEventBuffer.nextSlotToWrite + noOfSlots) % USER_EVENT_BUFFER_SIZE; /* Make sure we never end up outside the buffer */\r
1130 \r
1131         /* Write to the channel buffer to indicate that this user event is ready to be used */\r
1132         if (channel != 0)\r
1133         {\r
1134                 RecorderDataPtr->userEventBuffer.channelBuffer[old_nextSlotToWrite] = channel;\r
1135         }\r
1136         else\r
1137         {\r
1138                 /* 0xFF indicates that this is not a normal channel id */\r
1139                 RecorderDataPtr->userEventBuffer.channelBuffer[old_nextSlotToWrite] = (UserEventChannel)0xFF;\r
1140         }\r
1141         trcCRITICAL_SECTION_END();\r
1142 }\r
1143 \r
1144 /*******************************************************************************\r
1145  * xTraceRegisterChannelFormat\r
1146  *\r
1147  * Attempts to create a pair of the channel and format string.\r
1148  *\r
1149  * Note: This is only available if USE_SEPARATE_USER_EVENT_BUFFER is enabled in\r
1150  * trcConfig.h\r
1151  ******************************************************************************/\r
1152 UserEventChannel xTraceRegisterChannelFormat(traceLabel channel, traceLabel formatStr)\r
1153 {\r
1154         uint8_t i;\r
1155         UserEventChannel retVal = 0;\r
1156 \r
1157         TRACE_ASSERT(formatStr != 0, "vTraceRegisterChannelFormat: formatStr == 0", (UserEventChannel)0);\r
1158 \r
1159         trcCRITICAL_SECTION_BEGIN();\r
1160         for (i = 1; i <= CHANNEL_FORMAT_PAIRS; i++) /* Size of the channels buffer is CHANNEL_FORMAT_PAIRS + 1. Index 0 is unused. */\r
1161         {\r
1162                 if(RecorderDataPtr->userEventBuffer.channels[i].name == 0 && RecorderDataPtr->userEventBuffer.channels[i].defaultFormat == 0)\r
1163                 {\r
1164                         /* Found empty slot */\r
1165                         RecorderDataPtr->userEventBuffer.channels[i].name = channel;\r
1166                         RecorderDataPtr->userEventBuffer.channels[i].defaultFormat = formatStr;\r
1167                         retVal = (UserEventChannel)i;\r
1168                         break;\r
1169                 }\r
1170 \r
1171                 if (RecorderDataPtr->userEventBuffer.channels[i].name == channel && RecorderDataPtr->userEventBuffer.channels[i].defaultFormat == formatStr)\r
1172                 {\r
1173                         /* Found a match */\r
1174                         retVal = (UserEventChannel)i;\r
1175                         break;\r
1176                 }\r
1177         }\r
1178         trcCRITICAL_SECTION_END();\r
1179         return retVal;\r
1180 }\r
1181 \r
1182 /******************************************************************************\r
1183  * vTraceChannelPrintF\r
1184  *\r
1185  * Slightly faster version of vTracePrintF() due to no lookups.\r
1186  *\r
1187  * Note: This is only available if USE_SEPARATE_USER_EVENT_BUFFER is enabled in\r
1188  * trcConfig.h\r
1189  *\r
1190  ******************************************************************************/\r
1191 void vTraceChannelPrintF(UserEventChannel channelPair, ...)\r
1192 {\r
1193 #if (TRACE_SCHEDULING_ONLY == 0)\r
1194         va_list vl;\r
1195 \r
1196         va_start(vl, channelPair);\r
1197         vTraceChannelPrintF_Helper(channelPair, vl);\r
1198         va_end(vl);\r
1199 #endif /* TRACE_SCHEDULING_ONLY */\r
1200 }\r
1201 \r
1202 void vTraceChannelPrintF_Helper(UserEventChannel channelPair, va_list vl)\r
1203 {\r
1204         traceLabel channel;\r
1205         traceLabel formatStr;\r
1206 \r
1207         TRACE_ASSERT(channelPair != 0, "vTraceChannelPrintF: channelPair == 0", );\r
1208         TRACE_ASSERT(channelPair <= CHANNEL_FORMAT_PAIRS, "vTraceChannelPrintF: ", );\r
1209 \r
1210         channel = RecorderDataPtr->userEventBuffer.channels[channelPair].name;\r
1211         formatStr = RecorderDataPtr->userEventBuffer.channels[channelPair].defaultFormat;\r
1212 \r
1213         prvTraceUserEventHelper1(channelPair, channel, formatStr, vl);\r
1214 }\r
1215 \r
1216 /******************************************************************************\r
1217  * vTraceChannelUserEvent\r
1218  *\r
1219  * Slightly faster version of vTraceUserEvent() due to no lookups.\r
1220  ******************************************************************************/\r
1221 void vTraceChannelUserEvent(UserEventChannel channelPair)\r
1222 {\r
1223 #if (TRACE_SCHEDULING_ONLY == 0)\r
1224         uint32_t data[(3 + MAX_ARG_SIZE) / 4];\r
1225 \r
1226         TRACE_ASSERT(channelPair != 0, "vTraceChannelPrintF: channelPair == 0", );\r
1227         TRACE_ASSERT(channelPair <= CHANNEL_FORMAT_PAIRS, "vTraceChannelPrintF: ", );\r
1228 \r
1229         prvTraceUserEventHelper2(channelPair, data, 1); /* Only need one slot for timestamp */\r
1230 #endif /* TRACE_SCHEDULING_ONLY */\r
1231 }\r
1232 #endif /* USE_SEPARATE_USER_EVENT_BUFFER == 1 */\r
1233 \r
1234 /******************************************************************************\r
1235  * vTracePrintF\r
1236  *\r
1237  * Advanced user events (Professional Edition only)\r
1238  *\r
1239  * Generates User Event with formatted text and data, similar to a "printf".\r
1240  * It is very fast compared to a normal "printf" since this function only\r
1241  * stores the arguments. The actual formatting is done\r
1242  * on the host PC when the trace is displayed in the viewer tool.\r
1243  *\r
1244  * User Event labels are created using xTraceOpenLabel.\r
1245  * Example:\r
1246  *\r
1247  *       traceLabel adc_uechannel = xTraceOpenLabel("ADC User Events");\r
1248  *       ...\r
1249  *       vTracePrint(adc_uechannel,\r
1250  *                               "ADC channel %d: %lf volts",\r
1251  *                               ch, (double)adc_reading/(double)scale);\r
1252  *\r
1253  * This can be combined into one line, if desired, but this is slower:\r
1254  *\r
1255  *       vTracePrint(xTraceOpenLabel("ADC User Events"),\r
1256  *                               "ADC channel %d: %lf volts",\r
1257  *                               ch, (double)adc_reading/(double)scale);\r
1258  *\r
1259  * Calling xTraceOpenLabel multiple times will not create duplicate entries, but\r
1260  * it is of course faster to just do it once, and then keep the handle for later\r
1261  * use. If you don�t have any data arguments, only a text label/string, it is\r
1262  * better to use vTraceUserEvent - it is faster.\r
1263  *\r
1264  * Format specifiers supported:\r
1265  * %d - 32 bit signed integer\r
1266  * %u - 32 bit unsigned integer\r
1267  * %f - 32 bit float\r
1268  * %s - string (is copied to the recorder symbol table)\r
1269  * %hd - 16 bit signed integer\r
1270  * %hu - 16 bit unsigned integer\r
1271  * %bd - 8 bit signed integer\r
1272  * %bu - 8 bit unsigned integer\r
1273  * %lf - double-precision float (Note! See below...)\r
1274  *\r
1275  * Up to 15 data arguments are allowed, with a total size of maximum 32 byte.\r
1276  * In case this is exceeded, the user event is changed into an error message.\r
1277  *\r
1278  * The data is stored in trace buffer, and is packed to allow storing multiple\r
1279  * smaller data entries in the same 4-byte record, e.g., four 8-bit values.\r
1280  * A string requires two bytes, as the symbol table is limited to 64K. Storing\r
1281  * a double (%lf) uses two records, so this is quite costly. Use float (%f)\r
1282  * unless the higher precision is really necessary.\r
1283  *\r
1284  * Note that the double-precision float (%lf) assumes a 64 bit double\r
1285  * representation. This does not seem to be the case on e.g. PIC24 and PIC32.\r
1286  * Before using a %lf argument on a 16-bit MCU, please verify that\r
1287  * "sizeof(double)" actually gives 8 as expected. If not, use %f instead.\r
1288  ******************************************************************************/\r
1289 \r
1290 void vTracePrintF(traceLabel eventLabel, const char* formatStr, ...)\r
1291 {\r
1292 #if (TRACE_SCHEDULING_ONLY == 0)\r
1293         va_list vl;\r
1294 \r
1295         va_start(vl, formatStr);\r
1296         vTracePrintF_Helper(eventLabel, formatStr, vl);\r
1297         va_end(vl);\r
1298 #endif /* TRACE_SCHEDULING_ONLY */\r
1299 }\r
1300 \r
1301 void vTracePrintF_Helper(traceLabel eventLabel, const char* formatStr, va_list vl)\r
1302 {\r
1303 #if (USE_SEPARATE_USER_EVENT_BUFFER == 0)\r
1304         uint32_t noOfSlots;\r
1305         UserEvent* ue1;\r
1306         uint32_t tempDataBuffer[(3 + MAX_ARG_SIZE) / 4];\r
1307         TRACE_SR_ALLOC_CRITICAL_SECTION();\r
1308 \r
1309         /**************************************************************************\r
1310         * The array tempDataBuffer is a local buffer used in a two-phase commit of\r
1311         * the event data, since a vTracePrintF may span over multiple slots in the\r
1312         * buffer.\r
1313         * This buffer can be made larger, of course, but remember the risk for\r
1314         * stack overflow. Note: This should be a LOCAL buffer, must not be made\r
1315         * global. That would cause data corruption when two calls to vTracePrintF\r
1316         * from different tasks overlaps (interrupts are only disabled in a small\r
1317         * part of this function, otherwise enabled)\r
1318         ***************************************************************************/\r
1319 \r
1320         TRACE_ASSERT(formatStr != NULL, "vTracePrintF: formatStr == NULL", );\r
1321 \r
1322         trcCRITICAL_SECTION_BEGIN();\r
1323 \r
1324         if (RecorderDataPtr->recorderActive && (! inExcludedTask || nISRactive) && handle_of_last_logged_task)\r
1325         {\r
1326                 /* First, write the "primary" user event entry in the local buffer, but\r
1327                 let the event type be "EVENT_BEING_WRITTEN" for now...*/\r
1328 \r
1329                 ue1 = (UserEvent*)(&tempDataBuffer[0]);\r
1330 \r
1331                 ue1->type = EVENT_BEING_WRITTEN;         /* Update this as the last step */\r
1332 \r
1333                 noOfSlots = prvTraceUserEventFormat(formatStr, vl, (uint8_t*)tempDataBuffer, 4);\r
1334 \r
1335                 /* Store the format string, with a reference to the channel symbol */\r
1336                 ue1->payload = prvTraceOpenSymbol(formatStr, eventLabel);\r
1337 \r
1338                 ue1->dts = (uint8_t)prvTraceGetDTS(0xFF);\r
1339 \r
1340                  /* prvTraceGetDTS might stop the recorder in some cases... */\r
1341                 if (RecorderDataPtr->recorderActive)\r
1342                 {\r
1343 \r
1344                         /* If the data does not fit in the remaining main buffer, wrap around to\r
1345                         0 if allowed, otherwise stop the recorder and quit). */\r
1346                         if (RecorderDataPtr->nextFreeIndex + noOfSlots > RecorderDataPtr->maxEvents)\r
1347                         {\r
1348                                 #if (TRACE_RECORDER_STORE_MODE == TRACE_STORE_MODE_RING_BUFFER)\r
1349                                 (void)memset(& RecorderDataPtr->eventData[RecorderDataPtr->nextFreeIndex * 4],\r
1350                                                 0,\r
1351                                                 (RecorderDataPtr->maxEvents - RecorderDataPtr->nextFreeIndex)*4);\r
1352                                 RecorderDataPtr->nextFreeIndex = 0;\r
1353                                 RecorderDataPtr->bufferIsFull = 1;\r
1354                                 #else\r
1355 \r
1356                                 /* Stop recorder, since the event data will not fit in the\r
1357                                 buffer and not circular buffer in this case... */\r
1358                                 vTraceStop();\r
1359                                 #endif\r
1360                         }\r
1361 \r
1362                         /* Check if recorder has been stopped (i.e., vTraceStop above) */\r
1363                         if (RecorderDataPtr->recorderActive)\r
1364                         {\r
1365                                 /* Check that the buffer to be overwritten does not contain any user\r
1366                                 events that would be partially overwritten. If so, they must be "killed"\r
1367                                 by replacing the user event and following data with NULL events (i.e.,\r
1368                                 using a memset to zero).*/\r
1369                                 #if (TRACE_RECORDER_STORE_MODE == TRACE_STORE_MODE_RING_BUFFER)\r
1370                                 prvCheckDataToBeOverwrittenForMultiEntryEvents((uint8_t)noOfSlots);\r
1371                                 #endif\r
1372                                 /* Copy the local buffer to the main buffer */\r
1373                                 (void)memcpy(& RecorderDataPtr->eventData[RecorderDataPtr->nextFreeIndex * 4],\r
1374                                                 tempDataBuffer,\r
1375                                                 noOfSlots * 4);\r
1376 \r
1377                                 /* Update the event type, i.e., number of data entries following the\r
1378                                 main USER_EVENT entry (Note: important that this is after the memcpy,\r
1379                                 but within the critical section!)*/\r
1380                                 RecorderDataPtr->eventData[RecorderDataPtr->nextFreeIndex * 4] =\r
1381                                  (uint8_t) ( USER_EVENT + noOfSlots - 1 );\r
1382 \r
1383                                 /* Update the main buffer event index (already checked that it fits in\r
1384                                 the buffer, so no need to check for wrapping)*/\r
1385 \r
1386                                 RecorderDataPtr->nextFreeIndex += noOfSlots;\r
1387                                 RecorderDataPtr->numEvents += noOfSlots;\r
1388 \r
1389                                 if (RecorderDataPtr->nextFreeIndex >= EVENT_BUFFER_SIZE)\r
1390                                 {\r
1391                                         #if (TRACE_RECORDER_STORE_MODE == TRACE_STORE_MODE_RING_BUFFER)\r
1392                                         /* We have reached the end, but this is a ring buffer. Start from the beginning again. */\r
1393                                         RecorderDataPtr->bufferIsFull = 1;\r
1394                                         RecorderDataPtr->nextFreeIndex = 0;\r
1395                                         #else\r
1396                                         /* We have reached the end so we stop. */\r
1397                                         vTraceStop();\r
1398                                         #endif\r
1399                                 }\r
1400                         }\r
1401 \r
1402                         #if (TRACE_RECORDER_STORE_MODE == TRACE_STORE_MODE_RING_BUFFER)\r
1403                         /* Make sure the next entry is cleared correctly */\r
1404                         prvCheckDataToBeOverwrittenForMultiEntryEvents(1);\r
1405                         #endif\r
1406 \r
1407                 }\r
1408         }\r
1409         trcCRITICAL_SECTION_END();\r
1410 \r
1411 #elif (USE_SEPARATE_USER_EVENT_BUFFER == 1)\r
1412         /* Use the separate user event buffer */\r
1413         traceLabel formatLabel;\r
1414         UserEventChannel channel;\r
1415 \r
1416         if (RecorderDataPtr->recorderActive && (! inExcludedTask || nISRactive) && handle_of_last_logged_task)\r
1417         {\r
1418                 formatLabel = xTraceOpenLabel(formatStr);\r
1419 \r
1420                 channel = xTraceRegisterChannelFormat(eventLabel, formatLabel);\r
1421 \r
1422                 prvTraceUserEventHelper1(channel, eventLabel, formatLabel, vl);\r
1423         }\r
1424 #endif\r
1425 }\r
1426 \r
1427 /******************************************************************************\r
1428  * vTraceUserEvent\r
1429  *\r
1430  * Basic user event (Standard and Professional Edition only)\r
1431  *\r
1432  * Generates a User Event with a text label. The label is created/looked up\r
1433  * in the symbol table using xTraceOpenLabel.\r
1434  ******************************************************************************/\r
1435 void vTraceUserEvent(traceLabel eventLabel)\r
1436 {\r
1437 #if (TRACE_SCHEDULING_ONLY == 0)\r
1438 #if (USE_SEPARATE_USER_EVENT_BUFFER == 0)\r
1439         UserEvent* ue;\r
1440         uint8_t dts1;\r
1441         TRACE_SR_ALLOC_CRITICAL_SECTION();\r
1442 \r
1443         TRACE_ASSERT(eventLabel > 0, "vTraceUserEvent: Invalid value for eventLabel", );\r
1444 \r
1445         trcCRITICAL_SECTION_BEGIN();\r
1446         if (RecorderDataPtr->recorderActive && (! inExcludedTask || nISRactive) && handle_of_last_logged_task)\r
1447         {\r
1448                 dts1 = (uint8_t)prvTraceGetDTS(0xFF);\r
1449                 ue = (UserEvent*) xTraceNextFreeEventBufferSlot();\r
1450                 if (ue != NULL)\r
1451                 {\r
1452                         ue->dts = dts1;\r
1453                         ue->type = USER_EVENT;\r
1454                         ue->payload = eventLabel;\r
1455                         prvTraceUpdateCounters();\r
1456                 }\r
1457         }\r
1458         trcCRITICAL_SECTION_END();\r
1459 \r
1460 #elif (USE_SEPARATE_USER_EVENT_BUFFER == 1)\r
1461         UserEventChannel channel;\r
1462         uint32_t noOfSlots = 1;\r
1463         uint32_t tempDataBuffer[(3 + MAX_ARG_SIZE) / 4];\r
1464         if (RecorderDataPtr->recorderActive && (! inExcludedTask || nISRactive) && handle_of_last_logged_task)\r
1465         {\r
1466                 channel = xTraceRegisterChannelFormat(0, eventLabel);\r
1467 \r
1468                 if (channel == 0)\r
1469                 {\r
1470                         /* We are dealing with an unknown channel format pair */\r
1471                         noOfSlots++; /* Also need room for channel and format */\r
1472                         ((uint16_t*)tempDataBuffer)[2] = 0;\r
1473                         ((uint16_t*)tempDataBuffer)[3] = eventLabel;\r
1474                 }\r
1475 \r
1476                 prvTraceUserEventHelper2(channel, tempDataBuffer, noOfSlots);\r
1477         }\r
1478 #endif\r
1479 #endif /* TRACE_SCHEDULING_ONLY */\r
1480 }\r
1481 \r
1482 /*******************************************************************************\r
1483  * xTraceOpenLabel\r
1484  *\r
1485  * Creates user event labels for user event channels or for individual events.\r
1486  * User events can be used to log application events and data for display in\r
1487  * the visualization tool. A user event is identified by a label, i.e., a string,\r
1488  * which is stored in the recorder's symbol table.\r
1489  * When logging a user event, a numeric handle (reference) to this string is\r
1490  * used to identify the event. This is obtained by calling\r
1491  *\r
1492  *       xTraceOpenLabel()\r
1493  *\r
1494  * which adds the string to the symbol table (if not already present)\r
1495  * and returns the corresponding handle.\r
1496  *\r
1497  * This can be used in two ways:\r
1498  *\r
1499  * 1. The handle is looked up every time, when storing the user event.\r
1500  *\r
1501  * Example:\r
1502  *       vTraceUserEvent(xTraceOpenLabel("MyUserEvent"));\r
1503  *\r
1504  * 2. The label is registered just once, with the handle stored in an\r
1505  * application variable - much like using a file handle.\r
1506  *\r
1507  * Example:\r
1508  *       myEventHandle = xTraceOpenLabel("MyUserEvent");\r
1509  *       ...\r
1510  *       vTraceUserEvent(myEventHandle);\r
1511  *\r
1512  * The second option is faster since no lookup is required on each event, and\r
1513  * therefore recommended for user events that are frequently\r
1514  * executed and/or located in time-critical code. The lookup operation is\r
1515  * however fairly fast due to the design of the symbol table.\r
1516  ******************************************************************************/\r
1517 traceLabel xTraceOpenLabel(const char* label)\r
1518 {\r
1519         TRACE_ASSERT(label != NULL, "xTraceOpenLabel: label == NULL", (traceLabel)0);\r
1520 \r
1521         return prvTraceOpenSymbol(label, 0);\r
1522 }\r
1523 \r
1524 #endif\r
1525 \r
1526 #endif\r