summaryrefslogtreecommitdiff
path: root/mbgcmptime/mbgcmptime.c
blob: f6483ad51b5b272b17c26774215d85ca12c806ad (plain)
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485

/**************************************************************************
 *
 *  $Id: mbgcmptime.c 1.11 2021/11/15 17:08:52Z martin.burnicki REL_M $
 *
 *  Description:
 *    Main file for mbgcmptime program which compares the time on 2 devices
 *    by reading the time plus cycles from both devices immediately after
 *    each other, and compensates the execution delay based on the returned
 *    cycles counts.
 *
 * -----------------------------------------------------------------------
 *  $Log: mbgcmptime.c $
 *  Revision 1.11  2021/11/15 17:08:52Z  martin.burnicki
 *  Improved printing of usage information.
 *  Revision 1.10  2021/11/08 18:01:08  martin.burnicki
 *  Account for modified MBG_DEV_FN type.
 *  Revision 1.9  2021/04/12 21:57:54  martin
 *  Updated printing of usage information.
 *  Revision 1.8  2021/03/21 17:39:41  martin
 *  Updated some comments.
 *  Revision 1.7  2021/03/12 14:20:13  martin
 *  Use the new global variable pc_cycles_frequency.
 *  Revision 1.6  2020/06/17 10:06:48  martin
 *  New option -R to also print raw (hex) timestamps.
 *  Workaround for clreol which is unsupported on Windows.
 *  Revision 1.5  2020/05/11 08:47:01  martin
 *  Removed erroneous duplicate definition of variable 'cyc_freq'.
 *  Revision 1.4  2018/12/14 12:51:29  martin
 *  Fixed evaluation of device specification parameters.
 *  Improved error handling.
 *  Revision 1.3  2018/11/15 12:39:28  martin
 *  Individual MBG_MICRO_VERSION codes are now obsolete.
 *  Revision 1.2  2018/08/08 09:01:45  martin
 *  New option -a to compensate an initial offset automatically.
 *  New option -C which to append a marker '#' to the output if status changed.
 *  New option -L to specify a time offset limit. If the time offset change
 *  exceeds the specified limit, a marker '<<' is appended to the output.
 *  New option -q for quiet operation, i.e. output lines on the console
 *  are overwritten unless the previous line has a marker appended.
 *  New option -o to specify an output file that provides the full log
 *  even is -q is used, too.
 *  Options -s and -u also imply continuous mode.
 *  Fixed Windows build.
 *  Moved some common code to cmp_time_util module.
 *  Moved output unbuffering to toolutil.c::mbg_check_devices(), and account
 *  for additional parameter expected by the current version of that function.
 *  Use new, safe library functions.
 *  Close device handle when done.
 *  Proper return codes and exit codes.
 *  Revision 1.1  2013/01/25 10:26:13  martin
 *  Initial revision.
 *
 **************************************************************************/

// Include Meinberg headers.
#include <cmp_time_util.h>
#include <mbgdevio.h>
#include <toolutil.h>  // Common utility functions.
#include <str_util.h>

// Include system headers.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define MBG_FIRST_COPYRIGHT_YEAR   2013
#define MBG_LAST_COPYRIGHT_YEAR    0     // Use default.

static const char *pname = "mbgcmptime";


static int loops;
static int read_fast;
static int read_raw;
static long sleep_secs;
static long sleep_usecs;
static int print_raw;
static double warn_limit;
static double chk_limit;
static int auto_offset;
static int check_status;
static int quiet;

static const char *log_fn;

static const char *ref_dev_param;
static MBG_DEV_HANDLE dh_ref;
static PCPS_DEV dev_info_ref;

#if defined( MBG_TGT_WIN32 )
static const char term_clreol[] = "     ";     // ANSI not supported; just print some spaces to highlight end of line.
#else
static const char term_clreol[] = "\x1B[0K";   // ANSI escape sequence for clreol.
#endif



static /*HDR*/
FILE *fopen_log( const char *mode )
{
  FILE *fp = fopen( log_fn, mode );

  if ( fp == NULL )
  {
    fprintf( stderr, "Failed to open log file %s: %s. Giving up logging.\n", log_fn, strerror( errno ) );
    log_fn = NULL;
  }

  return fp;

}  // fopen_log



static /*HDR*/
int do_mbgcmptime( MBG_DEV_HANDLE dh, const PCPS_DEV *p_dev )
{
  PCPS_HR_TIME_CYCLES prv_htc1 = { 0 };
  PCPS_HR_TIME_CYCLES prv_htc2 = { 0 };
  PCPS_HR_TIME_CYCLES htc1 = { 0 };
  PCPS_HR_TIME_CYCLES htc2 = { 0 };
  double delta_ts;
  double delta_cyc;
  double delta_t;
  double prv_delta_t = 0.0;
  int prv_delta_t_avail = 0;
  int this_loops = loops;
  int rc;
  size_t n;
  char ws[256];
  char ws1[128];
  char ws2[128];
  char ws3[64];
  int add_marker;

  if ( read_fast )
  {
    rc = chk_fast_tstamp_supp( dh, p_dev, dh_ref, &dev_info_ref, NULL );  // TODO err_msg_fnc ?

    if ( mbg_rc_is_error( rc ) )
    {
      if ( rc != MBG_ERR_NOT_SUPP_BY_DEV )
        goto done;

      // TODO Show msg ...
      read_fast = 0;
    }
  }

  rc = mbg_init_pc_cycles_frequency( dh );

  if ( mbg_cond_err_msg( rc, "mbg_init_pc_cycles_frequency" ) )
    goto done;


  for (;;)
  {
    rc = get_htc_timestamps( dh, &htc1, dh_ref, &htc2, read_fast );

    if ( rc != MBG_SUCCESS )
      break;

    delta_t = get_htc_delta( &htc1, &htc2, &delta_ts, &delta_cyc );

    if ( auto_offset )
    {
      static double initial_offset;
      static int initial_offset_set;

      if ( !initial_offset_set )
      {
        initial_offset = delta_t;
        initial_offset_set = 1;
        printf( "Initial offset: %.1f us\n", initial_offset * 1e6 );
      }

      delta_t -= initial_offset;
    }

    n = mbg_snprint_hr_tstamp_ext( ws1, sizeof( ws1 ), &htc1.t.tstamp, print_raw );

    if ( check_status )
      snprintf_safe( ws1 + n, sizeof( ws1 ) - n, " st: %04X", htc1.t.status );

    n = mbg_snprint_hr_tstamp_ext( ws2, sizeof( ws2 ), &htc2.t.tstamp, print_raw );

    if ( check_status )
      snprintf_safe( ws2 + n, sizeof( ws2 ) - n, " st: %04X", htc2.t.status );

    snprintf_safe( ws3, sizeof( ws3 ), "%+.1f us", delta_t * 1e6 );

    n = 0;

    n += snprintf_safe( &ws[n], sizeof( ws ) - n, "%s, %s", ws1, ws2 );

    n += snprintf_safe( &ws[n], sizeof( ws ) - n, " ts: %.1f us, cyc: %.1f us, delta: %s",
                        delta_ts * 1e6, delta_cyc * 1e6, ws3 );

    add_marker = 0;

    if ( ( warn_limit > 0.0 ) && ( fabs( delta_t ) > warn_limit ) )
    {
      n += sn_cpy_str_safe( &ws[n], sizeof( ws ) - n, " *" );
      add_marker = 1;
    }

    if ( prv_delta_t_avail )
    {
      double ddelta_t = delta_t - prv_delta_t;

      if ( ( chk_limit > 0.0 ) && ( fabs( ddelta_t ) > chk_limit ) )
      {
        n += sn_cpy_str_safe( &ws[n], sizeof( ws ) - n, " <<" );
        add_marker = 1;
      }

      if ( check_status )
      {
        if ( ( htc1.t.status != prv_htc1.t.status )
          || ( htc2.t.status != prv_htc2.t.status ) )
        {
          n += sn_cpy_str_safe( &ws[n], sizeof( ws ) - n, " #" );
          add_marker = 1;
        }
      }
    }

    #if defined( DEBUG )
      if ( htc2.t.tstamp.sec != htc1.t.tstamp.sec )
      {
        n += sn_cpy_str_safe( &ws[n], sizeof( ws ) - n, " X" );
        add_marker = 1;
      }
    #endif

    if ( add_marker )
      n += sn_cpy_str_safe( &ws[n], sizeof( ws ) - n, " !!" );

    if ( quiet )
    {
      // Overwrite last line, and only append new line if the
      // current line has a marker appended, so it's visible
      // on the console that something unexpected has happened.
      printf( "\r%s%s%s", ws, term_clreol, ( add_marker ) ? "\n" : "" );
    }
    else
      printf( "%s\n", ws );

    if ( log_fn )
    {
      FILE *fp = fopen_log( "a" );

      if ( fp )
      {
        fprintf( fp, "%s\n", ws );
        fclose( fp );
      }
    }

    if ( this_loops > 0 )
      this_loops--;

    if ( this_loops == 0 )
      break;

    // If this_loops is < 0, loop forever.

    prv_htc1 = htc1;
    prv_htc2 = htc2;
    prv_delta_t = delta_t;
    prv_delta_t_avail = 1;

    if ( sleep_secs )
      sleep( sleep_secs );
    else
      if ( sleep_usecs )
        usleep( sleep_usecs );

    // printf( "\n" );
  }

done:
  return rc;

}  // do_mbgcmptime



static /*HDR*/
void usage( void )
{
  mbg_print_usage_intro( pname, true,
    "Compare the time on two devices by reading the time stamps plus cycles from\n"
    "both devices immediately after each other, and compensate the execution delay\n"
    "based on the returned cycles counts.\n"
    "The device to be used as reference has to be specified by parameter -i (see\n"
    "below), whereas the device under test is specified as last parameter on the\n"
    "command line."
  );
  mbg_print_help_options();
  mbg_print_opt_info( "-i dev", "Reference device to which the time of the device under test shall be compared" );
  mbg_print_opt_info( "-l limit", "Append a marker '*' to the output if delta exceeds limit [us]" );
  mbg_print_opt_info( "-L limit", "Append a marker '<<' to the output if delta changes [us]" );
  mbg_print_opt_info( "-C", "Append a marker '#' to the output if status changed" );
  mbg_print_opt_info( "-f", "Read fast (memory mapped) timestamps" );
  mbg_print_opt_info( "-c", "Run continuously" );
  mbg_print_opt_info( "-n num", "Run num loops" );
  mbg_print_opt_info( "-r", "Read raw time stamps, no cycles" );
  mbg_print_opt_info( "-R", "Also display raw timestamps (hex)" );
  mbg_print_opt_info( "-s num", "Sleep num seconds between calls (implies -c)" );
  mbg_print_opt_info( "-u num", "Sleep num microseconds between calls (implies -c)" );
  mbg_print_opt_info( "-o file", "Also log output to <file>" );
  mbg_print_opt_info( "-q", "quiet, Only log errors to console (use -o to specify file for full log)" );
  mbg_print_opt_info( "-a", "Auto-compensate initial offset" );
  mbg_print_device_options( DEV_OPT_PRINT_BUS_LEVEL );

  printf( "\nExamples:\n\n" );
  printf(
    "Run once and compare the time from the 2 devices with indexes 1 and 2\n"
    "to the time from reference device with index 0:\n\n"
    "  %s -i 0 1 2\n\n", pname
  );
  printf(
    "Run continuously in 1 s intervals and compare the time from %s\n"
    "to the time from reference device %s:\n\n"
    "  %s -s 1 -i %s %s\n\n", EXAMPLE_DEV_NAME_2, EXAMPLE_DEV_NAME_1,
    pname, EXAMPLE_DEV_NAME_1, EXAMPLE_DEV_NAME_2
  );

  mbg_print_usage_syn1588_support();

}  // usage



int main( int argc, char *argv[] )
{
  MBG_DEV_FN ref_dev_fn;
  int rc;
  int c;

  mbg_print_program_info( pname, MBG_FIRST_COPYRIGHT_YEAR, MBG_LAST_COPYRIGHT_YEAR );

  // Check command line parameters.
  while ( ( c = getopt( argc, argv, "acCfi:l:L:n:o:qrRs:u:h?" ) ) != -1 )
  {
    switch ( c )
    {
      case 'a':
        auto_offset = 1;
        break;

      case 'C':
        check_status = 1;
        break;

      case 'i':
        ref_dev_param = optarg;
        break;

      case 'l':
        warn_limit = (double) atoi( optarg ) / 1e6;
        break;

      case 'L':
        chk_limit = (double) atoi( optarg ) / 1e6;
        break;

      case 'f':
        read_fast = 1;
        break;

      case 'c':
        loops = -1;
        break;

      case 'n':
        loops = atoi( optarg );
        break;

      case 'o':
        log_fn = optarg;
        break;

      case 'q':
        quiet = 1;
        break;

      case 'r':
        read_raw = 1;
        break;

      case 'R':
        print_raw = 1;
        break;

      case 's':
        sleep_secs = atoi( optarg );
        loops = -1;
        break;

      case 'u':
        sleep_usecs = atoi( optarg );
        loops = -1;
        break;

      case 'h':
      case '?':
      default:
        must_print_usage = true;
    }
  }

  if ( ref_dev_param == NULL )
  {
    // No ref device specified.
    if ( !must_print_usage )
      fprintf( stderr, "A reference device has to be specified using the -i parameter.\n\n" );
    must_print_usage = true;
  }

  if ( must_print_usage )
  {
    usage();
    return MBG_EXIT_CODE_USAGE;
  }

  #if !MBG_TGT_SUPP_MEM_ACC
    fprintf( stderr, "** Memory mapped access not supported on this target platform.\n\n" );
    return MBG_EXIT_CODE_NOT_SUPP;
  #endif

  #if !MBG_PC_CYCLES_SUPPORTED
    fprintf( stderr, "** Warning: No cycles support to compute real latencies on this platform!\n" );
    return MBG_EXIT_CODE_NOT_SUPP;
  #endif

  if ( quiet )  // Make stdout unbuffered.
    setvbuf( stdout, NULL, _IONBF, 0 );

  if ( log_fn )
  {
    // Create new or truncate existing log file.
    FILE *fp = fopen_log( "w" );

    if ( fp )
      fclose( fp );
  }

  // We don't call mbg_open_device_by_param_chk() here because
  // we want to print our own error message in case of failure.
  rc = mbg_open_device_by_param( &dh_ref, ref_dev_param, 0,
                                 ref_dev_fn.s, sizeof( ref_dev_fn.s ) );

  if ( mbg_rc_is_error( rc ) )
  {
    fprintf( stderr, "** Failed to open ref device %s: %s.\n",
             ref_dev_param,  mbg_strerror( rc ) );
    goto out;
  }

  #if defined( DEBUG )
    fprintf( stderr, "Ref device %s (%s) opened successfully.\n",
             ref_dev_param, ref_dev_fn.s );
  #endif

  mbg_get_device_info( dh_ref, &dev_info_ref );

  if ( mbg_rc_is_error( rc ) )
  {
    fprintf( stderr, "** Failed to get device info for ref device %s: %s.\n",
                     ref_dev_param, mbg_strerror( rc ) );
    goto out_close;
  }

  // Handle each of the specified devices.
  rc = mbg_handle_devices( argc, argv, optind, do_mbgcmptime, 0 );

out_close:
  mbg_close_device( &dh_ref );

out:
  return mbg_rc_is_success( rc ) ? MBG_EXIT_CODE_SUCCESS : MBG_EXIT_CODE_FAIL;
}