Source

mpi3-fortran / ompi / contrib / vt / vt / vtlib / vt_cupti_events.c

Full commit
   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
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
/**
 * VampirTrace
 * http://www.tu-dresden.de/zih/vampirtrace
 *
 * Copyright (c) 2005-2012, ZIH, TU Dresden, Federal Republic of Germany
 *
 * Copyright (c) 1998-2005, Forschungszentrum Juelich, Juelich Supercomputing
 *                          Centre, Federal Republic of Germany
 *
 * See the file COPYING in the package base directory for details
 **/
#include "vt_defs.h"        /* VampirTrace constants */
#include "vt_env.h"         /* get environment variables */
#include "vt_pform.h"       /* VampirTrace time measurement */
#include "vt_trc.h"         /* VampirTrace events */
#include "vt_mallocwrap.h"  /* wrapping of malloc and free */
#include "vt_cupti_events.h"
#include "vt_gpu.h"

#include <string.h>

#define PRINT_CUPTI_ERROR(err, _msg){                    \
    const char *errstr;                                  \
    cuptiGetResultString(err, &errstr);                  \
    vt_warning("[CUPTI EVENTS] %s:%d:%s:'%s'",           \
                 __FILE__, __LINE__, _msg, errstr);      \
  }

/* some of CUPTI API functions have changed */
#if (defined(CUPTI_API_VERSION) && (CUPTI_API_VERSION >= 2))

# define VTCUPTIEVENTGETATTRIBUTE(_cuDev, _cuptiEvtID, _cuptiAttr, _valueSize, \
                                 _value) \
  VT_CUPTI_CALL(\
    cuptiEventGetAttribute(_cuptiEvtID, _cuptiAttr, _valueSize, _value), \
    "cuptiEventGetAttribute")

# define VTCUPTIEVENTDOMAINGETNUMEVENTS(_cuDev, _cuptiDomain, _numEvts) \
  VT_CUPTI_CALL(\
    cuptiEventDomainGetNumEvents(_cuptiDomain, _numEvts), \
    "cuptiEventDomainGetNumEvents")

# define VTCUPTIEVENTDOMAINENUMEVENTS(_cuDev, _cuptiDomain, _valueSize, _value)\
  VT_CUPTI_CALL(\
    cuptiEventDomainEnumEvents(_cuptiDomain, _valueSize, _value), \
    "cuptiEventDomainEnumEvents")

#else

# define VTCUPTIEVENTGETATTRIBUTE(_cuDev, _cuptiEvtID, _cuptiAttr, _valueSize, \
                                 _value) \
  VT_CUPTI_CALL(\
    cuptiEventGetAttribute(_cuDev, _cuptiEvtID, _cuptiAttr, _valueSize,_value),\
    "cuptiEventGetAttribute")

# define VTCUPTIEVENTDOMAINGETNUMEVENTS(_cuDev, _cuptiDomain, _numEvts) \
  VT_CUPTI_CALL(\
    cuptiEventDomainGetNumEvents(_cuDev, _cuptiDomain, _numEvts), \
    "cuptiEventDomainGetNumEvents")

# define VTCUPTIEVENTDOMAINENUMEVENTS(_cuDev, _cuptiDomain, _valueSize, _value)\
  VT_CUPTI_CALL(\
    cuptiEventDomainEnumEvents(_cuDev, _cuptiDomain, _valueSize, _value), \
    "cuptiEventDomainEnumEvents")

#endif

static uint32_t vt_cuptievt_rid_init;
static uint8_t vt_cuptievt_initialized = 0;
static uint8_t vt_cuptievt_finalized = 0;

/* VampirTrace counter group ID */
static uint32_t vt_cuptievt_cgid;

static vt_cupti_device_t *vtcuptievtCapList = NULL;

/***** --- Declaration of internally used functions --- *****/

/*
 * Enables the recording of CUPTI counters. Either thread if or pointer to the
 * host thread structure has to be given.
 * 
 * @param vtcuptiCtx pointer to the VampirTrace CUPTI context
 */
static void vt_cuptievt_start(vt_cupti_events_t *vtcuptiEvtCtx);

/*
 * Disables recording of CUPTI counters.
 * 
 * @param vtcuptiCtx pointer to the VampirTrace CUPTI context
 */
static void vt_cuptievt_stop(vt_cupti_events_t *vtcuptiEvtCtx);

/*
 * Initialize a VampirTrace CUPTI events context. This includes the creation/
 * memory allocation.
 * 
 * @param cuDev the CUDA device
 * 
 * @return pointer to the created VampirTrace CUPTI context
 */
static void vt_cuptievt_initCtx(vt_cupti_ctx_t *vtcuptiCtx);

/*
 * Get to current VampirTrace CUPTI context or create a new one, if CUDA context
 * is not registered yet.
 *
 * @param cuCtx the CUDA context to lookup the VampirTrace CUPTI context
 * @param ptid the VampirTrace thread id of current running thread
 *
 * @return the corresponding VampirTrace host thread structure.
 */
static vt_cupti_ctx_t* vt_cuptievt_getOrCreateCtx(CUcontext cuCtx, uint32_t ptid);

/*
 * Free the memory allocated for the given VampirTrace CUPTI events context.
 * 
 * @param vtcuptiEvtCtx pointer to the VampirTrace CUPTI events context
 */
static void vt_cuptievt_freeEventCtx(vt_cupti_events_t *vtcuptiEvtCtx);

/* 
 * De-initialize the VampirTrace CUPTI events context without destroying it.
 * 
 * @param vtcuptiCtx pointer to the VampirTrace CUPTI events context
 */
static void vt_cuptievt_finish(vt_cupti_events_t *vtcuptiEvtCtx);

/*
 * Create a VampirTrace CUPTI event group.
 * 
 * @param vtcuptiCtx pointer to the VampirTrace CUPTI context
 * 
 * @return the created VampirTrace CUPTI event group
 */
static vt_cupti_evtgrp_t* vt_cuptievt_createEvtGrp(vt_cupti_ctx_t *vtcuptiCtx);

/*
 * Setup a list of devices with different device capabilities and add the 
 * metrics, which are specified by the user.
 * 
 * @return a list of CUDA devices with different device capabilities
 */
static vt_cupti_device_t* vt_cuptievt_setupMetricList(void);

/*
 * Parse the environment variable for CUPTI metrics (including CUDA device
 * capabilities) and fill the capability metric list.
 *
 * @param capList points to the first element of the capability metric list
 */
static void vt_cupti_fillMetricList(vt_cupti_device_t *capList);

/*
 * Check whether the CUDA device capability is already listed.
 *
 * @param capList IN: list containing the CUDA device capabilities
 * @param major the major CUDA device capability
 * @param minor the minor CUDA device capability
 *
 * @return pointer to the list entry (NULL if not found)
 */
static vt_cupti_device_t* vt_cupti_checkMetricList(vt_cupti_device_t *capList,
                                                   int major, int minor);

/*
 * Print all available counters to stdout.
 *
 * @param capList list of CUDA devices with different capabilities
 */
static void vt_cupti_showAllCounters(vt_cupti_device_t *capList);

/*
 * Print all events for a given CUDA device and CUPTI event domain with name 
 * and ID.
 * 
 * @param cuDev the CUDA device
 * @param domainId the CUPTI event domain ID
 */
static void vt_cuptievt_enumEvents(CUdevice cuDev, CUpti_EventDomainID domainId);
/* ------ */

/* ----------------------- internally used functions ----------------------- */

static vt_cupti_evtgrp_t* vt_cuptievt_createEvtGrp(vt_cupti_ctx_t *vtcuptiCtx)
{
  CUptiResult cuptiErr = CUPTI_SUCCESS;
  vt_cupti_evtgrp_t *vtcuptiGrp = NULL;

  vtcuptiGrp = (vt_cupti_evtgrp_t*)malloc(sizeof(vt_cupti_evtgrp_t));
  vtcuptiGrp->evtNum = 0;
  vtcuptiGrp->enabled = 0;
  vtcuptiGrp->next = NULL;

  /* create initial CUPTI counter group */
  cuptiErr = cuptiEventGroupCreate(vtcuptiCtx->cuCtx, &(vtcuptiGrp->evtGrp), 0);
  VT_CUPTI_CALL(cuptiErr, "cuptiEventGroupCreate");

  {
    size_t evtNum = vtcuptiCtx->events->vtDevCap->evtNum;
    
    vtcuptiGrp->cuptiEvtIDs = 
            (CUpti_EventID *)malloc(evtNum*sizeof(CUpti_EventID));
    
    vtcuptiGrp->vtCIDs = 
            (uint32_t *)malloc(evtNum*sizeof(uint32_t));
  }

  return vtcuptiGrp;
}

static void vt_cupti_addEvtGrpsToCtx(vt_cupti_ctx_t *vtcuptiCtx)
{
    CUptiResult cuptiErr = CUPTI_SUCCESS;
    vt_cupti_evtgrp_t *vtcuptiGrp = vt_cuptievt_createEvtGrp(vtcuptiCtx);
    vt_cupti_events_t *vtcuptiEvents = vtcuptiCtx->events;
    vt_cupti_evtctr_t *vtcuptiEvt = vtcuptiEvents->vtDevCap->vtcuptiEvtList;

    /* try to add all events for current context/device */
    while(vtcuptiEvt != NULL && vtcuptiGrp->evtNum < vtcuptiEvents->vtDevCap->evtNum){
      cuptiErr = cuptiEventGroupAddEvent(vtcuptiGrp->evtGrp,
                                         vtcuptiEvt->cuptiEvtID);

      /* everything is fine */
      if(cuptiErr == CUPTI_SUCCESS){
        vtcuptiGrp->cuptiEvtIDs[vtcuptiGrp->evtNum] = vtcuptiEvt->cuptiEvtID;
        vtcuptiGrp->vtCIDs[vtcuptiGrp->evtNum] = vtcuptiEvt->vtCID;
        vtcuptiGrp->evtNum++;
      }else{
        /* we can at least try to put the event in another group */

        /* too many events in this group or
           event is in different domain or device limitation*/
        if(cuptiErr == CUPTI_ERROR_MAX_LIMIT_REACHED ||
           cuptiErr == CUPTI_ERROR_NOT_COMPATIBLE){

          vt_cntl_msg(2, "[CUPTI EVENTS] Create new event group for event %d",
                         vtcuptiEvt->cuptiEvtID);

          /* prepend last group to list, if it is not empty */
          if(vtcuptiGrp->evtNum > 0){
            vtcuptiGrp->next = vtcuptiEvents->vtGrpList;
            vtcuptiEvents->vtGrpList = vtcuptiGrp;
          }

          /* create new VampirTrace CUPTI event group */
          vtcuptiGrp = vt_cuptievt_createEvtGrp(vtcuptiCtx);

          /* try to add the same event to the just created group */
          continue;
        }

        PRINT_CUPTI_ERROR(cuptiErr, "cuptiEventGroupAddEvent");
      }

      vtcuptiEvt = vtcuptiEvt->next;
    }

    /* prepend last group to list, if it is not empty */
    if(vtcuptiGrp->evtNum > 0){
      vtcuptiGrp->next = vtcuptiEvents->vtGrpList;
      vtcuptiEvents->vtGrpList = vtcuptiGrp;
    }
}

/*
 * Initializes a CUPTI host thread and create the event group.
 *
 * @param vtcuptiCtx optionally given CUDA context
 */
static void vt_cuptievt_initCtx(vt_cupti_ctx_t *vtcuptiCtx)
{
  vt_cupti_events_t *vtcuptiEvtCtx = NULL;
  
  vt_cntl_msg(2, "[CUPTI Events] Initializing VampirTrace CUPTI events context");

  /* get a pointer to eventIDArray */
  {
    CUresult cuErr = CUDA_SUCCESS;
    int dev_major, dev_minor;
    vt_cupti_device_t *cuptiDev;
    
    /*CHECK_CU_ERROR(cuCtxGetDevice(&cuDev), "cuCtxGetDevice");*/

    cuErr = cuDeviceComputeCapability(&dev_major, &dev_minor, vtcuptiCtx->cuDev);
    CHECK_CU_ERROR(cuErr, "cuDeviceComputeCapability");

    /* check if device capability already listed */
    VT_CUPTI_LOCK();
      cuptiDev = vtcuptievtCapList;
    VT_CUPTI_UNLOCK();
    
    cuptiDev = vt_cupti_checkMetricList(cuptiDev, dev_major, dev_minor);
    if(cuptiDev){      
      /* allocate the VampirTrace CUPTI events context */
      vtcuptiEvtCtx = (vt_cupti_events_t *)malloc(sizeof(vt_cupti_events_t));
      if(vtcuptiEvtCtx == NULL)
        vt_error_msg("malloc(sizeof(vt_cupti_events_t)) failed!");
      
      vtcuptiEvtCtx->vtDevCap = cuptiDev;
      vtcuptiEvtCtx->vtGrpList = NULL;
      vtcuptiEvtCtx->counterData = NULL;
      vtcuptiEvtCtx->cuptiEvtIDs = NULL;
      
      vtcuptiCtx->events = vtcuptiEvtCtx;
    }else{
      return;
    }
  }

  /* create and add the VampirTrace CUPTI groups to the context */
  vt_cupti_addEvtGrpsToCtx(vtcuptiCtx);

  /* allocate memory for CUPTI counter reads */
  {
    size_t allocSize = vtcuptiEvtCtx->vtGrpList->evtNum;
    
    vtcuptiEvtCtx->counterData = 
            (uint64_t *)malloc(allocSize*sizeof(uint64_t));
    vtcuptiEvtCtx->cuptiEvtIDs = 
            (CUpti_EventID *)malloc(allocSize*sizeof(CUpti_EventID));
  }
}

static void vt_cuptievt_freeEventCtx(vt_cupti_events_t *vtcuptiEvtCtx)
{
  vt_cupti_evtgrp_t *vtcuptiGrp = vtcuptiEvtCtx->vtGrpList;

  while(vtcuptiGrp != NULL){
    free(vtcuptiGrp->cuptiEvtIDs);
    free(vtcuptiGrp->vtCIDs);
    
    vtcuptiGrp = vtcuptiGrp->next;
  }

  /* free memory for CUPTI counter reads */
  free(vtcuptiEvtCtx->counterData);
  free(vtcuptiEvtCtx->cuptiEvtIDs);
}

/*
 * Retrieve the VampirTrace CUPTI context from the CUDA context.
 * 
 * @param cuCtx the CUDA context
 * @param ptid the active VampirTrace thread id
 * 
 * @return VampirTrace CUPTI context
 */
static vt_cupti_ctx_t* vt_cuptievt_getOrCreateCtx(CUcontext cuCtx, uint32_t ptid)
{
  vt_cupti_ctx_t *vtcuptiCtx = NULL;
  
  uint64_t time;

  /* check, if the current VampirTrace thread is enabled for GPU counters */
  if((vt_gpu_prop[ptid] & VTGPU_NO_PC) == VTGPU_NO_PC)
    return NULL;
  
  time = vt_pform_wtime();
  vt_enter(ptid, &time, vt_cuptievt_rid_init);
  
  /* retrieve a global VampirTrace CUPTI context */
  vtcuptiCtx = vt_cupti_getCreateCtx(cuCtx);
  
  /* if the event context is not available yet, then create it */
  if(NULL == vtcuptiCtx->events){
    
    vt_cuptievt_initCtx(vtcuptiCtx);
    
    /* start gathering counter values, if context was successfully initialized */
    if(NULL != vtcuptiCtx->events){
      vt_cuptievt_start(vtcuptiCtx->events);
    }else{
      /* no performance counters for this thread available */
      vt_gpu_prop[ptid] |= VTGPU_NO_PC;
      vt_cntl_msg(2, "[CUPTI Events] Could not initialize!");
    }
    
  }
  
  time = vt_pform_wtime();
  vt_exit(ptid, &time);
  
  return vtcuptiCtx;
}

/*
 * Parse the environment variable for CUPTI metrics (including CUDA device
 * capabilities) and fill the capability metric list.
 *
 * @param capList points to the first element of the capability metric list
 */
static void vt_cupti_fillMetricList(vt_cupti_device_t *capList)
{
  char *metricString = vt_env_cupti_events();
  char *metric_sep = vt_env_metrics_sep();
  char *metric, *metric_cap;

  metric = strtok(metricString, metric_sep);

  while (metric != NULL){
    CUptiResult cuptiErr = CUPTI_SUCCESS;
    vt_cupti_device_t *cuptiDev = NULL;
    vt_cupti_evtctr_t *vtcuptiEvt = NULL;
    int metr_major = 0;
    int metr_minor = 0;

    /* try to get CUDA device capability parsed from metric */
    metr_major = atoi(metric);
    metric_cap = strchr(metric+1, '.');
    if(metric_cap){
      metr_minor = atoi(metric_cap+1);
      metric_cap = strchr(metric_cap+1, '_');
    }
    
    /* check whether device capability is given or not */
    if(metric_cap){
      metric = metric_cap + 1;

      vt_cntl_msg(2, "Metric '%s', %d.%d", metric, metr_major, metr_minor);

      cuptiDev = vt_cupti_checkMetricList(capList, metr_major, metr_minor);
      if(cuptiDev == NULL){
        metric = strtok(NULL, metric_sep);
        continue;
      }
      
      vtcuptiEvt = (vt_cupti_evtctr_t*)malloc(sizeof(vt_cupti_evtctr_t));
      cuptiErr = cuptiEventGetIdFromName(cuptiDev->cuDev, metric,
                                         &vtcuptiEvt->cuptiEvtID);
      if(cuptiErr != CUPTI_SUCCESS){
        if(!strncmp(metric, "help", 4)) vt_cupti_showAllCounters(capList);
        vt_warning("[CUPTI EVENTS] Skipping invalid event '%s' for device %d",
                   metric, cuptiDev->cuDev);
        metric = strtok(NULL, metric_sep);
        continue;
      }

      /* create VampirTrace counter ID */
#if (defined(VT_MT) || defined(VT_HYB))
      VTTHRD_LOCK_IDS();
#endif
      vtcuptiEvt->vtCID = vt_def_counter(VT_MASTER_THREAD, metric, "#",
            VT_CNTR_ABS | VT_CNTR_LAST | VT_CNTR_UNSIGNED, vt_cuptievt_cgid, 0);
#if (defined(VT_MT) || defined(VT_HYB))
      VTTHRD_UNLOCK_IDS();
#endif

      cuptiDev->evtNum++;
      vtcuptiEvt->next = cuptiDev->vtcuptiEvtList;
      cuptiDev->vtcuptiEvtList = vtcuptiEvt;
    }else{ 
      /* device capability is not given. Try to add metric to all devices */
      uint32_t cid_metric = VT_NO_ID;

      cuptiDev = capList;
      while(cuptiDev != NULL){
        vtcuptiEvt = (vt_cupti_evtctr_t*)malloc(sizeof(vt_cupti_evtctr_t));
        cuptiErr = cuptiEventGetIdFromName(cuptiDev->cuDev, metric,
                                           &vtcuptiEvt->cuptiEvtID);

        if(cuptiErr != CUPTI_SUCCESS){
          if(!strncmp(metric, "help", 4)) vt_cupti_showAllCounters(capList);
          vt_warning("[CUPTI EVENTS] Skipping invalid event '%s' for device %d",
                     metric, cuptiDev->cuDev);
        }else{
          /* create VampirTrace counter ID, if not yet done for other device */
          if(cid_metric == VT_NO_ID){
#if (defined(VT_MT) || defined(VT_HYB))
      VTTHRD_LOCK_IDS();
#endif
      cid_metric = vt_def_counter(VT_MASTER_THREAD, metric, "#", 
            VT_CNTR_ABS | VT_CNTR_LAST | VT_CNTR_UNSIGNED, vt_cuptievt_cgid, 0);
#if (defined(VT_MT) || defined(VT_HYB))
      VTTHRD_UNLOCK_IDS();
#endif
          }
          
          cuptiDev->evtNum++;
          vtcuptiEvt->vtCID = cid_metric;
          vtcuptiEvt->next = cuptiDev->vtcuptiEvtList;
          cuptiDev->vtcuptiEvtList = vtcuptiEvt;
        }

        cuptiDev = cuptiDev->next;
      }
    }

    metric = strtok(NULL, metric_sep);
  }
}

/*
 * Check whether the CUDA device capability is already listed.
 *
 * @param capList IN: list containing the CUDA device capabilities
 * @param major the major CUDA device capability
 * @param minor the minor CUDA device capability
 *
 * @return pointer to the list entry (NULL if not found)
 */
static vt_cupti_device_t* vt_cupti_checkMetricList(vt_cupti_device_t *capList,
                                                int major, int minor)
{
  vt_cupti_device_t *cuptiDev;

  /* check if device capability is already listed and return it if found */
  cuptiDev = capList;
  while(cuptiDev != NULL){
    if(cuptiDev->dev_major == major && cuptiDev->dev_minor == minor){
      return cuptiDev;
    }
    cuptiDev = cuptiDev->next;
  }

  return NULL;
}

/*
 * Setup a list of devices with different device capabilities and add the 
 * metrics, which are specified by the user.
 * 
 * @return a list of CUDA devices with different device capabilities
 */
static vt_cupti_device_t* vt_cuptievt_setupMetricList(void)
{
  CUresult err;
  int deviceCount, id;
  vt_cupti_device_t *capList = NULL;
  
  VT_SUSPEND_MALLOC_TRACING(VT_CURRENT_THREAD);
  
  /* CUDA initialization */
	CHECK_CU_ERROR(cuInit(0), "cuInit");
  
  /* How many GPGPU devices do we have? */
	err = cuDeviceGetCount( &deviceCount );
	CHECK_CU_ERROR(err, "cuDeviceGetCount");
	if(deviceCount == 0){
		vt_error_msg("[CUPTI EVENTS] There is no device supporting CUDA.");
	}

  /* create list with available compute capabilities */
  for(id = 0; id < deviceCount; id++){
    CUdevice cuDev;
    vt_cupti_device_t *cuptiDev;
    int dev_major, dev_minor;

    err = cuDeviceGet(&cuDev, id);
		CHECK_CU_ERROR(err, "cuDeviceGet");

    err = cuDeviceComputeCapability(&dev_major, &dev_minor, cuDev);
    CHECK_CU_ERROR(err, "cuDeviceComputeCapability");

    /* check if device capability already listed */
    cuptiDev = vt_cupti_checkMetricList(capList, dev_major, dev_minor);

    if(cuptiDev == NULL){
      /* allocate memory for device list entry */
      cuptiDev = (vt_cupti_device_t *)malloc(sizeof(vt_cupti_device_t));
      cuptiDev->dev_major = dev_major;
      cuptiDev->dev_minor = dev_minor;
      cuptiDev->cuDev = cuDev;
      cuptiDev->vtcuptiEvtList = NULL;
      cuptiDev->evtNum = 0;
      cuptiDev->next = NULL;

      /* prepend to list */
      cuptiDev->next = capList;
      capList = cuptiDev;
    }
  }

  vt_cupti_fillMetricList(capList);

  /* cleanup list: remove entries, which don't have metrics */
  {
    vt_cupti_device_t *curr = capList;
    vt_cupti_device_t *last = capList;

    while(curr != NULL){
      vt_cupti_device_t *freeDev = curr;
      curr = curr->next;

      if(freeDev->evtNum == 0){
        /* first element */
        if(freeDev == capList){
          capList = capList->next;
        }else{
          last->next = freeDev->next;
        }
        free(freeDev);
      }else last = freeDev;
    }
  }
  
  VT_RESUME_MALLOC_TRACING(VT_CURRENT_THREAD);

  return capList;
}

/*
 * Print all events for a given CUDA device and CUPTI event domain with name 
 * and ID.
 * 
 * @param cuDev the CUDA device
 * @param domainId the CUPTI event domain ID
 */
static void vt_cuptievt_enumEvents(CUdevice cuDev, CUpti_EventDomainID domainId)
{
  CUpti_EventID *eventId = NULL;
  uint32_t maxEvents = 0;
  uint32_t i = 0;
  size_t size = 0;
  uint8_t desc_on = 0;
  char *help = vt_env_cupti_events();
  
  if(!strncmp(&help[4], "_l", 2)) desc_on = 1;
  
  /*vt_cntl_msg(1, "############ %s", &help[5]);*/

  /* query num of events available in the domain */
  VTCUPTIEVENTDOMAINGETNUMEVENTS(cuDev,
                                 (CUpti_EventDomainID)domainId,
                                 &maxEvents);

  size = sizeof(CUpti_EventID) * maxEvents;
  eventId = (CUpti_EventID*)malloc(size);
  if(eventId == NULL) vt_error_msg("Failed to allocate memory for event ID");
  memset(eventId, 0, size);

  VTCUPTIEVENTDOMAINENUMEVENTS(cuDev,
                               (CUpti_EventDomainID)domainId,
                               &size,
                               eventId);

  /* query event info */
  {
    size_t NAME_SHORT = 32;
    size_t DESC_SHORT = 2048;
    char *eventname = (char*)malloc(NAME_SHORT*sizeof(char)); /* event name */
    char *shortdesc = NULL; /* short desc of the event */
    
    if(desc_on) shortdesc = malloc(DESC_SHORT*sizeof(char));
    
    for(i = 0; i < maxEvents; i++){
      NAME_SHORT = 32;
      DESC_SHORT = 2048;
      VTCUPTIEVENTGETATTRIBUTE(cuDev,
                               eventId[i],
                               CUPTI_EVENT_ATTR_NAME,
                               &NAME_SHORT,
                               eventname);

      if(desc_on){
        VTCUPTIEVENTGETATTRIBUTE(cuDev,
                                 eventId[i],
                                 CUPTI_EVENT_ATTR_LONG_DESCRIPTION,
                                 &DESC_SHORT,
                                 (uint8_t*)shortdesc);
      }

      vt_cntl_msg(1, "%d:%s", eventId[i], eventname);
      if(desc_on) vt_cntl_msg(1, "%s\n", shortdesc);
    }

    free(eventname);
    if(desc_on) free(shortdesc);
  }

  free(eventId);
}

/*
 * Print all available counters to stdout.
 *
 * @param capList list of CUDA devices with different capabilities
 */
static void vt_cupti_showAllCounters(vt_cupti_device_t *capList)
{
  CUptiResult cuptiErr = CUPTI_SUCCESS;
  CUpti_EventDomainID *domainId = NULL;
  uint32_t maxDomains = 0;
  uint32_t i;
  size_t size = 0;
  
  while(capList != NULL){
    CUdevice cuDev = capList->cuDev;
    vt_cntl_msg(1, "[CUPTI EVENTS] Available events for device %d (SM %d.%d):", 
                   cuDev, capList->dev_major, capList->dev_minor);
    vt_cntl_msg(1, "Id:Name");
    vt_cntl_msg(1, "Description\n"
         "-------------------------------------------------------------------");
    
    cuptiErr = cuptiDeviceGetNumEventDomains(cuDev, &maxDomains);
    VT_CUPTI_CALL(cuptiErr, "cuptiDeviceGetNumEventDomains");

    if(maxDomains == 0){
      vt_cntl_msg(1, "[CUPTI EVENTS] No domain is exposed by dev = %d\n", cuDev);
      return;
    }

    size = sizeof(CUpti_EventDomainID) * maxDomains;
    domainId = (CUpti_EventDomainID*)malloc(size);
    if(domainId == NULL){
      vt_cntl_msg(1, "[CUPTI EVENTS] Failed to allocate memory to domain ID");
      return;
    }
    memset(domainId, 0, size);

    cuptiErr = cuptiDeviceEnumEventDomains(cuDev, &size, domainId);
    VT_CUPTI_CALL(cuptiErr, "cuptiDeviceEnumEventDomains");

    /* enum domains */
    for(i = 0; i < maxDomains; i++) vt_cuptievt_enumEvents(cuDev, domainId[i]);

    vt_cntl_msg(1, "------------------------------------------------------");
    
    free(domainId);
    
    capList = capList->next;
  }
  
  /* as this function is in the call-path of the initialize functions
   * -> vt_cupti_setupMetrics 
   * -> vt_cupti_fillMetricList 
   * -> vt_cupti_showAllCounters
   */
  vt_cuptievt_initialized = 1;
  VT_CUPTI_UNLOCK();
  exit(0);
}


static void vt_cuptievt_start(vt_cupti_events_t *vtcuptiEvtCtx)
{
  CUptiResult cuptiErr = CUPTI_SUCCESS;
  vt_cupti_evtgrp_t *vtcuptiGrp = NULL;
  vt_cupti_evtgrp_t *lastGrp = NULL;

  if(vtcuptiEvtCtx == NULL) 
    return;

  /* start all groups */
  vtcuptiGrp = vtcuptiEvtCtx->vtGrpList;
  lastGrp = vtcuptiEvtCtx->vtGrpList;
  while(vtcuptiGrp != NULL){
    cuptiErr = cuptiEventGroupEnable(vtcuptiGrp->evtGrp);
    
    /* if the event group could not be enabled, remove it */
    if(cuptiErr != CUPTI_SUCCESS){
      size_t i;
      vt_cupti_evtgrp_t *freeGrp = vtcuptiGrp;
      size_t valueSize = 32;
      char name[32];

      vtcuptiGrp = vtcuptiGrp->next;

      /* give user information about the group, which cannot be enabled */
      for(i = 0; i < freeGrp->evtNum; i++){
        VTCUPTIEVENTGETATTRIBUTE(vtcuptiEvtCtx->vtDevCap->cuDev,
                                 *(freeGrp->cuptiEvtIDs)+i,
                                 CUPTI_EVENT_ATTR_NAME,
                                 &valueSize, (char*)name);
        vt_warning("[CUPTI Events] Event '%s' (%d) cannot be enabled",
                   name, *(freeGrp->cuptiEvtIDs)+i);
      }

      /* group is first element in linked list */
      if(vtcuptiEvtCtx->vtGrpList == freeGrp){
        vtcuptiEvtCtx->vtGrpList = vtcuptiEvtCtx->vtGrpList->next;
      }else{/* has to be at least the second group in linked list */
        lastGrp->next = freeGrp->next;
      }

      free(freeGrp);
      freeGrp = NULL;
    }else{
      vtcuptiGrp->enabled = 1;
      lastGrp= vtcuptiGrp;
      vtcuptiGrp = vtcuptiGrp->next;
    }
  }
  
}

/*
 * Stop CUPTI counter capturing by disabling the CUPTI event groups.
 * 
 * @param vtcuptiEvtCtx pointer to the VampirTrace CUPTI events context
 */
static void vt_cuptievt_stop(vt_cupti_events_t *vtcuptiEvtCtx)
{
  vt_cupti_evtgrp_t *vtcuptiGrp = NULL;
  
  /*vt_cntl_msg(1, "[CUPTI EVENTS] vt_cupti_stop() ... ");*/

  if(vtcuptiEvtCtx == NULL || vt_gpu_debug) 
    return;

  /* stop counter reading for all groups */
  vtcuptiGrp = vtcuptiEvtCtx->vtGrpList;
  while(vtcuptiGrp != NULL){
    if(vtcuptiGrp->enabled){
      CUptiResult cuptiErr = CUPTI_SUCCESS;
      
      cuptiErr = cuptiEventGroupDisable(vtcuptiGrp->evtGrp);
      VT_CUPTI_CALL(cuptiErr, "cuptiEventGroupDisable");

      vtcuptiGrp->enabled = 0;
    }

    vtcuptiGrp = vtcuptiGrp->next;
  }
}

/* 
 * De-initialize the VampirTrace CUPTI event context without destroying it.
 * 
 * @param vtcuptiEvtCtx pointer to the VampirTrace CUPTI events context
 */
static void vt_cuptievt_finish(vt_cupti_events_t *vtcuptiEvtCtx)
{
  CUptiResult cuptiErr = CUPTI_SUCCESS;

  if(vtcuptiEvtCtx == NULL || vt_gpu_debug) 
    return;

  /*uint64_t time = vt_pform_wtime();
  vt_cupti_resetCounter(vtcuptiCtx, 0, &time);*/

  /* stop CUPTI counter capturing */
  vt_cuptievt_stop(vtcuptiEvtCtx);

  /* destroy all CUPTI event groups, which have been created */
  {
    vt_cupti_evtgrp_t *vtcuptiGrp = vtcuptiEvtCtx->vtGrpList;
    
    while(vtcuptiGrp != NULL){
      cuptiErr = cuptiEventGroupRemoveAllEvents(vtcuptiGrp->evtGrp);
      VT_CUPTI_CALL(cuptiErr, "cuptiEventGroupRemoveAllEvents");

      cuptiErr = cuptiEventGroupDestroy(vtcuptiGrp->evtGrp);
      VT_CUPTI_CALL(cuptiErr, "cuptiEventGroupDestroy");

      vtcuptiGrp = vtcuptiGrp->next;
    }
  }
}


/* -------------START: Implementation of public functions ------------------ */
/* ------------------------------------------------------------------------- */

/*
 * Initialize VampirTrace IDs and registers the finalize function.
 * This may be done implicitly by vt_cupti_count().
 */
void vt_cupti_events_init()
{
  if(!vt_cuptievt_initialized){ /* fast check without lock */
    vt_cupti_init();
    VT_CUPTI_LOCK();
    if(!vt_cuptievt_initialized){
      vt_cntl_msg(2, "[CUPTI Events] Initializing ... ");

      /* create VampirTrace counter group ID only once */
  #if (defined(VT_MT) || defined(VT_HYB))
      VTTHRD_LOCK_IDS();
  #endif
      vt_cuptievt_rid_init = vt_def_region(VT_MASTER_THREAD, "vtcuptiHostThreadInit",
                      VT_NO_ID, VT_NO_LNO, VT_NO_LNO, "VT_CUPTI", VT_FUNCTION);

      vt_cuptievt_cgid = vt_def_counter_group(VT_MASTER_THREAD, "CUPTI");
  #if (defined(VT_MT) || defined(VT_HYB))
      VTTHRD_UNLOCK_IDS();
  #endif

      vtcuptievtCapList = vt_cuptievt_setupMetricList();

      /* register the finalize function of VampirTrace CUPTI to be called before
       * the program exits */
      atexit(vt_cupti_events_finalize);

      vt_cuptievt_initialized = 1;
      VT_CUPTI_UNLOCK();
    }
  }
}

/*
 * Finalizes the VampirTrace CUPTI events interface.
 */
void vt_cupti_events_finalize()
{
  if(!vt_cuptievt_finalized && vt_cuptievt_initialized){ /* fast check without lock */
    VT_CUPTI_LOCK();
    if(!vt_cuptievt_finalized && vt_cuptievt_initialized){
      vt_cupti_ctx_t *vtcuptiCtxList =  vt_cupti_ctxList;

      vt_cntl_msg(2, "[CUPTI Events] Finalizing ...");

      /* free VampirTrace CUPTI events context structures */
      while(vtcuptiCtxList != NULL){
        vt_cuptievt_finish(vtcuptiCtxList->events);

        vtcuptiCtxList = vtcuptiCtxList->next;

        free(vtcuptiCtxList->events);
        vtcuptiCtxList->events = NULL;
      }

      /* free capability metric list */
      while(vtcuptievtCapList != NULL){
        vt_cupti_device_t *tmp = vtcuptievtCapList;
        vtcuptievtCapList = vtcuptievtCapList->next;
        
        /* free VampirTrace CUPTI events */
        while(tmp->vtcuptiEvtList != NULL){
          vt_cupti_evtctr_t *tmpEvt = tmp->vtcuptiEvtList;
          tmp->vtcuptiEvtList = tmp->vtcuptiEvtList->next;
          free(tmpEvt);
          tmpEvt = NULL;
        }

        free(tmp);
        tmp = NULL;
      }

      vt_cuptievt_finalized = 1;
      VT_CUPTI_UNLOCK();
    }
  }
}

/*
 * Retrieves the VampirTrace CUPTI context for the CUDA context associated with
 * the calling host thread. Initiates context creation, if it is not available 
 * yet.
 *
 * @param ptid the VampirTrace thread id of the calling host thread
 * 
 * @return VampirTrace CUPTI context
 */
vt_cupti_ctx_t* vt_cuptievt_getOrCreateCurrentCtx(uint32_t ptid)
{
  CUcontext cuCtx = NULL;
  
  if(!vt_cuptievt_initialized) vt_cupti_events_init();

# if (defined(CUDA_VERSION) && (CUDA_VERSION < 4000))
  CHECK_CU_ERROR(cuCtxPopCurrent(&cuCtx), "cuCtxPopCurrent");
  CHECK_CU_ERROR(cuCtxPushCurrent(cuCtx), "cuCtxPushCurrent");
# else
  CHECK_CU_ERROR(cuCtxGetCurrent(&cuCtx), "cuCtxGetCurrent");
# endif
  
  if(cuCtx == NULL){
    vt_cntl_msg(2, "[CUPTI EVENTS] No context is bound to the calling CPU thread!");
    return NULL;
  }
  
  return vt_cuptievt_getOrCreateCtx(cuCtx, ptid);
}

/*
 * Request the CUTPI counter values and write it to the given VampirTrace
 * stream with the given timestamps.
 *
 * @param vtcuptiEvtCtx pointer to the VampirTrace CUPTI events context
 * @param strmid the stream id for the counter values
 * @param time the VampirTrace timestamps
 */
void vt_cuptievt_writeCounter(vt_cupti_events_t *vtcuptiEvtCtx, uint32_t strmid,
                              uint64_t *time)
{
  CUptiResult cuptiErr = CUPTI_SUCCESS;
  vt_cupti_evtgrp_t *vtcuptiGrp = NULL;

  size_t bufferSizeBytes;
  size_t arraySizeBytes;
  size_t numCountersRead;

  if(vtcuptiEvtCtx == NULL){
    VT_CHECK_THREAD;
    vtcuptiEvtCtx = vt_cuptievt_getOrCreateCurrentCtx(VT_MY_THREAD)->events;
    if(vtcuptiEvtCtx == NULL) return;
  }

  vtcuptiGrp = vtcuptiEvtCtx->vtGrpList;
  while(vtcuptiGrp != NULL){
    /* read events only, if the event group is enabled */
    if(vtcuptiGrp->enabled){

      bufferSizeBytes = vtcuptiGrp->evtNum * sizeof(uint64_t);
      arraySizeBytes = vtcuptiGrp->evtNum * sizeof(CUpti_EventID);

      /* read events */
      cuptiErr = cuptiEventGroupReadAllEvents(vtcuptiGrp->evtGrp,
                                              CUPTI_EVENT_READ_FLAG_NONE,
                                              &bufferSizeBytes, vtcuptiEvtCtx->counterData,
                                              &arraySizeBytes, vtcuptiEvtCtx->cuptiEvtIDs,
                                              &numCountersRead);
      VT_CUPTI_CALL(cuptiErr, "cuptiEventGroupReadAllEvents");
      
      if(vtcuptiGrp->evtNum != numCountersRead){
        vt_error_msg("[CUPTI EVENTS] %d counter reads, %d metrics specified in "
                   "VT_CUPTI_METRICS!", numCountersRead, vtcuptiGrp->evtNum);
      }

      /* For all events of the event group: map added event IDs to just read event
       * IDs, as the order may not be the same. For small numbers of counter reads
       * this simple mapping should be fast enough.
       */
      {
        size_t j;

        for(j = 0; j < numCountersRead; j++){
          size_t i;
          for(i = 0; i < vtcuptiGrp->evtNum; i++){
            if(vtcuptiEvtCtx->cuptiEvtIDs[j] == *(vtcuptiGrp->cuptiEvtIDs+i)){
              /* write the counter value as VampirTrace counter */
              vt_count(strmid, time, *(vtcuptiGrp->vtCIDs+i), vtcuptiEvtCtx->counterData[i]);
            }
          }
        }
      }

    }

    vtcuptiGrp = vtcuptiGrp->next;
  }
  
}

/*
 * Reset the VampirTrace counter values (to zero) for active CUPTI counters.
 *
 * @param vtcuptiEvtCtx pointer to the VampirTrace CUPTI events context
 * @param strmid the stream id for the counter values
 * @param time the VampirTrace timestamps
 */
void vt_cuptievt_resetCounter(vt_cupti_events_t *vtcuptiEvtCtx, uint32_t strmid,
                              uint64_t *time)
{
  size_t i;
  vt_cupti_evtgrp_t *vtcuptiGrp = NULL;

  /* create a VampirTrace CUPTI events context, if it is not available */
  if(vtcuptiEvtCtx == NULL){
    VT_CHECK_THREAD;
    vtcuptiEvtCtx = vt_cuptievt_getOrCreateCurrentCtx(VT_MY_THREAD)->events;
    if(vtcuptiEvtCtx == NULL) return;
  }

  if(vtcuptiEvtCtx==NULL) vt_warning("vtcuptiEvtCtx==NULL");
  if(vtcuptiEvtCtx->vtGrpList==NULL) vt_warning("vtGrpList==NULL");
  vtcuptiGrp = vtcuptiEvtCtx->vtGrpList;
  while(vtcuptiGrp != NULL){
    for(i = 0; i < vtcuptiGrp->evtNum; i++){
      vt_count(strmid, time, *(vtcuptiGrp->vtCIDs+i), 0);
    }

    /* reset counter values of this group */
    VT_CUPTI_CALL(cuptiEventGroupResetAllEvents(vtcuptiGrp->evtGrp),
                      "cuptiEventGroupResetAllEvents");
    
    vtcuptiGrp = vtcuptiGrp->next;
  }
}

/*
 * Finalizes CUPTI device.
 * 
 * @param ptid VampirTrace process/thread id
 * @param cleanExit 1 to cleanup CUPTI event group, otherwise 0
 */
void vt_cuptievt_finalize_device(uint32_t ptid, uint8_t cleanExit){
  CUptiResult cuptiErr = CUPTI_SUCCESS;
  vt_cupti_ctx_t *vtcuptiCtx = NULL;

  vt_cntl_msg(2, "[CUPTI EVENTS] Finalize device ... ");

  {
    CUcontext cuCtx;
    
#if (defined(CUDA_VERSION) && (CUDA_VERSION < 4000))
    CHECK_CU_ERROR(cuCtxPopCurrent(&cuCtx), "cuCtxPopCurrent");
    CHECK_CU_ERROR(cuCtxPushCurrent(cuCtx), "cuCtxPushCurrent");
#else
    CHECK_CU_ERROR(cuCtxGetCurrent(&cuCtx), "cuCtxGetCurrent");
#endif

    vtcuptiCtx = vt_cupti_removeCtx(&cuCtx);
    if(vtcuptiCtx == NULL) return;
  }

  if(cleanExit && vt_gpu_debug != 0){
    /*uint64_t time = vt_pform_wtime();

    vt_cupti_resetCounter(vtcuptiCtx, 0, &time);*/

    /* stop CUPTI counter capturing */
    vt_cuptievt_stop(vtcuptiCtx->events);

    /* destroy all CUPTI event groups, which have been created */
    {
      vt_cupti_evtgrp_t *vtcuptiGrp = vtcuptiCtx->events->vtGrpList;

      while(vtcuptiGrp != NULL){
        cuptiErr = cuptiEventGroupRemoveAllEvents(vtcuptiGrp->evtGrp);
        VT_CUPTI_CALL(cuptiErr, "cuptiEventGroupRemoveAllEvents");

        cuptiErr = cuptiEventGroupDestroy(vtcuptiGrp->evtGrp);
        VT_CUPTI_CALL(cuptiErr, "cuptiEventGroupDestroy");

        vtcuptiGrp = vtcuptiGrp->next;
      }
    }
  }

  /* free VampirTrace CUPTI event context */
  vt_cuptievt_freeEventCtx(vtcuptiCtx->events);
}

/* ------------------------------------------------------------------------- */
/* -------------- END: Implementation of public functions ------------------ */