summaryrefslogtreecommitdiffstats
path: root/cpukit/libmisc/cpuuse/cpuusagetop.c
blob: 7e7348a99d80c7f7ecca45892786d64511ecce3d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/**
 * @file
 *
 * @brief CPU Usage Top
 * @ingroup libmisc_cpuuse CPU Usage
 */

/*
 *  COPYRIGHT (c) 2014.
 *  On-Line Applications Research Corporation (OAR).
 *
 *  The license and distribution terms for this file may be
 *  found in the file LICENSE in this distribution or at
 *  http://www.rtems.org/license/LICENSE.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <inttypes.h>

#include <rtems/cpuuse.h>
#include <rtems/score/objectimpl.h>
#include <rtems/score/threadimpl.h>
#include <rtems/score/todimpl.h>
#include <rtems/score/watchdogimpl.h>


/*
 * Common variable to sync the load monitor task.
 */
static volatile int rtems_cpuusage_top_thread_active;


typedef struct {
  void                  *context;
  rtems_printk_plugin_t  print;
}rtems_cpu_usage_plugin_t;

#define RTEMS_CPUUSAGE_TOP_MAX_LOAD_TASKS (20)

/*
 * rtems_cpuusage_top_thread
 *
 *  DESCRIPTION:
 *
 * This function displays the load of the tasks on an ANSI terminal.
 *
 */

static void
rtems_cpuusage_top_thread (rtems_task_argument arg)
{
  uint32_t                  api_index;
  Thread_Control*           the_thread;
  int                       i;
  int                       j;
  int                       k;
  Objects_Information*      information;
    char                    name[13];
  int                       task_count = 0;
  uint32_t                  seconds, nanoseconds;
  rtems_cpu_usage_plugin_t* plugin = (rtems_cpu_usage_plugin_t*)arg;
  Thread_Control*           load_tasks[RTEMS_CPUUSAGE_TOP_MAX_LOAD_TASKS + 1];
  unsigned long long        load[RTEMS_CPUUSAGE_TOP_MAX_LOAD_TASKS + 1];

  while (true)
  {
    #ifndef __RTEMS_USE_TICKS_FOR_STATISTICS__
      Timestamp_Control  uptime, total, ran, uptime_at_last_reset;
    #else
      uint32_t           total_units = 0;
    #endif

    rtems_cpuusage_top_thread_active = 1;

    memset (load_tasks, 0, sizeof (load_tasks));
    memset (load, 0, sizeof (load));

   /*
     * Iterate over the tasks and sort the highest load tasks
     * into our local arrays. We only handle a limited number of
     * tasks.
     */
    for ( api_index = 1 ; api_index <= OBJECTS_APIS_LAST ; api_index++ ) {
      #if !defined(RTEMS_POSIX_API) || defined(RTEMS_DEBUG)
        if ( !_Objects_Information_table[ api_index ] )
          continue;
      #endif

      information = _Objects_Information_table[ api_index ][ 1 ];
      if ( information ) {
        for ( k=1 ; k <= information->maximum ; k++ ) {
          the_thread = (Thread_Control *)information->local_table[ k ];
          if ( the_thread ) {

            Thread_CPU_usage_t l = the_thread->cpu_time_used;

            /*
             *  When not using nanosecond CPU usage resolution, we have to count
             *  the number of "ticks" we gave credit for to give the user a rough
             *  guideline as to what each number means proportionally.
             */
            #ifdef __RTEMS_USE_TICKS_FOR_STATISTICS__
              total_units += l;
            #endif

            /* Count the number of tasks and sort this load value */
            task_count++;
            for (i = 0; i < RTEMS_CPUUSAGE_TOP_MAX_LOAD_TASKS; i++) {
              if (load_tasks[i]) {
                if ((l == 0) || (l < load[i]))
                  continue;
                for (j = (RTEMS_CPUUSAGE_TOP_MAX_LOAD_TASKS - 1); j >= i; j--){
                  load_tasks[j + 1] = load_tasks[j];
                  load[j + 1]  = load[j];
                }
              }
              load_tasks[i] = the_thread;
              load[i]  = l;
              break;
            }
          }
        }
      }
    }

    #ifndef __RTEMS_USE_TICKS_FOR_STATISTICS__
      _Timestamp_Set_to_zero( &total );
      uptime_at_last_reset = CPU_usage_Uptime_at_last_reset;
    #endif

    _TOD_Get_uptime( &uptime );
    seconds = _Timestamp_Get_seconds( &uptime );
    nanoseconds = _Timestamp_Get_nanoseconds( &uptime ) /
                  TOD_NANOSECONDS_PER_MICROSECOND;
    (*plugin->print)(plugin->context, "\x1b[H\x1b[J Press ENTER to exit.\n\n");
    (*plugin->print)(plugin->context, "uptime: ");
    (*plugin->print)(plugin->context,
      "%7" PRIu32 ".%06" PRIu32 "\n",  seconds, nanoseconds
    );

    (*plugin->print)(
       plugin->context,
       "-------------------------------------------------------------------------------\n"
       "                              CPU USAGE BY THREAD\n"
       "------------+---------------------+---------------+---------------+------------\n"
       #ifndef __RTEMS_USE_TICKS_FOR_STATISTICS__
        " ID         | NAME                | RPRI | CPRI   | SECONDS       | PERCENT\n"
       #else
         " ID        | NAME                | RPRI | CPRI   | TICKS         | PERCENT\n"
       #endif
       "------------+---------------------+---------------+---------------+------------\n"
    );

    for (i = 0; i < RTEMS_CPUUSAGE_TOP_MAX_LOAD_TASKS; i++)
    {

      if (!load_tasks[i])
        break;

      /*
       * If this is the currently executing thread, account for time
       * since the last context switch.
       */
      the_thread = load_tasks[i];

      rtems_object_get_name( the_thread->Object.id, sizeof(name), name );
      (*plugin->print)(
        plugin->context,
        " 0x%08" PRIx32 " | %-19s |  %3" PRId32 " |  %3" PRId32 "   |",
        the_thread->Object.id,
        name,
        the_thread->real_priority,
        the_thread->current_priority
      );

      #ifndef __RTEMS_USE_TICKS_FOR_STATISTICS__
      {
        Timestamp_Control last;
        uint32_t          ival, fval;

        /*
         * If this is the currently executing thread, account for time
         * since the last context switch.
         */
        ran = load[i];
        if ( _Thread_Get_time_of_last_context_switch( the_thread, &last ) ) {
          Timestamp_Control used;
          _TOD_Get_uptime( &uptime );
          _Timestamp_Subtract( &last, &uptime, &used );
          _Timestamp_Add_to( &ran, &used );
        } else {
          _TOD_Get_uptime( &uptime );
        }
        _Timestamp_Subtract( &uptime_at_last_reset, &uptime, &total );
        _Timestamp_Divide( &ran, &total, &ival, &fval );

        /*
         * Print the information
         */

        seconds = _Timestamp_Get_seconds( &ran );
        nanoseconds = _Timestamp_Get_nanoseconds( &ran ) /
          TOD_NANOSECONDS_PER_MICROSECOND;
       (*plugin->print)( plugin->context,
          "%7" PRIu32 ".%06" PRIu32 " |%4" PRIu32 ".%03" PRIu32 "\n",
          seconds, nanoseconds,
            ival, fval
        );
      }
      #else
        if (total_units) {
          uint64_t ival_64;

          ival_64 = load[i];
          ival_64 *= 100000;
          ival = ival_64 / total_units;
        } else {
          ival = 0;
        }

        fval = ival % 1000;
        ival /= 1000;
       (*plugin->print)( plugin->context,
          "%14" PRIu32 " |%4" PRIu32 ".%03" PRIu32 "\n",
          load[i],
          ival,
          fval
        );
      #endif
    }

    if (task_count < RTEMS_CPUUSAGE_TOP_MAX_LOAD_TASKS)
    {
      j = RTEMS_CPUUSAGE_TOP_MAX_LOAD_TASKS - task_count;
      while (j > 0)
      {
       (*plugin->print)( plugin->context, "\x1b[K\n");
        j--;
      }
    }

    rtems_cpuusage_top_thread_active = 0;

    rtems_task_wake_after (RTEMS_MICROSECONDS_TO_TICKS (5000000));
  }
}

void rtems_cpu_usage_top_with_plugin(
  void                  *context,
  rtems_printk_plugin_t  print
)
{
  rtems_status_code   sc;
  rtems_task_priority priority;
  rtems_name          name;
  rtems_id            id;
  rtems_cpu_usage_plugin_t  plugin;

  if ( !print )
    return;

  plugin.context = context;
  plugin.print   = print;

  sc = rtems_task_set_priority (RTEMS_SELF, RTEMS_CURRENT_PRIORITY, &priority);

  if (sc != RTEMS_SUCCESSFUL)
  {
    (*print)(
       context,
       "error: cannot obtain the current priority: %s\n",
       rtems_status_text (sc)
    );
    return;
  }

  name = rtems_build_name('C', 'P', 'l', 't');

  sc = rtems_task_create (name, priority, 4 * 1024,
                          RTEMS_NO_FLOATING_POINT | RTEMS_LOCAL,
                          RTEMS_PREEMPT | RTEMS_TIMESLICE | RTEMS_NO_ASR,
                          &id);

  if (sc != RTEMS_SUCCESSFUL)
  {
    (*print)(
       context,
       "error: cannot create helper thread: %s\n",
       rtems_status_text (sc)
    );
    return;
  }

  sc = rtems_task_start (
    id, rtems_cpuusage_top_thread, (rtems_task_argument)&plugin
  );
  if (sc != RTEMS_SUCCESSFUL)
  {
    (*print)(
       context,
       "error: cannot start helper thread: %s\n",
       rtems_status_text (sc)
    );
    rtems_task_delete (id);
    return;
  }

  for (;;)
  {
    int c = getchar ();

    if ((c == '\r') || (c == '\n'))
    {
      int loops = 20;

      while (loops && rtems_cpuusage_top_thread_active)
        rtems_task_wake_after (RTEMS_MICROSECONDS_TO_TICKS (100000));

      rtems_task_delete (id);

      (*print)(context, "load monitoring stopped.\n");
      return;
    }
  }
}

void rtems_cpu_usage_top( void )
{
  rtems_cpu_usage_top_with_plugin( NULL, printk_plugin );
}