File: cuda_occupancy.h

package info (click to toggle)
nvidia-cuda-toolkit 12.4.1-3
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 18,505,836 kB
  • sloc: ansic: 203,477; cpp: 64,769; python: 34,699; javascript: 22,006; xml: 13,410; makefile: 3,085; sh: 2,343; perl: 352
file content (1958 lines) | stat: -rw-r--r-- 67,179 bytes parent folder | download | duplicates (9)
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
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
/*
 * Copyright 1993-2017 NVIDIA Corporation.  All rights reserved.
 *
 * NOTICE TO LICENSEE:
 *
 * This source code and/or documentation ("Licensed Deliverables") are
 * subject to NVIDIA intellectual property rights under U.S. and
 * international Copyright laws.
 *
 * These Licensed Deliverables contained herein is PROPRIETARY and
 * CONFIDENTIAL to NVIDIA and is being provided under the terms and
 * conditions of a form of NVIDIA software license agreement by and
 * between NVIDIA and Licensee ("License Agreement") or electronically
 * accepted by Licensee.  Notwithstanding any terms or conditions to
 * the contrary in the License Agreement, reproduction or disclosure
 * of the Licensed Deliverables to any third party without the express
 * written consent of NVIDIA is prohibited.
 *
 * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
 * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
 * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE.  IT IS
 * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
 * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
 * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
 * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
 * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
 * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
 * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
 * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
 * OF THESE LICENSED DELIVERABLES.
 *
 * U.S. Government End Users.  These Licensed Deliverables are a
 * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
 * 1995), consisting of "commercial computer software" and "commercial
 * computer software documentation" as such terms are used in 48
 * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government
 * only as a commercial end item.  Consistent with 48 C.F.R.12.212 and
 * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
 * U.S. Government End Users acquire the Licensed Deliverables with
 * only those rights set forth herein.
 *
 * Any use of the Licensed Deliverables in individual and commercial
 * software must include, in the user documentation and internal
 * comments to the code, the above Disclaimer and U.S. Government End
 * Users Notice.
 */

/**
 * CUDA Occupancy Calculator
 *
 * NAME
 *
 *   cudaOccMaxActiveBlocksPerMultiprocessor,
 *   cudaOccMaxPotentialOccupancyBlockSize,
 *   cudaOccMaxPotentialOccupancyBlockSizeVariableSMem
 *   cudaOccAvailableDynamicSMemPerBlock
 *
 * DESCRIPTION
 *
 *   The CUDA occupancy calculator provides a standalone, programmatical
 *   interface to compute the occupancy of a function on a device. It can also
 *   provide occupancy-oriented launch configuration suggestions.
 *
 *   The function and device are defined by the user through
 *   cudaOccFuncAttributes, cudaOccDeviceProp, and cudaOccDeviceState
 *   structures. All APIs require all 3 of them.
 *
 *   See the structure definition for more details about the device / function
 *   descriptors.
 *
 *   See each API's prototype for API usage.
 *
 * COMPATIBILITY
 *
 *   The occupancy calculator will be updated on each major CUDA toolkit
 *   release. It does not provide forward compatibility, i.e. new hardwares
 *   released after this implementation's release will not be supported.
 *
 * NOTE
 *
 *   If there is access to CUDA runtime, and the sole intent is to calculate
 *   occupancy related values on one of the accessible CUDA devices, using CUDA
 *   runtime's occupancy calculation APIs is recommended.
 *
 */

#ifndef __cuda_occupancy_h__
#define __cuda_occupancy_h__

#include <stddef.h>
#include <limits.h>
#include <string.h>


// __OCC_INLINE will be undefined at the end of this header
//
#ifdef __CUDACC__
#define __OCC_INLINE inline __host__ __device__
#elif defined _MSC_VER
#define __OCC_INLINE __inline
#else // GNUCC assumed
#define __OCC_INLINE inline
#endif

enum cudaOccError_enum {
    CUDA_OCC_SUCCESS              = 0,  // no error encountered
    CUDA_OCC_ERROR_INVALID_INPUT  = 1,  // input parameter is invalid
    CUDA_OCC_ERROR_UNKNOWN_DEVICE = 2,  // requested device is not supported in
                                        // current implementation or device is
                                        // invalid
};
typedef enum cudaOccError_enum       cudaOccError;

typedef struct cudaOccResult         cudaOccResult;
typedef struct cudaOccDeviceProp     cudaOccDeviceProp;
typedef struct cudaOccFuncAttributes cudaOccFuncAttributes;
typedef struct cudaOccDeviceState    cudaOccDeviceState;

/**
 * The CUDA occupancy calculator computes the occupancy of the function
 * described by attributes with the given block size (blockSize), static device
 * properties (properties), dynamic device states (states) and per-block dynamic
 * shared memory allocation (dynamicSMemSize) in bytes, and output it through
 * result along with other useful information. The occupancy is computed in
 * terms of the maximum number of active blocks per multiprocessor. The user can
 * then convert it to other metrics, such as number of active warps.
 *
 * RETURN VALUE
 *
 * The occupancy and related information is returned through result.
 *
 * If result->activeBlocksPerMultiprocessor is 0, then the given parameter
 * combination cannot run on the device.
 *
 * ERRORS
 *
 *     CUDA_OCC_ERROR_INVALID_INPUT   input parameter is invalid.
 *     CUDA_OCC_ERROR_UNKNOWN_DEVICE  requested device is not supported in
 *     current implementation or device is invalid
 */
static __OCC_INLINE
cudaOccError cudaOccMaxActiveBlocksPerMultiprocessor(
    cudaOccResult               *result,           // out
    const cudaOccDeviceProp     *properties,       // in
    const cudaOccFuncAttributes *attributes,       // in
    const cudaOccDeviceState    *state,            // in
    int                          blockSize,        // in
    size_t                       dynamicSmemSize); // in

/**
 * The CUDA launch configurator C API suggests a grid / block size pair (in
 * minGridSize and blockSize) that achieves the best potential occupancy
 * (i.e. maximum number of active warps with the smallest number of blocks) for
 * the given function described by attributes, on a device described by
 * properties with settings in state.
 *
 * If per-block dynamic shared memory allocation is not needed, the user should
 * leave both blockSizeToDynamicSMemSize and dynamicSMemSize as 0.
 *
 * If per-block dynamic shared memory allocation is needed, then if the dynamic
 * shared memory size is constant regardless of block size, the size should be
 * passed through dynamicSMemSize, and blockSizeToDynamicSMemSize should be
 * NULL.
 *
 * Otherwise, if the per-block dynamic shared memory size varies with different
 * block sizes, the user needs to provide a pointer to an unary function through
 * blockSizeToDynamicSMemSize that computes the dynamic shared memory needed by
 * a block of the function for any given block size. dynamicSMemSize is
 * ignored. An example signature is:
 *
 *    // Take block size, returns dynamic shared memory needed
 *    size_t blockToSmem(int blockSize);
 *
 * RETURN VALUE
 *
 * The suggested block size and the minimum number of blocks needed to achieve
 * the maximum occupancy are returned through blockSize and minGridSize.
 *
 * If *blockSize is 0, then the given combination cannot run on the device.
 *
 * ERRORS
 *
 *     CUDA_OCC_ERROR_INVALID_INPUT   input parameter is invalid.
 *     CUDA_OCC_ERROR_UNKNOWN_DEVICE  requested device is not supported in
 *     current implementation or device is invalid
 *
 */
static __OCC_INLINE
cudaOccError cudaOccMaxPotentialOccupancyBlockSize(
    int                         *minGridSize,      // out
    int                         *blockSize,        // out
    const cudaOccDeviceProp     *properties,       // in
    const cudaOccFuncAttributes *attributes,       // in
    const cudaOccDeviceState    *state,            // in
    size_t                     (*blockSizeToDynamicSMemSize)(int), // in
    size_t                       dynamicSMemSize); // in

/**
 * The CUDA launch configurator C++ API suggests a grid / block size pair (in
 * minGridSize and blockSize) that achieves the best potential occupancy
 * (i.e. the maximum number of active warps with the smallest number of blocks)
 * for the given function described by attributes, on a device described by
 * properties with settings in state.
 *
 * If per-block dynamic shared memory allocation is 0 or constant regardless of
 * block size, the user can use cudaOccMaxPotentialOccupancyBlockSize to
 * configure the launch. A constant dynamic shared memory allocation size in
 * bytes can be passed through dynamicSMemSize.
 *
 * Otherwise, if the per-block dynamic shared memory size varies with different
 * block sizes, the user needs to use
 * cudaOccMaxPotentialOccupancyBlockSizeVariableSmem instead, and provide a
 * functor / pointer to an unary function (blockSizeToDynamicSMemSize) that
 * computes the dynamic shared memory needed by func for any given block
 * size. An example signature is:
 *
 *  // Take block size, returns per-block dynamic shared memory needed
 *  size_t blockToSmem(int blockSize);
 *
 * RETURN VALUE
 *
 * The suggested block size and the minimum number of blocks needed to achieve
 * the maximum occupancy are returned through blockSize and minGridSize.
 *
 * If *blockSize is 0, then the given combination cannot run on the device.
 *
 * ERRORS
 *
 *     CUDA_OCC_ERROR_INVALID_INPUT   input parameter is invalid.
 *     CUDA_OCC_ERROR_UNKNOWN_DEVICE  requested device is not supported in
 *     current implementation or device is invalid
 *
 */

#if defined(__cplusplus)
namespace {

__OCC_INLINE
cudaOccError cudaOccMaxPotentialOccupancyBlockSize(
    int                         *minGridSize,          // out
    int                         *blockSize,            // out
    const cudaOccDeviceProp     *properties,           // in
    const cudaOccFuncAttributes *attributes,           // in
    const cudaOccDeviceState    *state,                // in
    size_t                       dynamicSMemSize = 0); // in

template <typename UnaryFunction>
__OCC_INLINE
cudaOccError cudaOccMaxPotentialOccupancyBlockSizeVariableSMem(
    int                         *minGridSize,          // out
    int                         *blockSize,            // out
    const cudaOccDeviceProp     *properties,           // in
    const cudaOccFuncAttributes *attributes,           // in
    const cudaOccDeviceState    *state,                // in
    UnaryFunction                blockSizeToDynamicSMemSize); // in

} // namespace anonymous
#endif // defined(__cplusplus)

/**
 *
 * The CUDA dynamic shared memory calculator computes the maximum size of 
 * per-block dynamic shared memory if we want to place numBlocks blocks
 * on an SM.
 *
 * RETURN VALUE
 *
 * Returns in *dynamicSmemSize the maximum size of dynamic shared memory to allow 
 * numBlocks blocks per SM.
 *
 * ERRORS
 *
 *     CUDA_OCC_ERROR_INVALID_INPUT   input parameter is invalid.
 *     CUDA_OCC_ERROR_UNKNOWN_DEVICE  requested device is not supported in
 *     current implementation or device is invalid
 *
 */
static __OCC_INLINE
cudaOccError cudaOccAvailableDynamicSMemPerBlock(
    size_t                      *dynamicSmemSize,
    const cudaOccDeviceProp     *properties,
    const cudaOccFuncAttributes *attributes,
    const cudaOccDeviceState    *state,
    int                         numBlocks,
    int                         blockSize);

/**
 * Data structures
 *
 * These structures are subject to change for future architecture and CUDA
 * releases. C users should initialize the structure as {0}.
 *
 */

/**
 * Device descriptor
 *
 * This structure describes a device.
 */
struct cudaOccDeviceProp {
    int    computeMajor;                // Compute capability major version
    int    computeMinor;                // Compute capability minor
                                        // version. None supported minor version
                                        // may cause error
    int    maxThreadsPerBlock;          // Maximum number of threads per block
    int    maxThreadsPerMultiprocessor; // Maximum number of threads per SM
                                        // i.e. (Max. number of warps) x (warp
                                        // size)
    int    regsPerBlock;                // Maximum number of registers per block
    int    regsPerMultiprocessor;       // Maximum number of registers per SM
    int    warpSize;                    // Warp size
    size_t sharedMemPerBlock;           // Maximum shared memory size per block
    size_t sharedMemPerMultiprocessor;  // Maximum shared memory size per SM
    int    numSms;                      // Number of SMs available
    size_t sharedMemPerBlockOptin;      // Maximum optin shared memory size per block
    size_t reservedSharedMemPerBlock;   // Shared memory per block reserved by driver

#ifdef __cplusplus
    // This structure can be converted from a cudaDeviceProp structure for users
    // that use this header in their CUDA applications.
    //
    // If the application have access to the CUDA Runtime API, the application
    // can obtain the device properties of a CUDA device through
    // cudaGetDeviceProperties, and initialize a cudaOccDeviceProp with the
    // cudaDeviceProp structure.
    //
    // Example:
    /*
     {
         cudaDeviceProp prop;

         cudaGetDeviceProperties(&prop, ...);

         cudaOccDeviceProp occProp = prop;

         ...

         cudaOccMaxPotentialOccupancyBlockSize(..., &occProp, ...);
     }
     */
    //
    template<typename DeviceProp>
    __OCC_INLINE
    cudaOccDeviceProp(const DeviceProp &props)
    :   computeMajor                (props.major),
        computeMinor                (props.minor),
        maxThreadsPerBlock          (props.maxThreadsPerBlock),
        maxThreadsPerMultiprocessor (props.maxThreadsPerMultiProcessor),
        regsPerBlock                (props.regsPerBlock),
        regsPerMultiprocessor       (props.regsPerMultiprocessor),
        warpSize                    (props.warpSize),
        sharedMemPerBlock           (props.sharedMemPerBlock),
        sharedMemPerMultiprocessor  (props.sharedMemPerMultiprocessor),
        numSms                      (props.multiProcessorCount),
        sharedMemPerBlockOptin      (props.sharedMemPerBlockOptin),
        reservedSharedMemPerBlock   (props.reservedSharedMemPerBlock)
    {}

    __OCC_INLINE
    cudaOccDeviceProp()
    :   computeMajor                (0),
        computeMinor                (0),
        maxThreadsPerBlock          (0),
        maxThreadsPerMultiprocessor (0),
        regsPerBlock                (0),
        regsPerMultiprocessor       (0),
        warpSize                    (0),
        sharedMemPerBlock           (0),
        sharedMemPerMultiprocessor  (0),
        numSms                      (0),
        sharedMemPerBlockOptin      (0),
        reservedSharedMemPerBlock   (0)
    {}
#endif // __cplusplus
};

/**
 * Partitioned global caching option
 */
typedef enum cudaOccPartitionedGCConfig_enum {
    PARTITIONED_GC_OFF,        // Disable partitioned global caching
    PARTITIONED_GC_ON,         // Prefer partitioned global caching
    PARTITIONED_GC_ON_STRICT   // Force partitioned global caching
} cudaOccPartitionedGCConfig;

/**
 * Per function opt in maximum dynamic shared memory limit
 */
typedef enum cudaOccFuncShmemConfig_enum {
    FUNC_SHMEM_LIMIT_DEFAULT,   // Default shmem limit
    FUNC_SHMEM_LIMIT_OPTIN,     // Use the optin shmem limit
} cudaOccFuncShmemConfig;

/**
 * Function descriptor
 *
 * This structure describes a CUDA function.
 */
struct cudaOccFuncAttributes {
    int maxThreadsPerBlock; // Maximum block size the function can work with. If
                            // unlimited, use INT_MAX or any value greater than
                            // or equal to maxThreadsPerBlock of the device
    int numRegs;            // Number of registers used. When the function is
                            // launched on device, the register count may change
                            // due to internal tools requirements.
    size_t sharedSizeBytes; // Number of static shared memory used

    cudaOccPartitionedGCConfig partitionedGCConfig; 
                            // Partitioned global caching is required to enable
                            // caching on certain chips, such as sm_52
                            // devices. Partitioned global caching can be
                            // automatically disabled if the occupancy
                            // requirement of the launch cannot support caching.
                            //
                            // To override this behavior with caching on and
                            // calculate occupancy strictly according to the
                            // preference, set partitionedGCConfig to
                            // PARTITIONED_GC_ON_STRICT. This is especially
                            // useful for experimenting and finding launch
                            // configurations (MaxPotentialOccupancyBlockSize)
                            // that allow global caching to take effect.
                            //
                            // This flag only affects the occupancy calculation.

    cudaOccFuncShmemConfig shmemLimitConfig;
                            // Certain chips like sm_70 allow a user to opt into
                            // a higher per block limit of dynamic shared memory
                            // This optin is performed on a per function basis
                            // using the cuFuncSetAttribute function

    size_t maxDynamicSharedSizeBytes;
                            // User set limit on maximum dynamic shared memory
                            // usable by the kernel
                            // This limit is set using the cuFuncSetAttribute
                            // function.

    int numBlockBarriers;   // Number of block barriers used (default to 1)
#ifdef __cplusplus
    // This structure can be converted from a cudaFuncAttributes structure for
    // users that use this header in their CUDA applications.
    //
    // If the application have access to the CUDA Runtime API, the application
    // can obtain the function attributes of a CUDA kernel function through
    // cudaFuncGetAttributes, and initialize a cudaOccFuncAttributes with the
    // cudaFuncAttributes structure.
    //
    // Example:
    /*
      __global__ void foo() {...}

      ...

      {
          cudaFuncAttributes attr;

          cudaFuncGetAttributes(&attr, foo);

          cudaOccFuncAttributes occAttr = attr;

          ...

          cudaOccMaxPotentialOccupancyBlockSize(..., &occAttr, ...);
      }
     */
    //
    template<typename FuncAttributes>
    __OCC_INLINE
    cudaOccFuncAttributes(const FuncAttributes &attr)
    :   maxThreadsPerBlock  (attr.maxThreadsPerBlock),
        numRegs             (attr.numRegs),
        sharedSizeBytes     (attr.sharedSizeBytes),
        partitionedGCConfig (PARTITIONED_GC_OFF),
        shmemLimitConfig    (FUNC_SHMEM_LIMIT_OPTIN),
        maxDynamicSharedSizeBytes (attr.maxDynamicSharedSizeBytes),
        numBlockBarriers    (1)
    {}

    __OCC_INLINE
    cudaOccFuncAttributes()
    :   maxThreadsPerBlock  (0),
        numRegs             (0),
        sharedSizeBytes     (0),
        partitionedGCConfig (PARTITIONED_GC_OFF),
        shmemLimitConfig    (FUNC_SHMEM_LIMIT_DEFAULT),
        maxDynamicSharedSizeBytes (0),
        numBlockBarriers    (0)
    {}
#endif
};

typedef enum cudaOccCacheConfig_enum {
    CACHE_PREFER_NONE   = 0x00, // no preference for shared memory or L1 (default)
    CACHE_PREFER_SHARED = 0x01, // prefer larger shared memory and smaller L1 cache
    CACHE_PREFER_L1     = 0x02, // prefer larger L1 cache and smaller shared memory
    CACHE_PREFER_EQUAL  = 0x03  // prefer equal sized L1 cache and shared memory
} cudaOccCacheConfig;

typedef enum cudaOccCarveoutConfig_enum {
    SHAREDMEM_CARVEOUT_DEFAULT       = -1,  // no preference for shared memory or L1 (default)
    SHAREDMEM_CARVEOUT_MAX_SHARED    = 100, // prefer maximum available shared memory, minimum L1 cache
    SHAREDMEM_CARVEOUT_MAX_L1        = 0,    // prefer maximum available L1 cache, minimum shared memory
    SHAREDMEM_CARVEOUT_HALF          = 50   // prefer half of maximum available shared memory, with the rest as L1 cache
} cudaOccCarveoutConfig;

/**
 * Device state descriptor
 *
 * This structure describes device settings that affect occupancy calculation.
 */
struct cudaOccDeviceState
{
    // Cache / shared memory split preference. Deprecated on Volta 
    cudaOccCacheConfig cacheConfig; 
    // Shared memory / L1 split preference. Supported on only Volta
    int carveoutConfig;

#ifdef __cplusplus
    __OCC_INLINE
    cudaOccDeviceState()
    :   cacheConfig     (CACHE_PREFER_NONE),
        carveoutConfig  (SHAREDMEM_CARVEOUT_DEFAULT)
    {}
#endif
};

typedef enum cudaOccLimitingFactor_enum {
                                    // Occupancy limited due to:
    OCC_LIMIT_WARPS         = 0x01, // - warps available
    OCC_LIMIT_REGISTERS     = 0x02, // - registers available
    OCC_LIMIT_SHARED_MEMORY = 0x04, // - shared memory available
    OCC_LIMIT_BLOCKS        = 0x08, // - blocks available
    OCC_LIMIT_BARRIERS      = 0x10  // - barrier available
} cudaOccLimitingFactor;

/**
 * Occupancy output
 *
 * This structure contains occupancy calculator's output.
 */
struct cudaOccResult {
    int activeBlocksPerMultiprocessor; // Occupancy
    unsigned int limitingFactors;      // Factors that limited occupancy. A bit
                                       // field that counts the limiting
                                       // factors, see cudaOccLimitingFactor
    int blockLimitRegs;                // Occupancy due to register
                                       // usage, INT_MAX if the kernel does not
                                       // use any register.
    int blockLimitSharedMem;           // Occupancy due to shared memory
                                       // usage, INT_MAX if the kernel does not
                                       // use shared memory.
    int blockLimitWarps;               // Occupancy due to block size limit
    int blockLimitBlocks;              // Occupancy due to maximum number of blocks
                                       // managable per SM
    int blockLimitBarriers;            // Occupancy due to block barrier usage
    int allocatedRegistersPerBlock;    // Actual number of registers allocated per
                                       // block
    size_t allocatedSharedMemPerBlock; // Actual size of shared memory allocated
                                       // per block
    cudaOccPartitionedGCConfig partitionedGCConfig;
                                       // Report if partitioned global caching
                                       // is actually enabled.
};

/**
 * Partitioned global caching support
 *
 * See cudaOccPartitionedGlobalCachingModeSupport
 */
typedef enum cudaOccPartitionedGCSupport_enum {
    PARTITIONED_GC_NOT_SUPPORTED,  // Partitioned global caching is not supported
    PARTITIONED_GC_SUPPORTED,      // Partitioned global caching is supported
} cudaOccPartitionedGCSupport;

/**
 * Implementation
 */

/**
 * Max compute capability supported
 */
#define __CUDA_OCC_MAJOR__ 9
#define __CUDA_OCC_MINOR__ 0

//////////////////////////////////////////
//    Mathematical Helper Functions     //
//////////////////////////////////////////

static __OCC_INLINE int __occMin(int lhs, int rhs)
{
    return rhs < lhs ? rhs : lhs;
}

static __OCC_INLINE int __occDivideRoundUp(int x, int y)
{
    return (x + (y - 1)) / y;
}

static __OCC_INLINE int __occRoundUp(int x, int y)
{
    return y * __occDivideRoundUp(x, y);
}

//////////////////////////////////////////
//      Architectural Properties        //
//////////////////////////////////////////

/**
 * Granularity of shared memory allocation
 */
static __OCC_INLINE cudaOccError cudaOccSMemAllocationGranularity(int *limit, const cudaOccDeviceProp *properties)
{
    int value;

    switch(properties->computeMajor) {
        case 3:
        case 5:
        case 6:
        case 7:
            value = 256;
            break;
        case 8:
        case 9:
            value = 128;
            break;
        default:
            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
    }

    *limit = value;

    return CUDA_OCC_SUCCESS;
}

/**
 * Maximum number of registers per thread
 */
static __OCC_INLINE cudaOccError cudaOccRegAllocationMaxPerThread(int *limit, const cudaOccDeviceProp *properties)
{
    int value;

    switch(properties->computeMajor) {
        case 3:
        case 5:
        case 6:
            value = 255;
            break;
        case 7:
        case 8:
        case 9:
            value = 256;
            break;
        default:
            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
    }

    *limit = value;

    return CUDA_OCC_SUCCESS;
}

/**
 * Granularity of register allocation
 */
static __OCC_INLINE cudaOccError cudaOccRegAllocationGranularity(int *limit, const cudaOccDeviceProp *properties)
{
    int value;

    switch(properties->computeMajor) {
        case 3:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
            value = 256;
            break;
        default:
            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
    }

    *limit = value;

    return CUDA_OCC_SUCCESS;
}

/**
 * Number of sub-partitions
 */
static __OCC_INLINE cudaOccError cudaOccSubPartitionsPerMultiprocessor(int *limit, const cudaOccDeviceProp *properties)
{
    int value;

    switch(properties->computeMajor) {
        case 3:
        case 5:
        case 7:
        case 8:
        case 9:
            value = 4;
            break;
        case 6:
            value = properties->computeMinor ? 4 : 2;
            break;
        default:
            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
    }

    *limit = value;

    return CUDA_OCC_SUCCESS;
}


/**
 * Maximum number of blocks that can run simultaneously on a multiprocessor
 */
static __OCC_INLINE cudaOccError cudaOccMaxBlocksPerMultiprocessor(int* limit, const cudaOccDeviceProp *properties)
{
    int value;

    switch(properties->computeMajor) {
        case 3:
            value = 16;
            break;
        case 5:
        case 6:
            value = 32;
            break;
        case 7: {
            int isTuring = properties->computeMinor == 5;
            value = (isTuring) ? 16 : 32;
            break;
        }
        case 8:
            if (properties->computeMinor == 0) {
                value = 32;
            }
            else if (properties->computeMinor == 9) {
                value = 24;
            }
            else {
                value = 16;
            }
            break;
        case 9:
            value = 32;
            break;
        default:
            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
    }

    *limit = value;

    return CUDA_OCC_SUCCESS;
}

/** 
 * Align up shared memory based on compute major configurations
 */
static __OCC_INLINE cudaOccError cudaOccAlignUpShmemSizeVoltaPlus(size_t *shMemSize, const cudaOccDeviceProp *properties)
{
    // Volta and Turing have shared L1 cache / shared memory, and support cache
    // configuration to trade one for the other. These values are needed to
    // map carveout config ratio to the next available architecture size
    size_t size = *shMemSize;

    switch (properties->computeMajor) {
    case 7: {
        // Turing supports 32KB and 64KB shared mem.
        int isTuring = properties->computeMinor == 5;
        if (isTuring) {
            if      (size <= 32 * 1024) {
                *shMemSize = 32 * 1024;
            }
            else if (size <= 64 * 1024) {
                *shMemSize = 64 * 1024;
            }
            else {
                return CUDA_OCC_ERROR_INVALID_INPUT;
            }
        }
        // Volta supports 0KB, 8KB, 16KB, 32KB, 64KB, and 96KB shared mem.
        else {
            if      (size == 0) {
                *shMemSize = 0;
            }
            else if (size <= 8 * 1024) {
                *shMemSize = 8 * 1024;
            }
            else if (size <= 16 * 1024) {
                *shMemSize = 16 * 1024;
            }
            else if (size <= 32 * 1024) {
                *shMemSize = 32 * 1024;
            }
            else if (size <= 64 * 1024) {
                *shMemSize = 64 * 1024;
            }
            else if (size <= 96 * 1024) {
                *shMemSize = 96 * 1024;
            }
            else {
                return CUDA_OCC_ERROR_INVALID_INPUT;
            }
        }
        break;
    }
    case 8:
        if (properties->computeMinor == 0 || properties->computeMinor == 7) {
            if      (size == 0) {
                *shMemSize = 0;
            }
            else if (size <= 8 * 1024) {
                *shMemSize = 8 * 1024;
            }
            else if (size <= 16 * 1024) {
                *shMemSize = 16 * 1024;
            }
            else if (size <= 32 * 1024) {
                *shMemSize = 32 * 1024;
            }
            else if (size <= 64 * 1024) {
                *shMemSize = 64 * 1024;
            }
            else if (size <= 100 * 1024) {
                *shMemSize = 100 * 1024;
            }
            else if (size <= 132 * 1024) {
                *shMemSize = 132 * 1024;
            }
            else if (size <= 164 * 1024) {
                *shMemSize = 164 * 1024;
            }
            else {
                return CUDA_OCC_ERROR_INVALID_INPUT;
            }
        }
        else {
            if      (size == 0) {
                *shMemSize = 0;
            }
            else if (size <= 8 * 1024) {
                *shMemSize = 8 * 1024;
            }
            else if (size <= 16 * 1024) {
                *shMemSize = 16 * 1024;
            }
            else if (size <= 32 * 1024) {
                *shMemSize = 32 * 1024;
            }
            else if (size <= 64 * 1024) {
                *shMemSize = 64 * 1024;
            }
            else if (size <= 100 * 1024) {
                *shMemSize = 100 * 1024;
            }
            else {
                return CUDA_OCC_ERROR_INVALID_INPUT;
            }
        }
        break;
    case 9: {
        if      (size == 0) {
            *shMemSize = 0;
        }
        else if (size <= 8 * 1024) {
            *shMemSize = 8 * 1024;
        }
        else if (size <= 16 * 1024) {
            *shMemSize = 16 * 1024;
        }
        else if (size <= 32 * 1024) {
            *shMemSize = 32 * 1024;
        }
        else if (size <= 64 * 1024) {
            *shMemSize = 64 * 1024;
        }
        else if (size <= 100 * 1024) {
            *shMemSize = 100 * 1024;
        }
        else if (size <= 132 * 1024) {
            *shMemSize = 132 * 1024;
        }
        else if (size <= 164 * 1024) {
            *shMemSize = 164 * 1024;
        }
        else if (size <= 196 * 1024) {
            *shMemSize = 196 * 1024;
        }
        else if (size <= 228 * 1024) {
            *shMemSize = 228 * 1024;
        }
        else {
            return CUDA_OCC_ERROR_INVALID_INPUT;
        }
        break;
    }
    default:
        return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
    }

    return CUDA_OCC_SUCCESS;
}

/**
 * Shared memory based on the new carveoutConfig API introduced with Volta
 */
static __OCC_INLINE cudaOccError cudaOccSMemPreferenceVoltaPlus(size_t *limit, const cudaOccDeviceProp *properties, const cudaOccDeviceState *state)
{
    cudaOccError status = CUDA_OCC_SUCCESS;
    size_t preferenceShmemSize;

    // CUDA 9.0 introduces a new API to set shared memory - L1 configuration on supported
    // devices. This preference will take precedence over the older cacheConfig setting.
    // Map cacheConfig to its effective preference value.
    int effectivePreference = state->carveoutConfig;
    if ((effectivePreference < SHAREDMEM_CARVEOUT_DEFAULT) || (effectivePreference > SHAREDMEM_CARVEOUT_MAX_SHARED)) {
        return CUDA_OCC_ERROR_INVALID_INPUT;
    }
    
    if (effectivePreference == SHAREDMEM_CARVEOUT_DEFAULT) {
        switch (state->cacheConfig)
        {
        case CACHE_PREFER_L1:
            effectivePreference = SHAREDMEM_CARVEOUT_MAX_L1;
            break;
        case CACHE_PREFER_SHARED:
            effectivePreference = SHAREDMEM_CARVEOUT_MAX_SHARED;
            break;
        case CACHE_PREFER_EQUAL:
            effectivePreference = SHAREDMEM_CARVEOUT_HALF;
            break;
        default:
            effectivePreference = SHAREDMEM_CARVEOUT_DEFAULT;
            break;
        }
    }

    if (effectivePreference == SHAREDMEM_CARVEOUT_DEFAULT) {
        preferenceShmemSize = properties->sharedMemPerMultiprocessor;
    }
    else {
        preferenceShmemSize = (size_t) (effectivePreference * properties->sharedMemPerMultiprocessor) / 100;
    }

    status = cudaOccAlignUpShmemSizeVoltaPlus(&preferenceShmemSize, properties);
    *limit = preferenceShmemSize;
    return status;
}

/**
 * Shared memory based on the cacheConfig
 */
static __OCC_INLINE cudaOccError cudaOccSMemPreference(size_t *limit, const cudaOccDeviceProp *properties, const cudaOccDeviceState *state)
{
    size_t bytes                          = 0;
    size_t sharedMemPerMultiprocessorHigh = properties->sharedMemPerMultiprocessor;
    cudaOccCacheConfig cacheConfig        = state->cacheConfig;

    // Kepler has shared L1 cache / shared memory, and support cache
    // configuration to trade one for the other. These values are needed to
    // calculate the correct shared memory size for user requested cache
    // configuration.
    //
    size_t minCacheSize                   = 16384;
    size_t maxCacheSize                   = 49152;
    size_t cacheAndSharedTotal            = sharedMemPerMultiprocessorHigh + minCacheSize;
    size_t sharedMemPerMultiprocessorLow  = cacheAndSharedTotal - maxCacheSize;

    switch (properties->computeMajor) {
        case 3:
            // Kepler supports 16KB, 32KB, or 48KB partitions for L1. The rest
            // is shared memory.
            //
            switch (cacheConfig) {
                default :
                case CACHE_PREFER_NONE:
                case CACHE_PREFER_SHARED:
                    bytes = sharedMemPerMultiprocessorHigh;
                    break;
                case CACHE_PREFER_L1:
                    bytes = sharedMemPerMultiprocessorLow;
                    break;
                case CACHE_PREFER_EQUAL:
                    // Equal is the mid-point between high and low. It should be
                    // equivalent to low + 16KB.
                    //
                    bytes = (sharedMemPerMultiprocessorHigh + sharedMemPerMultiprocessorLow) / 2;
                    break;
            }
            break;
        case 5:
        case 6:
            // Maxwell and Pascal have dedicated shared memory.
            //
            bytes = sharedMemPerMultiprocessorHigh;
            break;
        default:
            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
    }

    *limit = bytes;

    return CUDA_OCC_SUCCESS;
}

/**
 * Shared memory based on config requested by User
 */
static __OCC_INLINE cudaOccError cudaOccSMemPerMultiprocessor(size_t *limit, const cudaOccDeviceProp *properties, const cudaOccDeviceState *state)
{
    // Volta introduces a new API that allows for shared memory carveout preference. Because it is a shared memory preference,
    // it is handled separately from the cache config preference.
    if (properties->computeMajor >= 7) {
        return cudaOccSMemPreferenceVoltaPlus(limit, properties, state);
    }
    return cudaOccSMemPreference(limit, properties, state);
}

/**
 * Return the per block shared memory limit based on function config
 */
static __OCC_INLINE cudaOccError cudaOccSMemPerBlock(size_t *limit, const cudaOccDeviceProp *properties, cudaOccFuncShmemConfig shmemLimitConfig, size_t smemPerCta)
{
    switch (properties->computeMajor) {
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
            *limit = properties->sharedMemPerBlock;
            break;
        case 7:
        case 8:
        case 9:
            switch (shmemLimitConfig) {
                default:
                case FUNC_SHMEM_LIMIT_DEFAULT:
                    *limit = properties->sharedMemPerBlock;
                    break;
                case FUNC_SHMEM_LIMIT_OPTIN:
                    if (smemPerCta > properties->sharedMemPerBlock) {
                        *limit = properties->sharedMemPerBlockOptin;
                    }
                    else {
                        *limit = properties->sharedMemPerBlock;
                    }
                    break;
            }
            break;
        default:
            return CUDA_OCC_ERROR_UNKNOWN_DEVICE;
    }

    // Starting Ampere, CUDA driver reserves additional shared memory per block
    if (properties->computeMajor >= 8) {
        *limit += properties->reservedSharedMemPerBlock;
    }

    return CUDA_OCC_SUCCESS;
}

/**
 * Partitioned global caching mode support
 */
static __OCC_INLINE cudaOccError cudaOccPartitionedGlobalCachingModeSupport(cudaOccPartitionedGCSupport *limit, const cudaOccDeviceProp *properties)
{
    *limit = PARTITIONED_GC_NOT_SUPPORTED;

    if ((properties->computeMajor == 5 && (properties->computeMinor == 2 || properties->computeMinor == 3)) ||
        properties->computeMajor == 6) {
        *limit = PARTITIONED_GC_SUPPORTED;
    }

    if (properties->computeMajor == 6 && properties->computeMinor == 0) {
        *limit = PARTITIONED_GC_NOT_SUPPORTED;
    }

    return CUDA_OCC_SUCCESS;
}

///////////////////////////////////////////////
//            User Input Sanity              //
///////////////////////////////////////////////

static __OCC_INLINE cudaOccError cudaOccDevicePropCheck(const cudaOccDeviceProp *properties)
{
    // Verify device properties
    //
    // Each of these limits must be a positive number.
    //
    // Compute capacity is checked during the occupancy calculation
    //
    if (properties->maxThreadsPerBlock          <= 0 ||
        properties->maxThreadsPerMultiprocessor <= 0 ||
        properties->regsPerBlock                <= 0 ||
        properties->regsPerMultiprocessor       <= 0 ||
        properties->warpSize                    <= 0 ||
        properties->sharedMemPerBlock           <= 0 ||
        properties->sharedMemPerMultiprocessor  <= 0 ||
        properties->numSms                      <= 0) {
        return CUDA_OCC_ERROR_INVALID_INPUT;
    }

    return CUDA_OCC_SUCCESS;
}

static __OCC_INLINE cudaOccError cudaOccFuncAttributesCheck(const cudaOccFuncAttributes *attributes)
{
    // Verify function attributes
    //
    if (attributes->maxThreadsPerBlock <= 0 ||
        attributes->numRegs < 0) {            // Compiler may choose not to use
                                              // any register (empty kernels,
                                              // etc.)
        return CUDA_OCC_ERROR_INVALID_INPUT;
    }

    return CUDA_OCC_SUCCESS;
}

static __OCC_INLINE cudaOccError cudaOccDeviceStateCheck(const cudaOccDeviceState *state)
{
    (void)state;   // silence unused-variable warning
    // Placeholder
    //

    return CUDA_OCC_SUCCESS;
}

static __OCC_INLINE cudaOccError cudaOccInputCheck(
    const cudaOccDeviceProp     *properties,
    const cudaOccFuncAttributes *attributes,
    const cudaOccDeviceState    *state)
{
    cudaOccError status = CUDA_OCC_SUCCESS;

    status = cudaOccDevicePropCheck(properties);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    status = cudaOccFuncAttributesCheck(attributes);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    status = cudaOccDeviceStateCheck(state);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    return status;
}

///////////////////////////////////////////////
//    Occupancy calculation Functions        //
///////////////////////////////////////////////

static __OCC_INLINE cudaOccPartitionedGCConfig cudaOccPartitionedGCExpected(
    const cudaOccDeviceProp     *properties,
    const cudaOccFuncAttributes *attributes)
{
    cudaOccPartitionedGCSupport gcSupport;
    cudaOccPartitionedGCConfig gcConfig;

    cudaOccPartitionedGlobalCachingModeSupport(&gcSupport, properties);

    gcConfig = attributes->partitionedGCConfig;

    if (gcSupport == PARTITIONED_GC_NOT_SUPPORTED) {
        gcConfig = PARTITIONED_GC_OFF;
    }

    return gcConfig;
}

// Warp limit
//
static __OCC_INLINE cudaOccError cudaOccMaxBlocksPerSMWarpsLimit(
    int                         *limit,
    cudaOccPartitionedGCConfig   gcConfig,
    const cudaOccDeviceProp     *properties,
    const cudaOccFuncAttributes *attributes,
    int                          blockSize)
{
    cudaOccError status = CUDA_OCC_SUCCESS;
    int maxWarpsPerSm;
    int warpsAllocatedPerCTA;
    int maxBlocks;
    (void)attributes;   // silence unused-variable warning

    if (blockSize > properties->maxThreadsPerBlock) {
        maxBlocks = 0;
    }
    else {
        maxWarpsPerSm = properties->maxThreadsPerMultiprocessor / properties->warpSize;
        warpsAllocatedPerCTA = __occDivideRoundUp(blockSize, properties->warpSize);
        maxBlocks = 0;

        if (gcConfig != PARTITIONED_GC_OFF) {
            int maxBlocksPerSmPartition;
            int maxWarpsPerSmPartition;

            // If partitioned global caching is on, then a CTA can only use a SM
            // partition (a half SM), and thus a half of the warp slots
            // available per SM
            //
            maxWarpsPerSmPartition  = maxWarpsPerSm / 2;
            maxBlocksPerSmPartition = maxWarpsPerSmPartition / warpsAllocatedPerCTA;
            maxBlocks               = maxBlocksPerSmPartition * 2;
        }
        // On hardware that supports partitioned global caching, each half SM is
        // guaranteed to support at least 32 warps (maximum number of warps of a
        // CTA), so caching will not cause 0 occupancy due to insufficient warp
        // allocation slots.
        //
        else {
            maxBlocks = maxWarpsPerSm / warpsAllocatedPerCTA;
        }
    }

    *limit = maxBlocks;

    return status;
}

// Shared memory limit
//
static __OCC_INLINE cudaOccError cudaOccMaxBlocksPerSMSmemLimit(
    int                         *limit,
    cudaOccResult               *result,
    const cudaOccDeviceProp     *properties,
    const cudaOccFuncAttributes *attributes,
    const cudaOccDeviceState    *state,
    int                          blockSize,
    size_t                       dynamicSmemSize)
{
    cudaOccError status = CUDA_OCC_SUCCESS;
    int allocationGranularity;
    size_t userSmemPreference = 0;
    size_t totalSmemUsagePerCTA;
    size_t maxSmemUsagePerCTA;
    size_t smemAllocatedPerCTA;
    size_t staticSmemSize;
    size_t sharedMemPerMultiprocessor;
    size_t smemLimitPerCTA;
    int maxBlocks;
    int dynamicSmemSizeExceeded = 0;
    int totalSmemSizeExceeded = 0;
    (void)blockSize;   // silence unused-variable warning

    status = cudaOccSMemAllocationGranularity(&allocationGranularity, properties);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    // Obtain the user preferred shared memory size. This setting is ignored if
    // user requests more shared memory than preferred.
    //
    status = cudaOccSMemPerMultiprocessor(&userSmemPreference, properties, state);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    staticSmemSize = attributes->sharedSizeBytes + properties->reservedSharedMemPerBlock;
    totalSmemUsagePerCTA = staticSmemSize + dynamicSmemSize;
    smemAllocatedPerCTA = __occRoundUp((int)totalSmemUsagePerCTA, (int)allocationGranularity);

    maxSmemUsagePerCTA = staticSmemSize + attributes->maxDynamicSharedSizeBytes;

    dynamicSmemSizeExceeded = 0;
    totalSmemSizeExceeded   = 0;

    // Obtain the user set maximum dynamic size if it exists
    // If so, the current launch dynamic shared memory must not
    // exceed the set limit
    if (attributes->shmemLimitConfig != FUNC_SHMEM_LIMIT_DEFAULT &&
        dynamicSmemSize > attributes->maxDynamicSharedSizeBytes) {
        dynamicSmemSizeExceeded = 1;
    }

    status = cudaOccSMemPerBlock(&smemLimitPerCTA, properties, attributes->shmemLimitConfig, maxSmemUsagePerCTA);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    if (smemAllocatedPerCTA > smemLimitPerCTA) {
        totalSmemSizeExceeded = 1;
    }

    if (dynamicSmemSizeExceeded || totalSmemSizeExceeded) {
        maxBlocks = 0;
    }
    else {
        // User requested shared memory limit is used as long as it is greater
        // than the total shared memory used per CTA, i.e. as long as at least
        // one CTA can be launched.
        if (userSmemPreference >= smemAllocatedPerCTA) {
            sharedMemPerMultiprocessor = userSmemPreference;
        }
        else {
            // On Volta+, user requested shared memory will limit occupancy
            // if it's less than shared memory per CTA. Otherwise, the
            // maximum shared memory limit is used.
            if (properties->computeMajor >= 7) {
                sharedMemPerMultiprocessor = smemAllocatedPerCTA;
                status = cudaOccAlignUpShmemSizeVoltaPlus(&sharedMemPerMultiprocessor, properties);
                if (status != CUDA_OCC_SUCCESS) {
                    return status;
                }
            }
            else {
                sharedMemPerMultiprocessor = properties->sharedMemPerMultiprocessor;
            }
        }

        if (smemAllocatedPerCTA > 0) {
            maxBlocks = (int)(sharedMemPerMultiprocessor / smemAllocatedPerCTA);
        }
        else {
            maxBlocks = INT_MAX;
        }
    }

    result->allocatedSharedMemPerBlock = smemAllocatedPerCTA;

    *limit = maxBlocks;

    return status;
}

static __OCC_INLINE
cudaOccError cudaOccMaxBlocksPerSMRegsLimit(
    int                         *limit,
    cudaOccPartitionedGCConfig  *gcConfig,
    cudaOccResult               *result,
    const cudaOccDeviceProp     *properties,
    const cudaOccFuncAttributes *attributes,
    int                          blockSize)
{
    cudaOccError status = CUDA_OCC_SUCCESS;
    int allocationGranularity;
    int warpsAllocatedPerCTA;
    int regsAllocatedPerCTA;
    int regsAssumedPerCTA;
    int regsPerWarp;
    int regsAllocatedPerWarp;
    int numSubPartitions;
    int numRegsPerSubPartition;
    int numWarpsPerSubPartition;
    int numWarpsPerSM;
    int maxBlocks;
    int maxRegsPerThread;

    status = cudaOccRegAllocationGranularity(
        &allocationGranularity,
        properties);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    status = cudaOccRegAllocationMaxPerThread(
        &maxRegsPerThread,
        properties);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    status = cudaOccSubPartitionsPerMultiprocessor(&numSubPartitions, properties);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    warpsAllocatedPerCTA = __occDivideRoundUp(blockSize, properties->warpSize);

    // GPUs of compute capability 2.x and higher allocate registers to warps
    //
    // Number of regs per warp is regs per thread x warp size, rounded up to
    // register allocation granularity
    //
    regsPerWarp          = attributes->numRegs * properties->warpSize;
    regsAllocatedPerWarp = __occRoundUp(regsPerWarp, allocationGranularity);
    regsAllocatedPerCTA  = regsAllocatedPerWarp * warpsAllocatedPerCTA;

    // Hardware verifies if a launch fits the per-CTA register limit. For
    // historical reasons, the verification logic assumes register
    // allocations are made to all partitions simultaneously. Therefore, to
    // simulate the hardware check, the warp allocation needs to be rounded
    // up to the number of partitions.
    //
    regsAssumedPerCTA = regsAllocatedPerWarp * __occRoundUp(warpsAllocatedPerCTA, numSubPartitions);

    if (properties->regsPerBlock < regsAssumedPerCTA ||   // Hardware check
        properties->regsPerBlock < regsAllocatedPerCTA || // Software check
        attributes->numRegs > maxRegsPerThread) {         // Per thread limit check
        maxBlocks = 0;
    }
    else {
        if (regsAllocatedPerWarp > 0) {
            // Registers are allocated in each sub-partition. The max number
            // of warps that can fit on an SM is equal to the max number of
            // warps per sub-partition x number of sub-partitions.
            //
            numRegsPerSubPartition  = properties->regsPerMultiprocessor / numSubPartitions;
            numWarpsPerSubPartition = numRegsPerSubPartition / regsAllocatedPerWarp;

            maxBlocks = 0;

            if (*gcConfig != PARTITIONED_GC_OFF) {
                int numSubPartitionsPerSmPartition;
                int numWarpsPerSmPartition;
                int maxBlocksPerSmPartition;

                // If partitioned global caching is on, then a CTA can only
                // use a half SM, and thus a half of the registers available
                // per SM
                //
                numSubPartitionsPerSmPartition = numSubPartitions / 2;
                numWarpsPerSmPartition         = numWarpsPerSubPartition * numSubPartitionsPerSmPartition;
                maxBlocksPerSmPartition        = numWarpsPerSmPartition / warpsAllocatedPerCTA;
                maxBlocks                      = maxBlocksPerSmPartition * 2;
            }

            // Try again if partitioned global caching is not enabled, or if
            // the CTA cannot fit on the SM with caching on (maxBlocks == 0).  In the latter
            // case, the device will automatically turn off caching, except
            // if the user forces enablement via PARTITIONED_GC_ON_STRICT to calculate
            // occupancy and launch configuration.
            //
            if (maxBlocks == 0 && *gcConfig != PARTITIONED_GC_ON_STRICT) {
               // In case *gcConfig was PARTITIONED_GC_ON flip it OFF since
               // this is what it will be if we spread CTA across partitions.
               //
               *gcConfig = PARTITIONED_GC_OFF;
               numWarpsPerSM = numWarpsPerSubPartition * numSubPartitions;
               maxBlocks     = numWarpsPerSM / warpsAllocatedPerCTA;
            }
        }
        else {
            maxBlocks = INT_MAX;
        }
    }


    result->allocatedRegistersPerBlock = regsAllocatedPerCTA;

    *limit = maxBlocks;

    return status;
}

// Barrier limit
//
static __OCC_INLINE cudaOccError cudaOccMaxBlocksPerSMBlockBarrierLimit(
    int                         *limit,
    int                          ctaLimitBlocks,
    const cudaOccFuncAttributes *attributes)
{
    cudaOccError status = CUDA_OCC_SUCCESS;
    int numBarriersAvailable = ctaLimitBlocks * 2;
    int numBarriersUsed = attributes->numBlockBarriers;
    int maxBlocks = INT_MAX;

    if (numBarriersUsed) {
        maxBlocks = numBarriersAvailable / numBarriersUsed;
    }

    *limit = maxBlocks;

    return status;
}

///////////////////////////////////
//      API Implementations      //
///////////////////////////////////

static __OCC_INLINE
cudaOccError cudaOccMaxActiveBlocksPerMultiprocessor(
    cudaOccResult               *result,
    const cudaOccDeviceProp     *properties,
    const cudaOccFuncAttributes *attributes,
    const cudaOccDeviceState    *state,
    int                          blockSize,
    size_t                       dynamicSmemSize)
{
    cudaOccError status          = CUDA_OCC_SUCCESS;
    int          ctaLimitWarps   = 0;
    int          ctaLimitBlocks  = 0;
    int          ctaLimitSMem    = 0;
    int          ctaLimitRegs    = 0;
    int          ctaLimitBars    = 0;
    int          ctaLimit        = 0;
    unsigned int limitingFactors = 0;
    
    cudaOccPartitionedGCConfig gcConfig = PARTITIONED_GC_OFF;

    if (!result || !properties || !attributes || !state || blockSize <= 0) {
        return CUDA_OCC_ERROR_INVALID_INPUT;
    }

    ///////////////////////////
    // Check user input
    ///////////////////////////

    status = cudaOccInputCheck(properties, attributes, state);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    ///////////////////////////
    // Initialization
    ///////////////////////////

    gcConfig = cudaOccPartitionedGCExpected(properties, attributes);

    ///////////////////////////
    // Compute occupancy
    ///////////////////////////

    // Limits due to registers/SM
    // Also compute if partitioned global caching has to be turned off
    //
    status = cudaOccMaxBlocksPerSMRegsLimit(&ctaLimitRegs, &gcConfig, result, properties, attributes, blockSize);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    // SMs on GP100 (6.0) have 2 subpartitions, while those on GP10x have 4.
    // As a result, an SM on GP100 may be able to run more CTAs than the one on GP10x.
    // For forward compatibility within Pascal family, if a function cannot run on GP10x (maxBlock == 0),
    // we do not let it run on any Pascal processor, even though it may be able to run on GP100.
    // Therefore, we check the occupancy on GP10x when it can run on GP100
    //
    if (properties->computeMajor == 6 && properties->computeMinor == 0 && ctaLimitRegs) {
        cudaOccDeviceProp propertiesGP10x;
        cudaOccPartitionedGCConfig gcConfigGP10x = gcConfig;
        int ctaLimitRegsGP10x = 0;

        // Set up properties for GP10x
        memcpy(&propertiesGP10x, properties, sizeof(propertiesGP10x));
        propertiesGP10x.computeMinor = 1;

        status = cudaOccMaxBlocksPerSMRegsLimit(&ctaLimitRegsGP10x, &gcConfigGP10x, result, &propertiesGP10x, attributes, blockSize);
        if (status != CUDA_OCC_SUCCESS) {
            return status;
        }

        if (ctaLimitRegsGP10x == 0) {
            ctaLimitRegs = 0;
        }
    }

    // Limits due to warps/SM
    //
    status = cudaOccMaxBlocksPerSMWarpsLimit(&ctaLimitWarps, gcConfig, properties, attributes, blockSize);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    // Limits due to blocks/SM
    //
    status = cudaOccMaxBlocksPerMultiprocessor(&ctaLimitBlocks, properties);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    // Limits due to shared memory/SM
    //
    status = cudaOccMaxBlocksPerSMSmemLimit(&ctaLimitSMem, result, properties, attributes, state, blockSize, dynamicSmemSize);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    ///////////////////////////
    // Overall occupancy
    ///////////////////////////

    // Overall limit is min() of limits due to above reasons
    //
    ctaLimit = __occMin(ctaLimitRegs, __occMin(ctaLimitSMem, __occMin(ctaLimitWarps, ctaLimitBlocks)));

    // Determine occupancy limiting factors
    //
    if (ctaLimit == ctaLimitWarps) {
        limitingFactors |= OCC_LIMIT_WARPS;
    }
    if (ctaLimit == ctaLimitRegs) {
        limitingFactors |= OCC_LIMIT_REGISTERS;
    }
    if (ctaLimit == ctaLimitSMem) {
        limitingFactors |= OCC_LIMIT_SHARED_MEMORY;
    }
    if (ctaLimit == ctaLimitBlocks) {
        limitingFactors |= OCC_LIMIT_BLOCKS;
    }

    // For Hopper onwards compute the limits to occupancy based on block barrier count
    //
    if (properties->computeMajor >= 9 && attributes->numBlockBarriers > 0) {
        // Limits due to barrier/SM
        //
        status = cudaOccMaxBlocksPerSMBlockBarrierLimit(&ctaLimitBars, ctaLimitBlocks, attributes);
        if (status != CUDA_OCC_SUCCESS) {
            return status;
        }

        // Recompute overall limit based on barrier/SM
        //
        ctaLimit = __occMin(ctaLimitBars, ctaLimit);

        // Determine if this is occupancy limiting factor
        //
        if (ctaLimit == ctaLimitBars) {
            limitingFactors |= OCC_LIMIT_BARRIERS;
        }
    }
    else {
        ctaLimitBars = INT_MAX;
    }

    // Fill in the return values
    //
    result->limitingFactors = limitingFactors;

    result->blockLimitRegs      = ctaLimitRegs;
    result->blockLimitSharedMem = ctaLimitSMem;
    result->blockLimitWarps     = ctaLimitWarps;
    result->blockLimitBlocks    = ctaLimitBlocks;
    result->blockLimitBarriers  = ctaLimitBars;
    result->partitionedGCConfig = gcConfig;

    // Final occupancy
    result->activeBlocksPerMultiprocessor = ctaLimit;

    return CUDA_OCC_SUCCESS;
}

static __OCC_INLINE
cudaOccError cudaOccAvailableDynamicSMemPerBlock(
    size_t                      *bytesAvailable,
    const cudaOccDeviceProp     *properties,
    const cudaOccFuncAttributes *attributes,
    const cudaOccDeviceState    *state,
    int                         numBlocks,
    int                         blockSize)
{
    int allocationGranularity;
    size_t smemLimitPerBlock;
    size_t smemAvailableForDynamic;
    size_t userSmemPreference = 0;
    size_t sharedMemPerMultiprocessor;
    cudaOccResult result;
    cudaOccError status = CUDA_OCC_SUCCESS;

    if (numBlocks <= 0)
        return CUDA_OCC_ERROR_INVALID_INPUT;

    // First compute occupancy of potential kernel launch.
    //
    status = cudaOccMaxActiveBlocksPerMultiprocessor(&result, properties, attributes, state, blockSize, 0);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }
    // Check if occupancy is achievable given user requested number of blocks. 
    //
    if (result.activeBlocksPerMultiprocessor < numBlocks) {
        return CUDA_OCC_ERROR_INVALID_INPUT;
    }

    status = cudaOccSMemAllocationGranularity(&allocationGranularity, properties);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    // Return the per block shared memory limit based on function config.
    //
    status = cudaOccSMemPerBlock(&smemLimitPerBlock, properties, attributes->shmemLimitConfig, properties->sharedMemPerMultiprocessor);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    // If there is only a single block needed per SM, then the user preference can be ignored and the fully SW
    // limit is allowed to be used as shared memory otherwise if more than one block is needed, then the user
    // preference sets the total limit of available shared memory.
    //
    cudaOccSMemPerMultiprocessor(&userSmemPreference, properties, state);
    if (numBlocks == 1) {
        sharedMemPerMultiprocessor = smemLimitPerBlock;
    }
    else {
        if (!userSmemPreference) {
            userSmemPreference = 1 ;
            status = cudaOccAlignUpShmemSizeVoltaPlus(&userSmemPreference, properties);
            if (status != CUDA_OCC_SUCCESS) {
                return status;
            }
        }
        sharedMemPerMultiprocessor = userSmemPreference;
    }

    // Compute total shared memory available per SM
    //
    smemAvailableForDynamic =  sharedMemPerMultiprocessor / numBlocks;
    smemAvailableForDynamic = (smemAvailableForDynamic / allocationGranularity) * allocationGranularity;

    // Cap shared memory
    //
    if (smemAvailableForDynamic > smemLimitPerBlock) {
        smemAvailableForDynamic = smemLimitPerBlock;
    }

    // Now compute dynamic shared memory size
    smemAvailableForDynamic = smemAvailableForDynamic - attributes->sharedSizeBytes; 

    // Cap computed dynamic SM by user requested limit specified via cuFuncSetAttribute()
    //
    if (smemAvailableForDynamic > attributes->maxDynamicSharedSizeBytes)
        smemAvailableForDynamic = attributes->maxDynamicSharedSizeBytes;

    *bytesAvailable = smemAvailableForDynamic;
    return CUDA_OCC_SUCCESS;
}

static __OCC_INLINE
cudaOccError cudaOccMaxPotentialOccupancyBlockSize(
    int                         *minGridSize,
    int                         *blockSize,
    const cudaOccDeviceProp     *properties,
    const cudaOccFuncAttributes *attributes,
    const cudaOccDeviceState    *state,
    size_t                     (*blockSizeToDynamicSMemSize)(int),
    size_t                       dynamicSMemSize)
{
    cudaOccError  status = CUDA_OCC_SUCCESS;
    cudaOccResult result;

    // Limits
    int occupancyLimit;
    int granularity;
    int blockSizeLimit;

    // Recorded maximum
    int maxBlockSize = 0;
    int numBlocks    = 0;
    int maxOccupancy = 0;

    // Temporary
    int blockSizeToTryAligned;
    int blockSizeToTry;
    int blockSizeLimitAligned;
    int occupancyInBlocks;
    int occupancyInThreads;

    ///////////////////////////
    // Check user input
    ///////////////////////////

    if (!minGridSize || !blockSize || !properties || !attributes || !state) {
        return CUDA_OCC_ERROR_INVALID_INPUT;
    }

    status = cudaOccInputCheck(properties, attributes, state);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // Try each block size, and pick the block size with maximum occupancy
    /////////////////////////////////////////////////////////////////////////////////

    occupancyLimit = properties->maxThreadsPerMultiprocessor;
    granularity    = properties->warpSize;

    blockSizeLimit        = __occMin(properties->maxThreadsPerBlock, attributes->maxThreadsPerBlock);
    blockSizeLimitAligned = __occRoundUp(blockSizeLimit, granularity);

    for (blockSizeToTryAligned = blockSizeLimitAligned; blockSizeToTryAligned > 0; blockSizeToTryAligned -= granularity) {
        blockSizeToTry = __occMin(blockSizeLimit, blockSizeToTryAligned);

        // Ignore dynamicSMemSize if the user provides a mapping
        //
        if (blockSizeToDynamicSMemSize) {
            dynamicSMemSize = (*blockSizeToDynamicSMemSize)(blockSizeToTry);
        }

        status = cudaOccMaxActiveBlocksPerMultiprocessor(
            &result,
            properties,
            attributes,
            state,
            blockSizeToTry,
            dynamicSMemSize);

        if (status != CUDA_OCC_SUCCESS) {
            return status;
        }

        occupancyInBlocks = result.activeBlocksPerMultiprocessor;
        occupancyInThreads = blockSizeToTry * occupancyInBlocks;

        if (occupancyInThreads > maxOccupancy) {
            maxBlockSize = blockSizeToTry;
            numBlocks    = occupancyInBlocks;
            maxOccupancy = occupancyInThreads;
        }

        // Early out if we have reached the maximum
        //
        if (occupancyLimit == maxOccupancy) {
            break;
        }
    }

    ///////////////////////////
    // Return best available
    ///////////////////////////

    // Suggested min grid size to achieve a full machine launch
    //
    *minGridSize = numBlocks * properties->numSms;
    *blockSize = maxBlockSize;

    return status;
}


#if defined(__cplusplus)

namespace {

__OCC_INLINE
cudaOccError cudaOccMaxPotentialOccupancyBlockSize(
    int                         *minGridSize,
    int                         *blockSize,
    const cudaOccDeviceProp     *properties,
    const cudaOccFuncAttributes *attributes,
    const cudaOccDeviceState    *state,
    size_t                       dynamicSMemSize)
{
    return cudaOccMaxPotentialOccupancyBlockSize(
        minGridSize,
        blockSize,
        properties,
        attributes,
        state,
        NULL,
        dynamicSMemSize);
}

template <typename UnaryFunction>
__OCC_INLINE
cudaOccError cudaOccMaxPotentialOccupancyBlockSizeVariableSMem(
    int                         *minGridSize,
    int                         *blockSize,
    const cudaOccDeviceProp     *properties,
    const cudaOccFuncAttributes *attributes,
    const cudaOccDeviceState    *state,
    UnaryFunction                blockSizeToDynamicSMemSize)
{
    cudaOccError  status = CUDA_OCC_SUCCESS;
    cudaOccResult result;

    // Limits
    int occupancyLimit;
    int granularity;
    int blockSizeLimit;

    // Recorded maximum
    int maxBlockSize = 0;
    int numBlocks    = 0;
    int maxOccupancy = 0;

    // Temporary
    int blockSizeToTryAligned;
    int blockSizeToTry;
    int blockSizeLimitAligned;
    int occupancyInBlocks;
    int occupancyInThreads;
    size_t dynamicSMemSize;

    ///////////////////////////
    // Check user input
    ///////////////////////////

    if (!minGridSize || !blockSize || !properties || !attributes || !state) {
        return CUDA_OCC_ERROR_INVALID_INPUT;
    }

    status = cudaOccInputCheck(properties, attributes, state);
    if (status != CUDA_OCC_SUCCESS) {
        return status;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // Try each block size, and pick the block size with maximum occupancy
    /////////////////////////////////////////////////////////////////////////////////

    occupancyLimit = properties->maxThreadsPerMultiprocessor;
    granularity    = properties->warpSize;
    blockSizeLimit        = __occMin(properties->maxThreadsPerBlock, attributes->maxThreadsPerBlock);
    blockSizeLimitAligned = __occRoundUp(blockSizeLimit, granularity);

    for (blockSizeToTryAligned = blockSizeLimitAligned; blockSizeToTryAligned > 0; blockSizeToTryAligned -= granularity) {
        blockSizeToTry = __occMin(blockSizeLimit, blockSizeToTryAligned);

        dynamicSMemSize = blockSizeToDynamicSMemSize(blockSizeToTry);

        status = cudaOccMaxActiveBlocksPerMultiprocessor(
            &result,
            properties,
            attributes,
            state,
            blockSizeToTry,
            dynamicSMemSize);

        if (status != CUDA_OCC_SUCCESS) {
            return status;
        }

        occupancyInBlocks = result.activeBlocksPerMultiprocessor;

        occupancyInThreads = blockSizeToTry * occupancyInBlocks;

        if (occupancyInThreads > maxOccupancy) {
            maxBlockSize = blockSizeToTry;
            numBlocks    = occupancyInBlocks;
            maxOccupancy = occupancyInThreads;
        }

        // Early out if we have reached the maximum
        //
        if (occupancyLimit == maxOccupancy) {
            break;
        }
    }

    ///////////////////////////
    // Return best available
    ///////////////////////////

    // Suggested min grid size to achieve a full machine launch
    //
    *minGridSize = numBlocks * properties->numSms;
    *blockSize = maxBlockSize;

    return status;
}

} // namespace anonymous

#endif /*__cplusplus */

#undef __OCC_INLINE

#endif /*__cuda_occupancy_h__*/