]> git.sur5r.net Git - freertos/blob - FreeRTOS-Plus/FreeRTOS-Plus-Trace/trcUser.c
Add FreeRTOS-Plus directory.
[freertos] / FreeRTOS-Plus / FreeRTOS-Plus-Trace / trcUser.c
1 /*******************************************************************************\r
2  * FreeRTOS+Trace v2.2.3 Recorder Library\r
3  * Percepio AB, www.percepio.se\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 trcPort.c and trcPort.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  * FreeRTOS+Trace is available as Free Edition and in two premium editions.\r
35  * You may use the premium features during 30 days for evaluation.\r
36  * Download FreeRTOS+Trace at http://www.percepio.se/index.php?page=downloads\r
37  *\r
38  * Copyright Percepio AB, 2012.\r
39  * www.percepio.se\r
40  ******************************************************************************/\r
41 \r
42 #include "FreeRTOS.h"\r
43 #include "task.h"\r
44 #include "queue.h"\r
45 \r
46 #if (configUSE_TRACE_FACILITY == 1)\r
47 \r
48 #include "string.h"\r
49 #include "stdarg.h"\r
50 #include "trcUser.h"\r
51 #include "trcKernel.h"\r
52 \r
53 extern uint8_t inExcludedTask;\r
54 extern uint8_t nISRactive;\r
55 extern uint8_t handle_of_last_logged_task;\r
56 extern uint32_t dts_min;\r
57 extern uint32_t hwtc_count_max_after_tick;\r
58 extern uint32_t hwtc_count_sum_after_tick;\r
59 extern uint32_t hwtc_count_sum_after_tick_counter;\r
60 extern unsigned char ucQueueGetQueueType(void*);\r
61 extern unsigned char ucQueueGetQueueNumber(void*);\r
62 extern char* traceErrorMessage;\r
63 \r
64 static void vTraceMonitorTask(void);\r
65     \r
66 /*******************************************************************************\r
67  * vTraceMonitorTask\r
68  *\r
69  * A task which periodically reports the recorder status to the console.\r
70  * This is included depending on USE_TRACE_PROGRESS_MONITOR_TASK.\r
71  ******************************************************************************/\r
72 static void vTraceMonitorTask(void)\r
73 {    \r
74     portTickType xNextWakeTime;\r
75     char localsprintbuffer[90];\r
76     char* err = NULL;    \r
77     char* lastErr = NULL;      \r
78     #define STATE_INIT 0\r
79     #define STATE_STARTED 1\r
80     #define STATE_STOPPED 2    \r
81     int state = STATE_INIT;\r
82     \r
83     vTraceConsoleMessage("\n\r[FreeRTOS+Trace] Monitor task started...\n\r");\r
84 \r
85     /* Initialise xNextWakeTime - this only needs to be done once. */\r
86     xNextWakeTime = xTaskGetTickCount();\r
87 \r
88     for (;;)\r
89     {\r
90         lastErr = err;        \r
91         err = xTraceGetLastError();\r
92         if (err != lastErr)\r
93         {\r
94             sprintf(localsprintbuffer, "\n\r[FreeRTOS+Trace] Error: %s\n\r", err);\r
95             vTraceConsoleMessage(localsprintbuffer); \r
96         }\r
97         \r
98         if (state == STATE_STOPPED || state == STATE_INIT) \r
99         {\r
100             if (RecorderDataPtr->recorderActive == 1)\r
101             {\r
102                 state = STATE_STARTED;\r
103                 vTraceConsoleMessage("\n\r[FreeRTOS+Trace] Recorder started.\n\r");                                       \r
104             }\r
105             else\r
106             {\r
107                 if (state == STATE_INIT)\r
108                 {\r
109                     \r
110                     vTraceConsoleMessage("\n\r[FreeRTOS+Trace] Recorder not started.\n\r");\r
111                     state = STATE_STOPPED;\r
112                 }\r
113             }\r
114         }\r
115         \r
116         if (state == STATE_STARTED)\r
117         {\r
118             if (RecorderDataPtr->frequency > 0)\r
119             {\r
120                 sprintf(localsprintbuffer, \r
121                     "\n\r[FreeRTOS+Trace] Event count: %d, Duration: %d ms. [%d ticks]\n\r", \r
122                     RecorderDataPtr->numEvents, \r
123                     RecorderDataPtr->absTimeLastEventSecond*1000 + (RecorderDataPtr->absTimeLastEvent*1000)/ RecorderDataPtr->frequency, xTaskGetTickCount());\r
124                 vTraceConsoleMessage(localsprintbuffer);\r
125             }\r
126 \r
127             if (RecorderDataPtr->recorderActive == 0)\r
128             {\r
129                 state = STATE_STOPPED;\r
130                 vTraceConsoleMessage("\n\r[FreeRTOS+Trace] Recorder stopped.\n\r");                                       \r
131                 vTracePortEnd();\r
132             }\r
133                 \r
134 \r
135         }\r
136 \r
137     /* Place this task in the blocked state until it is time to run again. */\r
138         vTaskDelayUntil( &xNextWakeTime, TRACE_PROGRESS_MONITOR_TASK_PERIOD);\r
139         \r
140     }\r
141 }\r
142 \r
143 /*******************************************************************************\r
144  * vTraceClear\r
145  *\r
146  * Resets the recorder. Only necessary if a restart is desired - this is not \r
147  * needed in the startup initialization.\r
148  ******************************************************************************/\r
149 void vTraceClear(void)\r
150 {\r
151     taskENTER_CRITICAL();\r
152 \r
153     RecorderDataPtr->absTimeLastEvent = 0;\r
154     RecorderDataPtr->nextFreeIndex = 0;\r
155     RecorderDataPtr->numEvents = 0;\r
156     RecorderDataPtr->bufferIsFull = 0;\r
157 \r
158     taskEXIT_CRITICAL();\r
159 }\r
160 \r
161 /*******************************************************************************\r
162  * vTraceStartStatusMonitor\r
163  *\r
164  * This starts a task to monitor the state of the recorder. \r
165  * This task periodically prints a line to the console window, which shows the \r
166  * number of events recorded and the latest timestamp. This task\r
167  * calls vTracePortEnd when the recorder has been stopped, where custom\r
168  * actions can be added, e.g., to store the trace to a file\r
169  * if a file system is available on the device.\r
170  ******************************************************************************/\r
171 void vTraceStartStatusMonitor(void)\r
172 {    \r
173     vTraceConsoleMessage("\n\r[FreeRTOS+Trace] Starting Trace Status Monitor...\n\r");\r
174     (void)xTaskCreate( (pdTASK_CODE)vTraceMonitorTask, (const signed char*)"TraceMon", TRACE_PROGRESS_MONITOR_TASK_STACKSIZE, NULL, TRACE_PROGRESS_MONITOR_TASK_PRIORITY, NULL );\r
175 }\r
176 \r
177 /*******************************************************************************\r
178  * uiTraceStart\r
179  *\r
180  * Starts the recorder. The recorder will not be started if an error has been\r
181  * indicated using vTraceError, e.g. if any of the Nx constants in trcConfig.h \r
182  * has a too small value (NTASK, NQUEUE, etc).\r
183  * \r
184  * Returns 1 if the recorder was started successfully.\r
185  * Returns 0 if the recorder start was prevented due to a previous internal \r
186  * error. In that case, check vTraceGetLastError to get the error message.\r
187  * Any error message is also presented when opening a trace file in \r
188  * FreeRTOS+Trace v2.2.2 or later.\r
189  ******************************************************************************/\r
190 uint32_t uiTraceStart(void)\r
191 {        \r
192     if (traceErrorMessage == NULL)\r
193     {\r
194         RecorderDataPtr->recorderActive = 1;\r
195         vTraceStoreTaskswitch(); /* Register the currently running task */\r
196     }\r
197 \r
198     return RecorderDataPtr->recorderActive;\r
199 }\r
200 \r
201 /*******************************************************************************\r
202  * vTraceStart \r
203  *\r
204  * Starts the recorder. The recorder will not be started if an error has been\r
205  * indicated using vTraceError, e.g. if any of the Nx constants in trcConfig.h \r
206  * has a too small value (NTASK, NQUEUE, etc).\r
207  * \r
208  * This function is obsolete, but has been saved for backwards compatibility. \r
209  * We recommend using uiTraceStart instead.\r
210  ******************************************************************************/\r
211 void vTraceStart(void)\r
212 {        \r
213     (void)uiTraceStart();\r
214 }\r
215 \r
216 /*******************************************************************************\r
217  * vTraceStop\r
218  *\r
219  * Stops the recorder. The recording can be resumed by calling vTraceStart.\r
220  * This does not reset the recorder. Use vTraceClear is that is desired.\r
221  ******************************************************************************/\r
222 void vTraceStop(void)\r
223 {\r
224     RecorderDataPtr->recorderActive = 0;\r
225 }\r
226 \r
227 /*******************************************************************************\r
228  * xTraceGetLastError\r
229  *\r
230  * Gives the last error message, if any. NULL if no error message is stored.\r
231  * The message is cleared on read.\r
232  * Any error message is also presented when opening a trace file in \r
233  * FreeRTOS+Trace v2.2.2 or later.\r
234  ******************************************************************************/\r
235 char* xTraceGetLastError(void)\r
236 {   \r
237     return traceErrorMessage;\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  * vTraceExcludeTask\r
267  * Excludes a task from the recording using a flag in the Object Property Table.\r
268  * This can be useful if some irrelevant task is very frequent and is "eating\r
269  * up the buffer". This should be called after the task has been created, but \r
270  * preferably before starting the FreeRTOS scheduler.\r
271  ******************************************************************************/\r
272 void vTraceExcludeTaskFromSchedulingTrace(const char* name)\r
273 {\r
274     objectHandleType i;\r
275     int32_t found = 0;\r
276     for (i = 1; i < RecorderDataPtr->ObjectPropertyTable.NumberOfObjectsPerClass[TRACE_CLASS_TASK]; i++)\r
277     {\r
278         if (strncmp(name, \r
279                     PROPERTY_NAME_GET(TRACE_CLASS_TASK, i), \r
280                     RecorderDataPtr->ObjectPropertyTable.NameLengthPerClass[TRACE_CLASS_TASK]) == 0)\r
281         {\r
282             found = 1;\r
283             SET_TASK_FLAG_ISEXCLUDED(i);\r
284             break;\r
285         }\r
286     }\r
287     if (!found)\r
288     {\r
289         vTraceError("Could not find task to exclude!");\r
290     }\r
291 }\r
292 \r
293 /*******************************************************************************\r
294  * vTraceSetQueueName\r
295  *\r
296  * Assigns a name to a FreeRTOS Queue, Semaphore or Mutex. This function should\r
297  * be called right after creation of the queue/mutex/semaphore. If not using \r
298  * this function, the queues/mutexes/semaphores will be presented by their\r
299  * numeric handle only.\r
300  *\r
301  * Example:\r
302  *     actuatorQ = xQueueCreate(3, sizeof(QueueMessage));\r
303  *     vTraceSetQueueName(actuatorQ, "ActuatorQueue");\r
304  ******************************************************************************/\r
305 void vTraceSetQueueName(void* queue, const char* name)\r
306 {\r
307     int t = ucQueueGetQueueType(queue);    \r
308     vTraceSetObjectName(TraceObjectClassTable[t], \r
309                         (objectHandleType)ucQueueGetQueueNumber(queue), name);\r
310 }\r
311 \r
312 \r
313 /******************************************************************************\r
314  * vTraceTaskInstanceIsFinished\r
315  * \r
316  * This defines an explicit Instance Finish Event for the current task. It tells \r
317  * the recorder that the current instance of this task is finished at the next \r
318  * kernel call of the task, e.g., a taskDelay or a queue receive. This function \r
319  * should be called right before the api function call considered to be the end \r
320  * of the current task instance, i.e., the Instance Finish Event.\r
321  *****************************************************************************/\r
322 void vTraceTaskInstanceIsFinished()\r
323 {\r
324     if (handle_of_last_logged_task)\r
325     {\r
326         SET_TASK_FLAG_MARKIFE(handle_of_last_logged_task);    \r
327     }\r
328 }\r
329 \r
330 /*******************************************************************************\r
331  * vvTraceTaskSkipDefaultInstanceFinishedEvents\r
332  *\r
333  * This is useful if there are implicit Instance Finish Events, such as \r
334  * vTaskDelayUntil or xQueueReceive, in a task where an explicit Instance Finish \r
335  * Event has been defined. This function tells the recorder that only the \r
336  * explicitly defined functions, using vTraceTaskInstanceIsFinished, should be\r
337  * treated as Instance Finish Events for this task. The implicit Instance Finish \r
338  * Events are thus disregarded for the calling task.\r
339  ******************************************************************************/\r
340 void vTraceTaskSkipDefaultInstanceFinishedEvents()\r
341 {    \r
342     if (handle_of_last_logged_task)\r
343     {\r
344         PROPERTY_TASK_IFE_SERVICECODE(handle_of_last_logged_task) = \r
345           RESERVED_DUMMY_CODE;\r
346     }\r
347 }\r
348 \r
349 /*******************************************************************************\r
350  * Interrupt recording functions \r
351  ******************************************************************************/\r
352 \r
353 #if (INCLUDE_ISR_TRACING == 1)\r
354 \r
355 #define MAX_ISR_NESTING 16\r
356 static uint8_t isrstack[MAX_ISR_NESTING];\r
357 \r
358 /*******************************************************************************\r
359  * vTraceSetISRProperties\r
360  * \r
361  * Registers an Interrupt Service Routine in the recorder library, This must be\r
362  * called before using vTraceStoreISRBegin to store ISR events. This is \r
363  * typically called in the startup of the system, before the scheduler is \r
364  * started.\r
365  *\r
366  * Example:\r
367  *     #define ID_ISR_TIMER1 1       // lowest valid ID is 1\r
368  *     #define PRIO_OF_ISR_TIMER1 3  // the hardware priority of the interrupt\r
369  *     ...\r
370  *     vTraceSetISRProperties(ID_ISR_TIMER1, "ISRTimer1", PRIO_OF_ISR_TIMER1);\r
371  *     ...\r
372  *     void ISR_handler()\r
373  *     {\r
374  *         portENTER_CRITICAL(); // Required if nested ISRs are allowed\r
375  *         vTraceStoreISRBegin(ID_OF_ISR_TIMER1);\r
376  *         portEXIT_CRITICAL();\r
377  *         ...\r
378  *         portENTER_CRITICAL(); // Required if nested ISRs are allowed\r
379  *         vTraceStoreISREnd();\r
380  *         portEXIT_CRITICAL();\r
381  *     }\r
382  ******************************************************************************/\r
383 void vTraceSetISRProperties(objectHandleType handle, char* name, char priority)\r
384 {\r
385     vTraceSetObjectName(TRACE_CLASS_ISR, handle, name);\r
386     vTraceSetPriorityProperty(TRACE_CLASS_ISR, handle, priority);\r
387 }\r
388 \r
389 /*******************************************************************************\r
390  * vTraceStoreISRBegin\r
391  * \r
392  * Registers the beginning of an Interrupt Service Routine. This must not be\r
393  * interrupted by another ISR containing recorder library calls, so if allowing\r
394  * nested ISRs this must be called with interrupts disabled.\r
395  *\r
396  * Example:\r
397  *     #define ID_ISR_TIMER1 1       // lowest valid ID is 1\r
398  *     #define PRIO_OF_ISR_TIMER1 3  // the hardware priority of the interrupt\r
399  *     ...\r
400  *     vTraceSetISRProperties(ID_ISR_TIMER1, "ISRTimer1", PRIO_OF_ISR_TIMER1);\r
401  *     ...\r
402  *     void ISR_handler()\r
403  *     {\r
404  *         portENTER_CRITICAL(); // Required if nested ISRs are allowed\r
405  *         vTraceStoreISRBegin(ID_OF_ISR_TIMER1);\r
406  *         portEXIT_CRITICAL();\r
407  *         ...\r
408  *         portENTER_CRITICAL(); // Required if nested ISRs are allowed\r
409  *         vTraceStoreISREnd();\r
410  *         portEXIT_CRITICAL();\r
411  *     }\r
412  ******************************************************************************/\r
413 void vTraceStoreISRBegin(objectHandleType handle)\r
414 {\r
415     uint16_t dts4;\r
416     TSEvent* ts = NULL;\r
417 \r
418     if (RecorderDataPtr->recorderActive && handle_of_last_logged_task)\r
419     {    \r
420         dts4 = (uint16_t)prvTraceGetDTS(0xFFFF);\r
421 \r
422         if (RecorderDataPtr->recorderActive) /* Need to repeat this check! */    \r
423         {    \r
424             if (nISRactive < MAX_ISR_NESTING)\r
425             {    \r
426                 isrstack[nISRactive] = handle;\r
427                 nISRactive++;            \r
428                 ts = (TSEvent*)xTraceNextFreeEventBufferSlot();\r
429                 if (ts != NULL)\r
430                 {\r
431                     ts->type = TS_ISR_BEGIN;\r
432                     ts->dts = dts4;\r
433                     ts->objHandle = handle;\r
434                     prvTraceUpdateCounters();                \r
435                 }\r
436             }\r
437             else\r
438             {            \r
439                 /* This should not occur unless something is very wrong */            \r
440                 vTraceError("Too many nested interrupts!");\r
441             }\r
442         }\r
443     }\r
444 }\r
445 \r
446 /*******************************************************************************\r
447  * vTraceStoreISREnd\r
448  * \r
449  * Registers the end of an Interrupt Service Routine. This must not be\r
450  * interrupted by another ISR containing recorder library calls, so if allowing\r
451  * nested ISRs this must be called with interrupts disabled.\r
452  *\r
453  * Example:\r
454  *     #define ID_ISR_TIMER1 1       // lowest valid ID is 1\r
455  *     #define PRIO_OF_ISR_TIMER1 3  // the hardware priority of the interrupt\r
456  *     ...\r
457  *     vTraceSetISRProperties(ID_ISR_TIMER1, "ISRTimer1", PRIO_OF_ISR_TIMER1);\r
458  *     ...\r
459  *     void ISR_handler()\r
460  *     {\r
461  *         portENTER_CRITICAL(); // Required if nested ISRs are allowed\r
462  *         vTraceStoreISRBegin(ID_OF_ISR_TIMER1);\r
463  *         portEXIT_CRITICAL();\r
464  *         ...\r
465  *         portENTER_CRITICAL(); // Required if nested ISRs are allowed\r
466  *         vTraceStoreISREnd();\r
467  *         portEXIT_CRITICAL();\r
468  *     }\r
469  ******************************************************************************/\r
470 void vTraceStoreISREnd(void)\r
471 {\r
472     TSEvent* ts;\r
473     uint16_t dts5;\r
474 \r
475     if (RecorderDataPtr->recorderActive && handle_of_last_logged_task)\r
476     {        \r
477         dts5 = (uint16_t)prvTraceGetDTS(0xFFFF);\r
478 \r
479         if (RecorderDataPtr->recorderActive) /* Need to repeat this check! */    \r
480         {                            \r
481             ts = (TSEvent*)xTraceNextFreeEventBufferSlot();\r
482             if (ts != NULL)\r
483             {\r
484                 if (nISRactive > 1)\r
485                 {\r
486                     /* return to another isr */\r
487                     ts->type = TS_ISR_RESUME;\r
488                     ts->objHandle = isrstack[nISRactive];\r
489                 }\r
490                 else\r
491                 {\r
492                     /* return to task */\r
493                     ts->type = TS_TASK_RESUME;\r
494                     ts->objHandle = handle_of_last_logged_task;\r
495                 }\r
496                 ts->dts = dts5;\r
497                 nISRactive--;\r
498                 prvTraceUpdateCounters();\r
499             }\r
500         }\r
501     }\r
502 }\r
503 \r
504 #endif\r
505 \r
506 \r
507 /*******************************************************************************\r
508  * User Event functions\r
509  ******************************************************************************/\r
510 \r
511 #if (INCLUDE_USER_EVENTS == 1)\r
512 \r
513  /******************************************************************************\r
514  * vTraceUserEvent\r
515  *\r
516  * Basic user event (Standard and Professional Edition only)\r
517  * \r
518  * Generates a User Event with a text label. The label is created/looked up\r
519  * in the symbol table using xTraceOpenLabel.\r
520  ******************************************************************************/\r
521 void vTraceUserEvent(traceLabel eventLabel)\r
522 {\r
523     UserEvent* ue;\r
524     uint8_t dts1;\r
525 \r
526     if (RecorderDataPtr->recorderActive && (! inExcludedTask || nISRactive ) && handle_of_last_logged_task)    \r
527     {    \r
528         taskENTER_CRITICAL();\r
529 \r
530         dts1 = (uint8_t)prvTraceGetDTS(0xFF);\r
531 \r
532         if (RecorderDataPtr->recorderActive) /* Need to repeat this check! */    \r
533         {                        \r
534             ue = (UserEvent*) xTraceNextFreeEventBufferSlot();\r
535             if (ue != NULL)\r
536             {\r
537                 ue->dts = dts1;\r
538                 ue->type = USER_EVENT;\r
539                 ue->payload = eventLabel;\r
540                 prvTraceUpdateCounters();\r
541             }\r
542         }\r
543         taskEXIT_CRITICAL();\r
544     }\r
545 }\r
546 \r
547 /*** Locally used in vTracePrintF ***/\r
548 \r
549 /* one word (32 bit) is required for the USER_EVENT entry, 8 words \r
550 (8*32 bit = 32 byte) available for argument data */\r
551 #define MAX_ARG_SIZE (4+32)    \r
552 \r
553 static uint8_t writeInt8(void * buffer, uint8_t index, uint8_t value);\r
554 static uint8_t writeInt16(void * buffer, uint8_t index, uint16_t value);\r
555 static uint8_t writeInt32(void * buffer, uint8_t index, uint32_t value);\r
556 \r
557 #if (INCLUDE_FLOAT_SUPPORT)\r
558 static uint8_t writeFloat(void * buffer, uint8_t index, float value);\r
559 static uint8_t writeDouble(void * buffer, uint8_t index, double value);\r
560 #endif\r
561 \r
562 /*** Locally used in vTracePrintF ***/\r
563 static uint8_t writeInt8(void * buffer, uint8_t index, uint8_t value)\r
564 {    \r
565     \r
566     if (index + 1 > MAX_ARG_SIZE)\r
567     {\r
568         return 255;\r
569     }\r
570 \r
571     ((uint8_t*)buffer)[index] = value;\r
572 \r
573     return index + 1;\r
574 }\r
575 \r
576 /*** Locally used in vTracePrintF ***/\r
577 static uint8_t writeInt16(void * buffer, uint8_t index, uint16_t value)\r
578 {\r
579     /* Align to multiple of 2 */\r
580     while ((index % 2) != 0)\r
581     {        \r
582         ((uint8_t*)buffer)[index] = 0;\r
583         index++;        \r
584     }\r
585     \r
586     if (index + 2 > MAX_ARG_SIZE)\r
587     {\r
588         return 255;\r
589     }\r
590 \r
591     ((uint16_t*)buffer)[index/2] = value;\r
592 \r
593     return index + 2;\r
594 }\r
595 \r
596 /*** Locally used in vTracePrintF ***/\r
597 static uint8_t writeInt32(void * buffer, uint8_t index, uint32_t value)\r
598 {\r
599     \r
600     /* A 32 bit value should begin at an even 4-byte address */\r
601     while ((index % 4) != 0)\r
602     {\r
603         ((uint8_t*)buffer)[index] = 0;\r
604         index++;\r
605     }\r
606     \r
607     if (index + 4 > MAX_ARG_SIZE)\r
608     {\r
609         return 255;\r
610     }        \r
611 \r
612     ((uint32_t*)buffer)[index/4] = value;\r
613 \r
614     return index + 4;\r
615 }\r
616 \r
617 #if (INCLUDE_FLOAT_SUPPORT)\r
618 \r
619 /*** Locally used in vTracePrintF ***/\r
620 static uint8_t writeFloat(void * buffer, uint8_t index, float value)\r
621 {\r
622     /* A 32 bit value should begin at an even 4-byte address */\r
623     while ((index % 4) != 0)\r
624     {\r
625         ((uint8_t*)buffer)[index] = 0;\r
626         index++;\r
627     }\r
628 \r
629     if (index + 4 > MAX_ARG_SIZE)\r
630     {\r
631         return 255;\r
632     }        \r
633 \r
634     ((float*)buffer)[index/4] = value;\r
635     \r
636     return index + 4;\r
637 }\r
638 \r
639 /*** Locally used in vTracePrintF ***/\r
640 static uint8_t writeDouble(void * buffer, uint8_t index, double value)\r
641 {\r
642     /* The double is written as two 32 bit values, and should begin at an even \r
643     4-byte address (to avoid having to align with 8 byte) */\r
644     while (index % 4 != 0)\r
645     {\r
646         ((uint8_t*)buffer)[index] = 0;\r
647         index++;        \r
648     }\r
649     \r
650     if (index + 8 > MAX_ARG_SIZE)\r
651     {\r
652         return 255;\r
653     }       \r
654     \r
655     ((uint32_t*)buffer)[index/4+0] = ((uint32_t*)&value)[0];\r
656     ((uint32_t*)buffer)[index/4+1] = ((uint32_t*)&value)[1];\r
657 \r
658     return index + 8;\r
659 }\r
660 \r
661 #endif\r
662 \r
663  /******************************************************************************\r
664  * vTracePrintF \r
665  * \r
666  * Advanced user events (Professional Edition only)\r
667  *\r
668  * Generates User Event with formatted text and data, similar to a "printf".\r
669  * It is very fast compared to a normal "printf" since this function only \r
670  * stores the arguments. The actual formatting is done\r
671  * on the host PC when the trace is displayed in the viewer tool. \r
672  *\r
673  * User Event labels are created using xTraceOpenLabel.\r
674  * Example:\r
675  *\r
676  *     traceLabel adc_uechannel = xTraceOpenLabel("ADC User Events");\r
677  *     ...\r
678  *     vTracePrint(adc_uechannel, \r
679  *                 "ADC channel %d: %lf volts", \r
680  *                 ch, (double)adc_reading/(double)scale);\r
681  *\r
682  * This can be combined into one line, if desired, but this is slower:\r
683  *\r
684  *     vTracePrint(xTraceOpenLabel("ADC User Events"), \r
685  *                 "ADC channel %d: %lf volts", \r
686  *                 ch, (double)adc_reading/(double)scale);\r
687  *\r
688  * Calling xTraceOpenLabel multiple times will not create duplicate entries, but\r
689  * it is of course faster to just do it once, and then keep the handle for later \r
690  * use. If you don´t have any data arguments, only a text label/string, it is \r
691  * better to use vTraceUserEvent - it is faster.\r
692  *\r
693  * Format specifiers supported:\r
694  *  %d - 32 bit signed integer\r
695  *  %u - 32 bit unsigned integer\r
696  *  %f - 32 bit float\r
697  *  %s - string (is copied to the recorder symbol table)\r
698  *  %hd - 16 bit signed integer\r
699  *  %hu - 16 bit unsigned integer\r
700  *  %bd - 8 bit signed integer\r
701  *  %bu - 8 bit unsigned integer\r
702  *  %lf - double-precision float\r
703  * \r
704  * Up to 15 data arguments are allowed, with a total size of maximum 32 byte.\r
705  * In case this is exceeded, the user event is changed into an error message.\r
706  * \r
707  * The data is stored in trace buffer, and is packed to allow storing multiple \r
708  * smaller data entries in the same 4-byte record, e.g., four 8-bit values.\r
709  * A string requires two bytes, as the symbol table is limited to 64K. Storing a \r
710  * double (%lf) uses two records, so this is quite costly. Use float (%f) unless\r
711  * the higher precision is really necessary.\r
712  ******************************************************************************/\r
713 void vTracePrintF(traceLabel eventLabel, const char* formatStr, ...)\r
714 {\r
715     UserEvent* ue1;\r
716     va_list vl;\r
717     uint8_t argCounter = 0;\r
718     uint8_t index = 0;\r
719     uint8_t nofEventEntries = 0;\r
720     uint16_t formatStrIndex = 0;    \r
721 \r
722     /**************************************************************************\r
723     * The array tempDataBuffer is a local buffer used in a two-phase commit of \r
724     * the event data, since a vTracePrintF may span over multiple slots in the \r
725     * buffer.\r
726     * This buffer can be made larger, of course, but remember the risk for \r
727     * stack overflow. Note: This should be a LOCAL buffer, must not be made \r
728     * global. That would cause data corruption when two calls to vTracePrintF\r
729     * from different tasks overlaps (interrupts are only disabled in a small \r
730     * part of this function, otherwise enabled)\r
731     ***************************************************************************/\r
732     uint32_t dummy = 0;                 /* for the alignment of tempDataBuffer*/\r
733     uint8_t tempDataBuffer[MAX_ARG_SIZE];   \r
734     dummy = dummy;                           /* to eliminate compiler warnings*/\r
735 \r
736     if ((inExcludedTask == 0) &&\r
737         (nISRactive == 0) &&\r
738         (RecorderDataPtr->recorderActive == 1) &&\r
739         (handle_of_last_logged_task > 0))\r
740     {        \r
741         /* First, write the "primary" user event entry in the local buffer, but \r
742         let the event type be "EVENT_BEING_WRITTEN" for now...*/\r
743 \r
744         ue1 = (UserEvent*)(&tempDataBuffer[0]);         \r
745         ue1->type = EVENT_BEING_WRITTEN;      /* Update this as the last step */\r
746         \r
747         index = 4;\r
748         formatStrIndex = 0;\r
749         va_start(vl, formatStr);          /* Begin reading the arguments list */\r
750 \r
751         while (formatStr[formatStrIndex] != '\0')\r
752         {\r
753             if (formatStr[formatStrIndex] == '%')\r
754             {\r
755                 argCounter++;\r
756 \r
757                 if (argCounter > 15)\r
758                 {\r
759                     vTraceError("vTracePrintF - Too many arguments, max 15 allowed!");\r
760                     va_end(vl);                    \r
761                     formatStr = "[vTracePrintF error] Too many arguments, max 15 allowed!";\r
762                     index = 4;\r
763                     break;            \r
764                 }\r
765 \r
766 /*******************************************************************************\r
767  * These below code writes raw data (primitive datatypes) in the event buffer, \r
768  * instead of the normal event structs (where byte 0 is event type).\r
769  * These data entries must never be interpreted as real event data, as the type\r
770  * field would be misleading since used for payload data. \r
771  * \r
772  * The correctness of this encoding depends on two mechanisms:\r
773  * \r
774  * 1. An initial USER_EVENT, which type code tells the number of 32-bit data \r
775  * entires that follows. (code - USER_EVENT = number of data entries). \r
776  * Note that a data entry corresponds to the slots that normally corresponds to \r
777  * one (1) event, i.e., 32 bits. vTracePrintF may encode several pieces of data \r
778  * in one data entry, e.g., two 16-bit values or four 8-bit values, one 16-bit\r
779  * value followes by two 8-bit values, etc.\r
780  *\r
781  * 2. A two-phase commit procedure, where the USER_EVENT and data entries are \r
782  * written to a local buffer at first, and when all checks are OK then copied to\r
783  * the main event buffer using a fast memcpy. The event code is finalized as the\r
784  * very last step. Before that that step, the event code indicates an unfinished\r
785  * event, which causes it to be ignored and stop the loading of the file (since \r
786  * an unfinished event is the last event in the trace).\r
787 *******************************************************************************/\r
788                 formatStrIndex++;\r
789                 switch (formatStr[formatStrIndex])\r
790                 {\r
791                 case 'd':    index = writeInt32(tempDataBuffer, \r
792                                                 index, \r
793                                                 (uint32_t)va_arg(vl, uint32_t)); \r
794                              break;\r
795                 case 'u':    index = writeInt32(tempDataBuffer, \r
796                                                 index, \r
797                                                 (uint32_t)va_arg(vl, uint32_t)); \r
798                              break;\r
799                 case 's':    index = writeInt16(tempDataBuffer, \r
800                                                 index, \r
801                                                 (uint16_t)xTraceOpenLabel((char*)va_arg(vl, uint32_t))); \r
802                              break;\r
803 \r
804 #if (INCLUDE_FLOAT_SUPPORT)\r
805                              /* Yes, "double" as type also in the float \r
806                              case. This since "float" is promoted into "double" \r
807                              by the va_arg stuff. */\r
808                 case 'f':    index = writeFloat(tempDataBuffer, \r
809                                                 index, \r
810                                                 (float)va_arg(vl, double)); \r
811                              break;    \r
812 #else\r
813 /* No support for floats, but attempt to store a float user event\r
814 avoid a possible crash due to float reference. Instead store the \r
815 data on uint_32 format (will not be displayed anyway). This is just\r
816 to keep va_arg and index consistent. */\r
817 \r
818                 case 'f':    index = writeInt32(tempDataBuffer,\r
819                                                 index, \r
820                                                 (uint32_t)va_arg(vl, double)); \r
821 #endif\r
822                 case 'l':\r
823                     formatStrIndex++;\r
824                     switch (formatStr[formatStrIndex])\r
825                     {\r
826 #if (INCLUDE_FLOAT_SUPPORT)\r
827                     case 'f':     index = writeDouble(tempDataBuffer, \r
828                                                       index, \r
829                                                       (double)va_arg(vl, double)); \r
830                                   break;\r
831 #else\r
832 /* No support for floats, but attempt to store a float user event\r
833 avoid a possible crash due to float reference. Instead store the \r
834 data on uint_32 format (will not be displayed anyway). This is just\r
835 to keep va_arg and index consistent. */\r
836                     case 'f':    index = writeInt32(tempDataBuffer, /* In this case, the value will not be shown anyway */\r
837                                                     index, \r
838                                                     (uint32_t)va_arg(vl, double)); \r
839                                  index = writeInt32(tempDataBuffer, /* Do it twice, to write in total 8 bytes */\r
840                                                     index, \r
841                                                     (uint32_t)va_arg(vl, double)); \r
842 #endif\r
843 \r
844                     }\r
845                     break;\r
846                 case 'h':\r
847                     formatStrIndex++;\r
848                     switch (formatStr[formatStrIndex])\r
849                     {\r
850                     case 'd':    index = writeInt16(tempDataBuffer, \r
851                                                     index, \r
852                                                     (uint16_t)va_arg(vl, uint32_t)); \r
853                                  break;\r
854                     case 'u':    index = writeInt16(tempDataBuffer, \r
855                                                     index, \r
856                                                     (uint16_t)va_arg(vl, uint32_t)); \r
857                                  break;\r
858                     }\r
859                     break;\r
860                 case 'b':\r
861                     formatStrIndex++;\r
862                     switch (formatStr[formatStrIndex])\r
863                     {\r
864                     case 'd':    index = writeInt8(tempDataBuffer, \r
865                                                    index, \r
866                                                    (uint8_t)va_arg(vl, uint32_t)); \r
867                                  break;\r
868                     case 'u':    index = writeInt8(tempDataBuffer, \r
869                                                    index, \r
870                                                    (uint8_t)va_arg(vl, uint32_t)); \r
871                                  break;\r
872                     }\r
873                     break;\r
874                 }\r
875             }                                    \r
876             formatStrIndex++;    \r
877             if (index == 255)\r
878             {\r
879                 va_end(vl);\r
880                 vTraceError("vTracePrintF - Too large arguments, max 32 byte allowed!");\r
881                 formatStr = "[vTracePrintF error] Too large arguments, max 32 byte allowed!";\r
882                 index = 4;\r
883                 break;\r
884             }\r
885         }\r
886 \r
887         va_end(vl);\r
888 \r
889         /* Store the format string, with a reference to the channel symbol */\r
890         ue1->payload = prvTraceOpenSymbol(formatStr, eventLabel);     \r
891 \r
892         taskENTER_CRITICAL();    \r
893 \r
894         ue1->dts = (uint8_t)prvTraceGetDTS(0xFF);\r
895         if (! RecorderDataPtr->recorderActive)\r
896         {\r
897             /* Abort, since an XTS event (created by prvTraceGetDTS) filled the \r
898             buffer, and the recorder stopped since not circular buffer. */\r
899             taskEXIT_CRITICAL();    \r
900             return;\r
901         }\r
902             \r
903         nofEventEntries = (index+3)/4;\r
904 \r
905         /* If the data does not fit in the remaining main buffer, wrap around to \r
906         0 if allowed, otherwise stop the recorder and quit). */\r
907         if (RecorderDataPtr->nextFreeIndex + nofEventEntries > RecorderDataPtr->maxEvents)\r
908         {\r
909 #if (RECORDER_STORE_MODE == STORE_MODE_RING_BUFFER)\r
910             (void)memset(& RecorderDataPtr->eventData[RecorderDataPtr->nextFreeIndex * 4], \r
911                    0, \r
912                    (RecorderDataPtr->maxEvents - RecorderDataPtr->nextFreeIndex)*4);\r
913             RecorderDataPtr->nextFreeIndex = 0;\r
914             RecorderDataPtr->bufferIsFull = 1;\r
915 #else\r
916             /* Abort and stop recorder, since the event data will not fit in the\r
917             buffer and not circular buffer in this case... */\r
918             taskEXIT_CRITICAL();\r
919             vTraceStop();\r
920             return;\r
921 #endif\r
922         }\r
923     \r
924 #if (RECORDER_STORE_MODE == STORE_MODE_RING_BUFFER)\r
925         /* Check that the buffer to be overwritten does not contain any user \r
926         events that would be partially overwritten. If so, they must be "killed"\r
927         by replacing the user event and following data with NULL events (i.e., \r
928         using a memset to zero).*/\r
929         prvCheckDataToBeOverwrittenForMultiEntryUserEvents(nofEventEntries);\r
930 #endif\r
931         /* Copy the local buffer to the main buffer */\r
932         (void)memcpy(& RecorderDataPtr->eventData[RecorderDataPtr->nextFreeIndex * 4], \r
933                tempDataBuffer, \r
934                index);\r
935 \r
936         /* Update the event type, i.e., number of data entries following the \r
937         main USER_EVENT entry (Note: important that this is after the memcpy, \r
938         but within the critical section!)*/\r
939         RecorderDataPtr->eventData[RecorderDataPtr->nextFreeIndex * 4] = \r
940           (uint8_t) USER_EVENT + nofEventEntries - 1;    \r
941         \r
942         /* Update the main buffer event index (already checked that it fits in \r
943         the buffer, so no need to check for wrapping)*/\r
944         \r
945         RecorderDataPtr->nextFreeIndex += nofEventEntries;\r
946         RecorderDataPtr->numEvents += nofEventEntries;\r
947         \r
948         if (RecorderDataPtr->nextFreeIndex >= EVENT_BUFFER_SIZE)\r
949         {\r
950         \r
951 #if (RECORDER_STORE_MODE == STORE_MODE_RING_BUFFER)\r
952             RecorderDataPtr->nextFreeIndex = 0;\r
953             RecorderDataPtr->bufferIsFull = 1;\r
954 #else\r
955             vTraceStop();\r
956 #endif\r
957         }\r
958 \r
959         taskEXIT_CRITICAL();\r
960     }\r
961 }\r
962     \r
963 /*******************************************************************************\r
964  * xTraceOpenLabel\r
965  * \r
966  * Creates user event labels for user event channels or for individual events.\r
967  * User events can be used to log application events and data for display in\r
968  * the visualization tool. A user event is identified by a label, i.e., a string,\r
969  * which is stored in the recorder's symbol table.\r
970  * When logging a user event, a numeric handle (reference) to this string is\r
971  * used to identify the event. This is obtained by calling \r
972  * \r
973  *     xTraceOpenLabel()\r
974  *\r
975  * whihc adds the string to the symbol table (if not already present)\r
976  * and returns the corresponding handle.\r
977  *\r
978  * This can be used in two ways:\r
979  *\r
980  * 1. The handle is looked up every time, when storing the user event.\r
981  *\r
982  * Example:\r
983  *     vTraceUserEvent(xTraceOpenLabel("MyUserEvent"));\r
984  *\r
985  * 2. The label is registered just once, with the handle stored in an\r
986  *  application variable - much like using a file handle.\r
987  *\r
988  * Example:\r
989  *     myEventHandle = xTraceOpenLabel("MyUserEvent");\r
990  *     ...\r
991  *     vTraceUserEvent(myEventHandle);\r
992  *\r
993  * The second option is faster since no lookup is required on each event, and \r
994  * therefore recommended for user events that are frequently\r
995  * executed and/or located in time-critical code. The lookup operation is\r
996  * however fairly fast due to the design of the symbol table.\r
997  ******************************************************************************/\r
998 traceLabel xTraceOpenLabel(char* label)\r
999 {\r
1000     return prvTraceOpenSymbol(label, 0);\r
1001 }\r
1002 #endif\r
1003 #endif\r
1004 \r